当前位置: 首页>>代码示例>>C#>>正文


C# IExecutionContext.Output方法代码示例

本文整理汇总了C#中IExecutionContext.Output方法的典型用法代码示例。如果您正苦于以下问题:C# IExecutionContext.Output方法的具体用法?C# IExecutionContext.Output怎么用?C# IExecutionContext.Output使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IExecutionContext的用法示例。


在下文中一共展示了IExecutionContext.Output方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetSourceAsync

        public async Task GetSourceAsync(IExecutionContext executionContext, ServiceEndpoint endpoint, CancellationToken cancellationToken)
        {
            Trace.Verbose("Entering SvnSourceProvider.GetSourceAsync");

            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNull(endpoint, nameof(endpoint));

            ISvnCommandManager svn = HostContext.CreateService<ISvnCommandManager>();
            svn.Init(executionContext, endpoint, cancellationToken);

            // Determine the sources directory.
            string sourcesDirectory = executionContext.Variables.Build_SourcesDirectory;
            executionContext.Debug($"sourcesDirectory={sourcesDirectory}");
            ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));

            string sourceBranch = executionContext.Variables.Build_SourceBranch;
            executionContext.Debug($"sourceBranch={sourceBranch}");

            string revision = executionContext.Variables.Build_SourceVersion;
            if (string.IsNullOrWhiteSpace(revision))
            {
                revision = "HEAD";
            }
            executionContext.Debug($"revision={revision}");

            bool clean = endpoint.Data.ContainsKey(WellKnownEndpointData.Clean) &&
                StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean], defaultValue: false);
            executionContext.Debug($"clean={clean}");

            // Get the definition mappings.
            List<SvnMappingDetails> allMappings = JsonConvert.DeserializeObject<SvnWorkspace>(endpoint.Data[WellKnownEndpointData.SvnWorkspaceMapping]).Mappings;

            if (executionContext.Variables.System_Debug.HasValue && executionContext.Variables.System_Debug.Value)
            {
                allMappings.ForEach(m => executionContext.Debug($"ServerPath: {m.ServerPath}, LocalPath: {m.LocalPath}, Depth: {m.Depth}, Revision: {m.Revision}, IgnoreExternals: {m.IgnoreExternals}"));
            }

            Dictionary<string, SvnMappingDetails> normalizedMappings = svn.NormalizeMappings(allMappings);
            if (executionContext.Variables.System_Debug.HasValue && executionContext.Variables.System_Debug.Value)
            {
                executionContext.Debug($"Normalized mappings count: {normalizedMappings.Count}");
                normalizedMappings.ToList().ForEach(p => executionContext.Debug($"    [{p.Key}] ServerPath: {p.Value.ServerPath}, LocalPath: {p.Value.LocalPath}, Depth: {p.Value.Depth}, Revision: {p.Value.Revision}, IgnoreExternals: {p.Value.IgnoreExternals}"));
            }

            string normalizedBranch = svn.NormalizeRelativePath(sourceBranch, '/', '\\');

            executionContext.Output(StringUtil.Loc("SvnSyncingRepo", endpoint.Name));

            string effectiveRevision = await svn.UpdateWorkspace(
                sourcesDirectory,
                normalizedMappings,
                clean,
                normalizedBranch,
                revision);

            executionContext.Output(StringUtil.Loc("SvnBranchCheckedOut", normalizedBranch, endpoint.Name, effectiveRevision));
            Trace.Verbose("Leaving SvnSourceProvider.GetSourceAsync");
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:59,代码来源:SvnSourceProvider.cs

示例2: DownloadAsync

        public async Task DownloadAsync(IExecutionContext executionContext, ArtifactDefinition artifactDefinition, string localFolderPath)
        {
            ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition));
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath));

            int buildId = Convert.ToInt32(artifactDefinition.Version, CultureInfo.InvariantCulture);
            if (buildId <= 0)
            {
                throw new ArgumentException("artifactDefinition.Version");
            }

            var buildArtifactDetails = artifactDefinition.Details as BuildArtifactDetails;
            if (buildArtifactDetails == null)
            {
                throw new ArgumentException("artifactDefinition.Details");
            }

            // Get the list of available artifacts from build. 
            executionContext.Output(StringUtil.Loc("RMPreparingToGetBuildArtifactList"));

            var vssConnection = new VssConnection(buildArtifactDetails.TfsUrl, buildArtifactDetails.Credentials);
            var buildClient = vssConnection.GetClient<BuildHttpClient>();
            var xamlBuildClient = vssConnection.GetClient<XamlBuildHttpClient>();
            List<ServerBuildArtifact> buildArtifacts = null;
            DefinitionType buildDefinitionType = DefinitionType.Build;

            try
            {
                buildArtifacts = await buildClient.GetArtifactsAsync(buildArtifactDetails.Project, buildId);
            }
            catch (BuildNotFoundException)
            {
                buildArtifacts = await xamlBuildClient.GetArtifactsAsync(buildArtifactDetails.Project, buildId);
                buildDefinitionType = DefinitionType.Xaml;
            }

            // No artifacts found in the build => Fail it. 
            if (buildArtifacts == null || !buildArtifacts.Any())
            {
                throw new ArtifactDownloadException(StringUtil.Loc("RMNoBuildArtifactsFound", buildId));
            }

            // DownloadFromStream each of the artifact sequentially. 
            // TODO: Should we download them parallely?
            foreach (ServerBuildArtifact buildArtifact in buildArtifacts)
            {
                if (Match(buildArtifact, artifactDefinition))
                {
                    executionContext.Output(StringUtil.Loc("RMPreparingToDownload", buildArtifact.Name));
                    await this.DownloadArtifactAsync(executionContext, buildArtifact, artifactDefinition, localFolderPath, buildClient, xamlBuildClient, buildDefinitionType, buildId);
                }
                else
                {
                    executionContext.Warning(StringUtil.Loc("RMArtifactMatchNotFound", buildArtifact.Name));
                }
            }
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:58,代码来源:BuildArtifact.cs

示例3: DownloadAsync

        public async Task DownloadAsync(
            IExecutionContext executionContext,
            ArtifactDefinition artifactDefinition,
            string localFolderPath)
        {
            ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition));
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath));

            var jenkinsDetails = artifactDefinition.Details as JenkinsArtifactDetails;
            executionContext.Output(StringUtil.Loc("RMGotJenkinsArtifactDetails"));
            executionContext.Output(StringUtil.Loc("RMJenkinsJobName", jenkinsDetails.JobName));
            executionContext.Output(StringUtil.Loc("RMJenkinsBuildId", jenkinsDetails.BuildId));

            Stream downloadedStream = null;
            using (HttpClient client = new HttpClient())
            {
                SetupHttpClient(client, jenkinsDetails.AccountName, jenkinsDetails.AccountPassword);
                var downloadArtifactsUrl =
                    new Uri(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "{0}/job/{1}/{2}/artifact/{3}/*zip*/",
                            jenkinsDetails.Url,
                            jenkinsDetails.JobName,
                            jenkinsDetails.BuildId,
                            jenkinsDetails.RelativePath));

                executionContext.Output(StringUtil.Loc("RMPrepareToGetFromJenkinsServer"));
                HttpResponseMessage response = client.GetAsync(downloadArtifactsUrl).Result;

                if (response.IsSuccessStatusCode)
                {
                    downloadedStream = response.Content.ReadAsStreamAsync().Result;
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new ArtifactDownloadException(StringUtil.Loc("RMNoArtifactsFound", jenkinsDetails.RelativePath));
                }
                else
                {
                    throw new ArtifactDownloadException(StringUtil.Loc("RMDownloadArtifactUnexpectedError"));
                }
            }

            var parentFolder = GetParentFolderName(jenkinsDetails.RelativePath);
            Trace.Info($"Found parentFolder {parentFolder} for relative path {jenkinsDetails.RelativePath}");
            
            executionContext.Output(StringUtil.Loc("RMDownloadingJenkinsArtifacts"));
            var zipStreamDownloader = HostContext.GetService<IZipStreamDownloader>();
            await zipStreamDownloader.DownloadFromStream(
                downloadedStream,
                string.IsNullOrEmpty(parentFolder) ? "archive" : string.Empty,
                parentFolder,
                localFolderPath);
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:56,代码来源:JenkinsArtifact.cs

示例4: EnableCodeCoverage

        public void EnableCodeCoverage(IExecutionContext context, CodeCoverageEnablerInputs ccInputs)
        {
            Trace.Entering();
            _executionContext = context;

            ccInputs.VerifyInputsForJacocoAnt(context);

            string sourcesDirectory = context.Variables.Build_SourcesDirectory;
            if (string.IsNullOrWhiteSpace(sourcesDirectory))
            {
                throw new InvalidOperationException(StringUtil.Loc("InvalidSourceDirectory"));
            }

            var buildFileDirectory = Path.GetDirectoryName(ccInputs.BuildFile);
            if (!buildFileDirectory.StartsWith(sourcesDirectory, StringComparison.OrdinalIgnoreCase))
            {
                // build file is not present in the repository.
                // Edit the build file though not present in repository. This will ensure that the single module ant project will work. 
                // Multi module ant project won't work if the build file is not in the repository. 
                EnableJacocoForBuildFile(ccInputs.BuildFile, ccInputs);
            }
            else
            {
                var buildFiles = Directory.GetFiles(sourcesDirectory, "*.xml", SearchOption.AllDirectories);
                foreach (var buildFile in buildFiles)
                {
                    EnableJacocoForBuildFile(buildFile, ccInputs);
                }
            }

            //add jacoco report
            CreateJacocoReport(ccInputs);
            context.Output(StringUtil.Loc("CodeCoverageEnabled", "jacoco", "ant"));
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:34,代码来源:CodeCoverageEnablerForJacocoAnt.cs

示例5: EnableCodeCoverage

        public void EnableCodeCoverage(IExecutionContext context, CodeCoverageEnablerInputs ccInputs)
        {
            Trace.Entering();
            _executionContext = context;

            ccInputs.VerifyInputsForJacocoMaven();

            context.Debug(StringUtil.Format(CodeCoverageConstants.EnablingEditingTemplate, "jacoco", "maven", ccInputs.BuildFile));

            // see jacoco maven documentation for more details. http://www.eclemma.org/jacoco/trunk/doc/maven.html
            XElement pomXml;
            try
            {
                pomXml = XElement.Load(ccInputs.BuildFile);
            }
            catch (XmlException e)
            {
                _executionContext.Warning(StringUtil.Loc("InvalidBuildXml", ccInputs.BuildFile, e.Message));
                throw;
            }

            XNamespace xNameSpace = pomXml.Attribute("xmlns").Value;

            if (pomXml.Element(xNameSpace + "modules") != null)
            {
                // aa multi module project 
                _isMultiModule = true;
                context.Debug(CodeCoverageConstants.MavenMultiModule);
            }

            // Add a build element if doesnot exist.
            var build = pomXml.Element(xNameSpace + "build");
            if (build == null)
            {
                pomXml.Add(new XElement("build"));
                build = pomXml.Element("build");
            }

            // Set jacoco plugins to enable code coverage.
            SetPlugins(build, ccInputs, xNameSpace);

            foreach (var e in build.DescendantsAndSelf().Where(e => string.IsNullOrEmpty(e.Name.Namespace.NamespaceName)))
            {
                e.Name = xNameSpace + e.Name.LocalName;
            }

            using (FileStream stream = new FileStream(ccInputs.BuildFile, FileMode.Create))
            {
                pomXml.Save(stream);
            }

            if (_isMultiModule)
            {
                CreateReportPomForMultiModule(ccInputs.ReportBuildFile, xNameSpace, pomXml, ccInputs);
            }

            context.Output(StringUtil.Loc("CodeCoverageEnabled", "jacoco", "maven"));
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:58,代码来源:CodeCoverageEnablerForJacocoMaven.cs

示例6: CodeCoverageEnablerInputs

        public CodeCoverageEnablerInputs(IExecutionContext context, string buildTool, Dictionary<string, string> eventProperties)
        {
            string classFilter;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.ClassFilter, out classFilter);

            string buildFile;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.BuildFile, out buildFile);

            string classFilesDirectories;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.ClassFilesDirectories, out classFilesDirectories);

            string sourceDirectories;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.SourceDirectories, out sourceDirectories);

            string summaryFile;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.SummaryFile, out summaryFile);

            string cCReportTask;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.CCReportTask, out cCReportTask);

            string reportBuildFile;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.ReportBuildFile, out reportBuildFile);

            string isMultiModuleInput;
            var isMultiModule = false;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.IsMultiModule, out isMultiModuleInput);
            if (!bool.TryParse(isMultiModuleInput, out isMultiModule) && buildTool.Equals("gradle", StringComparison.OrdinalIgnoreCase))
            {
                context.Output(StringUtil.Loc("IsMultiModuleParameterNotAvailable"));
            }

            string reportDirectory;
            eventProperties.TryGetValue(EnableCodeCoverageEventProperties.ReportDirectory, out reportDirectory);

            string include, exclude;
            CodeCoverageUtilities.GetFilters(classFilter, out include, out exclude);

            BuildFile = CodeCoverageUtilities.TrimNonEmptyParam(buildFile, "BuildFile");

            //validatebuild file exists
            if (!File.Exists(BuildFile))
            {
                throw new FileNotFoundException(StringUtil.Loc("FileDoesNotExist", BuildFile));
            }

            ClassFilesDirectories = classFilesDirectories;
            Include = include;
            Exclude = exclude;
            SourceDirectories = sourceDirectories;
            SummaryFile = summaryFile;
            ReportDirectory = reportDirectory;
            CCReportTask = cCReportTask;
            ReportBuildFile = reportBuildFile;
            IsMultiModule = isMultiModule;
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:55,代码来源:CodeCoverageEnablerInputs.cs

示例7: EnableCodeCoverage

        public void EnableCodeCoverage(IExecutionContext context, CodeCoverageEnablerInputs ccInputs)
        {
            Trace.Entering();

            ccInputs.VerifyInputsForCoberturaGradle();

            context.Debug(StringUtil.Format(CodeCoverageConstants.EnablingEditingTemplate, "cobertura", "gradle", ccInputs.BuildFile));
            var buildScript = new FileInfo(ccInputs.BuildFile);

            if (buildScript.Length == 0)
            {
                throw new InvalidOperationException(StringUtil.Loc("CodeCoverageBuildFileIsEmpty", ccInputs.BuildFile));
            }

            CodeCoverageUtilities.PrependDataToFile(ccInputs.BuildFile, GetCoberturaPluginDefination());
            File.AppendAllText(ccInputs.BuildFile, GetGradleCoberturaReport(ccInputs));
            context.Output(StringUtil.Loc("CodeCoverageEnabled", "cobertura", "gradle"));
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:18,代码来源:CodeCoverageEnablerForCoberturaGradle.cs

示例8: GetSourceAsync

        public virtual async Task GetSourceAsync(IExecutionContext executionContext, ServiceEndpoint endpoint, CancellationToken cancellationToken)
        {
            Trace.Entering();
            ArgUtil.NotNull(endpoint, nameof(endpoint));

            executionContext.Output($"Syncing repository: {endpoint.Name} (Git)");
            _gitCommandManager = HostContext.GetService<IGitCommandManager>();
            await _gitCommandManager.LoadGitExecutionInfo(executionContext);

            string targetPath = executionContext.Variables.Get(Constants.Variables.Build.SourcesDirectory);
            string sourceBranch = executionContext.Variables.Get(Constants.Variables.Build.SourceBranch);
            string sourceVersion = executionContext.Variables.Get(Constants.Variables.Build.SourceVersion);

            bool clean = false;
            if (endpoint.Data.ContainsKey(WellKnownEndpointData.Clean))
            {
                clean = StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean]);
            }

            bool checkoutSubmodules = false;
            if (endpoint.Data.ContainsKey(WellKnownEndpointData.CheckoutSubmodules))
            {
                checkoutSubmodules = StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.CheckoutSubmodules]);
            }

            bool exposeCred = executionContext.Variables.GetBoolean(Constants.Variables.System.EnableAccessToken) ?? false;

            Trace.Info($"Repository url={endpoint.Url}");
            Trace.Info($"targetPath={targetPath}");
            Trace.Info($"sourceBranch={sourceBranch}");
            Trace.Info($"sourceVersion={sourceVersion}");
            Trace.Info($"clean={clean}");
            Trace.Info($"checkoutSubmodules={checkoutSubmodules}");
            Trace.Info($"exposeCred={exposeCred}");

            // retrieve credential from endpoint.
            Uri repositoryUrl = endpoint.Url;
            if (!repositoryUrl.IsAbsoluteUri)
            {
                throw new InvalidOperationException("Repository url need to be an absolute uri.");
            }

            string username = string.Empty;
            string password = string.Empty;
            if (endpoint.Authorization != null)
            {
                switch (endpoint.Authorization.Scheme)
                {
                    case EndpointAuthorizationSchemes.OAuth:
                        username = EndpointAuthorizationSchemes.OAuth;
                        if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out password))
                        {
                            password = string.Empty;
                        }
                        break;
                    case EndpointAuthorizationSchemes.UsernamePassword:
                        if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out username))
                        {
                            // leave the username as empty, the username might in the url, like: http://[email protected]
                            username = string.Empty;
                        }
                        if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out password))
                        {
                            // we have username, but no password
                            password = string.Empty;
                        }
                        break;
                    default:
                        executionContext.Warning($"Unsupport endpoint authorization schemes: {endpoint.Authorization.Scheme}");
                        break;
                }
            }

            // Check the current contents of the root folder to see if there is already a repo
            // If there is a repo, see if it matches the one we are expecting to be there based on the remote fetch url
            // if the repo is not what we expect, remove the folder
            if (!await IsRepositoryOriginUrlMatch(executionContext, targetPath, repositoryUrl))
            {
                // Delete source folder
                IOUtil.DeleteDirectory(targetPath, cancellationToken);
            }
            else
            {
                // delete the index.lock file left by previous canceled build or any operation casue git.exe crash last time.
                string lockFile = Path.Combine(targetPath, ".git\\index.lock");
                if (File.Exists(lockFile))
                {
                    try
                    {
                        File.Delete(lockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the index.lock file: {lockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // When repo.clean is selected for a git repo, execute git clean -fdx and git reset --hard HEAD on the current repo.
                // This will help us save the time to reclone the entire repo.
//.........这里部分代码省略.........
开发者ID:codedebug,项目名称:vsts-agent,代码行数:101,代码来源:GitSourceProvider.cs

示例9: DownloadArtifactAsync

        private async Task DownloadArtifactAsync(
            IExecutionContext executionContext,
            ServerBuildArtifact buildArtifact,
            ArtifactDefinition artifactDefinition,
            string localFolderPath,
            BuildHttpClient buildClient,
            XamlBuildHttpClient xamlBuildClient,
            DefinitionType definitionType,
            int buildId)
        {
            var downloadFolderPath = Path.Combine(localFolderPath, buildArtifact.Name);
            var buildArtifactDetails = artifactDefinition.Details as BuildArtifactDetails;
            if ((buildArtifact.Resource.Type == null && buildArtifact.Id == 0) // bug on build API Bug 378900
                || string.Equals(buildArtifact.Resource.Type, WellKnownArtifactResourceTypes.FilePath, StringComparison.OrdinalIgnoreCase))
            {
                executionContext.Output("Artifact Type: FileShare");
                string fileShare;
                if (buildArtifact.Id == 0)
                {
                    fileShare = new Uri(buildArtifact.Resource.DownloadUrl).LocalPath;
                }
                else
                {
                    fileShare = new Uri(Path.Combine(buildArtifact.Resource.DownloadUrl, buildArtifact.Name)).LocalPath;
                    if (!Directory.Exists(fileShare))
                    {
                        // download path does not exist, log and fall back
                        var parenthPath = new Uri(buildArtifact.Resource.DownloadUrl).LocalPath;
                        executionContext.Output(StringUtil.Loc("RMArtifactNameDirectoryNotFound", fileShare, parenthPath));
                        fileShare = parenthPath;
                    }
                }

                if (!Directory.Exists(fileShare))
                {
                    // download path does not exist, raise exception
                    throw new ArtifactDownloadException(StringUtil.Loc("RMArtifactDirectoryNotFoundError", fileShare));
                }

                executionContext.Output(StringUtil.Loc("RMDownloadingArtifactFromFileShare", fileShare));

                var fileShareArtifact = new FileShareArtifact();
                await fileShareArtifact.DownloadArtifactAsync(executionContext, HostContext, artifactDefinition, fileShare, downloadFolderPath);
            }
            else if (string.Equals(buildArtifact.Resource.Type, WellKnownArtifactResourceTypes.Container, StringComparison.OrdinalIgnoreCase))
            {
                executionContext.Output("Artifact Type: ServerDrop");

                // TODO:Get VssBinFetchclient and get away from zipstream downloader
                Stream contentStream;
                
                if (definitionType == DefinitionType.Xaml)
                {
                    contentStream = await xamlBuildClient.GetArtifactContentZipAsync(buildArtifactDetails.Project, buildId, buildArtifact.Name);
                }
                else
                {
                    contentStream = await buildClient.GetArtifactContentZipAsync(buildArtifactDetails.Project, buildId, buildArtifact.Name);
                }
                

                var zipStreamDownloader = HostContext.GetService<IZipStreamDownloader>();
                string artifactRootFolder = StringUtil.Format("/{0}", buildArtifact.Name);
                await zipStreamDownloader.DownloadFromStream(contentStream, artifactRootFolder, buildArtifactDetails.RelativePath, downloadFolderPath);
            }
            else
            {
                executionContext.Warning(StringUtil.Loc("RMArtifactTypeNotSupported", buildArtifact.Resource.Type));
            }
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:70,代码来源:BuildArtifact.cs

示例10: EnableCodeCoverage


//.........这里部分代码省略.........

                    allprojects {
	                    repositories {
                            mavenCentral()
                        }
                    }

                    def jacocoExcludes = [" + CodeCoverageUtilities.TrimToEmptyString(exclude) + @"]
                    def jacocoIncludes = [" + CodeCoverageUtilities.TrimToEmptyString(include) + @"]

                    subprojects {
	
                        jacocoTestReport {
		                    doFirst {
			                    classDirectories = fileTree(dir: """ + ccInputs.ClassFilesDirectories + @""").exclude(jacocoExcludes).include(jacocoIncludes)
		                    }
		
		                    reports {
			                    html.enabled = true
			                    html.destination ""${buildDir}/jacocoHtml""
                                xml.enabled = true    
	                            xml.destination ""${buildDir}" + "/" + _summaryFile + @"""
                            }
                        }
	
	                    test {
		                    jacoco {
			                    append = true
			                    destinationFile = file(""" + ccInputs.ReportDirectory + "/" + _jacocoExecPrefix + ".exec\"" + @")
		                    }
	                    }
                    }" + @"
                    task jacocoRootReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) {
	                    dependsOn = subprojects.test
	                    executionData = files(subprojects.jacocoTestReport.executionData)
	                    sourceDirectories = files(subprojects.sourceSets.main.allSource.srcDirs)
	                    classDirectories = files()
	
	                    doFirst {
		                    subprojects.each {
			                    if (new File(""${it.sourceSets.main.output.classesDir}"").exists()) {
				                    logger.info(""Class directory exists in sub project: ${it.name}"")
				                    logger.info(""Adding class files ${it.sourceSets.main.output.classesDir}"")
				                    classDirectories += fileTree(dir: ""${it.sourceSets.main.output.classesDir}"", includes: jacocoIncludes, excludes: jacocoExcludes)
			                    } else {
				                    logger.error(""Class directory does not exist in sub project: ${it.name}"")
			                    }
		                    }
	                    }
	
	                    reports {
		                    html.enabled = true
                            xml.enabled = true    
		                    xml.destination """ + ccInputs.ReportDirectory + "/" + _summaryFile + @"""
		                    html.destination """ + ccInputs.ReportDirectory + @"""
	                    }
                    }
                    ";
            }
            else
            {
                enableJacoco = @"
                    allprojects { apply plugin: 'jacoco' }

                    allprojects {
	                    repositories {
                            mavenCentral()
                        }
                    }

                    def jacocoExcludes = [" + CodeCoverageUtilities.TrimToEmptyString(exclude) + @"]
                    def jacocoIncludes = [" + CodeCoverageUtilities.TrimToEmptyString(include) + @"]


	
                    jacocoTestReport {
	                    doFirst {
		                    classDirectories = fileTree(dir: """ + ccInputs.ClassFilesDirectories + @""").exclude(jacocoExcludes).include(jacocoIncludes)
	                    }
		
	                    reports {
	                        html.enabled = true
                            xml.enabled = true    
	                        xml.destination """ + ccInputs.ReportDirectory + "/" + _summaryFile + @"""
	                        html.destination """ + ccInputs.ReportDirectory + @"""
                        }
                    }
	
                    test {
                        finalizedBy jacocoTestReport
	                    jacoco {
		                    append = true
		                    destinationFile = file(""" + ccInputs.ReportDirectory + "/" + _jacocoExecPrefix + ".exec\"" + @")
	                    }
                    }
                    ";
            }
            File.AppendAllText(ccInputs.BuildFile, enableJacoco);
            context.Output(StringUtil.Loc("CodeCoverageEnabled", "jacoco", "gradle"));
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:101,代码来源:CodeCoverageEnablerForJacocoGradle.cs

示例11: GetSourceAsync

        public async Task GetSourceAsync(
            IExecutionContext executionContext,
            ServiceEndpoint endpoint,
            CancellationToken cancellationToken)
        {
            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNull(endpoint, nameof(endpoint));

            // Create the tf command manager.
            var tf = HostContext.CreateService<ITfsVCCommandManager>();
            tf.CancellationToken = cancellationToken;
            tf.Endpoint = endpoint;
            tf.ExecutionContext = executionContext;

            // Check if the administrator accepted the license terms of the TEE EULA when configuring the agent.
            AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings();
            if (tf.Features.HasFlag(TfsVCFeatures.Eula) && settings.AcceptTeeEula)
            {
                // Check if the "tf eula -accept" command needs to be run for the current user.
                bool skipEula = false;
                try
                {
                    skipEula = tf.TestEulaAccepted();
                }
                catch (Exception ex)
                {
                    Trace.Error("Unexpected exception while testing whether the TEE EULA has been accepted for the current security user.");
                    Trace.Error(ex);
                }

                if (!skipEula)
                {
                    // Run the command "tf eula -accept".
                    try
                    {
                        await tf.EulaAsync();
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        executionContext.Warning(ex.Message);
                    }
                }
            }

            // Get the workspaces.
            ITfsVCWorkspace[] tfWorkspaces = await tf.WorkspacesAsync();

            // Determine the workspace name.
            string buildDirectory = executionContext.Variables.Agent_BuildDirectory;
            ArgUtil.NotNullOrEmpty(buildDirectory, nameof(buildDirectory));
            string workspaceName = $"ws_{Path.GetFileName(buildDirectory)}_{settings.AgentId}";
            executionContext.Variables.Set(Constants.Variables.Build.RepoTfvcWorkspace, workspaceName);

            // Get the definition mappings.
            DefinitionWorkspaceMapping[] definitionMappings =
                JsonConvert.DeserializeObject<DefinitionWorkspaceMappings>(endpoint.Data[WellKnownEndpointData.TfvcWorkspaceMapping])?.Mappings;

            // Determine the sources directory.
            string sourcesDirectory = executionContext.Variables.Build_SourcesDirectory;
            ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));

            // Attempt to re-use an existing workspace if the command manager supports scorch
            // or if clean is not specified.
            ITfsVCWorkspace existingTFWorkspace = null;
            bool clean = endpoint.Data.ContainsKey(WellKnownEndpointData.Clean) &&
                StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean], defaultValue: false);
            if (tf.Features.HasFlag(TfsVCFeatures.Scorch) || !clean)
            {
                existingTFWorkspace = MatchExactWorkspace(
                    tfWorkspaces: tfWorkspaces,
                    name: workspaceName,
                    definitionMappings: definitionMappings,
                    sourcesDirectory: sourcesDirectory);
                if (existingTFWorkspace != null)
                {
                    if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
                    {
                        // Undo pending changes.
                        ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory);
                        if (tfStatus?.HasPendingChanges ?? false)
                        {
                            await tf.UndoAsync(localPath: sourcesDirectory);

                            // Cleanup remaining files/directories from pend adds.
                            tfStatus.AllAdds
                                .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
                                .ToList()
                                .ForEach(x =>
                                {
                                    executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
                                    IOUtil.Delete(x.LocalItem, cancellationToken);
                                });
                        }
                    }
                    else
                    {
                        // Perform "undo" for each map.
                        foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
//.........这里部分代码省略.........
开发者ID:codedebug,项目名称:vsts-agent,代码行数:101,代码来源:TfsVCSourceProvider.cs

示例12: EnableCodeCoverage

        public void EnableCodeCoverage(IExecutionContext context, CodeCoverageEnablerInputs ccInputs)
        {
            Trace.Entering();
            _executionContext = context;

            context.Debug(StringUtil.Format(CodeCoverageConstants.EnablingEditingTemplate, "cobertura", "maven", ccInputs.BuildFile));

            XElement pomXml;
            try
            {
                pomXml = XElement.Load(ccInputs.BuildFile);
            }
            catch (XmlException e)
            {
                _executionContext.Warning(StringUtil.Loc("InvalidBuildXml", ccInputs.BuildFile, e.Message));
                throw;
            }

            XNamespace xNameSpace = pomXml.Attribute("xmlns").Value;

            if (pomXml.Element(xNameSpace + "modules") != null)
            {
                // aa multi module project 
                _isMultiModule = true;
                context.Debug("This is a multi module project. Generating code coverage reports using ant task.");
            }

            // Add a build element if doesnot exist.
            var build = pomXml.Element(xNameSpace + "build");
            if (build == null)
            {
                pomXml.Add(new XElement(xNameSpace + "build"));
                build = pomXml.Element(xNameSpace + "build");
            }

            // Set cobertura plugins to enable code coverage.
            SetPlugins(build, ccInputs, xNameSpace);

            // Adding reporting enabler for cobertura
            var report = pomXml.Element(xNameSpace + "reporting");
            if (report == null)
            {
                pomXml.Add(new XElement(xNameSpace + "reporting"));
                report = pomXml.Element(xNameSpace + "reporting");
            }

            var pluginsInReport = report.Element(xNameSpace + _pluginsTag);
            if (pluginsInReport == null)
            {
                report.Add(new XElement(xNameSpace + _pluginsTag));
                pluginsInReport = report.Element(xNameSpace + _pluginsTag);
            }

            IList<XElement> pluginListInReport = pluginsInReport.Elements(xNameSpace + _pluginTag).ToList();

            foreach (var plugin in pluginListInReport.Where(plugin =>
            {
                var groupId = plugin.Element(xNameSpace + "groupId");
                var artifactId = plugin.Element(xNameSpace + "artifactId");
                return (artifactId != null && artifactId.Value == _coberturaArtifactId)
                    && (groupId != null && groupId.Value == _coberturaGroupId);
            }))
            {
                plugin.Parent.RemoveAll();
            }

            pluginsInReport.Add(GetDefaultReporting());

            foreach (var e in build.DescendantsAndSelf().Where(e => string.IsNullOrEmpty(e.Name.Namespace.NamespaceName)))
            {
                e.Name = xNameSpace + e.Name.LocalName;
            }

            foreach (var e in report.DescendantsAndSelf().Where(e => string.IsNullOrEmpty(e.Name.Namespace.NamespaceName)))
            {
                e.Name = xNameSpace + e.Name.LocalName;
            }

            using (FileStream stream = new FileStream(ccInputs.BuildFile, FileMode.Create))
            {
                pomXml.Save(stream);
            }
            context.Output(StringUtil.Loc("CodeCoverageEnabled", "cobertura", "maven"));
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:84,代码来源:CodeCoverageEnablerForCoberturaMaven.cs

示例13: LogEnvironmentVariables

        private void LogEnvironmentVariables(IExecutionContext executionContext)
        {
            Trace.Entering();
            string stringifiedEnvironmentVariables = AgentUtilities.GetPrintableEnvironmentVariables(executionContext.Variables.Public);

            // Use LogMessage to ensure that the logs reach the TWA UI, but don't spam the console cmd window
            executionContext.Output(StringUtil.Loc("RMEnvironmentVariablesAvailable", stringifiedEnvironmentVariables));
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:8,代码来源:ReleaseJobExtension.cs

示例14: CleanUpArtifactsFolder

 private void CleanUpArtifactsFolder(IExecutionContext executionContext, string artifactsWorkingFolder)
 {
     Trace.Entering();
     executionContext.Output(StringUtil.Loc("RMCleaningArtifactsDirectory", artifactsWorkingFolder));
     try
     {
         IOUtil.DeleteDirectory(artifactsWorkingFolder, executionContext.CancellationToken);
     }
     catch (Exception ex)
     {
         Trace.Error(ex);
         // Do not throw here
     }
     finally
     {
         executionContext.Output(StringUtil.Loc("RMCleanedUpArtifactsDirectory", artifactsWorkingFolder));
     }
 }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:18,代码来源:ReleaseJobExtension.cs

示例15: ProcessPublishCodeCoverageCommand

        private void ProcessPublishCodeCoverageCommand(IExecutionContext context, Dictionary<string, string> eventProperties)
        {
            ArgUtil.NotNull(context, nameof(context));

            _buildId = context.Variables.Build_BuildId ?? -1;
            if (!IsHostTypeBuild(context) || _buildId < 0)
            {
                //In case the publishing codecoverage is not applicable for current Host type we continue without publishing
                context.Warning(StringUtil.Loc("CodeCoveragePublishIsValidOnlyForBuild"));
                return;
            }

            LoadPublishCodeCoverageInputs(eventProperties);

            string project = context.Variables.System_TeamProject;

            long? containerId = context.Variables.Build_ContainerId;
            ArgUtil.NotNull(containerId, nameof(containerId));

            Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty;
            ArgUtil.NotEmpty(projectId, nameof(projectId));

            //step 1: read code coverage summary
            var reader = GetCodeCoverageSummaryReader(_codeCoverageTool);
            context.Output(StringUtil.Loc("ReadingCodeCoverageSummary", _summaryFileLocation));
            var coverageData = reader.GetCodeCoverageSummary(context, _summaryFileLocation);

            if (coverageData == null || coverageData.Count() == 0)
            {
                context.Warning(StringUtil.Loc("CodeCoverageDataIsNull"));
            }

            Client.VssConnection connection = WorkerUtilies.GetVssConnection(context);
            var codeCoveragePublisher = HostContext.GetService<ICodeCoveragePublisher>();
            codeCoveragePublisher.InitializePublisher(_buildId, connection);

            var commandContext = HostContext.CreateService<IAsyncCommandContext>();
            commandContext.InitializeCommandContext(context, StringUtil.Loc("PublishCodeCoverage"));
            commandContext.Task = PublishCodeCoverageAsync(context, commandContext, codeCoveragePublisher, coverageData, project, projectId, containerId.Value, context.CancellationToken);
            context.AsyncCommands.Add(commandContext);
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:41,代码来源:CodeCoverageCommands.cs


注:本文中的IExecutionContext.Output方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。