Example #1
0
        protected override void OnExecute()
        {
            if (!Directory.Exists(_testProjectsBaseDirectory))
            {
                return;
            }

            var unitTestProjects = _testProjectsBaseDirectory.GlobFiles(_projectsPattern);

            var failedTests = new List <(string UnitTestProject, Exception Exception)>();

            foreach (var unitTestProject in unitTestProjects)
            {
                var projectName = Path.GetFileNameWithoutExtension(unitTestProject);

                var testResultFile = Path.Combine(_resultsDirectory, $"{projectName}.{_resultFileExt}");

                try
                {
                    var testSettings =
                        CreateTestSettings(unitTestProject, testResultFile);

                    DotNetTasks.DotNetTest(testSettings);
                }
                catch (Exception e)
                {
                    failedTests.Add((UnitTestProject: unitTestProject, Exception: e));
                }
            }

            if (failedTests.Any())
            {
                throw failedTests.First().Exception;
            }
        }
Example #2
0
        public static int AddPackage(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript)
        {
            PrintInfo();
            Logging.Configure();
            Telemetry.AddPackage();
            ProjectModelTasks.Initialize();

            var packageId      = args.ElementAt(0);
            var packageVersion =
                (EnvironmentInfo.GetParameter <string>("version") ??
                 args.ElementAtOrDefault(1) ??
                 NuGetPackageResolver.GetLatestPackageVersion(packageId, includePrereleases: false).GetAwaiter().GetResult() ??
                 NuGetPackageResolver.GetGlobalInstalledPackage(packageId, version: null, packagesConfigFile: null)?.Version.ToString())
                .NotNull("packageVersion != null");

            var configuration    = GetConfiguration(buildScript, evaluate: true);
            var buildProjectFile = configuration[BUILD_PROJECT_FILE];

            Host.Information($"Installing {packageId}/{packageVersion} to {buildProjectFile} ...");
            AddOrReplacePackage(packageId, packageVersion, PACKAGE_TYPE_DOWNLOAD, buildProjectFile);
            DotNetTasks.DotNet($"restore {buildProjectFile}");

            var installedPackage = NuGetPackageResolver.GetGlobalInstalledPackage(packageId, packageVersion, packagesConfigFile: null)
                                   .NotNull("installedPackage != null");
            var hasToolsDirectory = installedPackage.Directory.GlobDirectories("tools").Any();

            if (!hasToolsDirectory)
            {
                AddOrReplacePackage(packageId, packageVersion, PACKAGE_TYPE_REFERENCE, buildProjectFile);
            }

            Host.Information($"Done installing {packageId}/{packageVersion} to {buildProjectFile}");
            return(0);
        }
Example #3
0
 public void OnBuildFinished(NukeBuild build)
 {
     if (NukeBuild.IsServerBuild)
     {
         DotNetTasks.DotNet("build-server shutdown", logInvocation: EnableLogging, logOutput: EnableLogging);
     }
 }
 private void PushPackage(string package)
 {
     DotNetTasks.DotNetNuGetPush(x => x
                                 .SetTargetPath(package)
                                 .FluentIf(_source != null, config => config.SetSource(_source))
                                 .FluentIf(_apiKey != null, config => config.SetApiKey(_apiKey))
                                 .FluentIf(_symbolSource != null, config => config.SetSymbolSource(_symbolSource))
                                 .FluentIf(_symbolApiKey != null, config => config.SetSymbolApiKey(_symbolApiKey))
                                 );
 }
 protected override void OnExecute()
 {
     DotNetTasks.DotNetBuild(s => s
                             .SetProjectFile(BuildInfo.Solution)
                             .SetConfiguration(BuildInfo.Configuration)
                             .SetAssemblyVersion(BuildInfo.VersionInfo.GetAssemblySemVer())
                             .SetFileVersion(BuildInfo.VersionInfo.GetAssemblySemFileVer())
                             .SetInformationalVersion(BuildInfo.VersionInfo.InformationalVersion)
                             .EnableNoRestore());
 }
Example #6
0
        public virtual IProcess StartProcess(
            string toolPath,
            string executionArguments = null,
            string outputArguments    = null,
            string workingDirectory   = null,
            IReadOnlyDictionary <string, string> environmentVariables = null,
            int?timeout    = null,
            bool logOutput = true,
            Func <string, LogLevel> logLevelParser = null,
            Func <string, string> outputFilter     = null)
        {
            ControlFlow.Assert(toolPath != null, "ToolPath was not set.");
            if (!Path.IsPathRooted(toolPath) && !toolPath.Contains(Path.DirectorySeparatorChar))
            {
                toolPath = ToolPathResolver.GetPathExecutable(toolPath);
            }

#if NETCORE
            string toolPathOverride = null;
            if (toolPath.EndsWith(".dll"))
            {
                toolPathOverride = DotNetTasks.GetToolPath();
            }
            else if (EnvironmentInfo.IsUnix && toolPath.EndsWithOrdinalIgnoreCase(".exe"))
            {
                toolPathOverride = ToolPathResolver.GetPathExecutable("mono");
            }

            if (!string.IsNullOrEmpty(toolPathOverride))
            {
                executionArguments = $"{toolPath.DoubleQuoteIfNeeded()} {executionArguments}".TrimEnd();
                outputArguments    = $"{toolPath.DoubleQuoteIfNeeded()} {outputArguments}".TrimEnd();
                toolPath           = toolPathOverride;
            }
#endif

            outputArguments = outputArguments ?? (outputFilter == null ? executionArguments : outputFilter(executionArguments));
            ControlFlow.Assert(File.Exists(toolPath), $"ToolPath '{toolPath}' does not exist.");
            Logger.Info($"> {Path.GetFullPath(toolPath).DoubleQuoteIfNeeded()} {outputArguments}");

            return(StartProcessInternal(toolPath,
                                        executionArguments,
                                        workingDirectory,
                                        environmentVariables,
                                        timeout,
                                        logOutput,
                                        logLevelParser,
                                        outputFilter ?? (x => x)));
        }
        public void OnBuildFinished(NukeBuild build)
        {
            if (NukeBuild.Host != HostType)
            {
                return;
            }

            // Note https://github.com/dotnet/cli/issues/11424
            if (ShutdownDotNetBuildServer)
            {
                DotNetTasks.DotNet("build-server shutdown");
            }

            OnBuildFinishedInternal(build);
        }
Example #8
0
    /// <summary>
    ///     Parses a project file.
    /// </summary>
    /// <param name="projectFile">The project path.</param>
    /// <param name="configuration"></param>
    /// <param name="runtimeValue"></param>
    /// <returns>The parsed project.</returns>
    public ProjectParseResult Parse(string projectFile,
                                    string configuration,
                                    string runtimeValue)
    {
        // Get the project file.
        var pf = Path.GetTempFileName();

        try
        {
            DotNetTasks.DotNet($"msbuild -preprocess:{pf} {projectFile.DoubleQuoteIfNeeded()}");

            XDocument document = XDocument.Load(pf);

            if (document.Root == null)
            {
                throw new Exception(
                          "Silly error: The parser should never make the root element of a document into a null value");
            }

            var projectProperties = new Dictionary <string, string>();
            projectProperties.Add("Platform", runtimeValue);
            projectProperties.Add("Configuration", configuration);

            // Parsing the build file is sensitive to the declared order of elements.
            // If there are include files, then these files must be honored too.
            ParseProjectProperties(document, configuration, runtimeValue, projectProperties);

            var targetFrameworks = GetValueOrDefault(projectProperties, "TargetFrameworks");
            if (string.IsNullOrEmpty(targetFrameworks))
            {
                targetFrameworks = GetValueOrDefault(projectProperties, "TargetFramework");
            }

            targetFrameworks ??= "";
            var targetFrameworksList = targetFrameworks.Split(";");

            var name = Path.GetFileNameWithoutExtension(projectFile);

            return(new ProjectParseResult(name,
                                          GetValueOrDefault(projectProperties, "Configuration"),
                                          GetValueOrDefault(projectProperties, "OutputType", "Library"),
                                          targetFrameworksList));
        }
        finally
        {
            File.Delete(pf);
        }
    }
 protected override void OnExecute()
 {
     DotNetTasks.DotNetPack(s => s
         //.SetWorkingDirectory(BuildInfo.Solution.Directory)
         .SetSymbolPackageFormat(_symbolPackageFormat)
         .SetProject(BuildInfo.Solution)
         .SetConfiguration(BuildInfo.Configuration)
         .EnableIncludeSymbols()
         .SetOutputDirectory(BuildInfo.ArtifactsDirectory)
         .SetVersion(BuildInfo.VersionInfo.NuGetVersionV2)
         .FluentIf(_enableNoBuild, x => x.EnableNoBuild())
         .FluentIf(!string.IsNullOrWhiteSpace(_copyright), x => x.SetCopyright(_copyright))
         .FluentIf(!string.IsNullOrWhiteSpace(_packageProjectUrl), x => x.SetPackageProjectUrl(_packageProjectUrl))
         .FluentIf(!string.IsNullOrEmpty(_packageLicenseUrl), x => x.SetPackageLicenseUrl(_packageLicenseUrl))
         .FluentIf(!string.IsNullOrWhiteSpace(_packageLicenseExpression),
             x => x.SetProperty("PackageLicenseExpression", _packageLicenseExpression))
     );
 }
Example #10
0
        private static void UpdateGlobalJsonFile(AbsolutePath rootDirectory)
        {
            var latestInstalledSdk = DotNetTasks.DotNet("--list-sdks", logInvocation: false, logOutput: false)
                                     .LastOrDefault().Text?.Split(" ").First();

            if (latestInstalledSdk == null)
            {
                return;
            }

            var globalJsonFile = rootDirectory / "global.json";
            var jobject        = File.Exists(globalJsonFile)
                ? SerializationTasks.JsonDeserializeFromFile <JObject>(globalJsonFile)
                : new JObject();

            jobject["sdk"] ??= new JObject();
            jobject["sdk"].NotNull()["version"] = latestInstalledSdk;
            SerializationTasks.JsonSerializeToFile(jobject, globalJsonFile);
        }
Example #11
0
    public static IReadOnlyCollection <Output> DotNetBuildTestSolution(
        string solutionFile,
        IEnumerable <Project> projects)
    {
        if (File.Exists(solutionFile))
        {
            return(Array.Empty <Output>());
        }

        var workingDirectory = Path.GetDirectoryName(solutionFile);
        var list             = new List <Output>();

        list.AddRange(DotNetTasks.DotNet($"new sln -n {Path.GetFileNameWithoutExtension(solutionFile)}", workingDirectory));

        var projectsArg = string.Join(" ", projects.Select(t => $"\"{t}\""));

        list.AddRange(DotNetTasks.DotNet($"sln \"{solutionFile}\" add {projectsArg}", workingDirectory));

        return(list);
    }
Example #12
0
 /// <summary>
 /// xunit test
 /// </summary>
 public static ITargetDefinition Test(ITargetDefinition _, IMsBuild build) => _
 .DependsOn(build.Build)
 .DependentFor(build.Pack)
 .Executes(
     () =>
 {
     foreach (var project in build.Solution.GetTestProjects())
     {
         DotNetTasks
         .DotNetTest(
             settings =>
             settings
             .SetProjectFile(project)
             .SetConfiguration(build.Configuration)
             .SetGitVersionEnvironment(build.GitVersion)
             .SetDefaultLoggers(build.LogsDirectory / "test.log")
             .EnableNoRestore()
             .SetLogger("trx")
             .SetProperty("VSTestResultsDirectory", build.TestResultsDirectory)
             );
     }
 }
     );
Example #13
0
    public static IReadOnlyCollection <Output> DotNetBuildSonarSolution(
        string solutionFile,
        IEnumerable <string> directories = null,
        Func <string, bool> include      = null)
    {
        if (File.Exists(solutionFile))
        {
            return(Array.Empty <Output>());
        }

        directories ??= Directories;

        IEnumerable <string> projects = GetAllProjects(Path.GetDirectoryName(solutionFile), directories, include);
        var workingDirectory          = Path.GetDirectoryName(solutionFile);
        var list = new List <Output>();

        list.AddRange(DotNetTasks.DotNet($"new sln -n {Path.GetFileNameWithoutExtension(solutionFile)}", workingDirectory));

        var projectsArg = string.Join(" ", projects.Select(t => $"\"{t}\""));

        list.AddRange(DotNetTasks.DotNet($"sln \"{solutionFile}\" add {projectsArg}", workingDirectory));

        return(list);
    }
 protected override void OnExecute()
 {
     DotNetTasks.DotNetRestore(s => s
                               .SetProjectFile(BuildInfo.Solution));
 }
Example #15
0
    async Task <string> GetSwaggerWay1()
    {
        //see Web -> GenerateSwaggerFiles
        DotNetTasks.DotNetRun(
            s => s
            //.SetWorkingDirectory(MySolutionDirectory)
            .SetProjectFile(Solution.GetProject("Web").Path)
            .SetLaunchProfile("localProfile")
            .SetApplicationArguments("swagger")
            );

        var apiVersion = "v1";

        var document = await SwaggerDocument.FromFileAsync($"./swagger/swagger-Web-{apiVersion}.json");

        var tsGenerator = new SwaggerToTypeScriptClientGenerator(document,
                                                                 new SwaggerToTypeScriptClientGeneratorSettings
        {
            ClassName             = "{controller}Client",
            CodeGeneratorSettings =
            {
                GenerateDefaultValues = true,
                SchemaType            = SchemaType.JsonSchema,
            },
            //RxJsVersion = 6,
            Template                    = TypeScriptTemplate.Angular,
            HttpClass                   = HttpClass.HttpClient,
            PromiseType                 = PromiseType.Promise,
            WrapResponses               = false,
            GenerateClientClasses       = true,
            GenerateClientInterfaces    = false,
            GenerateDtoTypes            = true,
            GenerateOptionalParameters  = true,
            GenerateResponseClasses     = true,
            ImportRequiredTypes         = true,
            InjectionTokenType          = InjectionTokenType.InjectionToken,
            UseSingletonProvider        = true,
            OperationNameGenerator      = new SingleClientFromPathSegmentsOperationNameGenerator(),
            WrapDtoExceptions           = false,
            BaseUrlTokenName            = "API_BASE_URL",
            TypeScriptGeneratorSettings =
            {
                GenerateDefaultValues           = true,
                SchemaType                      = SchemaType.JsonSchema,
                NullValue                       = TypeScriptNullValue.Null,
                ExportTypes                     = true,
                TypeStyle                       = TypeScriptTypeStyle.Class,
                DateTimeType                    = TypeScriptDateTimeType.MomentJS,
                MarkOptionalProperties          = true,
                TypeScriptVersion               =                            2.7m,
                ConvertConstructorInterfaceData = false,
                ModuleName                      = null,
            },
            UseGetBaseUrlMethod       = false,
            UseTransformOptionsMethod = false,
            UseTransformResultMethod  = false,
        });
        var ngApiClient = tsGenerator.GenerateFile();

        return(ngApiClient);
    }
 public void OnBuildFinished(NukeBuild build)
 {
     // Note https://github.com/dotnet/cli/issues/11424
     DotNetTasks.DotNet("build-server shutdown");
 }