Пример #1
0
        /// <inheritdoc/>
        public IDictionary <string, string> GetToolsToBeSetInPath(
            RepositoryContext context,
            PlatformDetectorResult detectorResult)
        {
            var rubyPlatformDetectorResult = detectorResult as RubyPlatformDetectorResult;

            if (rubyPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(RubyPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            var tools = new Dictionary <string, string>();

            tools[RubyConstants.PlatformName] = rubyPlatformDetectorResult.PlatformVersion;
            return(tools);
        }
Пример #2
0
        /// <inheritdoc/>
        public string GetInstallerScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var pythonPlatformDetectorResult = detectorResult as PythonPlatformDetectorResult;

            if (pythonPlatformDetectorResult != null && IsCondaEnvironment(pythonPlatformDetectorResult))
            {
                _logger.LogDebug(
                    "Application in the source directory is a Conda based app, " +
                    "so skipping dynamic installation of Python SDK.");
                return(null);
            }

            string installationScriptSnippet = null;

            if (_commonOptions.EnableDynamicInstall)
            {
                _logger.LogDebug("Dynamic install is enabled.");

                if (_platformInstaller.IsVersionAlreadyInstalled(detectorResult.PlatformVersion))
                {
                    _logger.LogDebug(
                        "Python version {version} is already installed. So skipping installing it again.",
                        detectorResult.PlatformVersion);
                }
                else
                {
                    _logger.LogDebug(
                        "Python version {version} is not installed. " +
                        "So generating an installation script snippet for it.",
                        detectorResult.PlatformVersion);

                    installationScriptSnippet = _platformInstaller.GetInstallerScriptSnippet(
                        detectorResult.PlatformVersion);
                }
            }
            else
            {
                _logger.LogDebug("Dynamic install not enabled.");
            }

            return(installationScriptSnippet);
        }
Пример #3
0
        /// <inheritdoc/>
        public string GetInstallerScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var dotNetCorePlatformDetectorResult = detectorResult as DotNetCorePlatformDetectorResult;

            if (dotNetCorePlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(DotNetCorePlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            string installationScriptSnippet = null;

            if (this.commonOptions.EnableDynamicInstall)
            {
                this.logger.LogDebug("Dynamic install is enabled.");

                if (this.platformInstaller.IsVersionAlreadyInstalled(dotNetCorePlatformDetectorResult.SdkVersion))
                {
                    this.logger.LogDebug(
                        "DotNetCore SDK version {globalJsonSdkVersion} is already installed. " +
                        "So skipping installing it again.",
                        dotNetCorePlatformDetectorResult.SdkVersion);
                }
                else
                {
                    this.logger.LogDebug(
                        "DotNetCore SDK version {globalJsonSdkVersion} is not installed. " +
                        "So generating an installation script snippet for it.",
                        dotNetCorePlatformDetectorResult.SdkVersion);

                    installationScriptSnippet = this.platformInstaller.GetInstallerScriptSnippet(
                        dotNetCorePlatformDetectorResult.SdkVersion);
                }
            }
            else
            {
                this.logger.LogDebug("Dynamic install is not enabled.");
            }

            return(installationScriptSnippet);
        }
Пример #4
0
        public void GeneratedScript_HasNpmVersion_SpecifiedInPackageJson()
        {
            // Arrange
            var scriptGenerator = GetNodePlatform(
                defaultNodeVersion: NodeVersions.Node12Version,
                new BuildScriptGeneratorOptions {
                PlatformVersion = "8.2.1"
            },
                new NodeScriptGeneratorOptions());
            var repo = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithNpmVersion, NodeConstants.PackageJsonFileName);
            var context        = CreateScriptGeneratorContext(repo);
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = NodeConstants.PlatformName,
                PlatformVersion = "10.10.10",
            };

            var expected = new NodeBashBuildSnippetProperties
            {
                PackageInstallCommand               = NpmInstallCommand,
                PackageInstallerVersionCommand      = NodeConstants.NpmVersionCommand,
                NpmRunBuildCommand                  = null,
                NpmRunBuildAzureCommand             = null,
                HasProdDependencies                 = true,
                HasDevDependencies                  = false,
                ProductionOnlyPackageInstallCommand = string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                CompressedNodeModulesFileName = null,
                CompressNodeModulesCommand    = null,
            };

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context, detectorResult);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(
                TemplateHelper.Render(TemplateHelper.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
Пример #5
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var manifestFileProperties = new Dictionary <string, string>();

            manifestFileProperties[ManifestFilePropertyKeys.HugoVersion] = detectorResult.PlatformVersion;

            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.HugoSnippet,
                model: null,
                _logger);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Пример #6
0
        public void Detect_ReturnsResult_MultiplePlatform_DotNetCoreReactApp()
        {
            Mock <IPlatformDetector>        mockNodePlatformDetector       = new Mock <IPlatformDetector>();
            Mock <IPlatformDetector>        mockDotnetcorePlatformDetector = new Mock <IPlatformDetector>();
            IEnumerable <IPlatformDetector> platformDetectors = new List <IPlatformDetector>()
            {
                mockNodePlatformDetector.Object, mockDotnetcorePlatformDetector.Object
            };

            var options    = new Mock <IOptions <DetectorOptions> >();
            var sourceRepo = new MemorySourceRepo();
            var detector   = new DefaultPlatformDetector(
                platformDetectors,
                NullLogger <DefaultPlatformDetector> .Instance,
                options.Object);
            var context = CreateContext(sourceRepo);

            var detectionResult1 = new PlatformDetectorResult();

            detectionResult1.Platform        = "node";
            detectionResult1.PlatformVersion = "12.16.1";

            var detectionResult2 = new PlatformDetectorResult();

            detectionResult2.Platform        = "dotnetcore";
            detectionResult2.PlatformVersion = "3.1";

            mockNodePlatformDetector.Setup(x => x.DetectorPlatformName).Returns(PlatformName.Node);
            mockDotnetcorePlatformDetector.Setup(x => x.DetectorPlatformName).Returns(PlatformName.DotNetCore);
            mockNodePlatformDetector.Setup(x => x.Detect(context)).Returns(detectionResult1);
            mockDotnetcorePlatformDetector.Setup(x => x.Detect(context)).Returns(detectionResult2);

            IPlatformDetector nodePlatformDetector       = mockNodePlatformDetector.Object;
            IPlatformDetector dotnetcorePlatformDetector = mockDotnetcorePlatformDetector.Object;

            // Act
            var detectionResults = detector.GetAllDetectedPlatforms(context);

            // Assert
            Assert.NotNull(detectionResults);
            Assert.Equal(2, detectionResults.Count);
        }
Пример #7
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext ctx,
            PlatformDetectorResult detectorResult)
        {
            var rubyPlatformDetectorResult = detectorResult as RubyPlatformDetectorResult;

            if (rubyPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(RubyPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            if (!rubyPlatformDetectorResult.GemfileExists)
            {
                throw new InvalidUsageException($"No Gemfile found at the root of the repo. Please provide a Gemfile.");
            }

            var buildProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            buildProperties[ManifestFilePropertyKeys.RubyVersion] = rubyPlatformDetectorResult.PlatformVersion;

            _logger.LogDebug("Selected Ruby version: {rubyVer}", rubyPlatformDetectorResult.PlatformVersion);

            var scriptProps = new RubyBashBuildSnippetProperties
            {
                UseBundlerToInstallDependencies = true,
                BundlerVersion = rubyPlatformDetectorResult.BundlerVersion,
            };

            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.RubyBuildSnippet,
                scriptProps,
                _logger);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = buildProperties,
            });
        }
Пример #8
0
        public void BuildScript_DoesNotHaveSdkInstallScript_IfDynamicInstallNotEnabled_AndSdkIsNotAlreadyInstalled()
        {
            // Arrange
            var nodePlatform = CreateNodePlatform(dynamicInstallIsEnabled: false, sdkAlreadyInstalled: false);
            var repo         = new MemorySourceRepo();

            repo.AddFile(string.Empty, NodeConstants.PackageJsonFileName);
            var context        = CreateContext(repo);
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = NodeConstants.PlatformName,
                PlatformVersion = "10.10",
            };

            // Act
            var buildScriptSnippet = nodePlatform.GetInstallerScriptSnippet(context, detectorResult);

            // Assert
            Assert.Null(buildScriptSnippet);
        }
Пример #9
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext ctx,
            PlatformDetectorResult detectorResult)
        {
            // confirm go detector not null
            var goPlatformDetectorResult = detectorResult as GolangPlatformDetectorResult;

            if (goPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(GolangPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            if (!goPlatformDetectorResult.GoModExists)
            {
                throw new InvalidUsageException("No go.mod found at the root of the repo. Please provide a go.mod file containing the version.");
            }

            // build properties & script snippets
            var buildProperties = new Dictionary <string, string>();

            // Write platform name and version to the manifest file
            buildProperties[ManifestFilePropertyKeys.GolangVersion] = goPlatformDetectorResult.PlatformVersion;
            this.logger.LogDebug($"Selected Go version: {goPlatformDetectorResult.PlatformVersion}");
            var scriptProps = new GolangBashBuildSnippetProperties(
                goPlatformDetectorResult.GoModExists,
                goPlatformDetectorResult.PlatformVersion);

            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.GolangSnippet,
                scriptProps,
                this.logger);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = buildProperties,
            });
        }
Пример #10
0
        /// <inheritdoc/>
        public string GetInstallerScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var javaPlatformDetectorResult = detectorResult as JavaPlatformDetectorResult;

            if (javaPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(JavaPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            if (_commonOptions.EnableDynamicInstall)
            {
                _logger.LogDebug("Dynamic install is enabled.");

                var scriptBuilder = new StringBuilder();

                InstallJavaSdk(javaPlatformDetectorResult.PlatformVersion, scriptBuilder);

                // We need not setup Maven if repo already uses a Maven wrapper script.
                if (!javaPlatformDetectorResult.UsesMavenWrapperTool)
                {
                    InstallMaven(javaPlatformDetectorResult.MavenVersion, scriptBuilder);
                }

                if (scriptBuilder.Length == 0)
                {
                    return(null);
                }

                return(scriptBuilder.ToString());
            }
            else
            {
                _logger.LogDebug("Dynamic install not enabled.");
                return(null);
            }
        }
Пример #11
0
        public void GeneratedSnippet_HasInstallationScript_IfDynamicInstallIsEnabled()
        {
            // Arrange
            var pythonScriptGeneratorOptions = new PythonScriptGeneratorOptions();
            var commonOptions = new BuildScriptGeneratorOptions()
            {
                EnableDynamicInstall = true
            };
            var installerScriptSnippet = "##INSTALLER_SCRIPT##";
            var versionProvider        = new TestPythonVersionProvider(new[] { "3.7.5", "3.8.0" }, defaultVersion: "3.7.5");
            var platformInstaller      = new TestPythonPlatformInstaller(
                isVersionAlreadyInstalled: false,
                installerScript: installerScriptSnippet,
                Options.Create(commonOptions),
                NullLoggerFactory.Instance);
            var platform = CreatePlatform(
                versionProvider,
                platformInstaller,
                commonOptions,
                pythonScriptGeneratorOptions);
            var repo = new MemorySourceRepo();

            repo.AddFile("", PythonConstants.RequirementsFileName);
            repo.AddFile("print(1)", "bla.py");
            var context = new BuildScriptGeneratorContext {
                SourceRepo = repo
            };
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = PythonConstants.PlatformName,
                PlatformVersion = "3.7.5",
            };

            // Act
            var snippet = platform.GetInstallerScriptSnippet(context, detectorResult);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(installerScriptSnippet, snippet);
        }
Пример #12
0
        private static PlatformDetectorResult GetPlatformDetectorResult(string name, string version)
        {
            var result = new PlatformDetectorResult();

            switch (name)
            {
            case DotNetCoreConstants.PlatformName:
                result = new DotNetCorePlatformDetectorResult();
                break;

            case NodeConstants.PlatformName:
                result = new NodePlatformDetectorResult();
                break;

            case PythonConstants.PlatformName:
                result = new PythonPlatformDetectorResult();
                break;

            case HugoConstants.PlatformName:
                result = new PlatformDetectorResult();
                break;

            case PhpConstants.PlatformName:
                result = new PhpPlatformDetectorResult();
                break;

            case JavaConstants.PlatformName:
                result = new JavaPlatformDetectorResult();
                break;

            case RubyConstants.PlatformName:
                result = new RubyPlatformDetectorResult();
                break;
            }

            result.Platform        = name;
            result.PlatformVersion = version;

            return(result);
        }
Пример #13
0
        public void GeneratedBuildSnippet_HasCustomNpmRunBuildCommand_EvenIfPackageJsonHasBuildNodes()
        {
            // Arrange
            const string packageJson   = @"{
              ""main"": ""server.js"",
              ""scripts"": {
                ""build"": ""build-node"",
                ""build:azure"": ""azure-node"",
              },
            }";
            var          expectedText  = "custom-npm-run-build";
            var          commonOptions = new BuildScriptGeneratorOptions();
            var          nodePlatform  = CreateNodePlatform(
                commonOptions,
                new NodeScriptGeneratorOptions {
                CustomRunBuildCommand = expectedText
            },
                new NodePlatformInstaller(
                    Options.Create(commonOptions),
                    NullLoggerFactory.Instance));
            var repo = new MemorySourceRepo();

            repo.AddFile(packageJson, NodeConstants.PackageJsonFileName);
            var context        = CreateContext(repo);
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = NodeConstants.PlatformName,
                PlatformVersion = "10.10",
            };

            // Act
            var buildScriptSnippet = nodePlatform.GenerateBashBuildScriptSnippet(context, detectorResult);

            // Assert
            Assert.NotNull(buildScriptSnippet);
            Assert.Contains(expectedText, buildScriptSnippet.BashBuildScriptSnippet);
            Assert.DoesNotContain("npm run build", buildScriptSnippet.BashBuildScriptSnippet);
            Assert.DoesNotContain("npm run build:azure", buildScriptSnippet.BashBuildScriptSnippet);
        }
Пример #14
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var manifestFileProperties = new Dictionary <string, string>();

            manifestFileProperties[ManifestFilePropertyKeys.HugoVersion] = detectorResult.PlatformVersion;
            manifestFileProperties[ManifestFilePropertyKeys.Frameworks]  = "hugo";
            this.logger.LogInformation("Detected the following frameworks: hugo");
            Console.WriteLine("Detected the following frameworks: hugo");

            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.HugoSnippet,
                model: null,
                this.logger);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Пример #15
0
        /// <inheritdoc/>
        public void ResolveVersions(RepositoryContext context, PlatformDetectorResult detectorResult)
        {
            var dotNetCorePlatformDetectorResult = detectorResult as DotNetCorePlatformDetectorResult;

            if (dotNetCorePlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(DotNetCorePlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            // Get runtime version
            var resolvedRuntimeVersion = this.GetRuntimeVersionUsingHierarchicalRules(
                dotNetCorePlatformDetectorResult.PlatformVersion);

            resolvedRuntimeVersion = this.GetMaxSatisfyingRuntimeVersionAndVerify(resolvedRuntimeVersion);
            dotNetCorePlatformDetectorResult.PlatformVersion = resolvedRuntimeVersion;

            var versionMap = this.versionProvider.GetSupportedVersions();
            var sdkVersion = this.GetSdkVersion(context, dotNetCorePlatformDetectorResult.PlatformVersion, versionMap);

            dotNetCorePlatformDetectorResult.SdkVersion = sdkVersion;
        }
Пример #16
0
        public void GeneratedBuildSnippet_ThrowsException_IfRequireBuildPropertyIsSet_AndNoBuildStepIsProvided()
        {
            // Arrange
            const string packageJson   = @"{
              ""main"": ""server.js"",
              ""scripts"": {
              },
            }";
            var          commonOptions = new BuildScriptGeneratorOptions();
            var          nodePlatform  = CreateNodePlatform(
                commonOptions,
                new NodeScriptGeneratorOptions(),
                new NodePlatformInstaller(
                    Options.Create(commonOptions),
                    NullLoggerFactory.Instance));
            var repo = new MemorySourceRepo();

            repo.AddFile(packageJson, NodeConstants.PackageJsonFileName);
            var context = CreateContext(repo);

            context.Properties[NodePlatform.RequireBuildPropertyKey] = "true";
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = NodeConstants.PlatformName,
                PlatformVersion = "10.10",
            };

            // Act & Assert
            var exception = Assert.Throws <NoBuildStepException>(
                () => nodePlatform.GenerateBashBuildScriptSnippet(context, detectorResult));

            Assert.Equal(
                "Could not find either 'build' or 'build:azure' node under 'scripts' in package.json. " +
                "Could not find value for custom run build command using the environment variable " +
                "key 'RUN_BUILD_COMMAND'.",
                exception.Message);
        }
Пример #17
0
        public void GeneratedScript_UsesComposerInstall()
        {
            // Arrange
            var scriptGenerator = GetScriptGenerator(
                defaultVersion: "7.3",
                new BuildScriptGeneratorOptions(),
                new PhpScriptGeneratorOptions());
            var repo = new MemorySourceRepo();

            repo.AddFile(ComposerFileWithBuildScript, PhpConstants.ComposerFileName);
            var context        = CreateBuildScriptGeneratorContext(repo);
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = PhpConstants.PlatformName,
                PlatformVersion = "10.10.10",
            };

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context, detectorResult);

            // Assert
            Assert.NotNull(snippet);
            Assert.Contains("$composer install", snippet.BashBuildScriptSnippet);
        }
Пример #18
0
        /// <inheritdoc/>
        public string GetInstallerScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var phpPlatformDetectorResult = detectorResult as PhpPlatformDetectorResult;

            if (phpPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(PhpPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            if (this.commonOptions.EnableDynamicInstall)
            {
                this.logger.LogDebug("Dynamic install is enabled.");

                var scriptBuilder = new StringBuilder();

                this.InstallPhp(phpPlatformDetectorResult.PlatformVersion, scriptBuilder);

                this.InstallPhpComposer(phpPlatformDetectorResult.PhpComposerVersion, scriptBuilder);

                if (scriptBuilder.Length == 0)
                {
                    return(null);
                }

                return(scriptBuilder.ToString());
            }
            else
            {
                this.logger.LogDebug("Dynamic install not enabled.");
                return(null);
            }
        }
Пример #19
0
        public void GeneratedBuildSnippet_DoesNotThrowException_IfNoBuildStepIsProvided_AndRequireBuildPropertyIsSet_ToFalse()
        {
            // Arrange
            const string packageJson   = @"{
              ""main"": ""server.js"",
              ""scripts"": {
              },
            }";
            var          commonOptions = new BuildScriptGeneratorOptions();
            var          nodePlatform  = CreateNodePlatform(
                commonOptions,
                new NodeScriptGeneratorOptions {
                CustomRunBuildCommand = "custom command here"
            },
                new NodePlatformInstaller(
                    Options.Create(commonOptions),
                    NullLoggerFactory.Instance));
            var repo = new MemorySourceRepo();

            repo.AddFile(packageJson, NodeConstants.PackageJsonFileName);
            var context = CreateContext(repo);

            context.Properties[NodePlatform.RequireBuildPropertyKey] = "false";
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = NodeConstants.PlatformName,
                PlatformVersion = "10.10",
            };

            // Act
            var buildScriptSnippet = nodePlatform.GenerateBashBuildScriptSnippet(context, detectorResult);

            // Assert
            Assert.NotNull(buildScriptSnippet);
            Assert.Contains("custom command here", buildScriptSnippet.BashBuildScriptSnippet);
        }
Пример #20
0
        public void GeneratedBuildSnippet_DoesNotThrowException_IfPackageJsonHasBuildNode_AndRequireBuildPropertyIsSet(
            string requireBuild)
        {
            // Arrange
            const string packageJson   = @"{
              ""main"": ""server.js"",
              ""scripts"": {
                ""build"": ""build-node"",
              },
            }";
            var          commonOptions = new BuildScriptGeneratorOptions();
            var          nodePlatform  = CreateNodePlatform(
                commonOptions,
                new NodeScriptGeneratorOptions(),
                new NodePlatformInstaller(
                    Options.Create(commonOptions),
                    NullLoggerFactory.Instance));
            var repo = new MemorySourceRepo();

            repo.AddFile(packageJson, NodeConstants.PackageJsonFileName);
            var context = CreateContext(repo);

            context.Properties[NodePlatform.RequireBuildPropertyKey] = requireBuild;
            var detectorResult = new PlatformDetectorResult
            {
                Platform        = NodeConstants.PlatformName,
                PlatformVersion = "10.10",
            };

            // Act
            var buildScriptSnippet = nodePlatform.GenerateBashBuildScriptSnippet(context, detectorResult);

            // Assert
            Assert.NotNull(buildScriptSnippet);
            Assert.Contains("npm run build", buildScriptSnippet.BashBuildScriptSnippet);
        }
Пример #21
0
        public IDictionary <string, string> GetToolsToBeSetInPath(
            RepositoryContext context,
            PlatformDetectorResult detectorResult)
        {
            var pythonPlatformDetectorResult = detectorResult as PythonPlatformDetectorResult;

            if (pythonPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(PythonPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            // Since conda is already in the path we do not need to set it explicitly in the path
            if (IsCondaEnvironment(pythonPlatformDetectorResult))
            {
                return(null);
            }

            var tools = new Dictionary <string, string>();

            tools[PythonConstants.PlatformName] = pythonPlatformDetectorResult.PlatformVersion;
            return(tools);
        }
Пример #22
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext ctx,
            PlatformDetectorResult detectorResult)
        {
            var nodePlatformDetectorResult = detectorResult as NodePlatformDetectorResult;

            if (nodePlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(NodePlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            var manifestFileProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            manifestFileProperties[ManifestFilePropertyKeys.NodeVersion] = nodePlatformDetectorResult.PlatformVersion;

            var    packageJson                    = GetPackageJsonObject(ctx.SourceRepo, _logger);
            string runBuildCommand                = null;
            string runBuildAzureCommand           = null;
            string runBuildLernaCommand           = null;
            string runBuildLageCommand            = null;
            string installLernaCommand            = null;
            bool   configureYarnCache             = false;
            string yarnCacheFolderName            = null;
            string packageManagerCmd              = null;
            string packageInstallCommand          = null;
            string packageInstallerVersionCommand = null;

            if (_nodeScriptGeneratorOptions.EnableNodeMonorepoBuild &&
                nodePlatformDetectorResult.HasLernaJsonFile &&
                nodePlatformDetectorResult.HasLageConfigJSFile)
            {
                _logger.LogError(
                    "Could not build monorepo with multiple package management tools. Both 'lerna.json' and 'lage.config.js' files are found.");
                throw new InvalidUsageException("Multiple monorepo package management tools are found, please choose to use either Lerna or Lage.");
            }

            if (ctx.SourceRepo.FileExists(NodeConstants.YarnLockFileName))
            {
                packageManagerCmd              = NodeConstants.YarnCommand;
                configureYarnCache             = false;
                packageInstallerVersionCommand = NodeConstants.YarnVersionCommand;

                // In Yarn 2+ and .yarnrc.yml file replaces .yarnrc in Yarn 2+.
                // Applying yarn 2 cache folder name and package install command.
                if (nodePlatformDetectorResult.HasYarnrcYmlFile)
                {
                    yarnCacheFolderName   = NodeConstants.Yarn2ConfigFolderName;
                    packageInstallCommand = NodeConstants.Yarn2PackageInstallCommand;
                }
                else
                {
                    yarnCacheFolderName   = NodeConstants.Yarn1ConfigFolderName;
                    packageInstallCommand = NodeConstants.YarnPackageInstallCommand;
                }
            }
            else
            {
                packageManagerCmd              = NodeConstants.NpmCommand;
                packageInstallCommand          = NodeConstants.NpmPackageInstallCommand;
                packageInstallerVersionCommand = NodeConstants.NpmVersionCommand;
            }

            if (_nodeScriptGeneratorOptions.EnableNodeMonorepoBuild)
            {
                // If a 'lerna.json' file exists, override the npm client that lerna chosen to build monorepo.
                if (nodePlatformDetectorResult.HasLernaJsonFile)
                {
                    packageManagerCmd    = nodePlatformDetectorResult.LernaNpmClient;
                    runBuildLernaCommand = string.Format(
                        NodeConstants.PkgMgrRunBuildCommandTemplate,
                        NodeConstants.LernaCommand);
                    if (!string.IsNullOrEmpty(nodePlatformDetectorResult.LernaNpmClient) &&
                        nodePlatformDetectorResult.LernaNpmClient.Equals(
                            NodeConstants.YarnCommand, StringComparison.OrdinalIgnoreCase))
                    {
                        packageInstallCommand          = NodeConstants.YarnPackageInstallCommand;
                        configureYarnCache             = false;
                        packageInstallerVersionCommand = NodeConstants.YarnVersionCommand;
                        installLernaCommand            = NodeConstants.InstallLernaCommandYarn;
                    }
                    else
                    {
                        packageInstallCommand          = NodeConstants.NpmPackageInstallCommand;
                        packageInstallerVersionCommand = NodeConstants.NpmVersionCommand;
                        installLernaCommand            = NodeConstants.InstallLernaCommandNpm;
                    }
                }

                // If a 'lage.config.js' file exits, run build using lage specifc commands.
                if (nodePlatformDetectorResult.HasLageConfigJSFile)
                {
                    runBuildLageCommand = ctx.SourceRepo.FileExists(NodeConstants.YarnLockFileName) ?
                                          NodeConstants.YarnRunLageBuildCommand : NodeConstants.NpmRunLageBuildCommand;
                }
            }

            _logger.LogInformation("Using {packageManager}", packageManagerCmd);

            var hasProdDependencies = false;

            if (packageJson?.dependencies != null)
            {
                hasProdDependencies = true;
            }

            var hasDevDependencies = false;

            if (packageJson?.devDependencies != null)
            {
                // If development time dependencies are present we want to avoid copying them to improve performance
                hasDevDependencies = true;
            }

            var productionOnlyPackageInstallCommand = string.Format(
                NodeConstants.ProductionOnlyPackageInstallCommandTemplate, packageInstallCommand);

            if (string.IsNullOrEmpty(_nodeScriptGeneratorOptions.CustomBuildCommand) &&
                string.IsNullOrEmpty(_nodeScriptGeneratorOptions.CustomRunBuildCommand) &&
                string.IsNullOrEmpty(runBuildLernaCommand) &&
                string.IsNullOrEmpty(runBuildLageCommand))
            {
                var scriptsNode = packageJson?.scripts;
                if (scriptsNode != null)
                {
                    if (scriptsNode.build != null)
                    {
                        runBuildCommand = string.Format(NodeConstants.PkgMgrRunBuildCommandTemplate, packageManagerCmd);
                    }

                    if (scriptsNode["build:azure"] != null && !_commonOptions.ShouldPackage)
                    {
                        runBuildAzureCommand = string.Format(
                            NodeConstants.PkgMgrRunBuildAzureCommandTemplate,
                            packageManagerCmd);
                    }
                }
            }

            if (IsBuildRequired(ctx) &&
                string.IsNullOrEmpty(_nodeScriptGeneratorOptions.CustomBuildCommand) &&
                string.IsNullOrEmpty(_nodeScriptGeneratorOptions.CustomRunBuildCommand) &&
                string.IsNullOrEmpty(runBuildCommand) &&
                string.IsNullOrEmpty(runBuildAzureCommand) &&
                string.IsNullOrEmpty(runBuildLernaCommand) &&
                string.IsNullOrEmpty(runBuildLageCommand))
            {
                throw new NoBuildStepException(
                          "Could not find either 'build' or 'build:azure' node under 'scripts' in package.json. " +
                          "Could not find value for custom run build command using the environment variable " +
                          "key 'RUN_BUILD_COMMAND'." +
                          "Could not find tools for building monorepos, no 'lerna.json' or 'lage.config.js' files found.");
            }

            if (packageJson?.dependencies != null)
            {
                var depSpecs = ((JObject)packageJson.dependencies).ToObject <IDictionary <string, string> >();
                _logger.LogDependencies(
                    _commonOptions.PlatformName,
                    nodePlatformDetectorResult.PlatformVersion,
                    depSpecs.Select(d => d.Key + d.Value));
            }

            if (packageJson?.devDependencies != null)
            {
                var depSpecs = ((JObject)packageJson.devDependencies).ToObject <IDictionary <string, string> >();
                _logger.LogDependencies(
                    _commonOptions.PlatformName,
                    nodePlatformDetectorResult.PlatformVersion,
                    depSpecs.Select(d => d.Key + d.Value), true);
            }

            string compressNodeModulesCommand    = null;
            string compressedNodeModulesFileName = null;

            GetNodeModulesPackOptions(ctx, out compressNodeModulesCommand, out compressedNodeModulesFileName);

            if (!string.IsNullOrWhiteSpace(compressedNodeModulesFileName))
            {
                manifestFileProperties[NodeConstants.NodeModulesFileBuildProperty] = compressedNodeModulesFileName;
            }

            bool   pruneDevDependencies     = ShouldPruneDevDependencies(ctx);
            string appInsightsInjectCommand = string.Empty;

            GetAppOutputDirPath(packageJson, manifestFileProperties);

            string customRegistryUrl = null;

            if (ctx.Properties != null)
            {
                ctx.Properties.TryGetValue(RegistryUrlPropertyKey, out customRegistryUrl);
                if (!string.IsNullOrWhiteSpace(customRegistryUrl))
                {
                    // Write the custom registry to the build manifest
                    manifestFileProperties[$"{NodeConstants.PlatformName}_{RegistryUrlPropertyKey}"] = customRegistryUrl;
                }
            }

            string packageDir = null;

            if (ctx.Properties != null)
            {
                ctx.Properties.TryGetValue(PackageDirectoryPropertyKey, out packageDir);
                if (!string.IsNullOrWhiteSpace(packageDir))
                {
                    // Write the package directory to the build manifest
                    manifestFileProperties[$"{PackageDirectoryPropertyKey}"] = packageDir;
                }
            }

            var scriptProps = new NodeBashBuildSnippetProperties
            {
                PackageRegistryUrl                  = customRegistryUrl,
                PackageDirectory                    = packageDir,
                PackageInstallCommand               = packageInstallCommand,
                NpmRunBuildCommand                  = runBuildCommand,
                NpmRunBuildAzureCommand             = runBuildAzureCommand,
                HasProdDependencies                 = hasProdDependencies,
                HasDevDependencies                  = hasDevDependencies,
                ProductionOnlyPackageInstallCommand = productionOnlyPackageInstallCommand,
                CompressNodeModulesCommand          = compressNodeModulesCommand,
                CompressedNodeModulesFileName       = compressedNodeModulesFileName,
                ConfigureYarnCache                  = configureYarnCache,
                YarnCacheFolderName                 = yarnCacheFolderName,
                PruneDevDependencies                = pruneDevDependencies,
                AppInsightsInjectCommand            = appInsightsInjectCommand,
                AppInsightsPackageName              = NodeConstants.NodeAppInsightsPackageName,
                AppInsightsLoaderFileName           = NodeAppInsightsLoader.NodeAppInsightsLoaderFileName,
                PackageInstallerVersionCommand      = packageInstallerVersionCommand,
                RunNpmPack            = _commonOptions.ShouldPackage,
                CustomBuildCommand    = _nodeScriptGeneratorOptions.CustomBuildCommand,
                CustomRunBuildCommand = _nodeScriptGeneratorOptions.CustomRunBuildCommand,
                LernaRunBuildCommand  = runBuildLernaCommand,
                InstallLernaCommand   = installLernaCommand,
                LernaInitCommand      = NodeConstants.LernaInitCommand,
                LernaBootstrapCommand = NodeConstants.LernaBootstrapCommand,
                InstallLageCommand    = NodeConstants.InstallLageCommand,
                LageRunBuildCommand   = runBuildLageCommand,
            };

            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.NodeBuildSnippet,
                scriptProps,
                _logger);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Пример #23
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var pythonPlatformDetectorResult = detectorResult as PythonPlatformDetectorResult;

            if (pythonPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(PythonPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            if (IsCondaEnvironment(pythonPlatformDetectorResult))
            {
                return(GetBuildScriptSnippetForConda(context, pythonPlatformDetectorResult));
            }

            var manifestFileProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            manifestFileProperties[ManifestFilePropertyKeys.PythonVersion] = pythonPlatformDetectorResult.PlatformVersion;

            var packageDir     = GetPackageDirectory(context);
            var virtualEnvName = GetVirtualEnvironmentName(context);
            var isPythonPackageCommandEnabled = _commonOptions.ShouldPackage;
            var pythonPackageWheelType        = GetPythonPackageWheelType(context);

            if (!isPythonPackageCommandEnabled && !string.IsNullOrWhiteSpace(pythonPackageWheelType))
            {
                throw new InvalidUsageException($"Option '{PythonPackageWheelPropertyKey}' can't exist" +
                                                $"without package command being enabled. Please provide --package along with wheel type");
            }

            if (isPythonPackageCommandEnabled &&
                !string.IsNullOrWhiteSpace(pythonPackageWheelType))
            {
                if (!string.Equals(pythonPackageWheelType.ToLower(), "universal"))
                {
                    throw new InvalidUsageException($"Option '{PythonPackageWheelPropertyKey}' can only have 'universal' as value.'");
                }

                manifestFileProperties[PythonManifestFilePropertyKeys.PackageWheel] = pythonPackageWheelType;
            }

            if (!string.IsNullOrWhiteSpace(packageDir) && !string.IsNullOrWhiteSpace(virtualEnvName))
            {
                throw new InvalidUsageException($"Options '{TargetPackageDirectoryPropertyKey}' and " +
                                                $"'{VirtualEnvironmentNamePropertyKey}' are mutually exclusive. Please provide " +
                                                $"only the target package directory or virtual environment name.");
            }

            if (string.IsNullOrWhiteSpace(packageDir))
            {
                // If the package directory was not provided, we default to virtual envs
                if (string.IsNullOrWhiteSpace(virtualEnvName))
                {
                    virtualEnvName = GetDefaultVirtualEnvName(pythonPlatformDetectorResult);
                }

                manifestFileProperties[PythonManifestFilePropertyKeys.VirtualEnvName] = virtualEnvName;
            }
            else
            {
                manifestFileProperties[PythonManifestFilePropertyKeys.PackageDir] = packageDir;
            }

            var virtualEnvModule = string.Empty;
            var virtualEnvParams = string.Empty;

            var pythonVersion = pythonPlatformDetectorResult.PlatformVersion;

            _logger.LogDebug("Selected Python version: {pyVer}", pythonVersion);

            if (!string.IsNullOrEmpty(pythonVersion) && !string.IsNullOrWhiteSpace(virtualEnvName))
            {
                (virtualEnvModule, virtualEnvParams) = GetVirtualEnvModules(pythonVersion);

                _logger.LogDebug(
                    "Using virtual environment {venv}, module {venvModule}",
                    virtualEnvName,
                    virtualEnvModule);
            }

            GetVirtualEnvPackOptions(
                context,
                virtualEnvName,
                out var compressVirtualEnvCommand,
                out var compressedVirtualEnvFileName);

            if (!string.IsNullOrWhiteSpace(compressedVirtualEnvFileName))
            {
                manifestFileProperties[PythonManifestFilePropertyKeys.CompressedVirtualEnvFile]
                    = compressedVirtualEnvFileName;
            }

            TryLogDependencies(pythonVersion, context.SourceRepo);

            var scriptProps = new PythonBashBuildSnippetProperties(
                virtualEnvironmentName: virtualEnvName,
                virtualEnvironmentModule: virtualEnvModule,
                virtualEnvironmentParameters: virtualEnvParams,
                packagesDirectory: packageDir,
                enableCollectStatic: _pythonScriptGeneratorOptions.EnableCollectStatic,
                compressVirtualEnvCommand: compressVirtualEnvCommand,
                compressedVirtualEnvFileName: compressedVirtualEnvFileName,
                runPythonPackageCommand: isPythonPackageCommandEnabled,
                pythonPackageWheelProperty: pythonPackageWheelType);
            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.PythonSnippet,
                scriptProps,
                _logger);

            return(new BuildScriptSnippet()
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Пример #24
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var dotNetCorePlatformDetectorResult = detectorResult as DotNetCorePlatformDetectorResult;

            if (dotNetCorePlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(DotNetCorePlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            var versionMap = _versionProvider.GetSupportedVersions();

            string globalJsonSdkVersion = null;

            if (_commonOptions.EnableDynamicInstall)
            {
                var availableSdks = versionMap.Values;
                globalJsonSdkVersion = _globalJsonSdkResolver.GetSatisfyingSdkVersion(
                    context.SourceRepo,
                    detectorResult.PlatformVersion,
                    availableSdks);
            }

            var manifestFileProperties = new Dictionary <string, string>();

            manifestFileProperties[ManifestFilePropertyKeys.OperationId] = context.OperationId;
            manifestFileProperties[ManifestFilePropertyKeys.DotNetCoreRuntimeVersion]
                = detectorResult.PlatformVersion;

            if (string.IsNullOrEmpty(globalJsonSdkVersion))
            {
                manifestFileProperties[ManifestFilePropertyKeys.DotNetCoreSdkVersion]
                    = versionMap[detectorResult.PlatformVersion];
            }
            else
            {
                manifestFileProperties[ManifestFilePropertyKeys.DotNetCoreSdkVersion] = globalJsonSdkVersion;
            }

            var projectFile = dotNetCorePlatformDetectorResult.ProjectFile;

            if (string.IsNullOrEmpty(projectFile))
            {
                return(null);
            }

            var templateProperties = new DotNetCoreBashBuildSnippetProperties
            {
                ProjectFile   = projectFile,
                Configuration = GetBuildConfiguration(),
            };

            var script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.DotNetCoreSnippet,
                templateProperties,
                _logger);

            SetStartupFileNameInfoInManifestFile(context, projectFile, manifestFileProperties);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,

                // Setting this to false to avoid copying files like '.cs' to the destination
                CopySourceDirectoryContentToDestinationDirectory = false,
            });
        }
Пример #25
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext ctx,
            PlatformDetectorResult detectorResult)
        {
            var javaPlatformDetectorResult = detectorResult as JavaPlatformDetectorResult;

            if (javaPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(JavaPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            var manifestFileProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            manifestFileProperties[ManifestFilePropertyKeys.JavaVersion] = detectorResult.PlatformVersion;

            string command = string.Empty;

            if (javaPlatformDetectorResult.UsesMavenWrapperTool)
            {
                if (_commonOptions.ShouldPackage)
                {
                    command = JavaConstants.CreatePackageCommandUsingMavenWrapper;
                }
                else
                {
                    command = JavaConstants.CompileCommandUsingMavenWrapper;
                }
            }
            else if (javaPlatformDetectorResult.UsesMaven)
            {
                if (_commonOptions.ShouldPackage)
                {
                    command = JavaConstants.CreatePackageCommandUsingMaven;
                }
                else
                {
                    command = JavaConstants.CompileCommandUsingMaven;
                }

                // Maven spits out lot of information related to downloading of packages which is too verbose.
                // Since the --quiet option is too quiet, we are trying to use a new switch below to just mute the
                // messages related to transfer progress of these downloads.
                // https://maven.apache.org/docs/3.6.1/release-notes.html#user-visible-changes
                var currentMavenVersion = new SemVer.Version(javaPlatformDetectorResult.MavenVersion);
                if (currentMavenVersion.CompareTo(JavaConstants.MinMavenVersionWithNoTransferProgressSupport) >= 0)
                {
                    command = $"{command} --no-transfer-progress";
                }
            }

            var scriptProps = new JavaBashBuildSnippetProperties();

            scriptProps.UsesMaven            = javaPlatformDetectorResult.UsesMaven;
            scriptProps.UsesMavenWrapperTool = javaPlatformDetectorResult.UsesMavenWrapperTool;
            scriptProps.Command = command;

            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.JavaBuildSnippet,
                scriptProps,
                _logger);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Пример #26
0
 public string GetInstallerScriptSnippet(
     BuildScriptGeneratorContext context,
     PlatformDetectorResult detectorResult)
 {
     return(_installationScriptContent);
 }
 public string GetInstallerScriptSnippet(
     BuildScriptGeneratorContext context,
     PlatformDetectorResult detectorResult)
 {
     throw new NotImplementedException();
 }
Пример #28
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var manifestFileProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            manifestFileProperties[ManifestFilePropertyKeys.PythonVersion] = detectorResult.PlatformVersion;

            var packageDir     = GetPackageDirectory(context);
            var virtualEnvName = GetVirtualEnvironmentName(context);

            if (!string.IsNullOrWhiteSpace(packageDir) && !string.IsNullOrWhiteSpace(virtualEnvName))
            {
                throw new InvalidUsageException($"Options '{TargetPackageDirectoryPropertyKey}' and " +
                                                $"'{VirtualEnvironmentNamePropertyKey}' are mutually exclusive. Please provide " +
                                                $"only the target package directory or virtual environment name.");
            }

            if (string.IsNullOrWhiteSpace(packageDir))
            {
                // If the package directory was not provided, we default to virtual envs
                if (string.IsNullOrWhiteSpace(virtualEnvName))
                {
                    virtualEnvName = GetDefaultVirtualEnvName(detectorResult);
                }

                manifestFileProperties[PythonManifestFilePropertyKeys.VirtualEnvName] = virtualEnvName;
            }
            else
            {
                manifestFileProperties[PythonManifestFilePropertyKeys.PackageDir] = packageDir;
            }

            var virtualEnvModule    = string.Empty;
            var virtualEnvCopyParam = string.Empty;

            var pythonVersion = detectorResult.PlatformVersion;

            _logger.LogDebug("Selected Python version: {pyVer}", pythonVersion);

            if (!string.IsNullOrEmpty(pythonVersion) && !string.IsNullOrWhiteSpace(virtualEnvName))
            {
                (virtualEnvModule, virtualEnvCopyParam) = GetVirtualEnvModules(pythonVersion);

                _logger.LogDebug(
                    "Using virtual environment {venv}, module {venvModule}",
                    virtualEnvName,
                    virtualEnvModule);
            }

            GetVirtualEnvPackOptions(
                context,
                virtualEnvName,
                out var compressVirtualEnvCommand,
                out var compressedVirtualEnvFileName);

            if (!string.IsNullOrWhiteSpace(compressedVirtualEnvFileName))
            {
                manifestFileProperties[PythonManifestFilePropertyKeys.CompressedVirtualEnvFile]
                    = compressedVirtualEnvFileName;
            }

            TryLogDependencies(pythonVersion, context.SourceRepo);

            var scriptProps = new PythonBashBuildSnippetProperties(
                virtualEnvironmentName: virtualEnvName,
                virtualEnvironmentModule: virtualEnvModule,
                virtualEnvironmentParameters: virtualEnvCopyParam,
                packagesDirectory: packageDir,
                enableCollectStatic: _pythonScriptGeneratorOptions.EnableCollectStatic,
                compressVirtualEnvCommand: compressVirtualEnvCommand,
                compressedVirtualEnvFileName: compressedVirtualEnvFileName);
            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.PythonSnippet,
                scriptProps,
                _logger);

            return(new BuildScriptSnippet()
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Пример #29
0
        // To enable unit testing
        internal static bool TryValidateSuppliedPlatformsAndVersions(
            IEnumerable <IProgrammingPlatform> availablePlatforms,
            string suppliedPlatformsAndVersions,
            string suppliedPlatformsAndVersionsFile,
            IConsole console,
            out List <PlatformDetectorResult> results)
        {
            results = new List <PlatformDetectorResult>();

            if (string.IsNullOrEmpty(suppliedPlatformsAndVersions) &&
                string.IsNullOrEmpty(suppliedPlatformsAndVersionsFile))
            {
                return(false);
            }

            if (!string.IsNullOrEmpty(suppliedPlatformsAndVersionsFile) &&
                !File.Exists(suppliedPlatformsAndVersionsFile))
            {
                console.WriteErrorLine($"Supplied file '{suppliedPlatformsAndVersionsFile}' does not exist.");
                return(false);
            }

            IEnumerable <string> platformsAndVersions;

            if (string.IsNullOrEmpty(suppliedPlatformsAndVersions))
            {
                var lines = File.ReadAllLines(suppliedPlatformsAndVersionsFile);
                platformsAndVersions = lines
                                       .Where(line => !string.IsNullOrEmpty(line) && !line.StartsWith('#'));
            }
            else
            {
                // Example: python,dotnet=3.1.300, node=12.3, Python=3.7.3
                platformsAndVersions = suppliedPlatformsAndVersions
                                       .Trim()
                                       .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                       .Select(nv => nv.Trim());
            }

            var platformNames = availablePlatforms.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase);

            foreach (var platformNameAndVersion in platformsAndVersions)
            {
                var parts = platformNameAndVersion.Split("=", StringSplitOptions.RemoveEmptyEntries);

                // It is OK to have a platform name without version in which case a default version of the platform
                // is installed.
                string platformName = null;
                string version      = null;
                platformName = parts[0].Trim();
                if (parts.Length == 2)
                {
                    version = parts[1].Trim();
                }

                if (!platformNames.ContainsKey(platformName))
                {
                    console.WriteErrorLine(
                        $"Platform name '{platformName}' is not valid. Make sure platform name matches one of the " +
                        $"following names: {string.Join(", ", platformNames.Keys)}");
                    return(false);
                }

                var platform        = platformNames[platformName];
                var resolvedVersion = platform.ResolveVersion(version);

                var platformDetectorResult = new PlatformDetectorResult
                {
                    Platform        = platform.Name,
                    PlatformVersion = resolvedVersion,
                };

                results.Add(platformDetectorResult);
            }

            return(true);
        }
Пример #30
0
 public IDictionary <string, string> GetToolsToBeSetInPath(
     RepositoryContext context,
     PlatformDetectorResult detectorResult)
 {
     throw new NotImplementedException();
 }