Search in sources :

Example 6 with GuruCliException

use of com.amazonaws.gurureviewercli.exceptions.GuruCliException in project aws-codeguru-cli by aws.

the class GitAdapter method treeForCommitId.

private static CanonicalTreeParser treeForCommitId(final Repository repo, final String commitId) {
    try (RevWalk walk = new RevWalk(repo)) {
        val commit = walk.parseCommit(repo.resolve(commitId));
        val treeId = commit.getTree().getId();
        try (ObjectReader reader = repo.newObjectReader()) {
            return new CanonicalTreeParser(null, reader, treeId);
        }
    } catch (NullPointerException e) {
        throw new GuruCliException(ErrorCodes.GIT_INVALID_COMMITS, "Not a valid commit id " + commitId, e);
    } catch (IOException e) {
        throw new GuruCliException(ErrorCodes.GIT_INVALID_COMMITS, "Cannot parse commit id " + commitId, e);
    }
}
Also used : lombok.val(lombok.val) ObjectReader(org.eclipse.jgit.lib.ObjectReader) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser)

Example 7 with GuruCliException

use of com.amazonaws.gurureviewercli.exceptions.GuruCliException in project aws-codeguru-cli by aws.

the class Main method main.

public static void main(String[] argv) {
    val textIO = new TextIO(new SystemTextTerminal());
    val main = new Main();
    val jCommander = JCommander.newBuilder().addObject(main).build();
    if (argv.length == 0) {
        jCommander.usage();
        return;
    }
    try {
        jCommander.parse(argv);
        val config = Configuration.builder().textIO(textIO).interactiveMode(!main.noPrompt).bucketName(main.bucketName).build();
        main.validateInitialConfig(config);
        // try to build the AWS client objects first.
        main.createAWSClients(config);
        String repoName = config.getRootDir().toFile().getName();
        config.setRepoName(repoName);
        // check if repo is valid git.
        val gitMetaData = main.readGitMetaData(config, Paths.get(main.repoDir).toRealPath());
        ScanMetaData scanMetaData = null;
        List<RecommendationSummary> results = new ArrayList<>();
        try {
            val sourcePaths = main.sourceDirs.stream().map(Paths::get).map(Path::toAbsolutePath).map(Path::normalize).collect(Collectors.toList());
            List<Path> buildPaths = null;
            if (main.buildDirs != null) {
                buildPaths = main.buildDirs.stream().map(Paths::get).map(Path::toAbsolutePath).map(Path::normalize).collect(Collectors.toList());
            }
            scanMetaData = ScanAdapter.startScan(config, gitMetaData, sourcePaths, buildPaths);
            results.addAll(ScanAdapter.fetchResults(config, scanMetaData));
        } finally {
            if (scanMetaData != null) {
                // try to clean up objects from S3.
                main.tryDeleteS3Object(config.getS3Client(), scanMetaData.getBucketName(), scanMetaData.getSourceKey());
                main.tryDeleteS3Object(config.getS3Client(), scanMetaData.getBucketName(), scanMetaData.getBuildKey());
            }
        }
        val outputPath = Paths.get(main.outputDir);
        if (!outputPath.toFile().exists()) {
            if (!outputPath.toFile().mkdirs()) {
                Log.error("Failed to create output directory %s.", outputPath);
            }
        }
        ResultsAdapter.saveResults(outputPath, results, scanMetaData);
        Log.info("Analysis finished.");
    } catch (GuruCliException e) {
        Log.error("%s: %s", e.getErrorCode(), e.getMessage());
        e.printStackTrace();
        System.exit(3);
    } catch (ParameterException e) {
        Log.error(e);
        jCommander.usage();
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        Log.error(e);
        System.exit(2);
    }
    System.exit(0);
}
Also used : lombok.val(lombok.val) Path(java.nio.file.Path) SystemTextTerminal(org.beryx.textio.system.SystemTextTerminal) ArrayList(java.util.ArrayList) TextIO(org.beryx.textio.TextIO) ParameterException(com.beust.jcommander.ParameterException) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException) IOException(java.io.IOException) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) ScanMetaData(com.amazonaws.gurureviewercli.model.ScanMetaData) RecommendationSummary(software.amazon.awssdk.services.codegurureviewer.model.RecommendationSummary) ParameterException(com.beust.jcommander.ParameterException) Paths(java.nio.file.Paths) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Example 8 with GuruCliException

use of com.amazonaws.gurureviewercli.exceptions.GuruCliException in project aws-codeguru-cli by aws.

the class Main method createAWSClients.

protected void createAWSClients(final Configuration config) {
    val credentials = getCredentials();
    try {
        config.setRegion(regionName);
        val callerIdentity = StsClient.builder().credentialsProvider(credentials).region(Region.of(regionName)).build().getCallerIdentity();
        config.setAccountId(callerIdentity.account());
        config.setGuruFrontendService(getNewGuruClient(credentials));
        config.setS3Client(getS3Client(credentials));
    } catch (IllegalArgumentException e) {
        // profile could not be found
        throw new GuruCliException(ErrorCodes.AWS_INIT_ERROR, "Error accessing the provided profile. " + this.profileName + "Ensure that the spelling is correct and" + " that the role has access to CodeGuru and S3.");
    } catch (SdkClientException e) {
        throw new GuruCliException(ErrorCodes.AWS_INIT_ERROR, "No AWS credentials found. Use 'aws configure' to set them up.");
    }
}
Also used : lombok.val(lombok.val) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Example 9 with GuruCliException

use of com.amazonaws.gurureviewercli.exceptions.GuruCliException in project aws-codeguru-cli by aws.

the class ArtifactAdapter method zipAndUpload.

/**
 * Zip and upload source and build artifacts to S3.
 *
 * @param config        The current {@link Configuration}
 * @param tempDir       A temp directory where files can be copied to and zipped. Will be deleted after completion.
 * @param repositoryDir The root directory of the repo to analyze
 * @param sourceDirs    The list of source directories under repositoryDir.
 * @param buildDirs     The list of build directories (can be empty).
 * @param bucketName    The name of the S3 bucket that should be used for the upload.
 * @return Metadata about what was zipped and uploaded.
 * @throws IOException If writing to tempDir fails.
 */
public static ScanMetaData zipAndUpload(final Configuration config, final Path tempDir, final Path repositoryDir, final List<Path> sourceDirs, final List<Path> buildDirs, final String bucketName) throws IOException {
    try {
        boolean scanVersionedFilesOnly = false;
        if (config.getVersionedFiles() != null && !config.getVersionedFiles().isEmpty()) {
            scanVersionedFilesOnly = !config.isInteractiveMode() || config.getTextIO().newBooleanInputReader().withTrueInput("y").withFalseInput("n").read("Only analyze files under version control?");
        }
        final String sourceKey;
        if (scanVersionedFilesOnly) {
            val filesToScan = new ArrayList<Path>(ZipUtils.getFilesInDirectories(sourceDirs));
            val totalFiles = filesToScan.size();
            // only keep versioned files.
            filesToScan.retainAll(config.getVersionedFiles());
            val versionedFiles = filesToScan.size();
            if (versionedFiles == 0) {
                Log.error(sourceDirs.toString());
                Log.error(config.getVersionedFiles().toString());
                throw new GuruCliException(ErrorCodes.GIT_EMPTY_DIFF, "No versioned files to analyze in directories: " + sourceDirs);
            }
            Log.info("Adding %d out of %d files under version control in %s", versionedFiles, totalFiles, repositoryDir.toAbsolutePath());
            filesToScan.addAll(ZipUtils.getFilesInDirectory(repositoryDir.resolve(".git")));
            sourceKey = zipAndUploadFiles("analysis-src-" + UUID.randomUUID(), filesToScan, repositoryDir, bucketName, tempDir, config.getAccountId(), config.getS3Client());
        } else {
            val sourceDirsAndGit = new ArrayList<Path>(sourceDirs);
            if (config.getBeforeCommit() != null && config.getAfterCommit() != null) {
                // only add the git folder if a commit range is provided.
                sourceDirsAndGit.add(repositoryDir.resolve(".git"));
            }
            sourceKey = zipAndUploadDir("analysis-src-" + UUID.randomUUID(), sourceDirsAndGit, repositoryDir, bucketName, tempDir, config.getAccountId(), config.getS3Client());
        }
        final String buildKey;
        if (buildDirs != null && !buildDirs.isEmpty()) {
            for (val buildDir : buildDirs) {
                if (!buildDir.toFile().isDirectory()) {
                    throw new FileNotFoundException("Provided build directory not found " + buildDir);
                }
            }
            buildKey = zipAndUploadDir("analysis-bin-" + UUID.randomUUID(), buildDirs, bucketName, tempDir, config.getAccountId(), config.getS3Client());
        } else {
            buildKey = null;
        }
        return ScanMetaData.builder().bucketName(bucketName).repositoryRoot(repositoryDir).sourceDirectories(sourceDirs).sourceKey(sourceKey).buildKey(buildKey).build();
    } finally {
        // Delete the temp dir.
        try (val walker = Files.walk(tempDir)) {
            walker.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
        }
    }
}
Also used : lombok.val(lombok.val) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException) File(java.io.File)

Example 10 with GuruCliException

use of com.amazonaws.gurureviewercli.exceptions.GuruCliException in project aws-codeguru-cli by aws.

the class AssociationAdapter method getAssociatedGuruRepo.

/**
 * Get or create a CodeGuru Repository Association (and, if necessary an S3 bucket).
 *
 * @param config The {@link Configuration} with name of repo, account, and region.
 * @return A CodeGuru Repository association.
 */
public static RepositoryAssociation getAssociatedGuruRepo(final Configuration config) {
    val guruFrontendService = config.getGuruFrontendService();
    val repositoryAssociationsRequest = ListRepositoryAssociationsRequest.builder().providerTypes(ProviderType.S3_BUCKET).names(config.getRepoName()).build();
    val associationResults = guruFrontendService.listRepositoryAssociations(repositoryAssociationsRequest);
    if (associationResults.repositoryAssociationSummaries().size() == 1) {
        val summary = associationResults.repositoryAssociationSummaries().get(0);
        val describeAssociationRequest = DescribeRepositoryAssociationRequest.builder().associationArn(summary.associationArn()).build();
        val association = guruFrontendService.describeRepositoryAssociation(describeAssociationRequest).repositoryAssociation();
        if (!RepositoryAssociationState.ASSOCIATED.equals(association.state())) {
            val msg = String.format("Repository association in unexpected state %s: %s", association.state(), association.stateReason());
            throw new GuruCliException(ErrorCodes.ASSOCIATION_FAILED, msg);
        }
        if (config.getKeyId() != null && !config.getKeyId().equals(association.kmsKeyDetails().kmsKeyId())) {
            val msg = String.format("Provided KMS Key alias %s for repository %s does " + "not match existing key: %s", config.getKeyId(), association.name(), association.kmsKeyDetails().kmsKeyId());
            throw new GuruCliException(ErrorCodes.ASSOCIATION_FAILED, msg);
        }
        if (config.getBucketName() != null && !config.getBucketName().equals(association.s3RepositoryDetails().bucketName())) {
            val msg = String.format("Provided Bucket name %s for repository %s does " + "not match existing key: %s", config.getBucketName(), association.name(), association.s3RepositoryDetails().bucketName());
            throw new GuruCliException(ErrorCodes.ASSOCIATION_FAILED, msg);
        }
        return association;
    } else if (associationResults.repositoryAssociationSummaries().isEmpty()) {
        return createBucketAndAssociation(config);
    } else {
        throw new RuntimeException("Found more than one matching association: " + associationResults);
    }
}
Also used : lombok.val(lombok.val) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Aggregations

GuruCliException (com.amazonaws.gurureviewercli.exceptions.GuruCliException)13 lombok.val (lombok.val)13 IOException (java.io.IOException)3 TextIO (org.beryx.textio.TextIO)3 Test (org.junit.jupiter.api.Test)3 ArrayList (java.util.ArrayList)2 MockTextTerminal (org.beryx.textio.mock.MockTextTerminal)2 SdkClientException (software.amazon.awssdk.core.exception.SdkClientException)2 ScanMetaData (com.amazonaws.gurureviewercli.model.ScanMetaData)1 ParameterException (com.beust.jcommander.ParameterException)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 Nonnull (javax.annotation.Nonnull)1 SystemTextTerminal (org.beryx.textio.system.SystemTextTerminal)1 Git (org.eclipse.jgit.api.Git)1 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)1 ObjectReader (org.eclipse.jgit.lib.ObjectReader)1 RevWalk (org.eclipse.jgit.revwalk.RevWalk)1