Inheritance: MonoBehaviour
 public void Can_dispose_of_configuration_after_usage()
 {
     var conf = new FullConfiguration();
     var parserBuilder = new Build().Configuration(conf);
     parserBuilder.Dispose();
     Assert.That(conf.DisposeCalled);
 }
Beispiel #2
0
        public ProBuilds(String champ)
        {
            Builds = new List<Build>();
            String htmlPage = new WebClient().DownloadString("http://lolbuilder.net/" + champ);
            foreach (Match buildsRegex in new Regex("#(build\\-[0-9]+)\">([a-zA-Z ]+) \\(<span class=\"hover-text\" tooltip=\"Seen in up to ([0-9]+)").Matches(htmlPage))
            {
                Build build = new Build();

                Match buildRegex = new Regex(buildsRegex.Groups[1].ToString()).Matches(htmlPage)[1];
                String buildSectionHtml = htmlPage.Substring(buildRegex.Index);

                String summaryHtml = buildSectionHtml.Substring(buildSectionHtml.IndexOf("build-summary-separator separator"));
                summaryHtml = summaryHtml.Substring(0, summaryHtml.IndexOf("build-box starting-items"));
                String startingHtml = buildSectionHtml.Substring(buildSectionHtml.IndexOf("build-box starting-items"));
                startingHtml = startingHtml.Substring(0, startingHtml.IndexOf("build-box early-game"));
                String orderHtml = buildSectionHtml.Substring(buildSectionHtml.IndexOf("build-box early-game"));
                orderHtml = orderHtml.Substring(0, orderHtml.IndexOf("build-box final-items"));
                String finalHtml = buildSectionHtml.Substring(buildSectionHtml.IndexOf("build-box final-items"));
                if (finalHtml.IndexOf("build-app-text") > 0)
                    finalHtml = finalHtml.Substring(0, finalHtml.IndexOf("build-app-text"));

                build.Name = buildsRegex.Groups[2].ToString();
                build.Popularity = buildsRegex.Groups[3].ToString();
                build.Summary = GetItemsFromHtml(summaryHtml);
                build.StartingItems = GetItemsFromHtml(startingHtml);
                build.Order = GetItemsFromHtml(orderHtml);
                build.BestItems = GetItemsFromHtml(finalHtml);

                Builds.Add(build);
            }
        }
 protected override bool Input()
 {
     Console.WriteLine("Please input script name:");
     _Name = Console.ReadLine();
     build = new Build(_DesPath, _Name);
     return true;
 }
        public shared()
        {
            this.firstDate = new DateTime(2000, 10, 10);
            this.secondDate = new DateTime(2000, 10, 11);
            this.failedBuild1 = new Build() { FinishedTime = firstDate, Status = DomainModel.CI.BuildStatus.FinishedWithFailure };
            this.failedBuild2 = new Build() { FinishedTime = firstDate, Status = DomainModel.CI.BuildStatus.FinishedWithFailure };
            this.failedBuild3 = new Build() { FinishedTime = secondDate, Status = DomainModel.CI.BuildStatus.FinishedWithFailure };
            this.successBuild1 = new Build() { FinishedTime = firstDate, Status = DomainModel.CI.BuildStatus.FinishedSuccefully };
            this.successBuild2 = new Build() { FinishedTime = secondDate, Status = DomainModel.CI.BuildStatus.FinishedSuccefully };

            this.project1 = new CIProject("test one");
            project1.AddBuild(failedBuild1);
            project1.AddBuild(successBuild1);

            this.project2 = new CIProject("test two");
            project2.AddBuild(failedBuild2);
            project2.AddBuild(failedBuild3);
            project2.AddBuild(successBuild2);

            this.ciserver = new CIServer("server", "serverurl");
            ciserver.AddProject(project1);
            ciserver.AddProject(project2);

            repository.Setup(r => r.Get(It.IsAny<AllSpecification<CIServer>>()))
                .Returns(new List<CIServer>() { ciserver });
        }
        public void deploy(ArtifactoryBuild task, Build build, BuildInfoLog log) 
        {
            ArtifactoryBuildInfoClient client = new ArtifactoryBuildInfoClient(task.Url, task.User, task.Password, log);
            client.setProxy(build.deployClient);
            client.setConnectionTimeout(build.deployClient);

            try
            {
                if (task.DeployEnabled != null && task.DeployEnabled.Equals("true"))
                {
                    /* Deploy every artifacts from the Map< module.name : artifact.name > => List<DeployDetails> */
                    task.deployableArtifactBuilderMap.ToList().ForEach(entry => entry.Value.ForEach(artifact => client.deployArtifact(artifact)));
                }

                if (task.BuildInfoEnabled != null && task.BuildInfoEnabled.Equals("true"))
                {
                    //Upload Build Info json file to Artifactory
                    log.Info("Uploading build info to Artifactory...");
                    /* Send Build Info  */
                    client.sendBuildInfo(build);
                }
            }
            catch (Exception e)
            {
                log.Error("Exception has append from ArtifactoryBuildInfoClient: " + e.Message, e);
                throw new Exception("Exception has append from ArtifactoryBuildInfoClient: " + e.Message, e);
            }
            finally 
            {
                client.Dispose();
            }         
        }
        public Build Parse(Project project, HtmlNode[] columns)
        {
            _log.DebugFormat("Parsing a build configuration for {0}", project.Name);

            if (columns.Length != 3)
            {
                throw new TeamcityStatusParseException("The build row had the incorrect number of columns");
            }

            var buildConfigurationColumn = columns[0];
            var buildConfigurationLink = buildConfigurationColumn.SelectSingleNode("a");
            var buildConfigurationUrl = buildConfigurationLink.Attributes["href"].Value;
            var currentBuildLink = columns[1].SelectSingleNode("div/a");

            var build = new Build
            {
                Project = project,
                Name = buildConfigurationLink.InnerText,
                Id = GetId(buildConfigurationUrl),
                State = GetBuildState(buildConfigurationColumn),
                Url = buildConfigurationUrl
            };

            if (currentBuildLink != null)
            {
                build.CurrentBuildNumber = currentBuildLink.InnerText.Replace("#", string.Empty);
                build.CurrentBuildUrl = currentBuildLink.Attributes["href"].Value;
            }

            _log.DebugFormat("Parsed build configuration {0} ({1}) - {2}", build.Name, build.Id, build.State);

            return build;
        }
Beispiel #7
0
        public Build Parse(string inputXmlData)
        {
            ValidateAndLoadXml(inputXmlData);

            try
            {
                var build = new Build();

                XmlElement integrationProperties = xmlDocument["cruisecontrol"]["integrationProperties"];

                string buildTrigger = integrationProperties["CCNetBuildCondition"].InnerText;
                string buildStatus = integrationProperties["CCNetIntegrationStatus"].InnerText;

                build.Trigger = GetTrigger(buildTrigger);

                build.StartTime = GetStartTime();
                TimeSpan duration = GetBuildDuration();
                build.FinishedTime = build.StartTime + duration;
                build.Status = ParseStatus(buildStatus);

                return build;
            }
            catch (Exception ex)
            {
                throw new CruiseControlRepositoryException(
                    "There was an error parsing the XML-file. " +
                    "Please refer to the inner exception for details.", ex);
            }
        }
 private Root GetRootModelFromBuild(Build b)
 {
     var server = new Isop.Server.IsopServerFromBuild( ()=> b );
     var data = JsonConvert.SerializeObject(server.GetModel());
     var client = new IsopClient(new JsonHttpClientThatOnlyReturns(data), "http://localhost:666");
     return client.GetModel().Result;
 }
 void AnalysisJson()
 {
     var BuildString = (new WebClient()).DownloadString("https://dewrito.halo.click/api/builds");
     _list = JsonConvert.DeserializeObject<List<JObject>>(BuildString).Select((t) =>
     {
         JArray jar = JArray.Parse(t["artifacts"].ToString());
         Build b = new Build()
         {
             Branch = t["branch"].ToString(),
             BuildVersion = t["buildVersion"].ToString(),
             CommitAuthor = t["commitAuthor"].ToString(),
             CommitId = t["commitId"].ToString(),
             CommitMessage = t["commitMessage"].ToString(),
             downloadUrl = t["downloadUrl"].ToString(),
             CommitDate = Convert.ToDateTime(t["commitDate"])
         };
         for (var i = 0; i < jar.Count; i++)
         {
             JObject j = JObject.Parse(jar[i].ToString());
             b.size = j["size"].ToString();
             b.url = j["url"].ToString();
         }
         return b;
     }).ToList() as List<Build>;
     _list.Reverse();
 }
Beispiel #10
0
 public static void OnBuildStarted(BuildStarted e, Build view)
 {
     view.buildId = e.Id;
     view.Tasks = new List<TaskInfo>(e.Status.Tasks);
     view.Tasks.ForEach(info => view.TerminalOutput[info.Id] = new List<string>(){""});
     view.Status = Build.BuildOverallStatus.Started;
 }
Beispiel #11
0
 private static Controller Controller(Build that, Type type)
 {
     return new Controller
                {
                    Name = type.ControllerName(),
                    Methods = type.GetControllerActionMethods().Select(m => Method(that, type, m)).ToArray()
                };
 }
Beispiel #12
0
 public void AbortBuild(MergeRequest mergeRequest, Build build)
 {
     var projectClient = client.GetRepository(mergeRequest.SourceProjectId);
     var actualBuild = build ?? projectClient.Builds.GetBuilds().FirstOrDefault();
     if (actualBuild == null || (actualBuild.Status != BuildStatus.pending && actualBuild.Status != BuildStatus.running))
         return;
     projectClient.Builds.Cancel(actualBuild);
 }
Beispiel #13
0
 public void Can_generate_tree_model_from_configuration_with_controllers()
 {
     var treemodel = new Build()
         .Recognize(new MyController())
         .GetMethodTreeModel();
     Assert.That(treemodel.Controllers.Count(), Is.EqualTo(1));
     Assert.That(treemodel.GlobalParameters.Count(), Is.EqualTo(0));
 }
Beispiel #14
0
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     var path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location)
         .FullName;
     ParserBuilder = new Build().ConfigurationFrom(
         path);
 }
Beispiel #15
0
 public void It_can_report_usage_for_actions_with_description()
 {
     var usage = new Build()
                             .Recognize(typeof(DescriptionController))
                             .ShouldRecognizeHelp()
                             .HelpFor("Description","action1");
     Assert.That(LineSplit(usage), Is.EquivalentTo(LineSplit(@"Action1   Some description 1")));
 }
Beispiel #16
0
 public void Can_read_documentation_for_properties()
 {
     var conf = new FullConfiguration();
     var parserBuilder = new Build().Configuration(conf);
     var globalDesc = parserBuilder.GlobalParameters
         .First(gp => gp.Argument.Prototype.Equals("Global")).Description;
     Assert.That(globalDesc, Is.EqualTo("GLOBAL!!"));
 }
Beispiel #17
0
 public MethodTreeModel(IEnumerable<Param> globalParameters, IEnumerable<Controller> controllers, Build build)
 {
     GlobalParameters=globalParameters;
     Controllers=controllers;
     singleEventHandlerScope = new SingleScopeOnly();
     GlobalParameters.RegisterPropertyChanged(globalValueChanged);
     Build = build;
 }
Beispiel #18
0
 public void Save(string path, Build build)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(Build));
     using (var stream = new FileStream(path, FileMode.Create))
     {
         serializer.Serialize(stream, build);
     }
 }
Beispiel #19
0
        private static void Main(string[] args)
        {
            using (var build = new Build()
                .Recognize(typeof(DotGraphController))
                .Recognize(typeof(GraphController))
                .Recognize(typeof(SerializeController)))
            {
                try
                {
                    var parsedMethod = build.Parse(args);
                    if (parsedMethod.UnRecognizedArguments.Any())//Warning:
                    {
                        var unRecognizedArgumentsMessage = string.Format(
                                                               @"Unrecognized arguments:
            {0}
            Did you mean any of these arguments?
            {1}", String.Join(",", parsedMethod.UnRecognizedArguments.Select(unrec => unrec.Value).ToArray()),
                                                               String.Join(",", parsedMethod.ArgumentWithOptions.Select(rec => rec.Name).ToArray()));
                        Console.WriteLine(unRecognizedArgumentsMessage);
                        Environment.Exit(1);
                    }
                    else
                    {
                        parsedMethod.Invoke(Console.Out);
                    }
                }
                catch (TypeConversionFailedException ex)
                {

                    Console.WriteLine(String.Format("Could not convert argument {0} with value {1} to type {2}",
                            ex.Argument, ex.Value, ex.TargetType));
                    if (null != ex.InnerException)
                    {
                        Console.WriteLine("Inner exception: ");
                        Console.WriteLine(ex.InnerException.Message);
                    }
                    Environment.Exit(1);
                }
                catch (MissingArgumentException ex)
                {
                    Console.WriteLine(String.Format("Missing argument(s): {0}", String.Join(", ", ex.Arguments.ToArray())));
                    if (build.RecognizesHelp)
                        Console.WriteLine(build.Help());
                    Environment.Exit(1);
                }
                #if DEBUG
                catch (Exception ex1)
                {
                    Console.WriteLine(string.Join(Environment.NewLine, new object[]
                            {
                                "The invokation failed with exception:",
                                ex1.Message, ex1.StackTrace
                            }));
                    Environment.Exit(1);
                }
                #endif
            }
        }
        public BuildUpdated(Build entity, IEnumerable<Expression<Func<Build, object>>> updatedValues)
        {
            _buildId = entity.Id;

            foreach (var updatedValue in updatedValues)
            {
                _updatedValues[GetMemberInfo(updatedValue).Member.Name] = updatedValue.Compile().Invoke(entity);
            }
        }
Beispiel #21
0
 private static bool? GetPublishSetting(Build.Execution.ProjectItemInstance item) {
     bool? publish = null;
     string pubValue = item.GetMetadataValue("Publish");
     bool pubSetting;
     if (!String.IsNullOrWhiteSpace(pubValue) && Boolean.TryParse(pubValue, out pubSetting)) {
         publish = pubSetting;
     }
     return publish;
 }
 protected override void When()
 {
     Agent = new Domain.Agent(Bus, Worker, url => Repo, new string[]{}, Guid.NewGuid());
     Agent.JoinTheParty();
     buildMessage1 = new Build { RepoUrl = "http://fle", Revision = new RevisionInfo { Revision = "2" } };
     Agent.Handle(buildMessage1);
     buildMessage2 = new Build { RepoUrl = "http://flo", Revision = new RevisionInfo { Revision = "2" } };
     Agent.Handle(buildMessage2);
 }
 private static Build GetBuild(IEnumerable<Assembly> assemblies)
 {
     var build = new Build();
     foreach (var assembly in assemblies)
     {
         build.ConfigurationFrom(assembly);
     }
     return build;
 }
Beispiel #24
0
 private static Method Method(Build that, Type type, MethodInfo m)
 {
     var t = new TurnParametersToArgumentWithOptions(that.CultureInfo, that.TypeConverter);
     var @params = t.GetRecognizers(m).Select(p => new Param(p.Type, p.Argument.Prototype, p));
     return new Method(m.Name, type.ControllerName(), that.HelpController())
                {
                    Parameters = new List<Param>(@params.ToArray())
                };
 }
Beispiel #25
0
        public void Can_read_configuration_from_example_project()
        {
            var path = TryGetExamplePath();

            var parserBuilder = new Build().ConfigurationFrom(path);

            Assert.That(parserBuilder.ControllerRecognizers.Count(),
                Is.AtLeast(2));
        }
Beispiel #26
0
 public void Can_invoke_configure_method_on_configuration()
 {
     var conf = new FullConfiguration();
     var parserBuilder = new Build().Configuration(conf);
     var parsed = parserBuilder.Parse(new[] { "--global", "globalvalue", "--globalrequired", "2", "My", "Action", "--value", "1" });
     var cout = new StringWriter();
     parsed.Invoke(cout);
     Assert.That(conf.Global, Is.EqualTo("globalvalue"));
 }
        public static Download_History createAndGetDownloadHistory(Benutzer downloadingUser, Build downloadedBuild, DateTime downloadDate)
        {
            Download_History dh = Download_History.CreateDownload_History(downloadingUser.BenutzerID, downloadedBuild.ReleaseID, downloadDate);

            HodorGlobals.getHodorContext().Download_History.AddObject(dh);
            HodorGlobals.save();

            return dh;
        }
Beispiel #28
0
 public Build(Build build) {
   BuildName = "";
   RunePage = build.RunePage;
   MasteryPage = build.MasteryPage;
   ItemSet = build.ItemSet;
   StartAbilities = build.StartAbilities;
   MaxOrder = build.MaxOrder;
   Champion = build.Champion;
 }
Beispiel #29
0
 public void Can_generate_tree_model_from_configuration()
 {
     var treemodel = new Build()
         .Parameter(
             new ArgumentParameter("name", new[] { "name" }))
         .GetMethodTreeModel();
     Assert.That(treemodel.Controllers.Count(), Is.EqualTo(0));
     Assert.That(treemodel.GlobalParameters.Count(), Is.EqualTo(1));
 }
    public static IAction CreateAction(string key)
    {
        IAction action = null;
        if (key.Contains("build"))
        {
            action = new Build();
        }

        return action;
    }
 static IEnumerable LoadDataReaderViaYieldReturn(IDataReader dataReader, IMappingEngineRunner mapper, Build buildFrom, ResolutionContext resolveUsingContext)
 {
     while (dataReader.Read())
     {
         var result = buildFrom(dataReader);
         MapPropertyValues(resolveUsingContext, mapper, result);
         yield return(result);
     }
 }
        /// <summary>
        ///     Append build description to the PR description
        /// </summary>
        /// <param name="update">Update</param>
        /// <param name="deps">Dependencies updated</param>
        /// <param name="committedFiles">List of commited files</param>
        /// <param name="build">Build</param>
        /// <returns>Task</returns>
        /// <remarks>
        ///     Because PRs tend to be live for short periods of time, we can put more information
        ///     in the description than the commit message without worrying that links will go stale.
        /// </remarks>
        public void AppendBuildDescription(UpdateAssetsParameters update, List <DependencyUpdate> deps, List <GitFile> committedFiles, Build build)
        {
            var changesLinks = new List <string>();

            //Find the Coherency section of the PR description
            if (update.IsCoherencyUpdate)
            {
                string sectionStartMarker = $"[marker]: <> (Begin:Coherency Updates)";
                string sectionEndMarker   = $"[marker]: <> (End:Coherency Updates)";
                int    sectionStartIndex  = RemovePRDescriptionSection(sectionStartMarker, sectionEndMarker);

                var coherencySection = new StringBuilder();
                coherencySection.AppendLine(sectionStartMarker);
                coherencySection.AppendLine("## Coherency Updates");
                coherencySection.AppendLine();
                coherencySection.AppendLine("The following updates ensure that dependencies with a *CoherentParentDependency*");
                coherencySection.AppendLine("attribute were produced in a build used as input to the parent dependency's build.");
                coherencySection.AppendLine("See [Dependency Description Format](https://github.com/dotnet/arcade/blob/master/Documentation/DependencyDescriptionFormat.md#dependency-description-overview)");
                coherencySection.AppendLine();
                coherencySection.AppendLine(DependencyUpdateBegin);
                coherencySection.AppendLine();
                coherencySection.AppendLine("- **Coherency Updates**:");
                foreach (DependencyUpdate dep in deps)
                {
                    coherencySection.AppendLine($"  - **{dep.To.Name}**: from {dep.From.Version} to {dep.To.Version} (parent: {dep.To.CoherentParentDependencyName})");
                }
                coherencySection.AppendLine();
                coherencySection.AppendLine(DependencyUpdateEnd);
                coherencySection.AppendLine();
                coherencySection.AppendLine(sectionEndMarker);
                _description.Insert(sectionStartIndex, coherencySection.ToString());
            }
            else
            {
                string sourceRepository     = update.SourceRepo;
                Guid   updateSubscriptionId = update.SubscriptionId;
                string sectionStartMarker   = $"[marker]: <> (Begin:{updateSubscriptionId})";
                string sectionEndMarker     = $"[marker]: <> (End:{updateSubscriptionId})";
                int    sectionStartIndex    = RemovePRDescriptionSection(sectionStartMarker, sectionEndMarker);

                var subscriptionSection = new StringBuilder();
                subscriptionSection.AppendLine(sectionStartMarker);
                subscriptionSection.AppendLine($"## From {sourceRepository}");
                subscriptionSection.AppendLine($"- **Subscription**: {updateSubscriptionId}");
                subscriptionSection.AppendLine($"- **Build**: {build.AzureDevOpsBuildNumber}");
                subscriptionSection.AppendLine($"- **Date Produced**: {build.DateProduced.ToUniversalTime():MMMM d, yyyy h:mm:ss tt UTC}");
                // This is duplicated from the files changed, but is easier to read here.
                subscriptionSection.AppendLine($"- **Commit**: {build.Commit}");
                string branch = build.AzureDevOpsBranch ?? build.GitHubBranch;
                if (!string.IsNullOrEmpty(branch))
                {
                    subscriptionSection.AppendLine($"- **Branch**: {branch}");
                }
                subscriptionSection.AppendLine();
                subscriptionSection.AppendLine(DependencyUpdateBegin);
                subscriptionSection.AppendLine();
                subscriptionSection.AppendLine($"- **Updates**:");

                var shaRangeToLinkId = new Dictionary <(string from, string to), int>();

                foreach (DependencyUpdate dep in deps)
                {
                    if (!shaRangeToLinkId.ContainsKey((dep.From.Commit, dep.To.Commit)))
                    {
                        string changesUri = string.Empty;
                        try
                        {
                            changesUri = GetChangesURI(dep.To.RepoUri, dep.From.Commit, dep.To.Commit);
                        }
                        catch (ArgumentNullException e)
                        {
                            _logger.LogError(e, $"Failed to create SHA comparison link for dependency {dep.To.Name} during asset update for subscription {update.SubscriptionId}");
                        }
                        shaRangeToLinkId.Add((dep.From.Commit, dep.To.Commit), _startingReferenceId + changesLinks.Count);
                        changesLinks.Add(changesUri);
                    }
                    subscriptionSection.AppendLine($"  - **{dep.To.Name}**: [from {dep.From.Version} to {dep.To.Version}][{shaRangeToLinkId[(dep.From.Commit, dep.To.Commit)]}]");
        static IEnumerable LoadDataReaderViaList(IDataReader dataReader, IMappingEngineRunner mapper, Build buildFrom, ResolutionContext resolveUsingContext, Type elementType)
        {
            var list = ObjectCreator.CreateList(elementType);

            while (dataReader.Read())
            {
                var result = buildFrom(dataReader);
                MapPropertyValues(resolveUsingContext, mapper, result);
                list.Add(result);
            }

            return(list);
        }
Beispiel #34
0
        internal static string AppendChangesToDescription(string prDescription, Build oldBuild, List <GitCommit> changes)
        {
            const int hardLimit = 4000; // Azure DevOps limitation

            if (!changes.Any())
            {
                return(prDescription);
            }

            var description = new StringBuilder(prDescription + Environment.NewLine);

            var repoURL = $"//github.com/{oldBuild.Repository.Id}";

            var commitHeaderAdded  = false;
            var mergePRHeaderAdded = false;
            var mergePRFound       = false;

            foreach (var commit in changes)
            {
                // Once we've found a Merge PR we can exclude commits not committed by GitHub since Merge and Squash commits are committed by GitHub
                if (commit.Committer != "GitHub" && mergePRFound)
                {
                    continue;
                }

                // Exclude arcade dependency updates
                if (commit.Author == "dotnet-maestro[bot]")
                {
                    mergePRFound = true;
                    continue;
                }

                // Exclude merge commits from auto code-flow PRs (e.g. merges/master-to-master-vs-deps)
                if (IsReleaseFlowCommit.Match(commit.Message).Success)
                {
                    mergePRFound = true;
                    continue;
                }

                string comment  = string.Empty;
                string prNumber = string.Empty;

                var match = IsMergePRCommit.Match(commit.Message);
                if (match.Success)
                {
                    prNumber = match.Groups[1].Value;

                    // Merge PR Messages are in the form "Merge pull request #39526 from mavasani/GetValueUsageInfoAssert\n\nFix an assert in IOperationExtension.GetValueUsageInfo"
                    // Try and extract the 3rd line since it is the useful part of the message, otherwise take the first line.
                    var lines = commit.Message.Split('\n');
                    comment = lines.Length > 2
                        ? $"{lines[2]} ({prNumber})"
                        : lines[0];
                }
                else
                {
                    match = IsSquashedPRCommit.Match(commit.Message);
                    if (match.Success)
                    {
                        prNumber = match.Groups[1].Value;

                        // Squash PR Messages are in the form "Nullable annotate TypeCompilationState and MessageID (#39449)"
                        // Take the 1st line since it should be descriptive.
                        comment = commit.Message.Split('\n')[0];
                    }
                }

                // We will print commit comments until we find the first merge PR
                if (!match.Success && mergePRFound)
                {
                    continue;
                }

                string prLink;

                if (match.Success)
                {
                    if (commitHeaderAdded && !mergePRHeaderAdded)
                    {
                        mergePRHeaderAdded = true;
                        description.AppendLine("### Merged PRs:");
                    }

                    mergePRFound = true;

                    // Replace "#{prNumber}" with "{prNumber}" so that AzDO won't linkify it
                    comment = comment.Replace($"#{prNumber}", prNumber);

                    prLink = $@"- [{comment}]({GetGitHubPullRequestUrl(repoURL, prNumber)})";
                }
                else
                {
                    if (!commitHeaderAdded)
                    {
                        commitHeaderAdded = true;
                        description.AppendLine("### Commits since last PR:");
                    }

                    var fullSHA  = commit.CommitId;
                    var shortSHA = fullSHA.Substring(0, 7);

                    // Take the 1st line since it should be descriptive.
                    comment = $"{commit.Message.Split('\n')[0]} ({shortSHA})";

                    prLink = $@"- [{comment}]({repoURL}/commit/{fullSHA})";
                }

                const string limitMessage = "Changelog truncated due to description length limit.";

                // we want to be able to fit this PR link, as well as the limit message (plus line breaks) in case the next PR link doesn't fit
                int limit = hardLimit - (prLink.Length + Environment.NewLine.Length) - (limitMessage.Length + Environment.NewLine.Length);
                if (description.Length > limit)
                {
                    description.AppendLine(limitMessage);
                    break;
                }
                else
                {
                    description.AppendLine(prLink);
                }
            }

            var result = description.ToString();

            if (result.Length > hardLimit)
            {
                LogWarning($"PR description is {result.Length} characters long, but the limit is {hardLimit}.");
                LogWarning(result);
            }

            return(result);
        }
        private List <Build> GetSampleGitHubBuilds()
        {
            List <Build> results = new List <Build>();
            Build        item1   = new Build
            {
                StartTime            = DateTime.Now.AddDays(-7).AddMinutes(-12),
                EndTime              = DateTime.Now.AddDays(-7).AddMinutes(0),
                BuildDurationPercent = 70,
                BuildNumber          = "1",
                Branch = "master",
                Status = "completed",
                Url    = "https://GitHub.com/samsmithnz/devopsmetrics/1"
            };

            results.Add(item1);
            Build item2 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-6).AddMinutes(-16),
                EndTime              = DateTime.Now.AddDays(-6).AddMinutes(0),
                BuildDurationPercent = 90,
                BuildNumber          = "2",
                Branch = "master",
                Status = "completed",
                Url    = "https://GitHub.com/samsmithnz/devopsmetrics/2"
            };

            results.Add(item2);
            results.Add(item2);
            Build item3 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-4).AddMinutes(-9),
                EndTime              = DateTime.Now.AddDays(-4).AddMinutes(0),
                BuildDurationPercent = 40,
                BuildNumber          = "3",
                Branch = "master",
                Status = "failed",
                Url    = "https://GitHub.com/samsmithnz/devopsmetrics/3"
            };

            results.Add(item3);
            Build item4 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-3).AddMinutes(-10),
                EndTime              = DateTime.Now.AddDays(-3).AddMinutes(0),
                BuildDurationPercent = 45,
                BuildNumber          = "4",
                Branch = "master",
                Status = "completed",
                Url    = "https://GitHub.com/samsmithnz/devopsmetrics/4"
            };

            results.Add(item4);
            results.Add(item4);
            Build item5 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-2).AddMinutes(-11),
                EndTime              = DateTime.Now.AddDays(-2).AddMinutes(0),
                BuildDurationPercent = 50,
                BuildNumber          = "5",
                Branch = "master",
                Status = "failed",
                Url    = "https://GitHub.com/samsmithnz/devopsmetrics/5"
            };

            results.Add(item5);
            results.Add(item5);
            Build item6 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-1).AddMinutes(-8),
                EndTime              = DateTime.Now.AddDays(-1).AddMinutes(0),
                BuildDurationPercent = 20,
                BuildNumber          = "6",
                Branch = "master",
                Status = "completed",
                Url    = "https://GitHub.com/samsmithnz/devopsmetrics/6"
            };

            results.Add(item6);
            results.Add(item6);

            return(results);
        }
Beispiel #36
0
        public async Task <ActionResult> AddBuild(Build build)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    build.Added    = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
                    build.Modified = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
                    if (build.BuildTime.HasValue)
                    {
                        build.BuildTime = DateTime.SpecifyKind(build.BuildTime.Value, DateTimeKind.Utc);
                    }

                    if (build.LeakDate.HasValue)
                    {
                        build.LeakDate = DateTime.SpecifyKind(build.LeakDate.Value, DateTimeKind.Utc);
                    }

                    build.RegenerateCachedProperties();


                    BuildDetails bi = new BuildDetails
                    {
                        MajorVersion = build.MajorVersion,
                        MinorVersion = build.MinorVersion,
                        Number       = build.Number,
                        Revision     = build.Revision,
                        Lab          = build.Lab,
                        BuildTime    = build.BuildTime.HasValue
                            ? DateTime.SpecifyKind(build.BuildTime.Value, DateTimeKind.Utc)
                            : null as DateTime?,
                        SourceType    = build.SourceType,
                        SourceDetails = build.SourceDetails
                    };

                    build.History = new List <ItemHistory <BuildDetails> >
                    {
                        new ItemHistory <BuildDetails>
                        {
                            Type     = ItemHistoryType.Added,
                            Time     = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc),
                            UserName = User.Identity.Name,
                            Item     = bi
                        }
                    };

                    await _bModel.Insert(build);
                }
                catch
                {
                    return(View("EditBuild", build));
                }

                OneSignalClient osc = new OneSignalClient(ConfigurationManager.AppSettings["push:OneSignalApiKey"]);
                osc.PushNewBuild(build, $"https://buildfeed.net{Url.Action(nameof(ViewBuild), new { id = build.Id })}?utm_source=notification&utm_campaign=new_build");

                return(RedirectToAction(nameof(ViewBuild),
                                        new
                {
                    id = build.Id
                }));
            }
            return(View("EditBuild", build));
        }
Beispiel #37
0
        public void CanGetVersion()
        {
            var build = new Build(new TeamCity.Api.Models.Build());

            build.Version.ShouldBeNull();
        }
Beispiel #38
0
 protected void ButtonSearch_Click(object sender, EventArgs e)
 {
     GridViewResult.DataSource = Build.GetBuildListByFilter("%" + TextBoxSearch.Text + "%");
     GridViewResult.DataBind();
 }
Beispiel #39
0
 private void Awake()
 {
     build     = FindObjectOfType <Build>();
     resources = FindObjectOfType <Resources>();
 }
        public void StartExecutePlugins(Build build)
        {
            ParameterizedThreadStart threadStart = ExecAsync;

            threadStart.BeginInvoke(build, null, null);
        }
Beispiel #41
0
        public override void Execute()
        {
            if (!PreExecutionChecks(false, true, false, false))
            {
                return;
            }
            Build       build       = new Build(Build.DEFAULT_BUILD_PATH);
            BuildTarget buildTarget = BuildTargetFactory.Construct(BuildTargetFactory.QFName, build);
            bool        preprocessed;
            Dictionary <int, List <int> > originalStageMap = StageMapFromMAPBuilder.BuildStageMapDictionary(buildTarget, "QF_FGC01Rats_01035713", out preprocessed);
            StageMap      stageMap = new StageMap(originalStageMap.ToDictionary(m => m.Key, m => m.Value.ToList()), preprocessed);//Copy dictionary
            StringBuilder output   = new StringBuilder(StageMapToMAPBuilder.GetContents(stageMap, originalStageMap));

            output.Append("Mapping index print");
            foreach (var kvp in stageMap.MappedTargetsIndex)
            {
                var originalTargetIndex = kvp.Key;
                var mappedTargetIndexes = kvp.Value;
                output.AppendLine();
                output.Append(originalTargetIndex + " - " + string.Join(" ", mappedTargetIndexes));
            }

            string outputString = output.ToString();

            Console.WriteLine(outputString);
            const string fgc01RatsResultFromPHP =
                @"10 - 0 0 0 1
10 - 0 0 0 1 0 0 0 0 0 0
20 - 1 0 0 0
20 - 1 0 0 0 0 0 0 0 0 0
30 - 0 0 0 1
30 - 0 0 0 0 1 0 0 0 0 0
40 - 0 0 1 0
40 - 0 0 1 0 0 0 0 0 0 0
50 - 0 0 1 0
50 - 0 0 1 0 0 0 0 0 0 0
55 - 0 0 0 1
55 - 0 0 0 0 0 1 0 0 0 0
60 - 1 0 0 0
60 - 0 0 0 0 0 0 1 0 0 0
65 - 0 0 0 1
65 - 0 0 0 0 0 0 0 1 0 0
70 - 0 1 0 0
70 - 0 1 0 0 0 0 0 0 0 0
80 - 0 1 0 0
80 - 0 1 0 0 0 0 0 0 0 0
90 - 0 0 0 1
90 - 0 0 0 0 0 0 0 0 1 0
100 - 0 0 0 0
100 - 0 0 0 0 0 0 0 0 0 0
105 - 0 1 0 0
105 - 0 0 0 0 0 0 0 0 0 1
110 - 0 0 0 0
110 - 0 0 0 0 0 0 0 0 0 0
200 - 0 0 0 0
200 - 0 0 0 0 0 0 0 0 0 0
Mapping index print
3 - 4 5 7 8
0 - 6
1 - 9";
            bool match = fgc01RatsResultFromPHP.Replace("\r\n", "\n") == outputString.Replace("\r\n", "\n");

            Console.WriteLine("Output " + (match ? "matched" : "did not match") + " the output of the PHP version.");
        }
Beispiel #42
0
        /// <summary>
        /// Update local dependencies based on a specific channel.
        /// </summary>
        /// <param name="options">Command line options</param>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                DarcSettings darcSettings = darcSettings = LocalSettings.GetDarcSettings(_options, Logger);

                // TODO: PAT only used for pulling the Arcade eng/common dir,
                // so hardcoded to GitHub PAT right now. Must be more generic in the future.
                darcSettings.GitType = GitRepoType.GitHub;
                LocalSettings localSettings = LocalSettings.LoadSettingsFile(_options);

                darcSettings.GitRepoPersonalAccessToken = localSettings != null && !string.IsNullOrEmpty(localSettings.GitHubToken) ?
                                                          localSettings.GitHubToken :
                                                          _options.GitHubPat;

                IRemoteFactory remoteFactory = new RemoteFactory(_options);
                IRemote        barOnlyRemote = await remoteFactory.GetBarOnlyRemoteAsync(Logger);

                Local local = new Local(Logger);
                List <DependencyDetail> dependenciesToUpdate = new List <DependencyDetail>();
                bool   someUpToDate = false;
                string finalMessage = $"Local dependencies updated from channel '{_options.Channel}'.";

                // First we need to figure out what to query for. Load Version.Details.xml and
                // find all repository uris, optionally restricted by the input dependency parameter.
                IEnumerable <DependencyDetail> localDependencies = await local.GetDependenciesAsync(_options.Name, false);

                // If the source repository was specified, filter away any local dependencies not from that
                // source repository.
                if (!string.IsNullOrEmpty(_options.SourceRepository))
                {
                    localDependencies = localDependencies.Where(
                        dependency => dependency.RepoUri.Contains(_options.SourceRepository, StringComparison.OrdinalIgnoreCase));
                }

                if (!localDependencies.Any())
                {
                    Console.WriteLine("Found no dependencies to update.");
                    return(Constants.ErrorCode);
                }

                List <DependencyDetail> currentDependencies = localDependencies.ToList();

                if (!string.IsNullOrEmpty(_options.Name) && !string.IsNullOrEmpty(_options.Version))
                {
                    DependencyDetail dependency = currentDependencies.First();
                    dependency.Version = _options.Version;
                    dependenciesToUpdate.Add(dependency);

                    Console.WriteLine($"Updating '{dependency.Name}': '{dependency.Version}' => '{_options.Version}'");

                    finalMessage = $"Local dependency {_options.Name} updated to version '{_options.Version}'.";
                }
                else if (!string.IsNullOrEmpty(_options.PackagesFolder))
                {
                    try
                    {
                        dependenciesToUpdate.AddRange(GetDependenciesFromPackagesFolder(_options.PackagesFolder, currentDependencies));
                    }
                    catch (DarcException exc)
                    {
                        Logger.LogError(exc, $"Error: Failed to update dependencies based on folder '{_options.PackagesFolder}'");
                        return(Constants.ErrorCode);
                    }

                    finalMessage = $"Local dependencies updated based on packages folder {_options.PackagesFolder}.";
                }
                else if (_options.BARBuildId > 0)
                {
                    try
                    {
                        if (!_options.CoherencyOnly)
                        {
                            Console.WriteLine($"Looking up build with BAR id {_options.BARBuildId}");
                            var specificBuild = await barOnlyRemote.GetBuildAsync(_options.BARBuildId);

                            int nonCoherencyResult = await NonCoherencyUpdatesForBuildAsync(specificBuild, barOnlyRemote, currentDependencies, dependenciesToUpdate)
                                                     .ConfigureAwait(false);

                            if (nonCoherencyResult != Constants.SuccessCode)
                            {
                                Console.WriteLine("Error: Failed to update non-coherent parent tied dependencies.");
                                return(nonCoherencyResult);
                            }

                            string sourceRepo   = specificBuild.GitHubRepository ?? specificBuild.AzureDevOpsRepository;
                            string sourceBranch = specificBuild.GitHubBranch ?? specificBuild.AzureDevOpsBranch;

                            finalMessage = $"Local dependencies updated based on build with BAR id {_options.BARBuildId} " +
                                           $"({specificBuild.AzureDevOpsBuildNumber} from {sourceRepo}@{sourceBranch})";
                        }

                        int coherencyResult = await CoherencyUpdatesAsync(barOnlyRemote, remoteFactory, currentDependencies, dependenciesToUpdate)
                                              .ConfigureAwait(false);

                        if (coherencyResult != Constants.SuccessCode)
                        {
                            Console.WriteLine("Error: Failed to update coherent parent tied dependencies.");
                            return(coherencyResult);
                        }

                        finalMessage = string.IsNullOrEmpty(finalMessage) ? "Local dependencies successfully updated." : finalMessage;
                    }
                    catch (RestApiException e) when(e.Response.Status == 404)
                    {
                        Console.WriteLine($"Could not find build with BAR id '{_options.BARBuildId}'.");
                        return(Constants.ErrorCode);
                    }
                }
                else
                {
                    if (!_options.CoherencyOnly)
                    {
                        if (string.IsNullOrEmpty(_options.Channel))
                        {
                            Console.WriteLine($"Please supply either a channel name (--channel), a packages folder (--packages-folder) " +
                                              "a BAR build id (--id), or a specific dependency name and version (--name and --version).");
                            return(Constants.ErrorCode);
                        }

                        // Start channel query.
                        Task <Channel> channel = barOnlyRemote.GetChannelAsync(_options.Channel);

                        // Limit the number of BAR queries by grabbing the repo URIs and making a hash set.
                        // We gather the latest build for any dependencies that aren't marked with coherent parent
                        // dependencies, as those will be updated based on additional queries.
                        HashSet <string> repositoryUrisForQuery = currentDependencies
                                                                  .Where(dependency => string.IsNullOrEmpty(dependency.CoherentParentDependencyName))
                                                                  .Select(dependency => dependency.RepoUri)
                                                                  .ToHashSet();

                        ConcurrentDictionary <string, Task <Build> > getLatestBuildTaskDictionary = new ConcurrentDictionary <string, Task <Build> >();

                        Channel channelInfo = await channel;
                        if (channelInfo == null)
                        {
                            Console.WriteLine($"Could not find a channel named '{_options.Channel}'.");
                            return(Constants.ErrorCode);
                        }

                        foreach (string repoToQuery in repositoryUrisForQuery)
                        {
                            Console.WriteLine($"Looking up latest build of {repoToQuery} on {_options.Channel}");
                            var latestBuild = barOnlyRemote.GetLatestBuildAsync(repoToQuery, channelInfo.Id);
                            getLatestBuildTaskDictionary.TryAdd(repoToQuery, latestBuild);
                        }

                        // For each build, first go through and determine the required updates,
                        // updating the "live" dependency information as we go.
                        // Then run a second pass where we update any assets based on coherency information.
                        foreach (KeyValuePair <string, Task <Build> > buildKvPair in getLatestBuildTaskDictionary)
                        {
                            string repoUri = buildKvPair.Key;
                            Build  build   = await buildKvPair.Value;

                            if (build == null)
                            {
                                Logger.LogTrace($"No build of '{repoUri}' found on channel '{_options.Channel}'.");
                                continue;
                            }

                            int nonCoherencyResult = await NonCoherencyUpdatesForBuildAsync(build, barOnlyRemote, currentDependencies, dependenciesToUpdate)
                                                     .ConfigureAwait(false);

                            if (nonCoherencyResult != Constants.SuccessCode)
                            {
                                Console.WriteLine("Error: Failed to update non-coherent parent tied dependencies.");
                                return(nonCoherencyResult);
                            }
                        }
                    }

                    int coherencyResult = await CoherencyUpdatesAsync(barOnlyRemote, remoteFactory, currentDependencies, dependenciesToUpdate)
                                          .ConfigureAwait(false);

                    if (coherencyResult != Constants.SuccessCode)
                    {
                        Console.WriteLine("Error: Failed to update coherent parent tied dependencies.");
                        return(coherencyResult);
                    }
                }

                if (!dependenciesToUpdate.Any())
                {
                    // If we found some dependencies already up to date,
                    // then we consider this a success. Otherwise, we didn't even
                    // find matching dependencies so we should let the user know.
                    if (someUpToDate)
                    {
                        Console.WriteLine($"All dependencies are up to date.");
                        return(Constants.SuccessCode);
                    }
                    else
                    {
                        Console.WriteLine($"Found no dependencies to update.");
                        return(Constants.ErrorCode);
                    }
                }

                if (_options.DryRun)
                {
                    return(Constants.SuccessCode);
                }

                // Now call the local updater to run the update.
                await local.UpdateDependenciesAsync(dependenciesToUpdate, remoteFactory);

                Console.WriteLine(finalMessage);

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to update dependencies.");
                return(Constants.ErrorCode);
            }
        }
 public override string ToString()
 {
     return(Major.ToString() + '.' + Minor.ToString() + '.' + Build.ToString() + '.' + Revision.ToString());
 }
Beispiel #44
0
        /// <summary>
        /// Solves the matrix equation AX = B, where A is the coefficient matrix (this matrix), B is the solution matrix and X is the unknown matrix.
        /// </summary>
        /// <param name="input">The solution matrix <c>B</c>.</param>
        /// <param name="result">The result matrix <c>X</c></param>
        /// <param name="solver">The iterative solver to use.</param>
        /// <param name="stopCriteria">Criteria to control when to stop iterating.</param>
        public IterationStatus TrySolveIterative(Matrix <T> input, Matrix <T> result, IIterativeSolver <T> solver, params IIterationStopCriterion <T>[] stopCriteria)
        {
            var iterator = new Iterator <T>(stopCriteria.Length == 0 ? Build.IterativeSolverStopCriteria() : stopCriteria);

            return(TrySolveIterative(input, result, solver, iterator));
        }
        public BuildControl(Build build, string logFilePath)
        {
            DataContext = build;

            InitializeComponent();

            UpdateWatermark();

            searchLogControl.ExecuteSearch = (searchText, maxResults, cancellationToken) =>
            {
                var search  = new Search(new[] { Build }, Build.StringTable.Instances, maxResults, SettingsService.MarkResultsInTree);
                var results = search.FindNodes(searchText, cancellationToken);
                return(results);
            };
            searchLogControl.ResultsTreeBuilder  = BuildResultTree;
            searchLogControl.WatermarkDisplayed += () =>
            {
                Search.ClearSearchResults(Build);
                UpdateWatermark();
            };

            findInFilesControl.ExecuteSearch      = FindInFiles;
            findInFilesControl.ResultsTreeBuilder = BuildFindResults;

            Build = build;

            LogFilePath = logFilePath;

            if (build.SourceFilesArchive != null)
            {
                // first try to see if the source archive was embedded in the log
                sourceFileResolver = new SourceFileResolver(build.SourceFiles.Values);
            }
            else
            {
                // otherwise try to read from the .zip file on disk if present
                sourceFileResolver = new SourceFileResolver(logFilePath);
            }

            sharedTreeContextMenu = new ContextMenu();
            copyAllItem           = new MenuItem()
            {
                Header = "Copy All"
            };
            copyAllItem.Click += (s, a) => CopyAll();
            sharedTreeContextMenu.AddItem(copyAllItem);

            var contextMenu = new ContextMenu();

            // TODO
            //contextMenu.Opened += ContextMenu_Opened;
            copyItem = new MenuItem()
            {
                Header = "Copy"
            };
            copySubtreeItem = new MenuItem()
            {
                Header = "Copy subtree"
            };
            sortChildrenItem = new MenuItem()
            {
                Header = "Sort children"
            };
            copyNameItem = new MenuItem()
            {
                Header = "Copy name"
            };
            copyValueItem = new MenuItem()
            {
                Header = "Copy value"
            };
            viewItem = new MenuItem()
            {
                Header = "View"
            };
            preprocessItem = new MenuItem()
            {
                Header = "Preprocess"
            };
            hideItem = new MenuItem()
            {
                Header = "Hide"
            };
            copyItem.Click         += (s, a) => Copy();
            copySubtreeItem.Click  += (s, a) => CopySubtree();
            sortChildrenItem.Click += (s, a) => SortChildren();
            copyNameItem.Click     += (s, a) => CopyName();
            copyValueItem.Click    += (s, a) => CopyValue();
            viewItem.Click         += (s, a) => Invoke(treeView.SelectedItem as BaseNode);
            preprocessItem.Click   += (s, a) => Preprocess(treeView.SelectedItem as IPreprocessable);
            hideItem.Click         += (s, a) => Delete();
            contextMenu.AddItem(viewItem);
            contextMenu.AddItem(preprocessItem);
            contextMenu.AddItem(copyItem);
            contextMenu.AddItem(copySubtreeItem);
            contextMenu.AddItem(sortChildrenItem);
            contextMenu.AddItem(copyNameItem);
            contextMenu.AddItem(copyValueItem);
            contextMenu.AddItem(hideItem);

            var treeViewItemStyle = new Style(s => s.OfType <TreeViewItem>())
            {
                Setters = new ISetter[]
                {
                    new Setter(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded")
                    {
                        Mode = BindingMode.TwoWay
                    }),
                    new Setter(TreeViewItem.IsSelectedProperty, new Binding("IsSelected")
                    {
                        Mode = BindingMode.TwoWay
                    }),
                    new Setter(IsVisibleProperty, new Binding("IsVisible")
                    {
                        Mode = BindingMode.TwoWay
                    })
                }
            };

            treeView.ContextMenu = contextMenu;
            treeView.Styles.Add(treeViewItemStyle);
            RegisterTreeViewHandlers(treeView);
            treeView.KeyDown         += TreeView_KeyDown;
            treeView.PropertyChanged += TreeView_SelectedItemChanged;
            treeView.GotFocus        += (s, a) => ActiveTreeView = treeView;

            ActiveTreeView = treeView;

            searchLogControl.ResultsList.Styles.Add(treeViewItemStyle);
            RegisterTreeViewHandlers(searchLogControl.ResultsList);
            searchLogControl.ResultsList.SelectionChanged += ResultsList_SelectionChanged;
            searchLogControl.ResultsList.GotFocus         += (s, a) => ActiveTreeView = searchLogControl.ResultsList;
            searchLogControl.ResultsList.ContextMenu       = sharedTreeContextMenu;

            findInFilesControl.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList;
            findInFilesControl.ResultsList.Styles.Add(treeViewItemStyle);
            RegisterTreeViewHandlers(findInFilesControl.ResultsList);
            findInFilesControl.ResultsList.GotFocus   += (s, a) => ActiveTreeView = findInFilesControl.ResultsList;
            findInFilesControl.ResultsList.ContextMenu = sharedTreeContextMenu;

            if (archiveFile != null)
            {
                filesTab.IsVisible       = true;
                findInFilesTab.IsVisible = true;
                PopulateFilesTab();
                filesTree.Styles.Add(treeViewItemStyle);
                RegisterTreeViewHandlers(filesTree);

                var text =
                    @"This log contains the full text of projects and imported files used during the build.
You can use the 'Files' tab in the bottom left to view these files and the 'Find in Files' tab for full-text search.
For many nodes in the tree (Targets, Tasks, Errors, Projects, etc) pressing SPACE or ENTER or double-clicking 
on the node will navigate to the corresponding source code associated with the node.

More functionality is available from the right-click context menu for each node.
Right-clicking a project node may show the 'Preprocess' option if the version of MSBuild was at least 15.3.";
                build.Unseal();
                build.AddChild(new Note {
                    Text = text
                });
                build.Seal();
            }

            breadCrumb.SelectionChanged += BreadCrumb_SelectionChanged;

            TemplateApplied += BuildControl_Loaded;

            preprocessedFileManager              = new PreprocessedFileManager(Build, sourceFileResolver);
            preprocessedFileManager.DisplayFile += path => DisplayFile(path);

            //PopulateTimeline();
        }
Beispiel #46
0
        static void Main(string[] args)
        {
            var APP_SETTINGS_PATH = "appsettings.json";
            var SMARTCODE_KEY     = "SmartCode";
            var AppDirectory      = AppDomain.CurrentDomain.BaseDirectory;

            Task.Factory.StartNew(async() =>
            {
                try
                {
                    #region Reader Config
                    var appSettingsbuilder = new ConfigurationBuilder()
                                             .SetBasePath(AppDirectory)
                                             .AddJsonFile(APP_SETTINGS_PATH, false, true);
                    var configuration    = appSettingsbuilder.Build();
                    var smartCodeOptions = configuration.GetSection(SMARTCODE_KEY).Get <SmartCodeOptions>();
                    #endregion

                    #region Auto Inject
                    var services = smartCodeOptions.Services;
                    services.AddSingleton(smartCodeOptions);
                    services.AddSingleton <IPluginManager, PluginManager>();
                    services.AddSingleton <IProjectBuilder, ProjectBuilder>();
                    services.AddLogging();
                    #endregion

                    #region Add Plugs
                    foreach (var plugin in smartCodeOptions.Plugins)
                    {
                        var pluginType = Assembly.Load(plugin.AssemblyName).GetType(plugin.TypeName);
                        if (pluginType == null)
                        {
                            throw new SmartCodeException($"Plugin.Type:{plugin.TypeName} can not find!");
                        }
                        var implType = Assembly.Load(plugin.ImplAssemblyName).GetType(plugin.ImplTypeName);
                        if (implType == null)
                        {
                            throw new SmartCodeException($"Plugin.ImplType:{plugin.ImplTypeName} can not find!");
                        }
                        if (!pluginType.IsAssignableFrom(implType))
                        {
                            throw new SmartCodeException($"Plugin.ImplType:{implType.FullName} can not Impl Plugin.Type:{pluginType.FullName}!");
                        }
                        services.AddSingleton(pluginType, implType);
                    }
                    #endregion

                    #region Project
                    var project = new Project()
                    {
                        DataSource = new DataSource
                        {
                            Name = "Sample"
                        },
                        Output = new Output()
                        {
                            Type = "File",
                            Path = "I:\\Builder"
                        },
                        BuildTasks  = new Dictionary <string, Build>(),
                        TableFilter = new TableFilter(),
                    };

                    var clearDir = new Build
                    {
                        Type       = "Clear",
                        Parameters = new Dictionary <String, object>()
                        {
                            { "Dirs", "." }
                        }
                    };
                    var entity = new Build
                    {
                        Type           = "Sample",
                        Module         = "entity",
                        Output         = new Output(),
                        TemplateEngine = new TemplateEngine()
                    };

                    entity.Output.Path      = "{{Project.Module}}.{{Build.Module}}";
                    entity.Output.Name      = "{{Items.CurrentTable.ConvertedName}}";
                    entity.Output.Extension = ".java";

                    entity.TemplateEngine.Root = "Java";
                    entity.TemplateEngine.Name = "Razor";
                    entity.TemplateEngine.Path = "Entity.cshtml";

                    project.BuildTasks.Add("ClearDir", clearDir);
                    project.BuildTasks.Add("Entity", entity);
                    services.AddSingleton(project);
                    #endregion

                    #region Build Project
                    var serviceProvider = services.BuildServiceProvider();
                    var projectBuilder  = serviceProvider.GetRequiredService <IProjectBuilder>();

                    await projectBuilder.Build();
                    #endregion
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
            Console.WriteLine("来源隔壁老萌的新手大礼包");
            Console.ReadLine();
        }
Beispiel #47
0
 public override int GetHashCode() =>
 (Major.GetHashCode() * 13) +
 (Minor.GetHashCode() * 13) +
 (Build.GetHashCode() * 13) +
 Name.GetHashCode();
Beispiel #48
0
        private static async Task ProcessLatestBuildAsync(TraceWriter log, Logger logger, Build latestBuild, string branch, int apiVersion)
        {
            await latestBuild.PopulateTimeLine(logger);

            var validations = latestBuild.TimelineRecords
                              .Where(r => r.Name == VALIDATE_VSIX || r.Name == VALIDATE_REPO);

            switch (apiVersion)
            {
            default:
            case 1:
                log.Info($"Processing {validations.Count()} validation records for branch {branch} wtih API version {apiVersion} using ProcessValidationRecordsV1");
                await ProcessValidationRecordsV1(log, logger, validations);

                break;

            case 2:
                log.Info($"Processing {validations.Count()} validation records for branch {branch} wtih API version {apiVersion} using ProcessValidationRecordsV2");
                await ProcessValidationRecordsV2(log, logger, validations);

                break;
            }
        }
Beispiel #49
0
        public async Task <ActionResult> TwitterCard(Guid id)
        {
            Build b = await _bModel.SelectById(id);

            if (b == null)
            {
                return(new HttpNotFoundResult());
            }

            string path       = Path.Combine(Server.MapPath("~/res/card/"), $"{b.Family}.png");
            bool   backExists = System.IO.File.Exists(path);

            using (Bitmap bm = backExists
                ? new Bitmap(path)
                : new Bitmap(1120, 600))
            {
                using (Graphics gr = Graphics.FromImage(bm))
                {
                    gr.CompositingMode    = CompositingMode.SourceOver;
                    gr.CompositingQuality = CompositingQuality.HighQuality;
                    gr.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    gr.TextRenderingHint  = TextRenderingHint.ClearTypeGridFit;
                    gr.SmoothingMode      = SmoothingMode.HighQuality;
                    gr.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                    if (!backExists)
                    {
                        gr.FillRectangle(new SolidBrush(Color.FromArgb(0x24, 0x24, 0x23)), 0, 0, 1120, 600);
                    }

                    int left = 40;
                    using (GraphicsPath gp = new GraphicsPath())
                    {
                        foreach (char c in "BUILDFEED")
                        {
                            gp.AddString(c.ToString(), new FontFamily("Segoe UI Semibold"), 0, 32, new Point(left, 32), StringFormat.GenericTypographic);

                            RectangleF bounds = gp.GetBounds();
                            left  = Convert.ToInt32(bounds.Width);
                            left += 52;
                        }

                        gr.FillPath(Brushes.White, gp);
                    }

                    using (GraphicsPath gp = new GraphicsPath())
                    {
                        gp.AddString(b.Number.ToString(), new FontFamily("Segoe UI Light"), 0, 260, new Point(32, 114), StringFormat.GenericTypographic);

                        RectangleF bounds = gp.GetBounds();
                        left  = Convert.ToInt32(bounds.Width);
                        left += 44;

                        if (b.Revision.HasValue)
                        {
                            gp.AddString($".{b.Revision}", new FontFamily("Segoe UI Light"), 0, 160, new Point(left, 220), StringFormat.GenericTypographic);
                        }

                        gr.DrawPath(new Pen(new SolidBrush(Color.FromArgb(0x24, 0x24, 0x23)), 4), gp);
                        gr.FillPath(Brushes.White, gp);
                    }

                    using (GraphicsPath gp = new GraphicsPath())
                    {
                        gp.AddString($"{MvcExtensions.GetDisplayTextForEnum(b.Family)} (NT {b.MajorVersion}.{b.MinorVersion})", new FontFamily("Segoe UI Light"), 0, 48, new Point(40, 80), StringFormat.GenericTypographic);

                        gp.AddString(char.ConvertFromUtf32(0xf126), new FontFamily("FontAwesome"), 0, 28, new Point(46, 468), StringFormat.GenericTypographic);
                        gp.AddString(b.Lab, new FontFamily("Segoe UI Light"), 0, 40, new Point(88, 450), StringFormat.GenericTypographic);

                        if (b.BuildTime.HasValue)
                        {
                            gp.AddString(char.ConvertFromUtf32(0xf017), new FontFamily("FontAwesome"), 0, 28, new Point(40, 538), StringFormat.GenericTypographic);
                            gp.AddString($"{b.BuildTime.Value.ToShortTimeString()} on {b.BuildTime.Value.ToLongDateString()}", new FontFamily("Segoe UI Light"), 0, 40, new Point(88, 520), StringFormat.GenericTypographic);
                        }

                        gr.FillPath(Brushes.White, gp);
                    }

                    Response.ContentType = "image/png";
                    bm.Save(Response.OutputStream, ImageFormat.Png);
                }
            }

            return(new EmptyResult());
        }
        private void BuildProjectAndroid(Build builder, string projectDirName, string externalSourceDir, string targetName, string additionalOptions = "")
        {
            var    projectName  = Path.GetFileName(projectDirName);
            string cmakeHomeDir = Path.Combine(externalSourceDir, projectDirName);//builder.LuminoRootDir;
            string platform     = AndoridBuildEnv.AndroidTargetPlatform;
            var    installDir   = builder.GetExternalProjectInstallDir(targetName, projectName);

            foreach (var config in new string[] { /*"Debug",*/ "Release" })
            {
                //var targetName = $"Android-{abi}-{buildType}";
                var buildDir = Path.Combine(builder.GetExternalProjectBuildDir(targetName, projectName), config);

                var args = new string[]
                {
                    // Basic options https://developer.android.com/ndk/guides/cmake.html
                    $"-H{cmakeHomeDir}",
                    $"-B{buildDir}",
                    //$"-G\"Android Gradle - Ninja\"",
                    $"-G\"Ninja\"",
                    $"-DANDROID_ABI={AndoridBuildEnv.GetABIFromTargetName(targetName)}",
                    $"-DANDROID_NDK={AndoridBuildEnv.AndroidNdkRootDir}",
                    $"-DCMAKE_BUILD_TYPE={config}",
                    $"-DCMAKE_MAKE_PROGRAM={AndoridBuildEnv.AndroidSdkNinja}",
                    $"-DCMAKE_TOOLCHAIN_FILE={AndoridBuildEnv.AndroidCMakeToolchain}",
                    $"-DANDROID_TOOLCHAIN=clang",

                    // Lumino required
                    $"-DCMAKE_INSTALL_PREFIX={installDir}",
                    $"-DCMAKE_DEBUG_POSTFIX=d",
                    $"-DANDROID_PLATFORM={platform}",
                    $"-DANDROID_STL=c++_shared",
                    $"-DANDROID_NATIVE_API_LEVEL=26",
                    $"-DLN_TARGET_ARCH={targetName}",
                    additionalOptions,
                };
#if false
                var args = new string[]
                {
                    $"-H{cmakeHomeDir}",
                    $"-B{buildDir}",
                    $"-DLN_TARGET_ARCH={targetName}",
                    $"-DCMAKE_INSTALL_PREFIX={installDir}",
                    $"-DCMAKE_DEBUG_POSTFIX=d",
                    $"-DANDROID_ABI={AndoridBuildEnv.GetABIFromTargetName(targetName)}",
                    $"-DANDROID_PLATFORM={platform}",
                    $"-DCMAKE_BUILD_TYPE={config}",
                    $"-DANDROID_NDK={AndoridBuildEnv.AndroidNdkRootDir}",
                    //$"-DCMAKE_CXX_FLAGS=-std=c++14",
                    $"-DANDROID_STL=c++_shared",
                    $"-DCMAKE_TOOLCHAIN_FILE={AndoridBuildEnv.AndroidCMakeToolchain}",
                    //$"-DCMAKE_MAKE_PROGRAM={AndoridBuildEnv.AndroidSdkNinja}",
                    $"-DANDROID_NATIVE_API_LEVEL=26",
                    additionalOptions,
                    //$"-G\"Android Gradle - Ninja\"",
                    $"-G\"Unix Makefile\"",
                };
#endif

                Utils.CallProcess(AndoridBuildEnv.AndroidSdkCMake, string.Join(' ', args));
                Utils.CallProcess(AndoridBuildEnv.AndroidSdkCMake, $"--build {buildDir} ");
                Utils.CallProcess(AndoridBuildEnv.AndroidSdkCMake, $"--build {buildDir} --target install");
            }
        }
Beispiel #51
0
        internal static async Task <(List <GitCommit> changes, string diffLink)> GetChangesBetweenBuildsAsync(Build fromBuild, Build tobuild, CancellationToken cancellationToken)
        {
            if (tobuild.Repository.Type == "GitHub")
            {
                var repoId = tobuild.Repository.Id; // e.g. dotnet/roslyn

                var fromSHA = fromBuild.SourceVersion;
                var toSHA   = tobuild.SourceVersion;

                var restEndpoint = $"https://api.github.com/repos/{repoId}/compare/{fromSHA}...{toSHA}";
                var client       = new HttpClient();
                var request      = new HttpRequestMessage(HttpMethod.Get, restEndpoint);
                request.Headers.Add("User-Agent", "RoslynInsertionTool");

                var response = await client.SendAsync(request);

                var content = await response.Content.ReadAsStringAsync();

                // https://developer.github.com/v3/repos/commits/
                var data = JsonConvert.DeserializeAnonymousType(content, new
                {
                    commits = new[]
                    {
                        new
                        {
                            sha    = "",
                            commit = new
                            {
                                author = new
                                {
                                    name  = "",
                                    email = "",
                                    date  = ""
                                },
                                committer = new
                                {
                                    name = ""
                                },
                                message = ""
                            },
                            html_url = ""
                        }
                    }
                });

                var result = data.commits
                             .Select(d =>
                                     new GitCommit()
                {
                    Author     = d.commit.author.name,
                    Committer  = d.commit.committer.name,
                    CommitDate = DateTime.Parse(d.commit.author.date),
                    Message    = d.commit.message,
                    CommitId   = d.sha,
                    RemoteUrl  = d.html_url
                })
                             // show HEAD first, base last
                             .Reverse()
                             .ToList();

                return(result, $"//github.com/{repoId}/compare/{fromSHA}...{toSHA}?w=1");
            }

            throw new NotSupportedException("Only builds created from GitHub repos support enumerating commits.");
        }
        public override void Build(Build builder)
        {
            if (builder.ExistsCache(builder.GetExternalInstallDir(BuildEnvironment.Target)))
            {
                Logger.WriteLine("BuildExternalProjects has cache.");
                return;
            }

            var reposDir = Path.Combine(builder.BuildDir, "ExternalSource");

            Directory.CreateDirectory(reposDir);
            Directory.SetCurrentDirectory(reposDir);

            if (!Directory.Exists("ios-cmake"))
            {
                Utils.CallProcess("git", "clone --depth 1 -b 3.0.1 https://github.com/leetal/ios-cmake.git ios-cmake");
            }
            if (!Directory.Exists("SDL2"))
            {
                var zip = Path.Combine(reposDir, "SDL2-2.0.12.zip");
                using (var wc = new System.Net.WebClient())
                {
                    wc.DownloadFile("https://www.libsdl.org/release/SDL2-2.0.12.zip", zip);
                }

                Utils.ExtractZipFile(zip, Path.Combine(reposDir, "SDL2-2.0.12"));
                var dst = Path.Combine(reposDir, "SDL2-2.0.12", "SDL2-2.0.12");
                Utils.CopyDirectory(dst, Path.Combine(reposDir, "SDL2"));

                //System.Threading.Thread.Sleep(1000);
                //var dst = Path.Combine(reposDir, "SDL2-2.0.12", "SDL2-2.0.12");
                //var dir = new DirectoryInfo(dst);
                //dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
                //Directory.Move(dst, Path.Combine(reposDir, "SDL2"));
            }
            if (!Directory.Exists("tmxlite"))
            {
                Utils.CallProcess("git", "clone https://github.com/fallahn/tmxlite.git tmxlite");
                Directory.SetCurrentDirectory("tmxlite");
                Utils.CallProcess("git", "checkout 8ed41071fe0774947fc7f7c6ece77de3061a5239");
                Directory.SetCurrentDirectory(reposDir);
            }
            if (!Directory.Exists("Effekseer"))
            {
                Utils.CallProcess("git", "clone https://github.com/effekseer/Effekseer Effekseer");
                Directory.SetCurrentDirectory("Effekseer");
                Utils.CallProcess("git", "submodule update --init");
                Directory.SetCurrentDirectory(reposDir);
            }
            if (!Directory.Exists("lua"))
            {
                Utils.CallProcess("git", "clone --depth 1 -b v5.4.0 https://github.com/lua/lua.git");
                Utils.CopyFile(Path.Combine(builder.LuminoExternalDir, "lua", "CMakeLists.txt"), "lua");
            }
            if (!Directory.Exists("nanovg"))
            {
                Utils.CallProcess("git", "clone https://github.com/memononen/nanovg.git");
                using (CurrentDir.Enter("nanovg"))
                {
                    Utils.CallProcess("git", "checkout c35e80c3fed7445b4e2973fccccc89afd97834cf");
                }

                // TODO: https://github.com/memononen/nanovg/pull/565 のマージ待ち
                Utils.CopyFile(Path.Combine(builder.LuminoExternalDir, "nanovg", "CMakeLists.txt"), "nanovg");
            }
            if (!BuildEnvironment.FromCI && !Directory.Exists("glTF-Sample-Models"))
            {
                Utils.CallProcess("git", "clone https://github.com/KhronosGroup/glTF-Sample-Models");
            }

            const string bulletOptions = "-DBUILD_BULLET2_DEMOS=OFF -DBUILD_CLSOCKET=OFF -DBUILD_CPU_DEMOS=OFF -DBUILD_ENET=OFF -DBUILD_EXTRAS=OFF -DBUILD_OPENGL3_DEMOS=OFF -DBUILD_UNIT_TESTS=OFF -DINSTALL_LIBS=ON";


            if (Utils.IsWin32)
            {
                // Visual C++
                if (BuildEnvironment.IsMSVCTarget)
                {
                    var targetName     = BuildEnvironment.Target;
                    var targetFullName = BuildEnvironment.TargetFullName;
                    var configuration  = BuildEnvironment.Configuration;
                    var oggInstallDir  = Utils.ToUnixPath(Path.Combine(builder.BuildDir, $"{BuildEnvironment.TargetFullName}", "ExternalInstall", "ogg"));
                    var targetInfo     = BuildEngine_MSVC.TargetInfoMap[builder.Triplet];
                    var altRuntime     = "-DUSE_MSVC_RUNTIME_LIBRARY_DLL=" + (targetInfo.StaticRuntime == "ON" ? "OFF" : "ON");
                    var cppyamlRuntime = "-DYAML_MSVC_SHARED_RT=" + (targetInfo.StaticRuntime == "ON" ? "OFF" : "ON");

                    BuildProjectMSVC(builder, "nanovg", reposDir, targetName, targetFullName, configuration);
                    BuildProjectMSVC(builder, "SDL2", reposDir, targetName, targetFullName, configuration, $"-DSDL_SHARED=OFF -DSDL_STATIC=ON -DSSE=OFF ");
                    BuildProjectMSVC(builder, "tmxlite/tmxlite", reposDir, targetName, targetFullName, configuration, $"-DTMXLITE_STATIC_LIB=ON");
                    BuildProjectMSVC(builder, "lua", reposDir, targetName, targetFullName, configuration);

                    if (builder.Args.Contains("--enable-Effekseer"))
                    {
                        BuildProjectMSVC(builder, "Effekseer", reposDir, targetName, targetFullName, configuration, $"{altRuntime} -DBUILD_VIEWER=ON -DBUILD_EDITOR=ON -DBUILD_VULKAN=ON");
                    }
                }

                // Android
                if (LuminoBuild.AndoridBuildEnv.AndroidStudioFound && BuildEnvironment.IsAndroidTarget)
                {
                    //foreach (var target in BuildEngine_AndroidJNI.Targets)
                    {
                        var targetName    = BuildEnvironment.Target;
                        var oggInstallDir = Utils.ToUnixPath(Path.Combine(builder.BuildDir, $"{targetName}", "ExternalInstall", "ogg"));

                        BuildProjectAndroid(builder, "tmxlite/tmxlite", reposDir, targetName, "-DTMXLITE_STATIC_LIB=ON");
                        BuildProjectAndroid(builder, "nanovg", reposDir, targetName);
                    }
                }

                // Emscripten
                if (BuildEnvironment.IsWebTarget)
                {
                    var externalInstallDir = Path.Combine(EmscriptenBuildEnv.EmscriptenSysRootLocal, "ExternalInstall");
                    var oggInstallDir      = Utils.ToUnixPath(Path.Combine(externalInstallDir, "ogg"));

                    BuildProjectEm(builder, "tmxlite/tmxlite", reposDir, "Emscripten", "-DTMXLITE_STATIC_LIB=ON");
                    BuildProjectEm(builder, "nanovg", reposDir, "Emscripten");
                }
            }
            else
            {
                // iOS
                if (BuildEnvironment.IsIOSTarget)
                {
                    //var targetInfos = new []
                    //{
                    //    new { Config = "", Platform = "OS64" },
                    //new { Config = "Release", Platform = "OS64" },
                    //    new { Config = "", Platform = "SIMULATOR64" },
                    //new { Config = "Release", Platform = "SIMULATOR64" },
                    //};


                    var iOSToolchainFile = Utils.ToUnixPath(Path.Combine(builder.BuildDir, "ExternalSource", "ios-cmake", "ios.toolchain.cmake "));

                    //foreach (var t in targetInfos)
                    {
                        var dirName   = BuildEnvironment.Target;//$"iOS-{t.Platform}";
                        var platform  = dirName.Replace("iOS-", "");
                        var args      = $"-DCMAKE_TOOLCHAIN_FILE=\"{iOSToolchainFile}\" -DPLATFORM={platform}";
                        var generator = "Xcode";

                        var oggInstallDir = Utils.ToUnixPath(Path.Combine(builder.BuildDir, dirName, "ExternalInstall", "ogg"));

                        BuildProject(builder, "tmxlite/tmxlite", "", reposDir, dirName, generator, $"-DTMXLITE_STATIC_LIB=ON " + args);
                        BuildProject(builder, "nanovg", "", reposDir, dirName, generator, args);
                    }
                }

                // macOS
                if (BuildEnvironment.IsMacOSTarget)
                {
                    var targetArgs = new[]
                    {
                        //new { DirName = "macOS", Config = "Debug",Args = "" },
                        new { DirName = "macOS", Config = "", Args = "" },
                    };

                    foreach (var t in targetArgs)
                    {
                        var dirName       = t.DirName;
                        var args          = t.Args;
                        var oggInstallDir = Utils.ToUnixPath(Path.Combine(builder.BuildDir, dirName, "ExternalInstall", "ogg"));

                        var generator = "Xcode";
                        BuildProject(builder, "tmxlite/tmxlite", t.Config, reposDir, dirName, generator, $"-DTMXLITE_STATIC_LIB=ON " + args);
                        BuildProject(builder, "nanovg", t.Config, reposDir, dirName, generator, args);
                    }
                }
            }

            if (BuildEnvironment.FromCI)
            {
                // CI 環境でディスク消費を抑えるため、一時ファイルを削除する
                var buildDir = builder.GetExternalProjectBuildDir(BuildEnvironment.Target);
                Utils.DeleteDirectory(buildDir);
            }

            builder.CommitCache(builder.GetExternalInstallDir(BuildEnvironment.Target));
        }
Beispiel #53
0
        public async Task <ActionResult> AddBulk(FormCollection values)
        {
            OneSignalClient osc     = new OneSignalClient(ConfigurationManager.AppSettings["push:OneSignalApiKey"]);
            var             success = new List <Build>();
            var             failed  = new List <string>();
            bool            notify  = bool.Parse(values[nameof(BulkAddition.SendNotifications)].Split(',')[0]);

            foreach (string line in values[nameof(BulkAddition.Builds)]
                     .Split(new[]
            {
                '\r',
                '\n'
            },
                            StringSplitOptions.RemoveEmptyEntries))
            {
                Match m = Regex.Match(line, @"(([\d]{1,2})\.([\d]{1,2})\.)?([\d]{4,5})(\.([\d]{1,5}))?(\.| \()([a-zA-Z][a-zA-Z0-9._\(\)-]+?)\.(\d\d\d\d\d\d-\d\d\d\d)\)?");
                if (m.Success)
                {
                    try
                    {
                        Build b = new Build
                        {
                            MajorVersion = uint.Parse(m.Groups[2].Value),
                            MinorVersion = uint.Parse(m.Groups[3].Value),
                            Number       = uint.Parse(m.Groups[4].Value),
                            Revision     = string.IsNullOrEmpty(m.Groups[6].Value)
                                ? null
                                : uint.Parse(m.Groups[6].Value) as uint?,
                            Lab       = m.Groups[8].Value,
                            BuildTime = string.IsNullOrEmpty(m.Groups[9].Value)
                                ? null
                                : DateTime.SpecifyKind(DateTime.ParseExact(m.Groups[9].Value, "yyMMdd-HHmm", CultureInfo.CurrentCulture.DateTimeFormat), DateTimeKind.Utc) as DateTime?,
                            Added      = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                            Modified   = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                            SourceType = TypeOfSource.PrivateLeak
                        };
                        b.RegenerateCachedProperties();

                        BuildDetails bi = new BuildDetails
                        {
                            MajorVersion = b.MajorVersion,
                            MinorVersion = b.MinorVersion,
                            Number       = b.Number,
                            Revision     = b.Revision,
                            Lab          = b.Lab,
                            BuildTime    = b.BuildTime.HasValue
                                ? DateTime.SpecifyKind(b.BuildTime.Value, DateTimeKind.Utc)
                                : null as DateTime?,
                            SourceType    = b.SourceType,
                            SourceDetails = b.SourceDetails
                        };

                        b.History = new List <ItemHistory <BuildDetails> >
                        {
                            new ItemHistory <BuildDetails>
                            {
                                Type     = ItemHistoryType.Added,
                                Time     = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc),
                                UserName = User.Identity.Name,
                                Item     = bi
                            }
                        };

                        string buildString = b.FullBuildString;
                        Build  existing    = await _bModel.SelectBuildByFullBuildString(buildString);

                        if (existing == null)
                        {
                            await _bModel.Insert(b);

                            if (notify)
                            {
                                osc.PushNewBuild(b, $"https://buildfeed.net{Url.Action(nameof(ViewBuild), new { id = b.Id })}?utm_source=notification&utm_campaign=new_build");
                            }

                            success.Add(b);
                        }
                        else
                        {
                            failed.Add(line);
                        }
                    }
                    catch (Exception)
                    {
                        failed.Add(line);
                    }
                }
            }

            ViewBag.Results = success.ToArray();
            return(View(new BulkAddition
            {
                Builds = string.Join("\r\n", failed),
                SendNotifications = notify
            }));
        }
Beispiel #54
0
        /// <summary>
        /// Gets the version number of the latest build/upgrade.
        /// </summary>
        /// <remarks>
        /// This is just plain wrong. This little algorithm is hardcoded into
        /// so many different places. If you change this here, be sure to pay
        /// a visit to the following places:
        /// - APSIM.POStats.Collector
        /// - Jenkins release scripts (batch and bash)
        /// - APSIM.Registration.Service
        /// - Possibly others which I still haven't realised are broken.
        /// </remarks>
        public string GetLatestVersion()
        {
            Build latest = GetLatestBuild();

            return(latest.date.ToString("yyyy.M.d.") + latest.issueNumber);
        }
        private static async Task <string> DownloadArtifactsAsync(BuildHttpClient buildClient, Build build, BuildArtifact artifact, CancellationToken cancellationToken)
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), string.Concat(Options.InsertionName, Options.BranchName).Replace(" ", "_").Replace("/", "_"));

            if (Directory.Exists(tempDirectory))
            {
                // Be judicious and clean up old artifacts so we do not eat up memory on the scheduler machine.
                Directory.Delete(tempDirectory, recursive: true);

                // Sometimes a creation of a directory races with deletion since at least in .net 4.6 deletion is not a blocking call.
                // Hence explictly waiting for the directory to be deleted before moving on.
                Stopwatch w = Stopwatch.StartNew();

                while (Directory.Exists(tempDirectory) && w.ElapsedMilliseconds < 20 * 1000)
                {
                    Thread.Sleep(100);
                }
            }

            Directory.CreateDirectory(tempDirectory);

            var archiveDownloadPath = Path.Combine(tempDirectory, string.Concat(artifact.Name, ".zip"));

            Log.Trace($"Downloading artifacts to {archiveDownloadPath}");

            Stopwatch watch = Stopwatch.StartNew();

            using (Stream s = await buildClient.GetArtifactContentZipAsync(Options.TFSProjectName, build.Id, artifact.Name, cancellationToken))
            {
                using (var fs = File.OpenWrite(archiveDownloadPath))
                {
                    // Using the default buffer size.
                    await s.CopyToAsync(fs, 81920, cancellationToken);
                }

                ZipFile.ExtractToDirectory(archiveDownloadPath, tempDirectory);
                File.Delete(archiveDownloadPath);
            }

            Log.Info($"Artifact download took {watch.ElapsedMilliseconds/1000} seconds");

            return(Path.Combine(tempDirectory, artifact.Name));
        }
Beispiel #56
0
        public async Task <ActionResult> EditBuild(Guid id)
        {
            Build b = await _bModel.SelectById(id);

            return(View(b));
        }
Beispiel #57
0
        public StepResult Perform(BuildListState state)
        {
            if (!Condition.Invoke())
            {
                return(new NextItem());
            }

            if (UnitTypes.LookUp[UnitType].TechRequirement != 0 &&
                Bot.Main.UnitManager.Completed(UnitTypes.LookUp[UnitType].TechRequirement) == 0 &&
                UnitTypes.LookUp[UnitType].TechRequirement != UnitTypes.HATCHERY &&
                UnitTypes.LookUp[UnitType].TechRequirement != UnitTypes.TECH_LAB)
            {
                Bot.Main.DrawText("Tech requirement not met to train " + UnitTypes.LookUp[UnitType].Name + " requires: " + UnitTypes.LookUp[UnitType].TechRequirement);
                return(new NextItem());
            }

            int          alreadyTrained = Bot.Main.UnitManager.Count(UnitType) + state.GetTraining(UnitType);
            TrainingType trainType      = TrainingType.LookUp[UnitType];

            foreach (Agent agent in ProductionTask.Task.Units)
            {
                if (Build.FoodLeft() < trainType.Food)
                {
                    Bot.Main.DrawText("Not enough food to train " + UnitTypes.LookUp[UnitType].Name);
                    break;
                }
                if (alreadyTrained >= Number)
                {
                    break;
                }

                if (agent.Unit.BuildProgress < 0.99)
                {
                    continue;
                }

                if (trainType.IsAddOn && agent.GetAddOn() != null)
                {
                    continue;
                }

                if (!trainType.ProducingUnits.Contains(agent.Unit.UnitType))
                {
                    continue;
                }

                if (agent.Unit.Orders != null && agent.Unit.Orders.Count >= 2)
                {
                    continue;
                }

                if (agent.CurrentAbility() != 0 && (agent.GetAddOn() == null || !IsReactor(agent.GetAddOn().Unit.UnitType)))
                {
                    continue;
                }

                if (agent.Command != null)
                {
                    continue;
                }

                if (Bot.Main.Frame - agent.LastOrderFrame < 5)
                {
                    continue;
                }

                if (agent.Unit.UnitType == UnitTypes.GATEWAY && UpgradeType.LookUp[UpgradeType.WarpGate].Done())
                {
                    continue;
                }

                Bot.Main.ReservedGas      += trainType.Gas;
                Bot.Main.ReservedMinerals += trainType.Minerals;

                if (Bot.Main.Build.Minerals() < 0)
                {
                    return(new NextList());
                }
                if (Bot.Main.Build.Gas() < 0)
                {
                    return(new NextItem());
                }

                if (agent.Unit.UnitType == UnitTypes.WARP_GATE)
                {
                    bool success = WarpIn(agent, trainType);
                    if (!success)
                    {
                        continue;
                    }
                }
                else
                {
                    agent.Order((int)trainType.Ability);
                    Bot.Main.UnitManager.UnitTraining(trainType.UnitType);
                }

                state.AddTraining(UnitType, 1);
                alreadyTrained++;
            }

            return(new NextItem());
        }
Beispiel #58
0
        public async Task <ActionResult> EditBuild(Guid id, Build build)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Build b = await _bModel.SelectById(id);

                    if (build.BuildTime.HasValue)
                    {
                        build.BuildTime = DateTime.SpecifyKind(build.BuildTime.Value, DateTimeKind.Utc);
                    }

                    if (build.LeakDate.HasValue)
                    {
                        build.LeakDate = DateTime.SpecifyKind(build.LeakDate.Value, DateTimeKind.Utc);
                    }

                    BuildDetails bi = new BuildDetails
                    {
                        MajorVersion = build.MajorVersion,
                        MinorVersion = build.MinorVersion,
                        Number       = build.Number,
                        Revision     = build.Revision,
                        Lab          = build.Lab,
                        BuildTime    = build.BuildTime.HasValue
                            ? DateTime.SpecifyKind(build.BuildTime.Value, DateTimeKind.Utc)
                            : null as DateTime?,
                        SourceType    = build.SourceType,
                        SourceDetails = build.SourceDetails
                    };

                    build.History = b.History;
                    if (build.History == null || build.History.Count == 0)
                    {
                        build.History = new List <ItemHistory <BuildDetails> >();
                    }

                    build.History.Add(new ItemHistory <BuildDetails>
                    {
                        Type     = ItemHistoryType.Edited,
                        Time     = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc),
                        UserName = User.Identity.Name,
                        Item     = bi
                    });

                    await _bModel.Update(build);
                }
                catch
                {
                    return(View(build));
                }

                return(RedirectToAction(nameof(ViewBuild),
                                        new
                {
                    id = build.Id
                }));
            }
            return(View(build));
        }
        /// <summary>
        /// Start release pipeline associated with a channel.
        /// </summary>
        /// <param name="buildId">Maestro build id.</param>
        /// <param name="channelId">Maestro channel id.</param>
        /// <returns></returns>
        public async Task RunAssociatedReleasePipelinesAsync(int buildId, int channelId, CancellationToken cancellationToken)
        {
            Logger.LogInformation($"Starting release pipeline for {buildId} in {channelId}");
            Build build = await Context.Builds
                          .Where(b => b.Id == buildId).FirstOrDefaultAsync();

            if (build == null)
            {
                Logger.LogError($"Could not find the specified BAR Build {buildId} to run a release pipeline.");
                return;
            }

            // If something uses the old API version we won't have this information available.
            // This will also be the case if something adds an existing build (created using
            // the old API version) to a channel
            if (build.AzureDevOpsBuildId == null)
            {
                Logger.LogInformation($"barBuildInfo.AzureDevOpsBuildId is null for BAR Build.Id {build.Id}.");
                return;
            }

            Channel channel = await Context.Channels
                              .Where(ch => ch.Id == channelId)
                              .Include(ch => ch.ChannelReleasePipelines)
                              .ThenInclude(crp => crp.ReleasePipeline)
                              .FirstOrDefaultAsync();

            if (channel == null)
            {
                Logger.LogInformation($"Could not find the specified channel {channelId} to run a release pipeline on.");
                return;
            }

            if (channel.ChannelReleasePipelines?.Any() != true)
            {
                Logger.LogInformation($"Channel {channel.Id}, which build with BAR ID {build.Id} is attached to, doesn't have an associated publishing pipeline.");
                return;
            }

            AzureDevOpsClient azdoClient = await GetAzureDevOpsClientForAccount(build.AzureDevOpsAccount);

            var azdoBuild = await azdoClient.GetBuildAsync(
                build.AzureDevOpsAccount,
                build.AzureDevOpsProject,
                build.AzureDevOpsBuildId.Value);

            var runningPipelines =
                await StateManager.GetOrAddAsync <IReliableDictionary <int, IList <ReleasePipelineStatusItem> > >(RunningPipelineDictionaryName);

            List <ReleasePipelineStatusItem> releaseList = new List <ReleasePipelineStatusItem>();

            Logger.LogInformation($"Found {channel.ChannelReleasePipelines.Count} pipeline(s) for channel {channelId}");

            foreach (ChannelReleasePipeline pipeline in channel.ChannelReleasePipelines)
            {
                try
                {
                    string organization = pipeline.ReleasePipeline.Organization;
                    string project      = pipeline.ReleasePipeline.Project;
                    int    pipelineId   = pipeline.ReleasePipeline.PipelineIdentifier;

                    Logger.LogInformation($"Going to create a release using pipeline {organization}/{project}/{pipelineId}");

                    AzureDevOpsReleaseDefinition pipeDef = await azdoClient.GetReleaseDefinitionAsync(organization, project, pipelineId);

                    pipeDef = await azdoClient.AdjustReleasePipelineArtifactSourceAsync(organization, project, pipeDef, azdoBuild);

                    int releaseId = await azdoClient.StartNewReleaseAsync(organization, project, pipeDef, build.Id);

                    var item = new ReleasePipelineStatusItem(releaseId, channelId, organization, project);
                    releaseList.Add(item);

                    Logger.LogInformation($"Created release {releaseId} using pipeline {organization}/{project}/{pipelineId}");
                }
                catch (Exception e)
                {
                    Logger.LogError($"Some problem happened while starting publishing pipeline " +
                                    $"{pipeline.ReleasePipeline.PipelineIdentifier} for build " +
                                    $"{build.AzureDevOpsBuildId}: {e.Message}", e);
                    throw;
                }
            }

            if (releaseList.Count > 0)
            {
                using (ITransaction tx = StateManager.CreateTransaction())
                {
                    var runningPipelinesForBuild = await runningPipelines.TryGetValueAsync(tx, buildId);

                    if (runningPipelinesForBuild.HasValue)
                    {
                        // Some channel already triggered release pipelines for this build. Need to update with the releases for the new channel.
                        releaseList.AddRange(runningPipelinesForBuild.Value);
                        await runningPipelines.TryUpdateAsync(tx, buildId, releaseList, runningPipelinesForBuild.Value);
                    }
                    else
                    {
                        await runningPipelines.AddAsync(tx, buildId, releaseList);
                    }
                    await tx.CommitAsync();
                }
            }
        }
        //Return a sample dataset to help with testing
        private List <Build> GetSampleAzureDevOpsBuilds()
        {
            List <Build> results = new List <Build>();
            Build        item1   = new Build
            {
                StartTime            = DateTime.Now.AddDays(-7).AddMinutes(-4),
                EndTime              = DateTime.Now.AddDays(-7).AddMinutes(0),
                BuildDurationPercent = 70,
                BuildNumber          = "1",
                Branch = "master",
                Status = "completed",
                Url    = "https://dev.azure.com/samsmithnz/samlearnsazure/1"
            };

            results.Add(item1);
            results.Add(item1);
            Build item2 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-5).AddMinutes(-5),
                EndTime              = DateTime.Now.AddDays(-5).AddMinutes(0),
                BuildDurationPercent = 40,
                BuildNumber          = "2",
                Branch = "master",
                Status = "completed",
                Url    = "https://dev.azure.com/samsmithnz/samlearnsazure/2"
            };

            results.Add(item2);
            results.Add(item2);
            Build item3 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-4).AddMinutes(-1),
                EndTime              = DateTime.Now.AddDays(-4).AddMinutes(0),
                BuildDurationPercent = 20,
                BuildNumber          = "3",
                Branch = "master",
                Status = "failed",
                Url    = "https://dev.azure.com/samsmithnz/samlearnsazure/3"
            };

            results.Add(item3);
            Build item4 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-3).AddMinutes(-4),
                EndTime              = DateTime.Now.AddDays(-3).AddMinutes(0),
                BuildDurationPercent = 50,
                BuildNumber          = "4",
                Branch = "master",
                Status = "completed",
                Url    = "https://dev.azure.com/samsmithnz/samlearnsazure/4"
            };

            results.Add(item4);
            results.Add(item4);
            Build item5 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-2).AddMinutes(-7),
                EndTime              = DateTime.Now.AddDays(-2).AddMinutes(0),
                BuildDurationPercent = 60,
                BuildNumber          = "5",
                Branch = "master",
                Status = "completed",
                Url    = "https://dev.azure.com/samsmithnz/samlearnsazure/5"
            };

            results.Add(item5);
            results.Add(item5);
            Build item6 = new Build
            {
                StartTime            = DateTime.Now.AddDays(-1).AddMinutes(-5),
                EndTime              = DateTime.Now.AddDays(-1).AddMinutes(0),
                BuildDurationPercent = 70,
                BuildNumber          = "6",
                Branch = "master",
                Status = "inProgress",
                Url    = "https://dev.azure.com/samsmithnz/samlearnsazure/6"
            };

            results.Add(item6);

            return(results);
        }