private static void FillTemplateDirectoryRecursivelyInternal( DirectoryInfo directory, [CanBeNull] IReadOnlyCollection<string> definitions, [CanBeNull] IReadOnlyDictionary<string, string> replacements, [CanBeNull] Func<DirectoryInfo, bool> excludeDirectory, [CanBeNull] Func<FileInfo, bool> excludeFile = null) { if (excludeDirectory != null && excludeDirectory(directory)) return; bool ShouldMove(FileSystemInfo info) => replacements?.Keys.Any(x => info.Name.Contains(x)) ?? false; foreach (var file in directory.GetFiles()) { if (excludeFile != null && excludeFile(file)) continue; FillTemplateFile(file.FullName, definitions, replacements); if (ShouldMove(file)) FileSystemTasks.RenameFile(file.FullName, file.Name.Replace(replacements), FileExistsPolicy.OverwriteIfNewer); } directory.GetDirectories() .ForEach(x => FillTemplateDirectoryRecursivelyInternal(x, definitions, replacements, excludeDirectory, excludeFile)); if (ShouldMove(directory)) { FileSystemTasks.RenameDirectory( directory.FullName, directory.Name.Replace(replacements), DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer); } }
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)}'."); } }
/// <summary> /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>. /// </summary> public static GitRepository FromLocalDirectory(string directory, string branch = null, string remote = "origin") { var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any()); ControlFlow.Assert(rootDirectory != null, $"Could not find root directory for '{directory}'."); var gitDirectory = Path.Combine(rootDirectory, ".git"); var headFile = Path.Combine(gitDirectory, "HEAD"); ControlFlow.Assert(File.Exists(headFile), $"File.Exists({headFile})"); var headFileContent = File.ReadAllLines(headFile); var head = headFileContent.First(); var branchMatch = Regex.Match(head, "^ref: refs/heads/(?<branch>.*)"); var configFile = Path.Combine(gitDirectory, "config"); var configFileContent = File.ReadAllLines(configFile); var url = configFileContent .Select(x => x.Trim()) .SkipWhile(x => x != $"[remote \"{remote}\"]") .Skip(count: 1) .TakeWhile(x => !x.StartsWith("[")) .SingleOrDefault(x => x.StartsWithOrdinalIgnoreCase("url = ")) ?.Split('=')[1]; ControlFlow.Assert(url != null, $"Could not parse remote URL for '{remote}'."); var(endpoint, identifier) = ParseUrl(url); return(new GitRepository( endpoint, identifier, rootDirectory, head, branch ?? (branchMatch.Success ? branchMatch.Groups["branch"].Value : null))); }
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); }
public static int Setup(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript) { PrintInfo(); Logging.Configure(); Telemetry.SetupBuild(); AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[bold]Let's setup a new build![/]"); AnsiConsole.WriteLine(); #region Basic var nukeLatestReleaseVersion = NuGetPackageResolver.GetLatestPackageVersion(NukeCommonPackageId, includePrereleases: false); var nukeLatestPrereleaseVersion = NuGetPackageResolver.GetLatestPackageVersion(NukeCommonPackageId, includePrereleases: true); var nukeLatestLocalVersion = NuGetPackageResolver.GetGlobalInstalledPackage(NukeCommonPackageId, version: null, packagesConfigFile: null) ?.Version.ToString(); if (rootDirectory == null) { var rootDirectoryItems = new[] { ".git", ".svn" }; rootDirectory = (AbsolutePath)FileSystemTasks.FindParentDirectory( WorkingDirectory, x => rootDirectoryItems.Any(y => x.GetFileSystemInfos(y, SearchOption.TopDirectoryOnly).Any())); } if (rootDirectory == null) { Host.Warning("Could not find root directory. Falling back to working directory ..."); rootDirectory = WorkingDirectory; } ShowInput("deciduous_tree", "Root directory", rootDirectory); var targetPlatform = !GetParameter <bool>("boot") ? PLATFORM_NETCORE : PromptForChoice("What runtime should be used?", (PLATFORM_NETCORE, ".NET Core SDK"), (PLATFORM_NETFX, ".NET Framework/Mono")); var targetFramework = targetPlatform == PLATFORM_NETFX ? FRAMEWORK_NETFX : FRAMEWORK_NETCORE; var projectFormat = targetPlatform == PLATFORM_NETCORE ? FORMAT_SDK : PromptForChoice("What project format should be used?", (FORMAT_SDK, "SDK-based Format: requires .NET Core SDK"), (FORMAT_LEGACY, "Legacy Format: supported by all MSBuild/Mono versions")); ShowInput("nut_and_bolt", "Build runtime", $"{(targetPlatform == PLATFORM_NETCORE ? ".NET" : ".NET Framework")} ({targetFramework})"); var buildProjectName = PromptForInput("How should the project be named?", "_build"); ClearPreviousLine(); ShowInput("bookmark", "Build project name", buildProjectName); var buildProjectRelativeDirectory = PromptForInput("Where should the project be located?", "./build"); ClearPreviousLine(); ShowInput("round_pushpin", "Build project location", buildProjectRelativeDirectory); var nukeVersion = PromptForChoice("Which Nuke.Common version should be used?", new[]
/// <summary> /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>. /// </summary> public static GitRepository FromLocalDirectory(string directory) { var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any()); var gitDirectory = Path.Combine(rootDirectory.NotNull($"No parent Git directory for '{directory}'"), ".git"); var head = GetHead(gitDirectory); var branch = (GetBranchFromCI() ?? GetHeadIfAttached(head))?.TrimStart("refs/heads/").TrimStart("origin/"); var commit = GetCommitFromCI() ?? GetCommitFromHead(gitDirectory, head); var tags = GetTagsFromCommit(gitDirectory, commit); var(remoteName, remoteBranch) = GetRemoteNameAndBranch(gitDirectory, branch); var(protocol, endpoint, identifier) = GetRemoteConnectionFromConfig(gitDirectory, remoteName ?? FallbackRemoteName); return(new GitRepository( protocol, endpoint, identifier, branch, rootDirectory, head, commit, tags, remoteName, remoteBranch)); }
private bool HasConfigurationChanged(IConfigurationGenerator generator) { generator.GeneratedFiles.ForEach(FileSystemTasks.EnsureExistingParentDirectory); var previousHashes = generator.GeneratedFiles .Where(File.Exists) .ToDictionary(x => x, FileSystemTasks.GetFileHash); var assembly = Assembly.GetEntryAssembly().NotNull("assembly != null"); ProcessTasks.StartProcess( assembly.Location, $"--{ConfigurationParameterName} {generator.Id} --host {generator.HostName}", logInvocation: false, logOutput: true) .AssertZeroExitCode(); var changedFiles = generator.GeneratedFiles .Where(x => FileSystemTasks.GetFileHash(x) != previousHashes.GetValueOrDefault(x)) .Select(x => NukeBuild.RootDirectory.GetRelativePathTo(x)).ToList(); if (changedFiles.Count == 0) { return(false); } Logger.Warn($"{generator.DisplayName} configuration files have changed."); changedFiles.ForEach(x => Logger.Trace($"Updated {x}")); return(true); }
/// <summary> /// Copies from the compiled directory to the publish directory with the version as the last folder for Visual Studio projects.. /// </summary> private void Publish_Copy_VS() { AOT_Normal("Publishing Visual Studio Projects"); foreach (SlugCIProject project in CISession.Projects) { if (project.Deploy != SlugCIDeployMethod.Copy) { continue; } // Each framework needs to be copied. foreach (string item in project.Frameworks) { project.Results.PublishedSuccess = false; AbsolutePath destFolder = BuildDestinationFolderLayout_VS(project, item); AbsolutePath srcFolder = project.VSProject.Directory / "bin" / CISession.CompileConfig / item; FileSystemTasks.CopyDirectoryRecursively(srcFolder, destFolder, DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer); AOT_Success("Copied: " + project.Name + " to Deployment folder: " + destFolder); } SetInprocessStageStatus(StageCompletionStatusEnum.Success); project.Results.PublishedSuccess = true; } }
/// <summary> /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>. /// </summary> public static GitRepository FromLocalDirectory(string directory) { var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any()); ControlFlow.Assert(rootDirectory != null, $"Could not find git directory for '{directory}'."); var gitDirectory = Path.Combine(rootDirectory, ".git"); var head = GetHead(gitDirectory); var branch = ((Host.Instance as IBuildServer)?.Branch ?? GetHeadIfAttached(head))?.TrimStart("refs/heads/").TrimStart("origin/"); var commit = (Host.Instance as IBuildServer)?.Commit ?? GetCommitFromHead(gitDirectory, head); var tags = GetTagsFromCommit(gitDirectory, commit); var(remoteName, remoteBranch) = GetRemoteNameAndBranch(gitDirectory, branch); var(protocol, endpoint, identifier) = GetRemoteConnectionFromConfig(gitDirectory, remoteName ?? FallbackRemoteName); return(new GitRepository( protocol, endpoint, identifier, branch, rootDirectory, head, commit, tags, remoteName, remoteBranch)); }
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); }
public TestsSetup() { ToolPathResolver.NuGetPackagesConfigFile = NukeBuild.RootDirectory / "tests" / "NMica.Tests" / "NMica.Tests.csproj"; // var userFolder = (AbsolutePath)Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var nugetCacheFolder = userFolder / ".nuget" / "packages"; return; // var nbgvDll = nugetCacheFolder / "nbgv" / "3.0.50" / "tools" / "netcoreapp2.1" / "any" / "nbgv.dll"; // // Console.WriteLine(ToolPathResolver.NuGetPackagesConfigFile); // Console.WriteLine(NukeBuild.RootDirectory); // if (File.Exists(nbgvDll)) // this is faster then letting tool resolver figure out where it lives // { // Console.WriteLine(nbgvDll); // // Environment.SetEnvironmentVariable("NERDBANKGITVERSIONING_EXE",nbgvDll); // } try { FileSystemTasks.DeleteDirectory(nugetCacheFolder / "NMica" / NMicaVersion.NuGetPackageVersion); } catch (UnauthorizedAccessException) { // something dumb is keeping locks on nuget cache between runs. this is a DIRTY hack to try to release any locks on that folder foreach (var process in Process.GetProcesses() .Where(x => x.ProcessName == "dotnet" && x.Id != Process.GetCurrentProcess().Id)) { process.Kill(true); } FileSystemTasks.DeleteDirectory(nugetCacheFolder / "NMica" / NMicaVersion.NuGetPackageVersion); } }
/// <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); }
public void OnAfterLogo( NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets, IReadOnlyCollection <ExecutableTarget> executionPlan) { if (!AutoGenerate || NukeBuild.IsServerBuild) { return; } Logger.LogLevel = LogLevel.Trace; var previousHashes = GeneratedFiles .Where(File.Exists) .ToDictionary(x => x, FileSystemTasks.GetFileHash); var assembly = Assembly.GetEntryAssembly().NotNull("assembly != null"); ProcessTasks.StartProcess( assembly.Location, $"--{ConfigurationParameterName} --host {HostType}", logInvocation: false, logOutput: true) .AssertZeroExitCode(); var changedFiles = GeneratedFiles .Where(x => FileSystemTasks.GetFileHash(x) != previousHashes.GetValueOrDefault(x)) .Select(x => GetRelativePath(NukeBuild.RootDirectory, x)).ToList(); if (changedFiles.Count > 0) { Logger.Warn($"{HostType} configuration files have changed."); changedFiles.ForEach(x => Logger.Trace($"Updated {x}")); } }
private static PathConstruction.AbsolutePath GetRootDirectory() { var parameterValue = ParameterService.Instance.GetParameter(() => RootDirectory); if (parameterValue != null) { return(parameterValue); } if (ParameterService.Instance.GetParameter <bool>(() => RootDirectory)) { return((PathConstruction.AbsolutePath)EnvironmentInfo.WorkingDirectory); } var rootDirectory = (PathConstruction.AbsolutePath)FileSystemTasks.FindParentDirectory( EnvironmentInfo.WorkingDirectory, x => x.GetFiles(ConfigurationFileName).Any()); ControlFlow.Assert(rootDirectory != null, new[] { $"Could not locate '{ConfigurationFileName}' file while walking up from '{EnvironmentInfo.WorkingDirectory}'.", "Either create the file to mark the root directory, or use the --root parameter." }.JoinNewLine()); return(rootDirectory); }
private static void PreProcess(ref CleanupCodeSettings toolSettings) { var installedPlugins = GetInstalledPlugins(); if (installedPlugins.Count == 0 && toolSettings.Extensions.Count == 0) { return; } var shadowDirectory = GetShadowDirectory(installedPlugins); FileSystemTasks.CopyDirectoryRecursively( Path.GetDirectoryName(toolSettings.ToolPath).NotNull(), shadowDirectory, DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer ); installedPlugins.Select(x => x.FileName) .ForEach(x => File.Copy(x, Path.Combine(shadowDirectory, Path.GetFileName(x).NotNull()), true)); toolSettings.Extensions.ForEach( x => HttpTasks.HttpDownloadFile( $"https://resharper-plugins.jetbrains.com/api/v2/package/{x}", Path.Combine(shadowDirectory, $"{x}.nupkg") ) ); }
static partial void PreProcess(InspectCodeSettings toolSettings) { var installedPlugins = GetInstalledPlugins(); if (installedPlugins.Count == 0 && toolSettings.Extensions.Count == 0) { return; } var shadowDirectory = GetShadowDirectory(toolSettings, installedPlugins); FileSystemTasks.CopyRecursively( Path.GetDirectoryName(toolSettings.ToolPath).NotNull(), shadowDirectory, FileSystemTasks.FileExistsPolicy.OverwriteIfNewer); installedPlugins.Select(x => x.FileName) .ForEach(x => File.Copy(x, Path.Combine(shadowDirectory, Path.GetFileName(x).NotNull()), overwrite: true)); #if !NETCORE toolSettings.Extensions.ForEach(x => HttpTasks.HttpDownloadFile( $"https://resharper-plugins.jetbrains.com/api/v2/package/{x}", Path.Combine(shadowDirectory, $"{x}.nupkg"))); #else ControlFlow.Assert(toolSettings.Extensions.Count == 0, "InspectCodeSettings.Extensions is currently not supported on .NET Core. However, after adding the ReSharper gallery feed " + "(https://resharper-plugins.jetbrains.com/api/v2), you can reference them as normal NuGet packages in your project file."); #endif }
private bool HasConfigurationChanged(IConfigurationGenerator generator, NukeBuild build) { generator.GeneratedFiles.ForEach(FileSystemTasks.EnsureExistingParentDirectory); var previousHashes = generator.GeneratedFiles .Where(File.Exists) .ToDictionary(x => x, FileSystemTasks.GetFileHash); ProcessTasks.StartProcess( NukeBuild.BuildAssemblyFile, $"--{ConfigurationParameterName} {generator.Id} --host {generator.HostName}", logInvocation: false, logOutput: false) .AssertZeroExitCode(); var changedFiles = generator.GeneratedFiles .Where(x => FileSystemTasks.GetFileHash(x) != previousHashes.GetValueOrDefault(x)) .Select(x => NukeBuild.RootDirectory.GetRelativePathTo(x)).ToList(); if (changedFiles.Count == 0) { return(false); } Telemetry.ConfigurationGenerated(generator.HostType, generator.Id, build); // TODO: multi-line logging Log.Warning("Configuration files for {Configuration} have changed.", generator.DisplayName); changedFiles.ForEach(x => Log.Verbose("Updated {File}", x)); return(true); }
public CustomFileWriter(string filename, int indentationFactor, FileMode fileMode = FileMode.Create) { FileSystemTasks.EnsureExistingParentDirectory(filename); _fileStream = File.Open(filename, fileMode); _streamWriter = new StreamWriter(_fileStream); _indentationFactor = indentationFactor; }
internal static AbsolutePath TryGetRootDirectoryFrom(string startDirectory, bool includeLegacy = true) { return((AbsolutePath)FileSystemTasks.FindParentDirectory( startDirectory, predicate: x => x.GetDirectories(NukeDirectoryName).Any() || includeLegacy && x.GetFiles(NukeFileName).Any())); }
private static void Handle(string[] args) { var rootDirectory = FileSystemTasks.FindParentDirectory( Directory.GetCurrentDirectory(), x => x.GetFiles(NukeBuild.ConfigurationFile).Any()); var hasCommand = args.FirstOrDefault()?.StartsWithOrdinalIgnoreCase(c_commandPrefix.ToString()) ?? false; if (hasCommand) { var command = args.First().Trim(trimChar: c_commandPrefix); if (string.IsNullOrWhiteSpace(command)) { ControlFlow.Fail($"No command specified. Usage is: nuke {c_commandPrefix}<command> [args]"); } var commandHandler = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(command)); ControlFlow.Assert(commandHandler != null, $"Command '{command}' is not supported."); try { commandHandler.Invoke(obj: null, parameters: new object[] { rootDirectory, args.Skip(count: 1).ToArray() }); return; } catch (TargetInvocationException ex) { ControlFlow.Fail(ex.InnerException.Message); } } var buildScript = rootDirectory != null ? new DirectoryInfo(rootDirectory) .EnumerateFiles($"build.{ScriptExtension}", maxDepth: 2) .FirstOrDefault()?.FullName.DoubleQuoteIfNeeded() : null; if (buildScript == null) { if (UserConfirms($"Could not find {NukeBuild.ConfigurationFile} file. Do you want to setup a build?")) { Setup(rootDirectory, new string[0]); } return; } // TODO: docker var arguments = args.Select(x => x.DoubleQuoteIfNeeded()).JoinSpace(); var process = Process.Start( ScriptHost, EnvironmentInfo.IsWin ? $"-ExecutionPolicy ByPass -NoProfile -File {buildScript} {arguments}" : $"{buildScript} {arguments}").NotNull(); process.WaitForExit(); Environment.Exit(process.ExitCode); }
/// <summary> /// Publish Angular projects /// </summary> private void Publish_Copy_Angular() { AOT_Normal("Publishing Angular Projects"); if (CISession.SkipAngularBuild) { AOT_Warning("All Angular Projects were skipped due to manually set argument."); } // Angular projects: We only support single app publishes per project. Angular NX supports more, we just don't have any examples at the moment. foreach (AngularProject project in CISession.SlugCIConfigObj.AngularProjects) { project.Results.PublishedSuccess = false; if (CISession.SkipAngularBuild) { continue; } // TODO - Replace "" with Angular Apps from dist folder AbsolutePath destFolder = BuildDestinationFolderName_Angular(project, ""); AbsolutePath angularDistPath = CISession.AngularDirectory / project.Name / "dist"; AbsolutePath angularAppsSubFolder = angularDistPath / "apps"; ControlFlow.Assert(Directory.Exists(angularDistPath), "Cannot find Angular dist folder. Has Angular app been compiled?"); AbsolutePath srcFolder = (AbsolutePath)"c:"; // Determine where the source distribution files are. This is either right in the dist folder OR there is a folder in dist called // "apps" with subfolders and the "web" is in each subfolder. if (!Directory.Exists(angularAppsSubFolder)) { srcFolder = angularDistPath; } else { List <string> dirNames = Directory.GetDirectories(angularAppsSubFolder).ToList(); ControlFlow.Assert(dirNames.Count > 0, "There are no compiled apps in the [" + angularAppsSubFolder + "]."); if (dirNames.Count == 1) { srcFolder = (AbsolutePath)dirNames [0]; } else { ControlFlow.Assert(dirNames.Count < 2, "There is more than 1 app in the folder [" + angularAppsSubFolder + "]. We can only handle 1 at this time."); } } FileSystemTasks.CopyDirectoryRecursively(srcFolder, destFolder, DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer); AOT_Success("Copied: " + project.Name + " to Deployment folder: " + destFolder); SetInprocessStageStatus(StageCompletionStatusEnum.Success); project.Results.PublishedSuccess = true; } }
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); }
private string WriteTextToDocusaurusPath(string path, string text) { string pathFromDocsSource = path.Replace($"{DocsSource}", ""); pathFromDocsSource = pathFromDocsSource.TrimStart("/"); var newPath = DocusaurusDocsPath / pathFromDocsSource; FileSystemTasks.EnsureExistingParentDirectory(newPath); File.WriteAllText(newPath, text); return(newPath); }
public IntegrationTestBase(ITestOutputHelper testOutputHelper) { TestOutputHelper = testOutputHelper; TestName = ((ITest)testOutputHelper.GetType() .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance).NotNull() .GetValue(testOutputHelper)).TestCase.TestMethod.Method.Name; FileSystemTasks.EnsureCleanDirectory(".tmp"); TestOutputDirectory = (AbsolutePath)Path.GetFullPath(".tmp"); Directory.CreateDirectory(TestOutputDirectory / ".git"); }
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>"}."); }
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}'."); }
private void CopyFileToArtifacts(AbsolutePath fullFileName) { var fileName = Path.GetFileName(fullFileName); if (string.IsNullOrEmpty(fileName)) { return; } var targetFile = Path.Combine(BuildInfo.ArtifactsDirectory, fileName); FileSystemTasks.CopyFile(fullFileName, targetFile, FileExistsPolicy.Overwrite); }
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); }
private static void Setup([CanBeNull] string rootDirectory, string[] args) { #region Basic var nukeLatestLocalVersion = NuGetPackageResolver.GetGlobalInstalledPackage("Nuke.Common", version: null)?.Version.ToString(); var nukeLatestReleaseVersion = NuGetPackageResolver.GetLatestPackageVersion("Nuke.Common", includePrereleases: false); var nukeLatestPrereleaseVersion = NuGetPackageResolver.GetLatestPackageVersion("Nuke.Common", includePrereleases: true); if (rootDirectory == null) { var rootDirectoryItems = new[] { ".git", ".svn" }; rootDirectory = FileSystemTasks.FindParentDirectory( EnvironmentInfo.WorkingDirectory, x => rootDirectoryItems.Any(y => x.GetFileSystemInfos(y, SearchOption.TopDirectoryOnly).Any())); } if (rootDirectory == null) { Logger.Warn("Could not find root directory. Falling back to working directory."); rootDirectory = EnvironmentInfo.WorkingDirectory; } var solutionFile = ConsoleHelper.PromptForChoice( "Which solution should be the default?", options: new DirectoryInfo(rootDirectory) .EnumerateFiles("*", SearchOption.AllDirectories) .Where(x => x.FullName.EndsWithOrdinalIgnoreCase(".sln")) .OrderByDescending(x => x.FullName) .Select(x => (x, GetRelativePath(rootDirectory, x.FullName))) .Concat((null, "None")).ToArray())?.FullName; var solutionDirectory = solutionFile != null?Path.GetDirectoryName(solutionFile) : null; var targetPlatform = ConsoleHelper.PromptForChoice("How should the build project be bootstrapped?", (PLATFORM_NETCORE, ".NET Core SDK"), (PLATFORM_NETFX, ".NET Framework/Mono")); var targetFramework = targetPlatform == PLATFORM_NETFX ? FRAMEWORK_NET461 : ConsoleHelper.PromptForChoice("What target framework should be used?", (FRAMEWORK_NETCOREAPP2, FRAMEWORK_NETCOREAPP2), (FRAMEWORK_NET461, FRAMEWORK_NET461)); var projectFormat = targetPlatform == PLATFORM_NETCORE ? FORMAT_SDK : ConsoleHelper.PromptForChoice("What format should the build project use?", (FORMAT_SDK, "SDK-based Format: requires .NET Core SDK"), (FORMAT_LEGACY, "Legacy Format: supported by all MSBuild/Mono versions")); var nukeVersion = ConsoleHelper.PromptForChoice("Which NUKE version should be used?", new[]
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]; }