Exemplo n.º 1
0
 public DotNetCliCommand(string cliPath, string arguments, GenerateResult generateResult, ILogger logger,
                         BuildPartition buildPartition, IReadOnlyList <EnvironmentVariable> environmentVariables, TimeSpan timeout, bool logOutput = false,
                         bool retryFailedBuildWithNoDeps = true)
 {
     CliPath                    = cliPath ?? DotNetCliCommandExecutor.DefaultDotNetCliPath.Value;
     Arguments                  = arguments;
     GenerateResult             = generateResult;
     Logger                     = logger;
     BuildPartition             = buildPartition;
     EnvironmentVariables       = environmentVariables;
     Timeout                    = timeout;
     LogOutput                  = logOutput || buildPartition.LogBuildOutput;
     RetryFailedBuildWithNoDeps = retryFailedBuildWithNoDeps;
 }
Exemplo n.º 2
0
        private static BenchmarkReport CreateReport(IConfig config)
        {
            var benchmark     = CreateBenchmark(config);
            var buildResult   = BuildResult.Success(GenerateResult.Success(ArtifactsPaths.Empty));
            var executeResult = new ExecuteResult(true, 0, new List <string>(), new string[0]);
            var measurements  = new List <Measurement>
            {
                new Measurement(1, IterationMode.Result, 1, 1, 1)
            };

            return(new BenchmarkReport(benchmark, buildResult, buildResult, new List <ExecuteResult> {
                executeResult
            }, measurements));
        }
Exemplo n.º 3
0
        public GenerateResult Execute()
        {
            try
            {
                var data = this.Encoding.GetBytes(this.Contents ?? "");
                var json = "";
                if (this.HttpMethod == HttpMethod.Get)
                {
                    json = wc.DownloadString(this.Url);
                }
                else
                {
                    var result = wc.UploadData(this.Url, this.HttpMethod.ToString(), data);
                    json = this.Encoding.GetString(result);
                }

                var js = new JavaScriptSerializer()
                {
                    MaxJsonLength = int.MaxValue
                };
                var obj = js.Deserialize(json, typeof(object));


                var genResult = new GenerateResult()
                {
                    IsDictionary = obj is IDictionary,
                    IsArray      = obj is IList
                };

                if (genResult.IsDictionary)
                {
                    genResult.ObjectDictionary = obj as IDictionary;
                }
                else if (genResult.IsArray)
                {
                    genResult.ObjectList = obj as IList;
                }
                else
                {
                    genResult.Object = obj;
                }

                return(genResult);
            }
            finally
            {
                wc.Dispose();
            }
        }
Exemplo n.º 4
0
        private List <GenerateResult> GenerateInternal(TemplateOption option, List <Table> tables, CodeGenerateHandler handler)
        {
            var result     = new List <GenerateResult>();
            var references = new List <Reference>();

            foreach (var table in tables)
            {
                references.AddRange(table.ForeignKeys);
            }

            var tparts = option.Partitions.Where(s => s.Loop == PartitionLoop.Tables).ToList();
            var nparts = option.Partitions.Where(s => s.Loop == PartitionLoop.None).ToList();

            var engine = new VelocityEngine();

            foreach (var table in tables)
            {
                var context = new VelocityContext();
                context.Put("Tables", tables);
                context.Put("References", references);
                context.Put("Current", table);
                context.Put("Profile", option.Profile);

                foreach (var part in option.Partitions)
                {
                    var props = new ExtendedProperties();
                    var info  = new FileInfo(part.FilePath);

                    props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
                    props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, info.DirectoryName);
                    props.AddProperty(RuntimeConstants.COUNTER_INITIAL_VALUE, "0");
                    engine.Init(props);

                    using (var writer = new StringWriter())
                    {
                        engine.MergeTemplate(info.Name, "gb2312", context, writer);
                        var r = new GenerateResult(part, writer.ToString());
                        if (option.WriteToDisk && r.WriteToDisk)
                        {
                            PartitionWriter.Write(r, table, option.Profile, option.OutputDirectory);
                        }

                        result.Add(r);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 5
0
        public static GenerateResult ShouldIndicateFailure([NotNull] this GenerateResult results)
        {
            if (results == null)
            {
                throw new ArgumentNullException(nameof(results));
            }

            if (results.Errors.Any() ||
                results.GeneratedFiles.Any(f => f.Errors.Any()))
            {
                return(results);
            }

            throw new SpecificationException($"Should indicate failure, but indicates success");
        }
Exemplo n.º 6
0
 public BenchmarkReport(
     BenchmarkCase benchmarkCase,
     GenerateResult generateResult,
     BuildResult buildResult,
     IReadOnlyList <ExecuteResult> executeResults,
     IReadOnlyList <Measurement> allMeasurements,
     GcStats gcStats)
 {
     BenchmarkCase   = benchmarkCase;
     GenerateResult  = generateResult;
     BuildResult     = buildResult;
     ExecuteResults  = executeResults ?? Array.Empty <ExecuteResult>();
     AllMeasurements = allMeasurements ?? Array.Empty <Measurement>();
     GcStats         = gcStats;
 }
Exemplo n.º 7
0
 public BenchmarkReport(
     Benchmark benchmark,
     GenerateResult generateResult,
     BuildResult buildResult,
     IReadOnlyList <ExecuteResult> executeResults,
     IReadOnlyList <Measurement> allMeasurements,
     GcStats gcStats)
 {
     Benchmark       = benchmark;
     GenerateResult  = generateResult;
     BuildResult     = buildResult;
     ExecuteResults  = executeResults ?? new ExecuteResult[0];
     AllMeasurements = allMeasurements ?? new Measurement[0];
     GcStats         = gcStats;
 }
Exemplo n.º 8
0
        public static GenerateResult ShouldIndicateSuccess([NotNull] this GenerateResult results)
        {
            if (results == null)
            {
                throw new ArgumentNullException(nameof(results));
            }

            var combinedErrors = results.Errors.Union(results.GeneratedFiles.SelectMany(f => f.Errors)).ToArray();

            if (!combinedErrors.Any())
            {
                return(results);
            }

            throw new SpecificationException($"Should indicate success, but indicates failure with the following errors {string.Join("\n- ", combinedErrors.Select(e => e.ToString()))}");
        }
 private static BenchmarkReport CreateReport(BenchmarkCase benchmarkCase, bool hugeSd, Metric[] metrics)
 {
     var buildResult = BuildResult.Success(GenerateResult.Success(ArtifactsPaths.Empty, Array.Empty<string>()));
     var executeResult = new ExecuteResult(true, 0, Array.Empty<string>(), Array.Empty<string>());
     bool isFoo = benchmarkCase.Descriptor.WorkloadMethodDisplayInfo == "Foo";
     bool isBar = benchmarkCase.Descriptor.WorkloadMethodDisplayInfo == "Bar";            
     var measurements = new List<Measurement>
     {
         new Measurement(1, IterationMode.Workload, IterationStage.Result, 1, 1, 1),
         new Measurement(1, IterationMode.Workload, IterationStage.Result, 2, 1, hugeSd && isFoo ? 2 : 1),
         new Measurement(1, IterationMode.Workload, IterationStage.Result, 3, 1, hugeSd && isBar ? 3 : 1),
         new Measurement(1, IterationMode.Workload, IterationStage.Result, 4, 1, hugeSd && isFoo ? 2 : 1),
         new Measurement(1, IterationMode.Workload, IterationStage.Result, 5, 1, hugeSd && isBar ? 3 : 1),
         new Measurement(1, IterationMode.Workload, IterationStage.Result, 6, 1, 1)
     };
     return new BenchmarkReport(true, benchmarkCase, buildResult, buildResult, new List<ExecuteResult> { executeResult }, measurements, default, metrics);
Exemplo n.º 10
0
 public BenchmarkReport(
     BenchmarkCase benchmarkCase,
     GenerateResult generateResult,
     BuildResult buildResult,
     IReadOnlyList <ExecuteResult> executeResults,
     IReadOnlyList <Measurement> allMeasurements,
     GcStats gcStats,
     IReadOnlyList <Metric> metrics)
 {
     BenchmarkCase   = benchmarkCase;
     GenerateResult  = generateResult;
     BuildResult     = buildResult;
     ExecuteResults  = executeResults ?? Array.Empty <ExecuteResult>();
     AllMeasurements = allMeasurements ?? Array.Empty <Measurement>();
     GcStats         = gcStats;
     Metrics         = metrics?.ToDictionary(metric => metric.Descriptor.Id);
 }
Exemplo n.º 11
0
        private static BenchmarkReport CreateReport(BenchmarkCase benchmarkCase, int measurementValue)
        {
            var buildResult   = BuildResult.Success(GenerateResult.Success(ArtifactsPaths.Empty, Array.Empty <string>()));
            var executeResult = new ExecuteResult(true, 0, Array.Empty <string>(), Array.Empty <string>());
            var measurements  = new List <Measurement>
            {
                new Measurement(1, IterationMode.Workload, IterationStage.Result, 1, 1, measurementValue),
                new Measurement(1, IterationMode.Workload, IterationStage.Result, 2, 1, measurementValue),
                new Measurement(1, IterationMode.Workload, IterationStage.Result, 3, 1, measurementValue),
                new Measurement(1, IterationMode.Workload, IterationStage.Result, 4, 1, measurementValue),
                new Measurement(1, IterationMode.Workload, IterationStage.Result, 5, 1, measurementValue),
                new Measurement(1, IterationMode.Workload, IterationStage.Result, 6, 1, measurementValue),
            };

            return(new BenchmarkReport(true, benchmarkCase, buildResult, buildResult, new List <ExecuteResult> {
                executeResult
            }, measurements, default, Array.Empty <Metric>()));
Exemplo n.º 12
0
 public BenchmarkReport(
     bool success,
     BenchmarkCase benchmarkCase,
     GenerateResult generateResult,
     BuildResult buildResult,
     IReadOnlyList <ExecuteResult> executeResults,
     IReadOnlyList <Metric> metrics)
 {
     Success         = success;
     BenchmarkCase   = benchmarkCase;
     GenerateResult  = generateResult;
     BuildResult     = buildResult;
     ExecuteResults  = executeResults ?? Array.Empty <ExecuteResult>();
     AllMeasurements = ExecuteResults.SelectMany((results, index) => results.Measurements).ToArray();
     GcStats         = ExecuteResults.Count > 0 ? executeResults[executeResults.Count - 1].GcStats : default;
     Metrics         = metrics?.ToDictionary(metric => metric.Descriptor.Id)
                       ?? (IReadOnlyDictionary <string, Metric>)ImmutableDictionary <string, Metric> .Empty;
 }
        private static BenchmarkReport CreateReport(Benchmark benchmark, bool hugeSd)
        {
            var buildResult   = BuildResult.Success(GenerateResult.Success(ArtifactsPaths.Empty, Array.Empty <string>()));
            var executeResult = new ExecuteResult(true, 0, Array.Empty <string>(), Array.Empty <string>());
            var measurements  = new List <Measurement>
            {
                new Measurement(1, IterationMode.Result, 1, 1, 1),
                new Measurement(1, IterationMode.Result, 2, 1, hugeSd ? 2 : 1),
                new Measurement(1, IterationMode.Result, 3, 1, 1),
                new Measurement(1, IterationMode.Result, 4, 1, hugeSd ? 2 : 1),
                new Measurement(1, IterationMode.Result, 5, 1, 1),
                new Measurement(1, IterationMode.Result, 6, 1, 1),
            };

            return(new BenchmarkReport(benchmark, buildResult, buildResult, new List <ExecuteResult> {
                executeResult
            }, measurements, default(GcStats)));
        }
Exemplo n.º 14
0
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark, IResolver resolver)
        {
            logger.WriteLineInfo($"BuildScript: {generateResult.ArtifactsPaths.BuildScriptFilePath}");

            var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(generateResult.ArtifactsPaths.ProgramCodePath));

            var compilationOptions = new CSharpCompilationOptions(
                outputKind: OutputKind.ConsoleApplication,
                optimizationLevel: OptimizationLevel.Release,
                allowUnsafe: true,
                platform: GetPlatform(benchmark.Job.ResolveValue(EnvMode.PlatformCharacteristic, resolver)),
                deterministic: true);

            var references = Generator
                             .GetAllReferences(benchmark)
                             .Select(assembly => AssemblyMetadata.CreateFromFile(assembly.Location))
                             .Concat(FrameworkAssembliesMetadata.Value)
                             .Distinct()
                             .Select(uniqueMetadata => uniqueMetadata.GetReference());

            var compilation = CSharpCompilation
                              .Create(assemblyName: Path.GetFileName(generateResult.ArtifactsPaths.ExecutablePath))
                              .AddSyntaxTrees(syntaxTree)
                              .WithOptions(compilationOptions)
                              .AddReferences(references);

            using (var executable = File.Create(generateResult.ArtifactsPaths.ExecutablePath))
            {
                var emitResult = compilation.Emit(executable);

                if (emitResult.Success)
                {
                    return(BuildResult.Success(generateResult));
                }

                foreach (var diagnostic in emitResult.Diagnostics
                         .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error))
                {
                    logger.WriteError($"{diagnostic.Id}: {diagnostic.GetMessage()}");
                }

                return(BuildResult.Failure(generateResult));
            }
        }
Exemplo n.º 15
0
        public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger)
        {
            logger.WriteLineInfo($"BuildScript: {generateResult.ArtifactsPaths.BuildScriptFilePath}");

            CancellationTokenSource cts = new CancellationTokenSource(buildPartition.Timeout);

            try
            {
                return(Build(generateResult, buildPartition, logger, cts.Token));
            }
            catch (OperationCanceledException)
            {
                return(BuildResult.Failure(generateResult, $"The configured timeout {buildPartition.Timeout} was reached!"));
            }
            finally
            {
                cts.Dispose();
            }
        }
Exemplo n.º 16
0
        public GenerateResult GenerateProject(
            BuildPartition buildPartition,
            ILogger logger,
            string rootArtifactsFolderPath)
        {
            var artifactsPaths = ArtifactsPaths.Empty;

            try
            {
                artifactsPaths = GetArtifactsPaths(buildPartition, rootArtifactsFolderPath);

                return(GenerateResult.Success(artifactsPaths, new List <string>()));
            }
            catch (Exception ex)
            {
                logger.WriteLineError($"Failed to generate partition: {ex}");
                return(GenerateResult.Failure(artifactsPaths, new List <string>()));
            }
        }
Exemplo n.º 17
0
        private DotNetCliCommandExecutor.CommandResult Build(GenerateResult generateResult)
        {
            var withoutDependencies = DotNetCliCommandExecutor.ExecuteCommand(
                GetBuildCommand(TargetFrameworkMoniker, justTheProjectItself: true),
                generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath);

            // at first we try to build the project without it's dependencies to save a LOT of time
            // in 99% of the cases it will work (the host process is running so it must be compiled!)
            if (withoutDependencies.IsSuccess)
            {
                return(withoutDependencies);
            }

            // but the host process might have different runtime or was build in Debug, not Release,
            // which requires all dependencies to be build anyway
            return(DotNetCliCommandExecutor.ExecuteCommand(
                       GetBuildCommand(TargetFrameworkMoniker, justTheProjectItself: false),
                       generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath));
        }
        public static GeneratedFile Configuration([NotNull] this GenerateResult generationResults, [NotNull] string configurationName)
        {
            if (generationResults == null)
            {
                throw new ArgumentNullException(nameof(generationResults));
            }
            if (configurationName == null)
            {
                throw new ArgumentNullException(nameof(configurationName));
            }

            var match = generationResults.GeneratedFiles.FirstOrDefault(file => file.ConfigurationName == configurationName);

            if (match == null)
            {
                throw new ConfigurationNotFoundException(configurationName);
            }

            return(match);
        }
Exemplo n.º 19
0
        public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger)
        {
            BuildResult buildResult = dotnetCliBuilder.Build(generateResult, buildPartition, logger);

            if (buildResult.IsBuildSuccess ||
                File.Exists(generateResult.ArtifactsPaths.ExecutablePath))    // the build has failed, but produced an exe
            {
                RenameSharedLibaries(generateResult, logger);
            }

            if (!buildResult.IsBuildSuccess && File.Exists(generateResult.ArtifactsPaths.ExecutablePath))
            {
                logger.WriteLineError($"The buid has failed with following error: {buildResult.ErrorMessage}");
                logger.WriteLine("But it has produced the executable file, so we are going to try to use it.");

                return(BuildResult.Success(generateResult)); // we lie on purpose
            }

            return(buildResult);
        }
Exemplo n.º 20
0
        private BuildResult BuildWithBat(GenerateResult generateResult, ILogger logger, string exeFilePath)
        {
            logger.WriteLineInfo($"Let's try to build it via {GeneratorBase.BuildBenchmarkScriptFileName}!");

            var buildProcess = new Process
            {
                StartInfo =
                {
                    FileName               = Path.Combine(generateResult.DirectoryPath, GeneratorBase.BuildBenchmarkScriptFileName),
                    WorkingDirectory       = generateResult.DirectoryPath,
                    UseShellExecute        = false,
                    RedirectStandardOutput = false,
                }
            };

            buildProcess.Start();
            buildProcess.WaitForExit();

            return(new BuildResult(generateResult, File.Exists(exeFilePath), null, exeFilePath));
        }
Exemplo n.º 21
0
        public BuildResult Build(
            GenerateResult generateResult,
            ILogger logger,
            Benchmark benchmark,
            IResolver resolver)
        {
            if (!(benchmark is ExternalProcessBenchmark externalProcessBenchmark))
            {
                return(BuildResult.Failure(generateResult));
            }

            var exitCode = externalProcessBenchmark.BuildFunc((string)benchmark.Parameters["Commit"]);

            if (exitCode != 0)
            {
                return(BuildResult.Failure(generateResult));
            }

            return(BuildResult.Success(generateResult));
        }
Exemplo n.º 22
0
 public BenchmarkReport(
     bool success,
     BenchmarkCase benchmarkCase,
     GenerateResult generateResult,
     BuildResult buildResult,
     IReadOnlyList <ExecuteResult> executeResults,
     IReadOnlyList <Measurement> allMeasurements,
     GcStats gcStats,
     IReadOnlyList <Metric> metrics)
 {
     Success         = success;
     BenchmarkCase   = benchmarkCase;
     GenerateResult  = generateResult;
     BuildResult     = buildResult;
     ExecuteResults  = executeResults ?? Array.Empty <ExecuteResult>();
     AllMeasurements = allMeasurements ?? Array.Empty <Measurement>();
     GcStats         = gcStats;
     Metrics         = metrics?.ToDictionary(metric => metric.Descriptor.Id)
                       ?? (IReadOnlyDictionary <string, Metric>)ImmutableDictionary <string, Metric> .Empty;
 }
Exemplo n.º 23
0
        private static BuildResult Build(ILogger logger, IToolchain toolchain, GenerateResult generateResult, Benchmark benchmark)
        {
            logger.WriteLineInfo("// *** Build ***");
            var buildResult = toolchain.Builder.Build(generateResult, logger, benchmark);

            if (buildResult.IsBuildSuccess)
            {
                logger.WriteLineInfo("// Result = Success");
            }
            else
            {
                logger.WriteLineError("// Result = Failure");
                if (buildResult.BuildException != null)
                {
                    logger.WriteLineError($"// Exception: {buildResult.BuildException.Message}");
                }
            }
            logger.WriteLine();
            return(buildResult);
        }
Exemplo n.º 24
0
        public BuildResult Build(GenerateResult generateResult, ILogger logger)
        {
            lock (buildLock)
            {
                var projectFileName  = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".csproj");
                var exeFileName      = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".exe");
                var consoleLogger    = new MsBuildConsoleLogger(logger);
                var globalProperties = new Dictionary <string, string>();
                var buildRequest     = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
                var buildParameters  = new BuildParameters(new ProjectCollection())
                {
                    DetailedSummary = false, Loggers = new Microsoft.Build.Framework.ILogger[] { consoleLogger }
                };
                var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);

                if (buildResult.OverallResult != BuildResultCode.Success && !File.Exists(exeFileName))
                {
                    logger.WriteLineInfo("BuildManager.DefaultBuildManager can't build this project. =(");
                    logger.WriteLineInfo("Let's try to build it via BuildBenchmark.bat!");
                    var buildProcess = new Process
                    {
                        StartInfo =
                        {
                            FileName               = Path.Combine(generateResult.DirectoryPath, "BuildBenchmark.bat"),
                            WorkingDirectory       = generateResult.DirectoryPath,
                            UseShellExecute        = false,
                            RedirectStandardOutput = false,
                        }
                    };
                    buildProcess.Start();
                    buildProcess.WaitForExit();
                    if (File.Exists(exeFileName))
                    {
                        return(new BuildResult(generateResult, true, null));
                    }
                }

                return(new BuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success, buildResult.Exception));
            }
        }
Exemplo n.º 25
0
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark, IResolver resolver)
        {
            var extraArguments = DotNetCliGenerator.GetCustomArguments(benchmark, resolver);

            if (!string.IsNullOrEmpty(RestoreCommand))
            {
                var restoreResult = DotNetCliCommandExecutor.ExecuteCommand(
                    CustomDotNetCliPath,
                    $"{RestoreCommand} {extraArguments}",
                    generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath);

                logger.WriteLineInfo($"// dotnet restore took {restoreResult.ExecutionTime.TotalSeconds:0.##}s");

                if (!restoreResult.IsSuccess)
                {
                    return(BuildResult.Failure(generateResult, new Exception(restoreResult.ProblemDescription)));
                }
            }

            var buildResult = Build(
                generateResult,
                benchmark.Job.ResolveValue(InfrastructureMode.BuildConfigurationCharacteristic, resolver),
                extraArguments);

            logger.WriteLineInfo($"// dotnet build/publish took {buildResult.ExecutionTime.TotalSeconds:0.##}s");

            if (!buildResult.IsSuccess)
            {
                // dotnet cli could have succesfully builded the program, but returned 1 as exit code because it had some warnings
                // so we need to check whether the exe exists or not, if it does then it is OK
                if (File.Exists(generateResult.ArtifactsPaths.ExecutablePath))
                {
                    return(BuildResult.Success(generateResult));
                }

                return(BuildResult.Failure(generateResult, new Exception(buildResult.ProblemDescription)));
            }

            return(BuildResult.Success(generateResult));
        }
Exemplo n.º 26
0
        // This method is as work around because the MonoAOTCompilerTask
        // does not generate files with the right names.
        // In the future it may have an option to write .so/.dylib files,
        // and we can get rid of this method.
        public void RenameSharedLibaries(GenerateResult generateResult, ILogger logger)
        {
            string[] publishDirFiles       = Directory.GetFiles(generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath, ".dll.o");
            string   sharedObjectExtension = "";

            if (RuntimeInformation.IsMacOSX())
            {
                sharedObjectExtension = "dylib";
            }
            else if (RuntimeInformation.IsLinux())
            {
                sharedObjectExtension = "so";
            }

            foreach (string fileName in publishDirFiles)
            {
                string newFileName = Path.ChangeExtension(fileName, sharedObjectExtension);

                logger.WriteLine($"RenameSharedLibraries: Moving ${fileName} to {newFileName}");
                File.Move(fileName, newFileName);
            }
        }
Exemplo n.º 27
0
        private DotNetCliCommandExecutor.CommandResult Build(GenerateResult generateResult, string configuration, string extraArguments, ILogger logger)
        {
            var withoutDependencies = DotNetCliCommandExecutor.ExecuteCommand(
                CustomDotNetCliPath,
                $"{GetBuildCommand(TargetFrameworkMoniker, true, configuration)} {extraArguments}",
                generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath,
                logger);

            // at first we try to build the project without it's dependencies to save a LOT of time
            // in 99% of the cases it will work (the host process is running so it must be compiled!)
            if (withoutDependencies.IsSuccess)
            {
                return(withoutDependencies);
            }

            // but the host process might have different runtime or was build in Debug, not Release,
            // which requires all dependencies to be build anyway
            var withDependencies = DotNetCliCommandExecutor.ExecuteCommand(
                CustomDotNetCliPath,
                $"{GetBuildCommand(TargetFrameworkMoniker, false, configuration)} {extraArguments}",
                generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath,
                logger);

            if (withDependencies.IsSuccess)
            {
                return(withDependencies);
            }

            // there are some crazy edge-cases, where executing dotnet build --no-restore AFTER dotnet restore will fail
            // an example: ML.NET has default values like Configuration = Debug in Directory.Build.props file
            // when we run dotnet restore for it, it restores for Debug. When we run dotnet build -c Release --no-restore, it fails because it can't find project.assets.json file
            // The problem is that dotnet cli does not allow to set the configuration from console arguments
            // But when we run dotnet build -c Release (without --no-restore) it's going to restore the right things for us ;)
            return(DotNetCliCommandExecutor.ExecuteCommand(
                       CustomDotNetCliPath,
                       $"{GetBuildCommand(TargetFrameworkMoniker, false, configuration)} {extraArguments}".Replace(" --no-restore", string.Empty),
                       generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath,
                       logger));
        }
Exemplo n.º 28
0
        public GenerateResult GenerateProject(Benchmark benchmark, ILogger logger, string rootArtifactsFolderPath, IConfig config, IResolver resolver)
        {
            ArtifactsPaths artifactsPaths = null;

            try
            {
                artifactsPaths = GetArtifactsPaths(benchmark, config, rootArtifactsFolderPath);

                CopyAllRequiredFiles(benchmark, artifactsPaths);

                GenerateCode(benchmark, artifactsPaths);
                GenerateAppConfig(benchmark, artifactsPaths, resolver);
                GenerateProject(benchmark, artifactsPaths, resolver, logger);
                GenerateBuildScript(benchmark, artifactsPaths, resolver);

                return(GenerateResult.Success(artifactsPaths, GetArtifactsToCleanup(benchmark, artifactsPaths)));
            }
            catch (Exception ex)
            {
                return(GenerateResult.Failure(artifactsPaths, GetArtifactsToCleanup(benchmark, artifactsPaths), ex));
            }
        }
Exemplo n.º 29
0
        public void Run([NotNull] string[] args)
        {
            ShowTitle();

            IEnumerable <PreferenceGroupInfo> preferenceGroups = _generationService.GetPreferences();

            if (args.Contains("--help", StringComparer.OrdinalIgnoreCase) ||
                args.Contains("-help", StringComparer.OrdinalIgnoreCase) ||
                args.Contains("-?", StringComparer.OrdinalIgnoreCase) ||
                args.Contains("--?", StringComparer.OrdinalIgnoreCase))
            {
                _helpWriter.WriteHelp(preferenceGroups);

                Environment.ExitCode = (int)ExitCodes.HelpShown;
                return;
            }

            var consoleInputToPreferenceConverter = new ConsoleInputToPreferenceConverter();

            ParsedConsoleInput preferences = consoleInputToPreferenceConverter.ParseConsoleInput(args, preferenceGroups);

            if (preferences.ParseErrors.Any())
            {
                foreach (var parseError in preferences.ParseErrors)
                {
                    _consoleWriter.Info(parseError);
                }

                Environment.ExitCode = (int)ExitCodes.ConsoleInputParseError;
                return;
            }

            GenerateResult results = _generationService.Generate(preferences.ParsedPreferences.ToDictionary(kvp => kvp.Key.Name, kvp => kvp.Value)); //TODO: cleanup

            _resultWriter.Report(results);

            Environment.ExitCode = results.AllErrors.Any() ? (int)ExitCodes.GenerationFailed : (int)ExitCodes.Success;
        }
Exemplo n.º 30
0
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark)
        {
            var projectFilePath = Path.Combine(generateResult.DirectoryPath, GeneratorBase.MainClassName + ".csproj");
            var executablePath  = Path.Combine(generateResult.DirectoryPath, GeneratorBase.MainClassName + ".exe");

            try
            {
                var buildResult = BuildWithManagedApi(logger, projectFilePath);

                if (buildResult.OverallResult != BuildResultCode.Success && !File.Exists(executablePath))
                {
                    logger.WriteLineInfo("BuildManager.DefaultBuildManager can't build this project. =(");

                    return(BuildWithBat(generateResult, logger, executablePath));
                }

                return(new BuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success,
                                       buildResult.Exception, executablePath));
            }
            catch (FileLoadException msBuildDllNotFound)
            {
                logger.WriteLineInfo($"Unable to load {msBuildDllNotFound.FileName}");

                return(BuildWithBat(generateResult, logger, executablePath));
            }
            catch (FileNotFoundException msBuildDllNotFound)
            {
                logger.WriteLineInfo($"Unable to find {msBuildDllNotFound.FileName}");

                return(BuildWithBat(generateResult, logger, executablePath));
            }
            catch (InvalidOperationException exception)
            {
                logger.WriteLine($"Unable to build (InvalidOperationException). More information: {exception.Message}");

                return(BuildWithBat(generateResult, logger, executablePath));
            }
        }
Exemplo n.º 31
0
        public GenerateResult Execute()
        {
            try
            {
                var data = this.Encoding.GetBytes(this.Contents ?? "");
                var json = "";
                if (this.HttpMethod == HttpMethod.Get)
                {
                    json = wc.DownloadString(this.Url);
                }
                else
                {
                    var result = wc.UploadData(this.Url, this.HttpMethod.ToString(), data);
                    json = this.Encoding.GetString(result);
                }

                var js = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };
                var obj = js.Deserialize(json, typeof(object));


                var genResult = new GenerateResult()
                {
                    IsDictionary = obj is IDictionary,
                    IsArray = obj is IList
                };

                if (genResult.IsDictionary) genResult.ObjectDictionary = obj as IDictionary;
                else if (genResult.IsArray) genResult.ObjectList = obj as IList;
                else genResult.Object = obj;

                return genResult;
            }
            finally
            {
                wc.Dispose();
            }

        }