Exemple #1
0
        private string GetVersionFromGemFile(DetectorContext context)
        {
            try
            {
                var gemFileContent      = context.SourceRepo.ReadFile(RubyConstants.GemFileName);
                var gemFileContentLines = gemFileContent.Split('\n');

                // Example content from a Gemfile:
                // source "https://rubygems.org"
                // gem 'sinatra'
                // ruby "2.5.1"
                foreach (var gemFileContentLine in gemFileContentLines)
                {
                    if (gemFileContentLine.Trim().StartsWith("ruby", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var rubyVersionLine = gemFileContentLine.Trim().Split(' ');
                        // Make sure it's in valid format.
                        if (rubyVersionLine.Length == 2)
                        {
                            return(rubyVersionLine[1].Trim('\"').Trim('\''));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(
                    ex,
                    $"Exception caught while trying to parse {RubyConstants.GemFileName}");
            }

            return(null);
        }
Exemple #2
0
        /// <inheritdoc/>
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            var projectFile = _projectFileProvider.GetRelativePathToProjectFile(context);

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

            var sourceRepo             = context.SourceRepo;
            var appDirectory           = Path.GetDirectoryName(projectFile);
            var projectFileDoc         = XDocument.Load(new StringReader(sourceRepo.ReadFile(projectFile)));
            var targetFrameworkElement = projectFileDoc.XPathSelectElement(
                DotNetCoreConstants.TargetFrameworkElementXPathExpression);
            var targetFramework = targetFrameworkElement?.Value;

            if (string.IsNullOrEmpty(targetFramework))
            {
                _logger.LogDebug(
                    $"Could not find 'TargetFramework' element in the project file.");
                return(null);
            }

            var version = GetVersion(targetFramework);

            return(new DotNetCorePlatformDetectorResult
            {
                Platform = DotNetCoreConstants.PlatformName,
                PlatformVersion = version,
                ProjectFile = projectFile,
                AppDirectory = appDirectory,
            });
        }
Exemple #3
0
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            string appDirectory = string.Empty;
            var    sourceRepo   = context.SourceRepo;

            // check if go.mod exists
            if (!sourceRepo.FileExists(GolangConstants.GoModFileName))
            {
                this.logger.LogError(
                    $"Could not find {GolangConstants.GoModFileName} in repo");
                return(null);
            }

            this.logger.LogInformation($"Found {GolangConstants.GoModFileName} at the root of the repo. ");

            var version = this.GetVersion(context);

            // TODO: add additional fields that are helpful
            return(new GolangPlatformDetectorResult
            {
                Platform = GolangConstants.PlatformName,
                GoModExists = true,
                PlatformVersion = version,
                AppDirectory = appDirectory,
            });
        }
Exemple #4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"[request] C# HTTP trigger function processed a request.");

            try
            {
                var dbContextOptionsBuilder = new DbContextOptionsBuilder <DetectorContext>();

                dbContextOptionsBuilder.UseSqlServer(_connectionString);

                using (var context = new DetectorContext(dbContextOptionsBuilder.Options))
                {
                    context.Set <IntrudeRecordEntity>().Add(new IntrudeRecordEntity());
                    context.SaveChanges();
                }

                log.LogInformation($"[failed] C# HTTP trigger function processed a request success.");
            }
            catch (Exception ex)
            {
                log.LogInformation($"[failed] C# HTTP trigger function processed a request failed. ({ex.Message})");

                return(new JsonResult(new { Status = false }));
            }

            return(new JsonResult(new { Status = true }));
        }
        public string GetRelativePathToProjectFile(DetectorContext context)
        {
            var projectPath = GetProjectInfoFromSettings(context);

            if (string.IsNullOrEmpty(projectPath))
            {
                _logger.LogDebug(
                    "No request to build a particular project file explicitly using the " +
                    $"PROJECT environment variable");
                return(null);
            }

            var projectFileWithRelativePath = projectPath.Trim();
            var projectFile = Path.Combine(context.SourceRepo.RootPath, projectFileWithRelativePath);

            if (context.SourceRepo.FileExists(projectFile))
            {
                _logger.LogDebug($"Using the given .NET Core project file to build.");
            }
            else
            {
                _logger.LogWarning($"Could not find the .NET Core project file.");
                throw new InvalidProjectFileException("Could not find the .NET Core project file.");
            }

            return(projectFileWithRelativePath);
        }
Exemple #6
0
        internal override int Execute(IServiceProvider serviceProvider, IConsole console)
        {
            var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger <DetectCommand>();
            var sourceRepo    = new LocalSourceRepo(this.SourceDir, loggerFactory);
            var ctx           = new DetectorContext
            {
                SourceRepo = sourceRepo,
            };

            var detector = serviceProvider.GetRequiredService <IDetector>();
            var detectedPlatformResults = detector.GetAllDetectedPlatforms(ctx);

            using (var timedEvent = logger.LogTimedEvent("DetectCommand"))
            {
                if (detectedPlatformResults == null || !detectedPlatformResults.Any())
                {
                    logger?.LogError($"No platforms and versions detected from source directory: '{this.SourceDir}'");
                    console.WriteErrorLine($"No platforms and versions detected from source directory: '{this.SourceDir}'");
                }

                if (!string.IsNullOrEmpty(this.OutputFormat) &&
                    string.Equals(this.OutputFormat, "json", StringComparison.OrdinalIgnoreCase))
                {
                    PrintJsonResult(detectedPlatformResults, console);
                }
                else
                {
                    PrintTableResult(detectedPlatformResults, console);
                }

                return(ProcessConstants.ExitSuccess);
            }
        }
Exemple #7
0
        private string GetLernaJsonNpmClient(DetectorContext context)
        {
            var npmClientName = string.Empty;

            if (!context.SourceRepo.FileExists(NodeConstants.LernaJsonFileName))
            {
                return(npmClientName);
            }

            try
            {
                dynamic lernaJson = ReadJsonObjectFromFile(context.SourceRepo, NodeConstants.LernaJsonFileName);
                if (lernaJson?.npmClient != null)
                {
                    npmClientName = lernaJson["npmClient"].Value as string;
                }
                else
                {
                    // Default Client for Lerna is npm.
                    npmClientName = NodeConstants.NpmToolName;
                }
            }
            catch (Exception exc)
            {
                // Leave malformed lerna.json files for Node.js to handle.
                // This prevents Oryx from erroring out when Node.js itself might be able to tolerate the file.
                this.logger.LogWarning(
                    exc,
                    $"Exception caught while trying to deserialize {NodeConstants.LernaJsonFileName.Hash()}");
            }

            return(npmClientName);
        }
Exemple #8
0
        public void GetAllDetectedPlatforms_InvokesCustomDetector()
        {
            // Arrange
            var configuration = new ConfigurationBuilder().Build();
            var services      = new ServiceCollection();

            services
            .AddPlatformDetectorServices()
            .AddSingleton <IConfiguration>(configuration)
            .TryAddEnumerable(ServiceDescriptor.Singleton <IPlatformDetector, TestDetector>());

            var serviceProvider = services.BuildServiceProvider();
            var sourceDir       = Directory.CreateDirectory(Path.Combine(_tempRootDirPath, Guid.NewGuid().ToString()))
                                  .FullName;
            var context = new DetectorContext
            {
                SourceRepo = new LocalSourceRepo(sourceDir)
            };
            var defaultPlatformDetector = serviceProvider.GetRequiredService <IDetector>();

            // Act
            var detectorResults = defaultPlatformDetector.GetAllDetectedPlatforms(context);

            // Assert
            Assert.NotNull(detectorResults);
            var result = Assert.Single(detectorResults);

            Assert.Equal("test", result.Platform);
            Assert.Equal("1.0.0", result.PlatformVersion);
        }
Exemple #9
0
        private string GetBundlerVersionFromGemFileLock(DetectorContext context)
        {
            try
            {
                var gemFileLockContent      = context.SourceRepo.ReadFile(RubyConstants.GemFileLockName);
                var gemFileLockContentLines = gemFileLockContent.Split('\n');
                gemFileLockContentLines = gemFileLockContentLines.Select(x => x.Trim()).ToArray();

                // Example content from a Gemfile.lock:
                // BUNDLED WITH
                //   1.11.2
                int bundlerVersionLineIndex = Array.IndexOf(gemFileLockContentLines, "BUNDLED WITH");
                if (bundlerVersionLineIndex != -1)
                {
                    return(gemFileLockContentLines[bundlerVersionLineIndex + 1]);
                }
            }
            catch (Exception ex)
            {
                this.logger.LogWarning(
                    ex,
                    $"Exception caught while trying to parse {RubyConstants.GemFileLockName}");
            }

            return(null);
        }
Exemple #10
0
 private string GetVersionFromGemFileLock(DetectorContext context)
 {
     try
     {
         var gemFileLockContent      = context.SourceRepo.ReadFile(RubyConstants.GemFileLockName);
         var gemFileLockContentLines = gemFileLockContent.Split('\n');
         gemFileLockContentLines = gemFileLockContentLines.Select(x => x.Trim()).ToArray();
         // Example content from a Gemfile.lock:
         // PLATFORMS
         //   ruby
         // RUBY VERSION
         //   ruby 2.3.1p112
         int rubyVersionLineIndex = Array.IndexOf(gemFileLockContentLines, "RUBY VERSION");
         if (rubyVersionLineIndex != -1)
         {
             var rubyVersionLine = gemFileLockContentLines[rubyVersionLineIndex + 1].Split(' ');
             // Make sure it's in valid format.
             if (rubyVersionLine.Length == 2)
             {
                 return(rubyVersionLine[1]);
             }
         }
     }
     catch (Exception ex)
     {
         _logger.LogWarning(
             ex,
             $"Exception caught while trying to parse {RubyConstants.GemFileLockName}");
     }
     return(null);
 }
Exemple #11
0
        private IEnumerable <FrameworkInfo> DetectFrameworkInfos(DetectorContext context)
        {
            var detectedFrameworkResult = new List <FrameworkInfo>();
            var packageJson             = GetPackageJsonObject(context.SourceRepo, _logger);

            if (packageJson?.devDependencies != null)
            {
                var devDependencyObject = packageJson?.devDependencies;
                foreach (var keyWordToName in NodeConstants.DevDependencyFrameworkKeyWordToName)
                {
                    var keyword = keyWordToName.Key;
                    try
                    {
                        var frameworkInfo = new FrameworkInfo
                        {
                            Framework        = keyWordToName.Value,
                            FrameworkVersion = devDependencyObject[keyword].Value as string
                        };
                        detectedFrameworkResult.Add(frameworkInfo);
                    }
                    catch (RuntimeBinderException)
                    {
                    }
                }
            }

            if (packageJson?.dependencies != null)
            {
                var dependencyObject = packageJson?.dependencies;
                foreach (var keyWordToName in NodeConstants.DependencyFrameworkKeyWordToName)
                {
                    var keyword = keyWordToName.Key;
                    try
                    {
                        var frameworkInfo = new FrameworkInfo
                        {
                            Framework        = keyWordToName.Value,
                            FrameworkVersion = dependencyObject[keyword].Value as string
                        };
                        detectedFrameworkResult.Add(frameworkInfo);
                    }
                    catch (RuntimeBinderException)
                    {
                    }
                }
            }

            if (context.SourceRepo.FileExists(NodeConstants.FlutterYamlFileName))
            {
                var frameworkInfo = new FrameworkInfo
                {
                    Framework        = NodeConstants.FlutterFrameworkeName,
                    FrameworkVersion = string.Empty
                };
                detectedFrameworkResult.Add(frameworkInfo);
            }

            return(detectedFrameworkResult);
        }
Exemple #12
0
 public PlatformDetectorResult Detect(DetectorContext context)
 {
     return(new PlatformDetectorResult
     {
         Platform = "test",
         PlatformVersion = "1.0.0",
     });
 }
 public PlatformDetectorResult Detect(DetectorContext context)
 {
     return(new PhpPlatformDetectorResult
     {
         Platform = PhpConstants.PlatformName,
         PlatformVersion = _detectedVersion,
     });
 }
        private string GetProjectInfoFromSettings(DetectorContext context)
        {
            if (!string.IsNullOrEmpty(_options.Value.Project))
            {
                return(_options.Value.Project);
            }

            return(null);
        }
 public PlatformDetectorResult Detect(DetectorContext context)
 {
     return(new DotNetCorePlatformDetectorResult
     {
         Platform = DotNetCoreConstants.PlatformName,
         PlatformVersion = _detectedVersion,
         ProjectFile = _detectedProjectFile,
     });
 }
Exemple #16
0
 private string GetVersion(DetectorContext context, string versionFromRuntimeFile)
 {
     if (versionFromRuntimeFile != null)
     {
         return(versionFromRuntimeFile);
     }
     _logger.LogDebug(
         "Could not get version from runtime file. ");
     return(null);
 }
Exemple #17
0
        private string GetVersion(DetectorContext context)
        {
            var version = GetVersionFromPackageJson(context);

            if (version != null)
            {
                return(version);
            }
            _logger.LogDebug("Could not get version from package Json.");
            return(null);
        }
Exemple #18
0
        private string GetVersion(DetectorContext context)
        {
            var version = GetVersionFromComposerFile(context);

            if (version != null)
            {
                return(version);
            }
            _logger.LogDebug("Could not get version from the composer file. ");
            return(null);
        }
Exemple #19
0
        private string GetVersion(DetectorContext context)
        {
            var versionFromGoDotMod = this.GetVersionFromGoDotMod(context);

            if (versionFromGoDotMod != null)
            {
                return(versionFromGoDotMod);
            }

            return(null);
        }
        public virtual string GetRelativePathToProjectFile(DetectorContext context)
        {
            foreach (var projectFileProvider in _projectFileProviders)
            {
                var projectFile = projectFileProvider.GetRelativePathToProjectFile(context);
                if (!string.IsNullOrEmpty(projectFile))
                {
                    return(projectFile);
                }
            }

            return(null);
        }
Exemple #21
0
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            DetectInvoked = true;

            if (!string.IsNullOrEmpty(_platformName))
            {
                return(new PlatformDetectorResult
                {
                    Platform = _platformName,
                    PlatformVersion = _platformVersion,
                });
            }
            return(null);
        }
Exemple #22
0
        /// <inheritdoc/>
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            var isHugoApp = IsHugoApp(context.SourceRepo);

            if (isHugoApp)
            {
                return(new PlatformDetectorResult
                {
                    Platform = HugoConstants.PlatformName,
                });
            }

            return(null);
        }
Exemple #23
0
        /// <inheritdoc/>
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            var projectFile = this.projectFileProvider.GetRelativePathToProjectFile(context);

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

            var sourceRepo             = context.SourceRepo;
            var appDirectory           = Path.GetDirectoryName(projectFile);
            var installAOTWorkloads    = false;
            var projectFileDoc         = XDocument.Load(new StringReader(sourceRepo.ReadFile(projectFile)));
            var targetFrameworkElement = projectFileDoc.XPathSelectElement(
                DotNetCoreConstants.TargetFrameworkElementXPathExpression);
            var targetFramework = targetFrameworkElement?.Value;

            if (string.IsNullOrEmpty(targetFramework))
            {
                this.logger.LogDebug(
                    $"Could not find 'TargetFramework' element in the project file.");
                return(null);
            }

            var outputTypeElement = projectFileDoc.XPathSelectElement(
                DotNetCoreConstants.OutputTypeXPathExpression);
            var outputType = GetOutputType(outputTypeElement);

            var version = this.GetVersion(targetFramework);

            // Any Blazor WebAssembly app on .NET 6 should have the workload installed.
            // https://github.com/microsoft/Oryx/issues/1026
            if (ProjectFileHelpers.IsBlazorWebAssemblyProject(projectFileDoc) &&
                !string.IsNullOrEmpty(version) &&
                version.StartsWith("6"))
            {
                installAOTWorkloads = true;
            }

            return(new DotNetCorePlatformDetectorResult
            {
                Platform = DotNetCoreConstants.PlatformName,
                PlatformVersion = version,
                ProjectFile = projectFile,
                AppDirectory = appDirectory,
                OutputType = outputType,
                InstallAOTWorkloads = installAOTWorkloads,
            });
        }
Exemple #24
0
        public string GetRelativePathToProjectFile(DetectorContext context)
        {
            var sourceRepo = context.SourceRepo;

            // Check if root of the repo has a .csproj or a .fsproj file
            var projectFile = GetProjectFileAtRoot(sourceRepo, DotNetCoreConstants.CSharpProjectFileExtension) ??
                              GetProjectFileAtRoot(sourceRepo, DotNetCoreConstants.FSharpProjectFileExtension);

            if (projectFile != null)
            {
                return(new FileInfo(projectFile).Name);
            }

            return(null);
        }
Exemple #25
0
        /// <inheritdoc/>
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            var isHugoApp = this.IsHugoApp(context.SourceRepo, out string appDirectory);

            if (isHugoApp)
            {
                return(new PlatformDetectorResult
                {
                    Platform = HugoConstants.PlatformName,
                    AppDirectory = appDirectory,
                });
            }

            return(null);
        }
Exemple #26
0
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            var sourceRepo = context.SourceRepo;

            if (!sourceRepo.FileExists(PythonConstants.RequirementsFileName) &&
                !sourceRepo.FileExists(PythonConstants.SetupDotPyFileName))
            {
                _logger.LogDebug($"'{PythonConstants.SetupDotPyFileName}' or '{PythonConstants.RequirementsFileName}' " +
                                 $"does not exist in source repo");
                return(null);
            }
            else if (!sourceRepo.FileExists(PythonConstants.RequirementsFileName) &&
                     sourceRepo.FileExists(PythonConstants.SetupDotPyFileName))
            {
                _logger.LogInformation($"'{PythonConstants.RequirementsFileName} doesn't exist in source repo.' " +
                                       $"Detected '{PythonConstants.SetupDotPyFileName}'that exists in source repo");
            }
            else
            {
                _logger.LogInformation($"'{PythonConstants.SetupDotPyFileName} doesn't exist in source repo.' " +
                                       $"Detected '{PythonConstants.RequirementsFileName}'that exists in source repo");
            }

            // This detects if a runtime.txt file exists if that is a python file
            var versionFromRuntimeFile = DetectPythonVersionFromRuntimeFile(context.SourceRepo);

            if (string.IsNullOrEmpty(versionFromRuntimeFile))
            {
                var files = sourceRepo.EnumerateFiles(
                    PythonConstants.PythonFileNamePattern,
                    searchSubDirectories: false);

                if (files == null || !files.Any())
                {
                    _logger.LogDebug($"Files with extension '{PythonConstants.PythonFileNamePattern}' do not exist " +
                                     "in source repo root");
                    return(null);
                }
            }

            var version = GetVersion(context, versionFromRuntimeFile);

            return(new PlatformDetectorResult
            {
                Platform = PythonConstants.PlatformName,
                PlatformVersion = version,
            });
        }
Exemple #27
0
        private string GetVersion(DetectorContext context)
        {
            var versionFromGemfile = GetVersionFromGemFile(context);

            if (versionFromGemfile != null)
            {
                return(versionFromGemfile);
            }
            var versionFromGemfileLock = GetVersionFromGemFileLock(context);

            if (versionFromGemfileLock != null)
            {
                return(versionFromGemfileLock);
            }
            _logger.LogDebug("Could not get version from the gemfile or gemfile.lock. ");
            return(null);
        }
Exemple #28
0
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            DetectInvoked = true;

            if (_shouldMatch)
            {
                return(new PlatformDetectorResult
                {
                    Platform = _platformName,
                    PlatformVersion = _platformVersion
                });
            }
            else
            {
                return(null);
            }
        }
Exemple #29
0
        private string GetVersionFromGoDotMod(DetectorContext context)
        {
            try
            {
                var goDotModFileContent      = context.SourceRepo.ReadFile(GolangConstants.GoModFileName);
                var goDotModFileContentLines = goDotModFileContent.Split('\n');
                var sourceRepo = context.SourceRepo;

                // Example content of go.mod:
                // module myModule
                //
                // go 1.16

                // Match regex:
                //     - start with 0 or more white spaces
                //     - match string: go
                //     - 0 or more white spaces
                //     - digit(s)
                //     - (a period followed by digit(s)) once or twice
                //     - any number of white spaces
                // Regex matching valid version format:
                //      go 1.16
                //      go 1.16.7
                Regex regex = new Regex(@"^[\s]*go[\s]+[0-9]+(\.([0-9])+){1,2}[\s]*$");
                foreach (var goDotModFileContentLine in goDotModFileContentLines)
                {
                    Match match = regex.Match(goDotModFileContentLine);
                    if (match.Success)
                    {
                        // After matching regex is found we trim off 'go' and trailing quotes
                        // allowing us to only retain the version.
                        // Example: "go 1.16.7" -> 1.16.7
                        return(goDotModFileContentLine.Trim().Split(' ')[1].Trim('\"').Trim('\''));
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.LogError(
                    ex,
                    $"Exception caught while trying to parse {GolangConstants.GoModFileName}.");
            }

            return(null);
        }
Exemple #30
0
        public PlatformDetectorResult Detect(DetectorContext context)
        {
            var sourceRepo = context.SourceRepo;

            if (!sourceRepo.FileExists(PhpConstants.ComposerFileName))
            {
                _logger.LogDebug($"File '{PhpConstants.ComposerFileName}' does not exist in source repo");
                return(null);
            }

            var version = GetVersion(context);

            return(new PlatformDetectorResult
            {
                Platform = PhpConstants.PlatformName,
                PlatformVersion = version,
            });
        }