use of com.google.copybara.exception.ValidationException in project copybara by google.
the class GitMirrorContext method merge.
@StarlarkMethod(name = "merge", doc = "Merge one or more commits into a local branch.", parameters = { @Param(name = "branch", named = true), @Param(name = "commits", allowedTypes = { @ParamType(type = Sequence.class, generic1 = String.class) }, named = true), @Param(name = "msg", named = true, defaultValue = "None") })
public MergeResult merge(String branch, Sequence<?> commits, Object msg) throws RepoException, ValidationException, EvalException, IOException {
ValidationException.checkCondition(!commits.isEmpty(), "At least one commit should be passed to merge");
GitRepository withWorktree = this.repo.withWorkTree(dirFactory.newTempDir("mirror"));
try {
withWorktree.forceCheckout(branch);
} catch (RepoException e) {
throw new ValidationException("Cannot merge commits " + commits + " into branch " + branch + " because of failure during merge checkout", e);
}
String strMsg = SkylarkUtil.convertFromNoneable(msg, null);
// Clean everything before the merge
withWorktree.simpleCommand("reset", "--hard");
withWorktree.forceClean();
List<String> cmd = Lists.newArrayList("merge");
if (strMsg != null) {
cmd.add("-m");
cmd.add(strMsg);
}
cmd.addAll(SkylarkUtil.convertStringList(commits, "commits"));
try {
withWorktree.simpleCommand(cmd);
} catch (RepoException e) {
logger.atWarning().withCause(e).log("Error running merge in action %s for branch %s and commits %s", getActionName(), branch, commits);
return MergeResult.error(e.getMessage());
}
return MergeResult.success();
}
use of com.google.copybara.exception.ValidationException 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 (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));
}
use of com.google.copybara.exception.ValidationException in project copybara by google.
the class HgRepository method pull.
public void pull(String url, boolean force, @Nullable String ref) throws RepoException, ValidationException {
ImmutableList.Builder<String> builder = ImmutableList.builder();
builder.add("pull", validateNotHttp(url));
if (force) {
builder.add("--force");
}
if (!Strings.isNullOrEmpty(ref)) {
builder.add("--rev", ref);
}
try {
hg(hgDir, builder.build(), fetchTimeout);
} catch (RepoException e) {
if (INVALID_HG_REPOSITORY.matcher(e.getMessage()).find()) {
throw new ValidationException("Repository not found: " + e.getMessage());
}
if (UNKNOWN_REVISION.matcher(e.getMessage()).find()) {
throw new ValidationException("Unknown revision: " + e.getMessage());
}
throw e;
}
}
use of com.google.copybara.exception.ValidationException in project copybara by google.
the class HgVisitorUtil method visitChanges.
/**
* Visits Hg changes, up to the termination point specified by the visitor.
*/
static void visitChanges(HgRevision start, ChangesVisitor visitor, ChangeReader.Builder queryChanges, GeneralOptions generalOptions, String type, int visitChangePageSize) throws RepoException {
Preconditions.checkNotNull(start);
int offset = 0;
boolean finished = false;
try (ProfilerTask ignore = generalOptions.profiler().start(type + "/visit_changes")) {
while (!finished) {
ImmutableList<Change<HgRevision>> result;
try (ProfilerTask ignore2 = generalOptions.profiler().start(String.format("hg_log_%d_%d", offset, visitChangePageSize))) {
try {
result = queryChanges.setSkip(offset).setLimit(visitChangePageSize).build().run(start.getGlobalId()).reverse();
} catch (ValidationException e) {
throw new RepoException(String.format("Error querying changes: %s", e.getMessage()), e.getCause());
}
}
if (result.isEmpty()) {
break;
}
offset += result.size();
for (Change<HgRevision> current : result) {
if (visitor.visit(current) == VisitResult.TERMINATE) {
finished = true;
break;
}
}
}
}
}
use of com.google.copybara.exception.ValidationException in project copybara by google.
the class RemoteFileModule method gitHubTarball.
@SuppressWarnings("unused")
@StarlarkMethod(name = "github_archive", doc = "A tarball for a specific SHA1 on GitHub. Experimental.", documented = false, parameters = { @Param(name = "project", named = true, defaultValue = "[]", doc = "The GitHub project from which to load the file, e.g. google/copybara"), @Param(name = "revision", named = true, defaultValue = "[]", doc = "The revision to download from the project, typically a commit SHA1."), @Param(name = "type", named = true, defaultValue = "'TARBALL'", doc = "Archive type to download, options are 'TARBALL' or 'ZIP'.") })
@UsesFlags(RemoteFileOptions.class)
public GithubArchive gitHubTarball(String project, String revision, String type) throws EvalException {
GeneralOptions generalOptions = options.get(GeneralOptions.class);
RemoteFileOptions remoteFileOptions = options.get(RemoteFileOptions.class);
try {
return new GithubArchive(project, revision, Enums.getIfPresent(GithubArchive.Type.class, type).toJavaUtil().orElseThrow(() -> errorf("Unsupported archive type: '%s'. " + "Supported values: %s", type, Arrays.asList(GithubArchive.Type.values()))), remoteFileOptions.getTransport(), generalOptions.profiler(), generalOptions.console());
} catch (ValidationException e) {
throw Starlark.errorf("Error setting up remote http file: %s", e.getMessage());
}
}
Aggregations