Esempio n. 1
0
        async Task <int> OnExecute()
        {
            Console.WriteLine();

            // check parameter values
            if (string.IsNullOrEmpty(SolutionOrProjectFile))
            {
                Console.Error.WriteLine($"A path is required");
                return((int)ExitCode.SolutionOrProjectFileParameterMissing);
            }

            if (string.IsNullOrEmpty(outputDirectory))
            {
                Console.Error.WriteLine($"The output directory is required");
                return((int)ExitCode.OutputDirectoryParameterMissing);
            }

            if (string.IsNullOrEmpty(githubUsername) ^ string.IsNullOrEmpty(githubToken))
            {
                Console.Error.WriteLine($"Both GitHub username and token are required");
                return((int)ExitCode.GitHubParameterMissing);
            }

            // instantiate services
            var fileDiscoveryService = new FileDiscoveryService(Program.fileSystem);
            // GitHubService requires its own HttpClient as it adds a default authorization header
            GithubService githubService;

            if (string.IsNullOrEmpty(githubUsername) || string.IsNullOrEmpty(githubToken))
            {
                githubService = new GithubService(new HttpClient());
            }
            else
            {
                githubService = new GithubService(new HttpClient(), githubUsername, githubToken);
            }
            var nugetService        = new NugetService(Program.httpClient, githubService, baseUrl);
            var packagesFileService = new PackagesFileService(Program.fileSystem);
            var projectFileService  = new ProjectFileService(Program.fileSystem);
            var solutionFileService = new SolutionFileService(Program.fileSystem);
            var packages            = new HashSet <NugetPackage>();

            // determine what we are analyzing and do the analysis
            var fullSolutionOrProjectFilePath = Program.fileSystem.Path.GetFullPath(SolutionOrProjectFile);
            var attr = Program.fileSystem.File.GetAttributes(fullSolutionOrProjectFilePath);

            if (SolutionOrProjectFile.ToLowerInvariant().EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
            {
                packages = await solutionFileService.GetSolutionNugetPackages(fullSolutionOrProjectFilePath);
            }
            else if (Utils.IsSupportedProjectType(SolutionOrProjectFile) && scanProjectReferences)
            {
                packages = await projectFileService.RecursivelyGetProjectNugetPackagesAsync(fullSolutionOrProjectFilePath);
            }
            else if (Utils.IsSupportedProjectType(SolutionOrProjectFile))
            {
                packages = await projectFileService.GetProjectNugetPackagesAsync(fullSolutionOrProjectFilePath);
            }
            else if (Program.fileSystem.Path.GetFileName(SolutionOrProjectFile).ToLowerInvariant().Equals("packages.config", StringComparison.OrdinalIgnoreCase))
            {
                packages = await packagesFileService.GetNugetPackagesAsync(fullSolutionOrProjectFilePath);
            }
            else if (attr.HasFlag(FileAttributes.Directory))
            {
                packages = await packagesFileService.RecursivelyGetNugetPackagesAsync(fullSolutionOrProjectFilePath);
            }
            else
            {
                Console.Error.WriteLine($"Only .sln, .csproj, .vbproj, and packages.config files are supported");
                return((int)ExitCode.InvalidOptions);
            }

            // get all the components from the NuGet packages
            var components = new HashSet <Component>();

            try
            {
                foreach (var package in packages)
                {
                    var component = await nugetService.GetComponentAsync(package);

                    if (component != null)
                    {
                        components.Add(component);
                    }
                }
            }
            catch (InvalidGitHubApiCredentialsException)
            {
                return((int)ExitCode.InvalidGitHubApiCredentials);
            }
            catch (GitHubApiRateLimitExceededException)
            {
                return((int)ExitCode.GitHubApiRateLimitExceeded);
            }

            // create the BOM
            Console.WriteLine();
            Console.WriteLine("Creating CycloneDX BoM");
            var bomXml = BomService.CreateXmlDocument(components, noSerialNumber);

            // check if the output directory exists and create it if needed
            var bomPath = Program.fileSystem.Path.GetFullPath(outputDirectory);

            if (!Program.fileSystem.Directory.Exists(bomPath))
            {
                Program.fileSystem.Directory.CreateDirectory(bomPath);
            }

            // write the BOM to disk
            var bomFile = Program.fileSystem.Path.Combine(bomPath, "bom.xml");

            Console.WriteLine("Writing to: " + bomFile);
            using (var fileStream = Program.fileSystem.FileStream.Create(bomFile, FileMode.Create))
                using (var writer = new StreamWriter(fileStream, new UTF8Encoding(false))) {
                    bomXml.Save(writer);
                }

            return(0);
        }
Esempio n. 2
0
        async Task <int> OnExecuteAsync()
        {
            Console.WriteLine();

            // check parameter values
            if (string.IsNullOrEmpty(SolutionOrProjectFile))
            {
                Console.Error.WriteLine($"A path is required");
                return((int)ExitCode.SolutionOrProjectFileParameterMissing);
            }

            if (string.IsNullOrEmpty(outputDirectory))
            {
                Console.Error.WriteLine($"The output directory is required");
                return((int)ExitCode.OutputDirectoryParameterMissing);
            }

            if ((string.IsNullOrEmpty(githubUsername) ^ string.IsNullOrEmpty(githubToken)) ||
                (string.IsNullOrEmpty(githubUsernameDeprecated) ^ string.IsNullOrEmpty(githubTokenDeprecated)))
            {
                Console.Error.WriteLine($"Both GitHub username and token are required");
                return((int)ExitCode.GitHubParameterMissing);
            }

            dotnetCommandService.TimeoutMilliseconds = dotnetCommandTimeout;

            // retrieve nuget package cache paths
            var packageCachePathsResult = dotnetUtilsService.GetPackageCachePaths();

            if (!packageCachePathsResult.Success)
            {
                Console.Error.WriteLine("Unable to find local package cache locations...");
                Console.Error.WriteLine(packageCachePathsResult.ErrorMessage);
                return((int)ExitCode.LocalPackageCacheError);
            }

            Console.WriteLine("Found the following local nuget package cache locations:");
            foreach (var path in packageCachePathsResult.Result)
            {
                Console.WriteLine($"    {path}");
            }

            // instantiate services

            var           fileDiscoveryService = new FileDiscoveryService(Program.fileSystem);
            GithubService githubService        = null;

            if (!(disableGithubLicenses || disableGithubLicensesDeprecated))
            {
                // GitHubService requires its own HttpClient as it adds a default authorization header
                if (!string.IsNullOrEmpty(githubBearerToken))
                {
                    githubService = new GithubService(new HttpClient(), githubBearerToken);
                }
                else if (!string.IsNullOrEmpty(githubBearerTokenDeprecated))
                {
                    githubService = new GithubService(new HttpClient(), githubBearerTokenDeprecated);
                }
                else if (!string.IsNullOrEmpty(githubUsername))
                {
                    githubService = new GithubService(new HttpClient(), githubUsername, githubToken);
                }
                else if (!string.IsNullOrEmpty(githubUsernameDeprecated))
                {
                    githubService = new GithubService(new HttpClient(), githubUsernameDeprecated, githubTokenDeprecated);
                }
                else
                {
                    githubService = new GithubService(new HttpClient());
                }
            }
            var nugetService = new NugetService(
                Program.fileSystem,
                packageCachePathsResult.Result,
                githubService,
                Program.httpClient,
                baseUrl);

            var packages = new HashSet <NugetPackage>();

            // determine what we are analyzing and do the analysis
            var fullSolutionOrProjectFilePath = Program.fileSystem.Path.GetFullPath(SolutionOrProjectFile);
            var attr = Program.fileSystem.File.GetAttributes(fullSolutionOrProjectFilePath);

            try
            {
                if (SolutionOrProjectFile.ToLowerInvariant().EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
                {
                    packages = await solutionFileService.GetSolutionNugetPackages(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                }
                else if (Core.Utils.IsSupportedProjectType(SolutionOrProjectFile) && scanProjectReferences)
                {
                    packages = await projectFileService.RecursivelyGetProjectNugetPackagesAsync(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                }
                else if (Core.Utils.IsSupportedProjectType(SolutionOrProjectFile))
                {
                    packages = await projectFileService.GetProjectNugetPackagesAsync(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                }
                else if (Program.fileSystem.Path.GetFileName(SolutionOrProjectFile).ToLowerInvariant().Equals("packages.config", StringComparison.OrdinalIgnoreCase))
                {
                    packages = await packagesFileService.GetNugetPackagesAsync(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                }
                else if (attr.HasFlag(FileAttributes.Directory))
                {
                    packages = await packagesFileService.RecursivelyGetNugetPackagesAsync(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                }
                else
                {
                    Console.Error.WriteLine($"Only .sln, .csproj, .vbproj, and packages.config files are supported");
                    return((int)ExitCode.InvalidOptions);
                }
            }
            catch (DotnetRestoreException)
            {
                return((int)ExitCode.DotnetRestoreFailed);
            }

            // get all the components from the NuGet packages
            var components = new HashSet <Component>();

            try
            {
                foreach (var package in packages)
                {
                    var component = await nugetService.GetComponentAsync(package).ConfigureAwait(false);

                    if (component != null &&
                        (component.Scope != "excluded" || !excludeDev)
                        )
                    {
                        components.Add(component);
                    }
                }
            }
            catch (InvalidGitHubApiCredentialsException)
            {
                return((int)ExitCode.InvalidGitHubApiCredentials);
            }
            catch (GitHubApiRateLimitExceededException)
            {
                return((int)ExitCode.GitHubApiRateLimitExceeded);
            }
            catch (GitHubLicenseResolutionException)
            {
                return((int)ExitCode.GitHubLicenseResolutionFailed);
            }

            // create the BOM
            Console.WriteLine();
            Console.WriteLine("Creating CycloneDX BOM");
            var bom = new Bom();

            if (!(noSerialNumber || noSerialNumberDeprecated))
            {
                bom.SerialNumber = "urn:uuid:" + System.Guid.NewGuid().ToString();
            }
            bom.Components = components;

            var bomContents = BomService.CreateDocument(bom, json);

            // check if the output directory exists and create it if needed
            var bomPath = Program.fileSystem.Path.GetFullPath(outputDirectory);

            if (!Program.fileSystem.Directory.Exists(bomPath))
            {
                Program.fileSystem.Directory.CreateDirectory(bomPath);
            }

            // write the BOM to disk
            var bomFilename = Program.fileSystem.Path.Combine(bomPath, json ? "bom.json" : "bom.xml");

            Console.WriteLine("Writing to: " + bomFilename);
            Program.fileSystem.File.WriteAllText(bomFilename, bomContents);

            return(0);
        }