Search in sources :

Example 1 with GuruCliException

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

the class AssociationAdapterTest method test_getAssociatedGuruRepo_createNewWithCreateBucketInteractiveAbort.

@Test
public void test_getAssociatedGuruRepo_createNewWithCreateBucketInteractiveAbort() {
    val bucketName = "some-bucket";
    val emptyListResponse = ListRepositoryAssociationsResponse.builder().repositoryAssociationSummaries(Collections.emptyList()).build();
    when(guruFrontendService.listRepositoryAssociations(any(ListRepositoryAssociationsRequest.class))).thenReturn(emptyListResponse);
    when(s3client.headBucket(any(HeadBucketRequest.class))).thenThrow(NoSuchBucketException.class);
    val mockTerminal = new MockTextTerminal();
    mockTerminal.getInputs().add("n");
    val config = Configuration.builder().guruFrontendService(guruFrontendService).interactiveMode(true).s3Client(s3client).repoName("some-repo-name").textIO(new TextIO(mockTerminal)).build();
    GuruCliException ret = Assertions.assertThrows(GuruCliException.class, () -> AssociationAdapter.getAssociatedGuruRepo(config));
    Assertions.assertEquals(ErrorCodes.USER_ABORT, ret.getErrorCode());
}
Also used : lombok.val(lombok.val) HeadBucketRequest(software.amazon.awssdk.services.s3.model.HeadBucketRequest) MockTextTerminal(org.beryx.textio.mock.MockTextTerminal) ListRepositoryAssociationsRequest(software.amazon.awssdk.services.codegurureviewer.model.ListRepositoryAssociationsRequest) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException) TextIO(org.beryx.textio.TextIO) Test(org.junit.jupiter.api.Test)

Example 2 with GuruCliException

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

the class Main method readGitMetaData.

protected GitMetaData readGitMetaData(final Configuration config, final Path repoRoot) throws IOException {
    if (commitRange != null) {
        val commits = commitRange.split(":");
        if (commits.length != 2) {
            throw new GuruCliException(ErrorCodes.GIT_INVALID_COMMITS, "Invalid value for --commit-range. Use '[before commit]:[after commit]'.");
        }
        config.setBeforeCommit(commits[0]);
        config.setAfterCommit(commits[1]);
    }
    return GitAdapter.getGitMetaData(config, repoRoot);
}
Also used : lombok.val(lombok.val) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Example 3 with GuruCliException

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

the class Main method validateInitialConfig.

private void validateInitialConfig(final Configuration config) throws IOException {
    if (config.getBucketName() != null && !config.getBucketName().startsWith("codeguru-reviewer-")) {
        Log.warn("CodeGuru Reviewer has default settings only for buckets that are prefixed with " + "codeguru-reviewer. If you choose a different name, read the instructions in the README.");
    }
    if (!Paths.get(repoDir).toFile().isDirectory()) {
        throw new GuruCliException(ErrorCodes.DIR_NOT_FOUND, repoDir + " is not a valid directory.");
    }
    config.setRootDir(Paths.get(repoDir).toRealPath());
    if (this.sourceDirs == null || this.sourceDirs.isEmpty()) {
        this.sourceDirs = Arrays.asList(config.getRootDir().toString());
    }
    sourceDirs.forEach(sourceDir -> {
        val path = Paths.get(sourceDir);
        if (!path.toFile().isDirectory()) {
            throw new GuruCliException(ErrorCodes.DIR_NOT_FOUND, sourceDir + " is not a valid directory.");
        }
        if (!path.toAbsolutePath().normalize().startsWith(config.getRootDir())) {
            throw new GuruCliException(ErrorCodes.DIR_NOT_FOUND, sourceDir + " is not a sub-directory of " + config.getRootDir());
        }
    });
    if (this.buildDirs != null) {
        buildDirs.forEach(buildDir -> {
            if (!Paths.get(buildDir).toFile().isDirectory()) {
                throw new GuruCliException(ErrorCodes.DIR_NOT_FOUND, buildDir + " is not a valid directory.");
            }
        });
    }
    config.setKeyId(this.kmsKeyId);
}
Also used : lombok.val(lombok.val) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Example 4 with GuruCliException

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

the class AssociationAdapter method createBucketAndAssociation.

private static RepositoryAssociation createBucketAndAssociation(final Configuration config) {
    final String bucketName;
    if (config.getBucketName() != null) {
        bucketName = config.getBucketName();
    } else {
        bucketName = String.format(BUCKET_NAME_PATTERN, config.getAccountId(), config.getRegion());
    }
    try {
        config.getS3Client().headBucket(HeadBucketRequest.builder().bucket(bucketName).build());
    } catch (NoSuchBucketException e) {
        Log.info("CodeGuru Reviewer requires an S3 bucket to upload the analysis artifacts to.");
        val createBucket = !config.isInteractiveMode() || config.getTextIO().newBooleanInputReader().withTrueInput("y").withFalseInput("n").read("Do you want to create a new S3 bucket: " + bucketName, bucketName);
        if (createBucket) {
            Log.info("Creating new bucket: %s", bucketName);
            config.getS3Client().createBucket(CreateBucketRequest.builder().bucket(bucketName).build());
        } else {
            throw new GuruCliException(ErrorCodes.USER_ABORT, "CodeGuru needs an S3 bucket to continue.");
        }
    }
    val repository = Repository.builder().s3Bucket(S3Repository.builder().bucketName(bucketName).name(config.getRepoName()).build()).build();
    AssociateRepositoryRequest associateRequest;
    if (config.getKeyId() != null) {
        val keyDetails = KMSKeyDetails.builder().encryptionOption(EncryptionOption.CUSTOMER_MANAGED_CMK).kmsKeyId(config.getKeyId()).build();
        associateRequest = AssociateRepositoryRequest.builder().repository(repository).kmsKeyDetails(keyDetails).build();
    } else {
        associateRequest = AssociateRepositoryRequest.builder().repository(repository).build();
    }
    val associateResponse = config.getGuruFrontendService().associateRepository(associateRequest);
    val associationArn = associateResponse.repositoryAssociation().associationArn();
    Log.print("Creating association ");
    DescribeRepositoryAssociationRequest associationRequest = DescribeRepositoryAssociationRequest.builder().associationArn(associationArn).build();
    DescribeRepositoryAssociationResponse associationResponse = config.getGuruFrontendService().describeRepositoryAssociation(associationRequest);
    while (associationResponse != null) {
        val association = associationResponse.repositoryAssociation();
        if (RepositoryAssociationState.ASSOCIATED.equals(association.state())) {
            Log.println(" done");
            Log.print("Created new repository association: ");
            Log.awsUrl("?region=%s#/ciworkflows/associationdetails/%s", config.getRegion(), association.associationArn());
            return association;
        } else if (RepositoryAssociationState.ASSOCIATING.equals(association.state())) {
            Log.print(".");
            try {
                Thread.sleep(TimeUnit.SECONDS.toMillis(WAIT_TIME_IN_SECONDS));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } else {
            val msg = String.format("Repository association in unexpected state %s: %s", association.state(), association.stateReason());
            throw new GuruCliException(ErrorCodes.ASSOCIATION_FAILED, msg);
        }
        associationResponse = config.getGuruFrontendService().describeRepositoryAssociation(associationRequest);
    }
    throw new GuruCliException(ErrorCodes.ASSOCIATION_FAILED, "Unexpected error during association");
}
Also used : lombok.val(lombok.val) DescribeRepositoryAssociationRequest(software.amazon.awssdk.services.codegurureviewer.model.DescribeRepositoryAssociationRequest) DescribeRepositoryAssociationResponse(software.amazon.awssdk.services.codegurureviewer.model.DescribeRepositoryAssociationResponse) AssociateRepositoryRequest(software.amazon.awssdk.services.codegurureviewer.model.AssociateRepositoryRequest) NoSuchBucketException(software.amazon.awssdk.services.s3.model.NoSuchBucketException) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Example 5 with GuruCliException

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

the class GitAdapter method validateCommits.

private static boolean validateCommits(final Configuration config, final Repository repo) throws GitAPIException {
    val beforeTreeIter = treeForCommitId(repo, config.getBeforeCommit());
    val afterTreeIter = treeForCommitId(repo, config.getAfterCommit());
    // Resolve git constants, such as HEAD^^ to the actual commit hash
    config.setBeforeCommit(resolveSha(repo, config.getBeforeCommit()));
    config.setAfterCommit(resolveSha(repo, config.getAfterCommit()));
    val diffEntries = new Git(repo).diff().setOldTree(beforeTreeIter).setNewTree(afterTreeIter).call();
    if (diffEntries.isEmpty()) {
        throw new GuruCliException(ErrorCodes.GIT_EMPTY_DIFF, String.format("No difference between {} and {}", beforeTreeIter, afterTreeIter));
    }
    return true;
}
Also used : lombok.val(lombok.val) Git(org.eclipse.jgit.api.Git) 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