Search in sources :

Example 1 with Console

use of com.google.copybara.util.console.Console in project copybara by google.

the class GithubPrDestination method newWriter.

@Override
public Writer<GitRevision> newWriter(Glob destinationFiles, boolean dryRun, @Nullable String groupId, @Nullable Writer<GitRevision> oldWriter) throws ValidationException {
    WriterImpl gitOldWriter = (WriterImpl) oldWriter;
    boolean effectiveSkipPush = GithubPrDestination.this.effectiveSkipPush || dryRun;
    GithubWriterState state;
    String pushBranchName = branchFromGroupId(groupId);
    if (oldWriter != null && gitOldWriter.skipPush == effectiveSkipPush) {
        state = (GithubWriterState) ((WriterImpl) oldWriter).state;
    } else {
        state = new GithubWriterState(localRepo, destinationOptions.localRepoPath != null ? pushBranchName : "copybara/push-" + UUID.randomUUID() + (dryRun ? "-dryrun" : ""));
    }
    return new WriterImpl<GithubWriterState>(destinationFiles, effectiveSkipPush, url, destinationRef, pushBranchName, generalOptions, commitGenerator, processPushOutput, state, /*nonFastForwardPush=*/
    true, integrates, destinationOptions.lastRevFirstParent, destinationOptions.ignoreIntegrationErrors, destinationOptions.localRepoPath, destinationOptions.committerName, destinationOptions.committerEmail, destinationOptions.rebaseWhenBaseline(), gitOptions.visitChangePageSize) {

        @Override
        public ImmutableList<DestinationEffect> write(TransformResult transformResult, Console console) throws ValidationException, RepoException, IOException {
            ImmutableList.Builder<DestinationEffect> result = ImmutableList.<DestinationEffect>builder().addAll(super.write(transformResult, console));
            if (effectiveSkipPush || state.pullRequestNumber != null) {
                return result.build();
            }
            if (!githubDestinationOptions.createPullRequest) {
                console.infoFmt("Please create a PR manually following this link: %s/compare/%s...%s" + " (Only needed once)", asHttpsUrl(), destinationRef, pushBranchName);
                state.pullRequestNumber = -1L;
                return result.build();
            }
            GithubApi api = githubOptions.getApi(GithubUtil.getProjectNameFromUrl(url));
            for (PullRequest pr : api.getPullRequests(getProjectName())) {
                if (pr.isOpen() && pr.getHead().getRef().equals(pushBranchName)) {
                    console.infoFmt("Pull request for branch %s already exists as %s/pull/%s", pushBranchName, asHttpsUrl(), pr.getNumber());
                    if (!pr.getBase().getRef().equals(destinationRef)) {
                        // TODO(malcon): Update PR or create a new one?
                        console.warnFmt("Current base branch '%s' is different from the PR base branch '%s'", destinationRef, pr.getBase().getRef());
                    }
                    result.add(new DestinationEffect(DestinationEffect.Type.UPDATED, String.format("Pull Request %s updated", pr.getHtmlUrl()), transformResult.getChanges().getCurrent(), new DestinationEffect.DestinationRef(Long.toString(pr.getNumber()), "pull_request", pr.getHtmlUrl()), ImmutableList.of()));
                    return result.build();
                }
            }
            ChangeMessage msg = ChangeMessage.parseMessage(transformResult.getSummary());
            PullRequest pr = api.createPullRequest(getProjectName(), new CreatePullRequest(title == null ? msg.firstLine() : title, body == null ? msg.getText() : body, pushBranchName, destinationRef));
            console.infoFmt("Pull Request %s/pull/%s created using branch '%s'.", asHttpsUrl(), pr.getNumber(), pushBranchName);
            state.pullRequestNumber = pr.getNumber();
            result.add(new DestinationEffect(DestinationEffect.Type.CREATED, String.format("Pull Request %s created", pr.getHtmlUrl()), transformResult.getChanges().getCurrent(), new DestinationEffect.DestinationRef(Long.toString(pr.getNumber()), "pull_request", pr.getHtmlUrl()), ImmutableList.of()));
            return result.build();
        }
    };
}
Also used : TransformResult(com.google.copybara.TransformResult) ImmutableList(com.google.common.collect.ImmutableList) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) PullRequest(com.google.copybara.git.github.api.PullRequest) GithubApi(com.google.copybara.git.github.api.GithubApi) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) WriterImpl(com.google.copybara.git.GitDestination.WriterImpl) DestinationEffect(com.google.copybara.DestinationEffect) Console(com.google.copybara.util.console.Console) ChangeMessage(com.google.copybara.ChangeMessage)

Example 2 with Console

use of com.google.copybara.util.console.Console in project copybara by google.

the class TestingConsoleTest method programmedResponses.

@Test
public void programmedResponses() throws Exception {
    Console console = new TestingConsole().respondYes().respondNo();
    assertThat(console.promptConfirmation("Proceed?")).isTrue();
    assertThat(console.promptConfirmation("Proceed?")).isFalse();
}
Also used : Console(com.google.copybara.util.console.Console) Test(org.junit.Test)

Example 3 with Console

use of com.google.copybara.util.console.Console in project copybara by google.

the class Main method run.

protected final ExitCode run(String[] args) {
    // We need a console before parsing the args because it could fail with wrong
    // arguments and we need to show the error.
    Console console = getConsole(args);
    // Configure logs location correctly before anything else. We want to write to the
    // correct location in case of any error.
    FileSystem fs = FileSystems.getDefault();
    try {
        configureLog(fs);
    } catch (IOException e) {
        handleUnexpectedError(console, e.getMessage(), args, e);
        return ExitCode.ENVIRONMENT_ERROR;
    }
    // This is useful when debugging user issues
    logger.info("Running: " + Joiner.on(' ').join(args));
    console.startupMessage(getVersion());
    ExitCode exitCode = runInternal(args, console, fs);
    try {
        shutdown(exitCode);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        handleUnexpectedError(console, "Execution was interrupted.", args, e);
    }
    return exitCode;
}
Also used : FileSystem(java.nio.file.FileSystem) ExitCode(com.google.copybara.util.ExitCode) AnsiConsole(com.google.copybara.util.console.AnsiConsole) Console(com.google.copybara.util.console.Console) LogConsole(com.google.copybara.util.console.LogConsole) IOException(java.io.IOException)

Example 4 with Console

use of com.google.copybara.util.console.Console in project copybara by google.

the class Copybara method validate.

/**
 * Validates that the configuration is correct and that there is a valid migration specified by
 * {@code migrationName}.
 *
 * <p>Note that, besides validating the specific migration, all the configuration will be
 * validated syntactically.
 */
public boolean validate(Options options, ConfigLoader<?> configLoader, String migrationName) throws IOException {
    Console console = options.get(GeneralOptions.class).console();
    ArrayList<Message> messages = new ArrayList<>();
    try {
        Config config = configLoader.loadConfig(options, console);
        messages.addAll(validateConfig(config, migrationName));
    } catch (ValidationException e) {
        // The validate subcommand should not throw Validation exceptions but log a result
        StringBuilder error = new StringBuilder(e.getMessage()).append("\n");
        Throwable cause = e.getCause();
        while (cause != null) {
            error.append("  CAUSED BY: ").append(cause.getMessage()).append("\n");
            cause = cause.getCause();
        }
        messages.add(Message.error(error.toString()));
    }
    messages.forEach(message -> message.printTo(console));
    boolean hasNoErrors = messages.stream().noneMatch(message -> message.getType() == MessageType.ERROR);
    if (hasNoErrors) {
        console.info(String.format("Configuration '%s' is valid.", configLoader.location()));
    } else {
        console.error(String.format("Configuration '%s' is invalid.", configLoader.location()));
    }
    return hasNoErrors;
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) Message(com.google.copybara.util.console.Message) Config(com.google.copybara.config.Config) Console(com.google.copybara.util.console.Console) ArrayList(java.util.ArrayList)

Example 5 with Console

use of com.google.copybara.util.console.Console in project copybara by google.

the class Copybara method info.

/**
 * Retrieves the {@link Info} of the {@code migrationName} and prints it to the console.
 */
public void info(Options options, Config config, String migrationName) throws ValidationException, RepoException {
    @SuppressWarnings("unchecked") Info<? extends Revision> info = getInfo(migrationName, config);
    Console console = options.get(GeneralOptions.class).console();
    int outputSize = 0;
    for (MigrationReference<? extends Revision> migrationRef : info.migrationReferences()) {
        console.info(String.format("'%s': last_migrated %s - last_available %s.", migrationRef.getLabel(), migrationRef.getLastMigrated() != null ? migrationRef.getLastMigrated().asString() : "None", migrationRef.getLastAvailableToMigrate() != null ? migrationRef.getLastAvailableToMigrate().asString() : "None"));
        ImmutableList<? extends Change<? extends Revision>> availableToMigrate = migrationRef.getAvailableToMigrate();
        int outputLimit = options.get(GeneralOptions.class).getOutputLimit();
        if (!availableToMigrate.isEmpty()) {
            console.infoFmt("Available changes%s:", availableToMigrate.size() <= outputLimit ? "" : String.format(" (showing only first %d out of %d)", outputLimit, availableToMigrate.size()));
            int changeNumber = 1;
            for (Change<? extends Revision> change : Iterables.limit(availableToMigrate, outputLimit)) {
                outputSize++;
                console.info(String.format("%d - %s %s by %s", changeNumber++, change.getRevision().asString(), change.firstLineMessage(), change.getAuthor()));
            }
        }
        // TODO(danielromero): Check flag usage on 2018-06 and decide if we keep it
        if (outputSize > 100) {
            console.infoFmt("Use %s to limit the output of the command.", GeneralOptions.OUTPUT_LIMIT_FLAG);
        }
    }
    options.get(GeneralOptions.class).eventMonitor().onInfoFinished(new InfoFinishedEvent(info));
}
Also used : InfoFinishedEvent(com.google.copybara.monitor.EventMonitor.InfoFinishedEvent) Console(com.google.copybara.util.console.Console)

Aggregations

Console (com.google.copybara.util.console.Console)8 ImmutableList (com.google.common.collect.ImmutableList)3 ValidationException (com.google.copybara.exception.ValidationException)3 IOException (java.io.IOException)3 Config (com.google.copybara.config.Config)2 RepoException (com.google.copybara.exception.RepoException)2 InfoFinishedEvent (com.google.copybara.monitor.EventMonitor.InfoFinishedEvent)2 Message (com.google.copybara.util.console.Message)2 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 Preconditions (com.google.common.base.Preconditions)1 Iterables (com.google.common.collect.Iterables)1 ChangeMessage (com.google.copybara.ChangeMessage)1 DestinationEffect (com.google.copybara.DestinationEffect)1 MigrationReference (com.google.copybara.Info.MigrationReference)1 TransformResult (com.google.copybara.TransformResult)1 ConfigValidator (com.google.copybara.config.ConfigValidator)1 Migration (com.google.copybara.config.Migration)1 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)1 ChangeRejectedException (com.google.copybara.exception.ChangeRejectedException)1