Exemplo n.º 1
0
        private void CopySolutionFile(RelativePath solutionFileRelative = null)
        {
            var solutionDirectory = TestOutputDirectory / (solutionFileRelative ?? string.Empty);

            FileSystemTasks.EnsureExistingDirectory(solutionDirectory);
            File.WriteAllText(solutionDirectory / "Dummy.sln",
                              @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2036
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary1"", ""ClassLibrary1\ClassLibrary1.csproj"", ""{3B8A39C0-EB3C-42F7-8880-F9C2F7F8852A}""
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{3B8A39C0-EB3C-42F7-8880-F9C2F7F8852A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{3B8A39C0-EB3C-42F7-8880-F9C2F7F8852A}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{3B8A39C0-EB3C-42F7-8880-F9C2F7F8852A}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{3B8A39C0-EB3C-42F7-8880-F9C2F7F8852A}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {C58E3D98-D10A-40C6-B6AB-517BCCD785AD}
	EndGlobalSection
EndGlobal
",
                              Encoding.UTF8);
        }
Exemplo n.º 2
0
        public void OnBuildCreated(NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets)
        {
            var accessToken         = EnvironmentInfo.GetParameter <string>(nameof(EnterpriseAccessToken));
            var enterpriseDirectory = ((Build)build).ExternalRepositoriesDirectory / "enterprise";

            if (accessToken.IsNullOrEmpty())
            {
                var enterpriseProjectDirectory = enterpriseDirectory / "src" / "Nuke.Enterprise";
                FileSystemTasks.EnsureExistingDirectory(enterpriseProjectDirectory);
                File.WriteAllText(
                    enterpriseProjectDirectory / "Nuke.Enterprise.csproj",
                    @"
<Project Sdk=""Microsoft.NET.Sdk"">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <IsPackable>False</IsPackable>
  </PropertyGroup>

</Project>
");
                return;
            }

            var url = $"https://{accessToken}@github.com/nuke-build/enterprise";

            GitTasks.Git($"clone {url} {enterpriseDirectory}", logOutput: false, logInvocation: false);

            Logger.Info("Restarting with Nuke.Enterprise integration...");
            var arguments = Environment.CommandLine.Split(' ').Skip(1).JoinSpace();
            var process   = Process.Start(DotNetTasks.DotNetPath, $"run --project {BuildProjectFile} -- {arguments}");

            process.NotNull().WaitForExit();
            Environment.Exit(process.ExitCode);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Run the coverage tool
        /// </summary>
        /// <returns></returns>
        protected override StageCompletionStatusEnum ExecuteProcess()
        {
            if (!CISession.SlugCIConfigObj.UseCodeCoverage)
            {
                Logger.Info("Code Coverage is not enabled for this solution.");
                return(StageCompletionStatusEnum.Skipped);
            }

            FileSystemTasks.EnsureExistingDirectory(CISession.CoveragePath);
            ReportGeneratorSettings settings = new ReportGeneratorSettings()
            {
                ProcessWorkingDirectory = CISession.CoveragePath,
                TargetDirectory         = CISession.CoveragePath,
                ProcessToolPath         = "reportgenerator",
                ReportsInternal         = new List <string>()
                {
                    "coverage.cobertura.xml"
                },
                ReportTypesInternal = new List <ReportTypes>()
                {
                    ReportTypes.Badges,
                    ReportTypes.HtmlInline
                },
            };

            AbsolutePath   coverageFile   = CISession.CoveragePath / "index.html";
            SlugCmdProcess slugCmdProcess = new SlugCmdProcess("Code Coverage", SlugCmdProcess.GetDefaultProcessSettings());

            Process.Start(@"cmd.exe ", @"/c " + coverageFile);

            // TODO Await completion

            return(StageCompletionStatusEnum.Success);
        }
Exemplo n.º 4
0
        public static void GenerateCode(
            IReadOnlyCollection <string> specificationFiles,
            string baseDirectory,
            bool useNestedNamespaces,
            [CanBeNull] string baseNamespace,
            [CanBeNull] GitRepository repository)
        {
            foreach (var specificationFile in specificationFiles)
            {
                var tool = ToolSerializer.Load(specificationFile);
                // for formatting and ordering of properties
                ToolSerializer.Save(tool);
                ApplyRuntimeInformation(tool, repository);

                var generationDirectory = useNestedNamespaces ? Path.Combine(baseDirectory, tool.Name) : baseDirectory;
                var generationFile      = Path.Combine(generationDirectory, $"{Path.GetFileNameWithoutExtension(tool.DefinitionFile)}.Generated.cs");
                FileSystemTasks.EnsureExistingDirectory(generationDirectory);

                var @namespace =
                    !useNestedNamespaces
                        ? baseNamespace
                        : string.IsNullOrEmpty(baseNamespace)
                            ? tool.Name
                            : $"{baseNamespace}.{tool.Name}";

                using (var fileStream = File.Open(generationFile, FileMode.Create))
                    using (var streamWriter = new StreamWriter(fileStream))
                    {
                        ToolGenerator.Run(tool, @namespace, streamWriter);
                    }

                Logger.Info($"Generated code from '{Path.GetFileName(tool.DefinitionFile)}'.");
            }
        }
Exemplo n.º 5
0
        private void AssertOutput()
        {
            FileSystemTasks.EnsureExistingDirectory(ApprovalDirectory);
            var oldFiles = Directory.GetFiles(ApprovalDirectory, "*.tmp");

            foreach (var oldFile in oldFiles)
            {
                File.Delete(oldFile);
            }

            var fixFiles = new List <string>();
            var builder  = new StringBuilder();

            var enumerable = Directory.GetFiles(TestOutputDirectory, "*", SearchOption.AllDirectories);

            foreach (var file in enumerable)
            {
                var fileName     = Path.GetFileName(file);
                var approvalFile = ApprovalDirectory / (fileName + ".gold");
                var tempFile     = Path.ChangeExtension(approvalFile, "tmp").NotNull();
                File.Move(file, tempFile);

                string fixFile = null;
                if (!File.Exists(approvalFile))
                {
                    fixFile = CreateMoveScript(approvalFile, tempFile);
                    builder.AppendLine($"{fileName} COPY {fixFile}");
                }
                else if (!File.ReadAllText(approvalFile).Equals(File.ReadAllText(tempFile)))
                {
                    fixFile = CreateMoveScript(approvalFile, tempFile);
                    builder.AppendLine($"{fileName} COPY {fixFile}");
                    builder.AppendLine($"{fileName} COMPARE {CreateRiderComparisonScript(approvalFile, tempFile)}");
                }
                else
                {
                    File.Delete(tempFile);
                }

                if (fixFile != null)
                {
                    fixFiles.Add(fixFile);
                }
            }

            if (fixFiles.Count > 0)
            {
                TestOutputHelper.WriteLine($"COPY ALL {CreateCompositeScript(fixFiles)}");
            }

            TestOutputHelper.WriteLine(builder.ToString());

            Assert.True(fixFiles.Count == 0);
        }
Exemplo n.º 6
0
        public static void GenerateCode(Tool tool, string outputFile)
        {
            FileSystemTasks.EnsureExistingDirectory(Path.GetDirectoryName(outputFile));

            using (var fileStream = File.Open(outputFile, FileMode.Create))
                using (var streamWriter = new StreamWriter(fileStream))
                {
                    ToolGenerator.Run(tool, streamWriter);
                }

            Logger.Info($"Generated code for {tool.Name} from {Path.GetFileName(tool.SpecificationFile) ?? "<in-memory>"}.");
        }
Exemplo n.º 7
0
        private static void UncompressTar(string archiveFile, string directory, Func <Stream, Stream> inputStreamFactory)
        {
            using (var fileStream = File.OpenRead(archiveFile))
                using (var inputStream = inputStreamFactory(fileStream))
                    using (var tarArchive = TarArchive.CreateInputTarArchive(inputStream))
                    {
                        FileSystemTasks.EnsureExistingDirectory(directory);

                        tarArchive.ExtractContents(directory);
                    }

            Logger.Log($"Uncompressed '{archiveFile}' to '{directory}'.");
        }
Exemplo n.º 8
0
        static NukeBuild()
        {
            RootDirectory      = GetRootDirectory();
            TemporaryDirectory = GetTemporaryDirectory(RootDirectory);
            FileSystemTasks.EnsureExistingDirectory(TemporaryDirectory);

            BuildAssemblyDirectory = GetBuildAssemblyDirectory();
            BuildProjectFile       = GetBuildProjectFile(BuildAssemblyDirectory);
            BuildProjectDirectory  = BuildProjectFile?.Parent;

            Verbosity           = EnvironmentInfo.GetParameter <Verbosity?>(() => Verbosity) ?? Verbosity.Normal;
            Host                = EnvironmentInfo.GetParameter(() => Host) ?? Host.Default;
            LoadedLocalProfiles = EnvironmentInfo.GetParameter(() => LoadedLocalProfiles) ?? new string[0];
        }
Exemplo n.º 9
0
        static NukeBuild()
        {
            RootDirectory      = GetRootDirectory();
            TemporaryDirectory = GetTemporaryDirectory(RootDirectory);
            FileSystemTasks.EnsureExistingDirectory(TemporaryDirectory);
            BuildAssemblyDirectory = GetBuildAssemblyDirectory();
            BuildProjectDirectory  = GetBuildProjectDirectory(BuildAssemblyDirectory);

            Verbosity = ParameterService.Instance.GetParameter <Verbosity?>(() => Verbosity) ?? Verbosity.Normal;
            Host      = ParameterService.Instance.GetParameter <HostType?>(() => Host) ?? GetHostType();
            Continue  = ParameterService.Instance.GetParameter(() => Continue);
            Plan      = ParameterService.Instance.GetParameter(() => Plan);
            Help      = ParameterService.Instance.GetParameter(() => Help);
        }
Exemplo n.º 10
0
        static NukeBuild()
        {
            RootDirectory      = GetRootDirectory();
            TemporaryDirectory = GetTemporaryDirectory(RootDirectory);
            FileSystemTasks.EnsureExistingDirectory(TemporaryDirectory);
            BuildAssemblyDirectory = GetBuildAssemblyDirectory();
            BuildProjectDirectory  = GetBuildProjectDirectory(BuildAssemblyDirectory);

            Verbosity = EnvironmentInfo.GetParameter <Verbosity?>(() => Verbosity) ?? Verbosity.Normal;
            Host      = EnvironmentInfo.GetParameter <HostType?>(() => Host) ?? GetHostType();
            Continue  = EnvironmentInfo.GetParameter(() => Continue);
            Plan      = EnvironmentInfo.GetParameter(() => Plan);
            Help      = EnvironmentInfo.GetParameter(() => Help);
            NoLogo    = EnvironmentInfo.GetParameter(() => NoLogo);
        }
Exemplo n.º 11
0
        static NukeBuild()
        {
            RootDirectory      = GetRootDirectory();
            TemporaryDirectory = RootDirectory / TemporaryDirectoryName;
            FileSystemTasks.EnsureExistingDirectory(TemporaryDirectory);
            BuildAssemblyDirectory = GetBuildAssemblyDirectory();
            BuildProjectDirectory  = GetBuildProjectDirectory(BuildAssemblyDirectory);

            InvokedTargets = ParameterService.Instance.GetParameter(() => InvokedTargets) ??
                             ParameterService.Instance.GetPositionalCommandLineArguments <string>(separator: TargetsSeparator.Single()) ??
                             new[] { BuildExecutor.DefaultTarget };
            SkippedTargets = ParameterService.Instance.GetParameter(() => SkippedTargets);

            Verbosity = ParameterService.Instance.GetParameter <Verbosity?>(() => Verbosity) ?? Verbosity.Normal;
            Host      = ParameterService.Instance.GetParameter <HostType?>(() => Host) ?? GetHostType();
            Graph     = ParameterService.Instance.GetParameter(() => Graph);
            Help      = ParameterService.Instance.GetParameter(() => Help);
        }
Exemplo n.º 12
0
        static NukeBuild()
        {
            RootDirectory      = GetRootDirectory();
            TemporaryDirectory = GetTemporaryDirectory(RootDirectory);
            FileSystemTasks.EnsureExistingDirectory(TemporaryDirectory);
            BuildAssemblyDirectory = GetBuildAssemblyDirectory();
            BuildProjectFile       = GetBuildProjectFile(BuildAssemblyDirectory);
            BuildProjectDirectory  = BuildProjectFile?.Parent;

            Verbosity = EnvironmentInfo.GetParameter <Verbosity?>(() => Verbosity) ?? Verbosity.Normal;
            Host      = EnvironmentInfo.GetParameter <HostType?>(() => Host) ?? GetHostType();
            Continue  = EnvironmentInfo.GetParameter(() => Continue);
            Plan      = EnvironmentInfo.GetParameter(() => Plan);
            Help      = EnvironmentInfo.GetParameter(() => Help);
            NoLogo    = EnvironmentInfo.GetParameter(() => NoLogo);

            // LoadedProfiles = BuildProfileManagementAttributeBase.GetLoadProfiles();
            // SaveProfile = BuildProfileManagementAttributeBase.GetSaveProfile();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Run Unit Test Runner Process
        /// </summary>
        /// <returns></returns>
        protected override StageCompletionStatusEnum ExecuteProcess()
        {
            if (CISession.SkipTests)
            {
                return(StageCompletionStatusEnum.Skipped);
            }

            FileSystemTasks.EnsureExistingDirectory(CISession.CoveragePath);

            DotNetTestSettings settings = new DotNetTestSettings()
            {
                ProjectFile                 = CISession.Solution,
                Configuration               = CISession.CompileConfig,
                NoRestore                   = true,
                NoBuild                     = true,
                Verbosity                   = DotNetVerbosity.Minimal,
                ProcessLogOutput            = true,
                ResultsDirectory            = CISession.TestOutputPath,
                ProcessArgumentConfigurator = arguments => arguments.Add("/p:CollectCoverage={0}", true)
                                              .Add("", false)
                                              .Add("/p:CoverletOutput={0}/", CISession.CoveragePath)
                                              .Add("/p:CoverletOutputFormat={0}", "cobertura")
                                              .Add("/p:Threshold={0}", CISession.SlugCIConfigObj.CodeCoverageThreshold)
                                              .Add("/p:SkipAutoProps={0}", true)
                                              .Add("/p:ExcludeByAttribute={0}",
                                                   "\"Obsolete%2cGeneratedCodeAttribute%2cCompilerGeneratedAttribute\"")
                                              .Add("/p:UseSourceLink={0}", true)
            };


            (BlockingCollection <ILineOut> outputs, int exitCode) = DotNetTest(settings);
            StageOutput.AddRange(outputs);
            if (exitCode > 0 && CISession.FailedUnitTestsOkay)
            {
                AOT_Warning("One or more unit tests failed.  HOWEVER, the Failed Unit Tests Okay flag was set, so this is not stopping the CI process");
                return(StageCompletionStatusEnum.Warning);
            }

            return(StageCompletionStatusEnum.Success);
        }
Exemplo n.º 14
0
        private void ExecuteSetup(
            RelativePath setupDirectoryRelative = null,
            int?solutionChoice            = null,
            TargetPlatform targetPlatform = TargetPlatform.Core,
            ProjectFormat projectFormat   = ProjectFormat.Sdk,
            string nugetVersion           = null,
            string nukeVersion            = null,
            string buildDirectoryName     = null,
            string buildProjectName       = null)
        {
            var bootstrappingDirectory = RootDirectory / "bootstrapping";
            var setupFileName          = EnvironmentInfo.IsWin ? "setup.ps1" : "setup.sh";
            var workingDirectory       = TestOutputDirectory / (setupDirectoryRelative ?? string.Empty);

            FileSystemTasks.EnsureExistingDirectory(workingDirectory);
            var setupFileAbsolute = workingDirectory / setupFileName;

            var bootstrappingUri = EnvironmentInfo.IsWin ? new Uri(bootstrappingDirectory).AbsoluteUri : $"file://{bootstrappingDirectory}";
            var content          = File.ReadAllText(bootstrappingDirectory / setupFileName)
                                   .Replace("https://raw.githubusercontent.com/nuke-build/nuke/master/bootstrapping", bootstrappingUri)
                                   .Replace("[guid]::NewGuid().ToString().ToUpper()", "99351CF7-E7C8-45AE-8A5B-E3E964AC5F12".DoubleQuote())
                                   .Replace("$(python -c \"import uuid; print str(uuid.uuid4()).upper()\")", "99351CF7-E7C8-45AE-8A5B-E3E964AC5F12".DoubleQuote())
                                   .ReplaceRegex("\\$NukeVersion = \\$\\(Invoke.*", x => "$NukeVersion = \"1.3.3.7\"")
                                   .ReplaceRegex("NUKE_VERSION=\\$\\(curl.*", x => "NUKE_VERSION=\"1.3.3.7\"");

            File.WriteAllText(setupFileAbsolute, content);

            TestOutputHelper.WriteLine("Starting setup script...");
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = EnvironmentInfo.IsWin ? "powershell" : "bash",
                    Arguments              = setupFileAbsolute,
                    WorkingDirectory       = workingDirectory,
                    UseShellExecute        = false,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true
                }
            };

            process.OutputDataReceived += (s, e) =>
            {
                Logger.Log(e.Data);
                TestOutputHelper.WriteLine("STD: " + e.Data);
            };
            process.ErrorDataReceived += (s, e) =>
            {
                Logger.Error(e.Data);
                TestOutputHelper.WriteLine("ERR: " + e.Data);
            };
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            if (solutionChoice.HasValue)
            {
                process.StandardInput.WriteLine(solutionChoice.Value);
            }

            process.StandardInput.WriteLine(EnvironmentInfo.IsWin
                ? targetPlatform == TargetPlatform.Framework ? "F" : "C"
                : ((int)targetPlatform).ToString());

            if (targetPlatform == TargetPlatform.Framework)
            {
                process.StandardInput.WriteLine(EnvironmentInfo.IsWin
                    ? projectFormat == ProjectFormat.Legacy ? "L" : "S"
                    : ((int)projectFormat).ToString());

                process.StandardInput.WriteLine(nugetVersion);
            }

            if (targetPlatform == TargetPlatform.Core || projectFormat == ProjectFormat.Sdk)
            {
                process.StandardInput.WriteLine(nukeVersion);
            }

            process.StandardInput.WriteLine(buildDirectoryName);
            process.StandardInput.WriteLine(buildProjectName);

            process.WaitForExit();
            Trace.Assert(process.ExitCode == 0);

            File.WriteAllText(TestOutputDirectory / "structure.txt",
                              Directory.GetFiles(TestOutputDirectory, "*", SearchOption.AllDirectories)
                              .Select(x => GetRelativePath(TestOutputDirectory, x).Replace(oldChar: '\\', newChar: '/'))
                              .OrderBy(x => x.Length)
                              .ThenBy(x => x).JoinNewLine(PlatformFamily.Windows));
        }
Exemplo n.º 15
0
 public void Generate(AbsolutePath dir)
 {
     FileSystemTasks.EnsureExistingDirectory(dir);
     File.WriteAllText(dir / "nuget.config", this.ToXml());
 }