use of com.google.copybara.effect.DestinationEffect.DestinationRef in project copybara by google.
the class ConsoleEventMonitorTest method testEventMonitorPrintsToConsole.
@Test
public void testEventMonitorPrintsToConsole() {
eventMonitor.onMigrationStarted(new MigrationStartedEvent());
eventMonitor.onMigrationFinished(new MigrationFinishedEvent(ExitCode.SUCCESS));
eventMonitor.onChangeMigrationStarted(new ChangeMigrationStartedEvent());
DestinationEffect destinationEffect = new DestinationEffect(Type.CREATED, "Created revision 1234", ImmutableList.of(new OriginRef("ABCD")), new DestinationRef("1234", "commit", /*url=*/
null));
eventMonitor.onChangeMigrationFinished(new ChangeMigrationFinishedEvent(ImmutableList.of(destinationEffect), ImmutableMultimap.of(), ImmutableMultimap.of()));
MigrationReference<DummyRevision> workflow = MigrationReference.create("workflow", new DummyRevision("1111"), ImmutableList.of(newChange("2222"), newChange("3333")));
Info<?> info = Info.create(ImmutableMultimap.of("origin", "foo"), ImmutableMultimap.of("dest", "bar"), ImmutableList.of(workflow));
eventMonitor.onInfoFinished(new InfoFinishedEvent(info, ImmutableMap.of("foo_a", "foo_b")));
console.assertThat().equalsNext(VERBOSE, "onMigrationStarted(): MigrationStartedEvent").equalsNext(VERBOSE, "onMigrationFinished(): " + "MigrationFinishedEvent{exitCode=SUCCESS, profiler=null}").equalsNext(VERBOSE, "onChangeMigrationStarted(): ChangeMigrationStartedEvent{}").matchesNext(VERBOSE, "onChangeMigrationFinished[(][)]: ChangeMigrationFinishedEvent[{].*[}]").matchesNext(VERBOSE, "onInfoFinished[(][)]: InfoFinishedEvent[{].*(origin).*" + "(foo).*(dest).*(bar).*(foo_a).*(foo_b).*[}]").containsNoMoreMessages();
}
use of com.google.copybara.effect.DestinationEffect.DestinationRef in project copybara by google.
the class FeedbackTest method runAndVerifyDestinationEffects.
private void runAndVerifyDestinationEffects(String actionsCode, ImmutableList<String> expectedErrors, String expectedSummary, String expectedOriginRef, String expectedDestRef, String expectedDestType, @Nullable String expectedDestUrl) throws IOException, ValidationException, RepoException {
Feedback feedback = feedback(actionsCode, "test_action");
feedback.run(workdir, ImmutableList.of());
console.assertThat().equalsNext(MessageType.INFO, "Action 'test_action' returned success");
assertThat(eventMonitor.changeMigrationStartedEventCount()).isEqualTo(1);
assertThat(eventMonitor.changeMigrationFinishedEventCount()).isEqualTo(1);
ChangeMigrationFinishedEvent event = Iterables.getOnlyElement(eventMonitor.changeMigrationFinishedEvents);
DestinationEffect effect = Iterables.getOnlyElement(event.getDestinationEffects());
assertThat(effect.getSummary()).isEqualTo(expectedSummary);
assertThat(effect.getOriginRefs()).hasSize(1);
assertThat(effect.getOriginRefs().get(0).getRef()).isEqualTo(expectedOriginRef);
DestinationRef destinationRef = effect.getDestinationRef();
assertThat(destinationRef.getId()).isEqualTo(expectedDestRef);
assertThat(destinationRef.getType()).isEqualTo(expectedDestType);
if (expectedDestUrl == null) {
assertThat(destinationRef.getUrl()).isNull();
} else {
assertThat(destinationRef.getUrl()).isEqualTo(expectedDestUrl);
}
assertThat(effect.getErrors()).containsExactlyElementsIn(expectedErrors);
}
use of com.google.copybara.effect.DestinationEffect.DestinationRef in project copybara by google.
the class GitHubWriteHook method afterPush.
@Override
public ImmutableList<DestinationEffect> afterPush(String serverResponse, MessageInfo messageInfo, GitRevision pushedRevision, List<? extends Change<?>> originChanges) throws ValidationException, RepoException {
ImmutableList.Builder<DestinationEffect> baseEffects = ImmutableList.<DestinationEffect>builder().addAll(super.afterPush(serverResponse, messageInfo, pushedRevision, originChanges));
if (prBranchToUpdate == null || !deletePrBranch) {
return baseEffects.build();
}
String projectId = ghHost.getProjectNameFromUrl(repoUrl);
GitHubApi api = gitHubOptions.newGitHubApi(projectId);
for (Change<?> change : originChanges) {
Dict<String, String> labelDict = change.getLabelsForSkylark();
String updatedPrBranchName = getUpdatedPrBranch(labelDict);
checkCondition(!Objects.equals(updatedPrBranchName, "master"), "Cannot delete 'master' branch from GitHub");
String completeRef = String.format("refs/heads/%s", updatedPrBranchName);
try {
api.deleteReference(projectId, completeRef);
baseEffects.add(new DestinationEffect(Type.UPDATED, String.format("Reference '%s' deleted", completeRef), ImmutableList.of(change), new DestinationRef(completeRef, "ref_deleted", "https://github.com/" + projectId + "/tree/" + updatedPrBranchName)));
} catch (GitHubApiException e) {
if (e.getResponseCode() == ResponseCode.NOT_FOUND || e.getResponseCode() == ResponseCode.UNPROCESSABLE_ENTITY) {
console.infoFmt("Branch %s does not exist", updatedPrBranchName);
logger.atInfo().log("Branch %s does not exist", updatedPrBranchName);
continue;
}
throw e;
}
}
return baseEffects.build();
}
use of com.google.copybara.effect.DestinationEffect.DestinationRef in project copybara by google.
the class Mirror method run.
@Override
public void run(Path workdir, ImmutableList<String> sourceRefs) throws RepoException, IOException, ValidationException {
try (ProfilerTask ignore = generalOptions.profiler().start("run/" + name)) {
GitRepository repo = gitOptions.cachedBareRepoForUrl(origin);
if (!Strings.isNullOrEmpty(gitDestinationOptions.committerName)) {
repo.simpleCommand("config", "user.name", gitDestinationOptions.committerName);
}
if (!Strings.isNullOrEmpty(gitDestinationOptions.committerEmail)) {
repo.simpleCommand("config", "user.email", gitDestinationOptions.committerEmail);
}
if (Iterables.isEmpty(actions)) {
defaultMirror(repo);
} else {
ImmutableList.Builder<ActionResult> allResultsBuilder = ImmutableList.builder();
for (Action action : actions) {
GitMirrorContext context = new GitMirrorContext(action, new SkylarkConsole(generalOptions.console()), sourceRefs, refspec, origin, destination, generalOptions.isForced(), repo, generalOptions.getDirFactory(), Dict.empty());
try {
action.run(context);
ActionResult actionResult = context.getActionResult();
allResultsBuilder.add(actionResult);
// First error aborts the execution of the other actions unless --force is used
ValidationException.checkCondition(generalOptions.isForced() || actionResult.getResult() != Result.ERROR, "Feedback migration '%s' action '%s' returned error: %s. Aborting execution.", name, action.getName(), actionResult.getMsg());
} catch (NonFastForwardRepositoryException e) {
allResultsBuilder.add(ActionResult.error(action.getName() + ": " + e.getMessage()));
if (!generalOptions.isForced()) {
throw e;
}
logger.atWarning().withCause(e).log();
} finally {
generalOptions.eventMonitors().dispatchEvent(m -> m.onChangeMigrationFinished(new ChangeMigrationFinishedEvent(ImmutableList.copyOf(context.getNewDestinationEffects()), getOriginDescription(), getDestinationDescription())));
}
}
ImmutableList<ActionResult> allResults = allResultsBuilder.build();
if (allResults.stream().anyMatch(a -> a.getResult() == Result.ERROR)) {
String errors = allResults.stream().filter(a -> a.getResult() == Result.ERROR).map(ActionResult::getMsg).collect(Collectors.joining("\n - "));
throw new ValidationException("One or more errors happened during the migration:\n" + " - " + errors);
}
// This check also returns true if there are no actions
if (allResults.stream().allMatch(a -> a.getResult() == Result.NO_OP)) {
String detailedMessage = allResults.isEmpty() ? "actions field is empty" : allResults.stream().map(ActionResult::getMsg).collect(ImmutableList.toImmutableList()).toString();
throw new EmptyChangeException(String.format("git.mirror migration '%s' was noop. Detailed messages: %s", name, detailedMessage));
}
}
}
// More fine grain events based on the references created/updated/deleted:
ChangeMigrationFinishedEvent event = new ChangeMigrationFinishedEvent(ImmutableList.of(new DestinationEffect(generalOptions.dryRunMode ? DestinationEffect.Type.NOOP : DestinationEffect.Type.UPDATED, generalOptions.dryRunMode ? "Refspecs " + refspec + " can be mirrored" : "Refspecs " + refspec + " mirrored successfully", // TODO(danielromero): Populate OriginRef here
ImmutableList.of(), new DestinationRef(getOriginDestinationRef(destination), "mirror", /*url=*/
null))), getOriginDescription(), getDestinationDescription());
generalOptions.eventMonitors().dispatchEvent(m -> m.onChangeMigrationFinished(event));
}
Aggregations