Search in sources :

Example 1 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class Copybara method run.

/**
 * Runs the migration specified by {@code migrationName}.
 */
public void run(Options options, ConfigLoader<?> configLoader, String migrationName, Path workdir, @Nullable String sourceRef) throws RepoException, ValidationException, IOException {
    Config config = loadConfig(options, configLoader, migrationName);
    Migration migration = config.getMigration(migrationName);
    if (configLoaderProvider == null) {
        this.migrationRanConsumer.accept(migration);
        migration.run(workdir, sourceRef);
        return;
    }
    // A safeguard, mirror workflows are not supported in the service anyway
    if (!(migration instanceof Workflow)) {
        throw new ValidationException("Flag --read-config-from-change is not supported for non-workflow migrations: %s", migrationName);
    }
    migrationRanConsumer.accept(migration);
    @SuppressWarnings("unchecked") Workflow<? extends Revision, ? extends Revision> workflow = (Workflow<? extends Revision, ? extends Revision>) migration;
    new ReadConfigFromChangeWorkflow<>(workflow, options, configLoaderProvider, configValidator).run(workdir, sourceRef);
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) Config(com.google.copybara.config.Config) Migration(com.google.copybara.config.Migration)

Example 2 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class CopyOrMove method transform.

@Override
public void transform(TransformWork work) throws IOException, ValidationException {
    work.getConsole().progress("Moving " + this.before);
    Path before = work.getCheckoutDir().resolve(this.before).normalize();
    if (!Files.exists(before)) {
        workflowOptions.reportNoop(work.getConsole(), String.format("Error moving '%s'. It doesn't exist in the workdir", this.before));
        return;
    }
    Path after = work.getCheckoutDir().resolve(this.after).normalize();
    if (Files.isDirectory(after, LinkOption.NOFOLLOW_LINKS) && after.startsWith(before)) {
        // When moving from a parent dir to a sub-directory, make sure after doesn't already have
        // files in it - this is most likely a mistake.
        new VerifyDirIsEmptyVisitor(after).walk();
    }
    createParentDirs(after);
    try {
        boolean beforeIsDir = Files.isDirectory(before);
        if (paths != Glob.ALL_FILES && !beforeIsDir) {
            throw new ValidationException("Cannot use user defined 'paths' filter when the 'before' is not a directory: " + paths);
        }
        Files.walkFileTree(before, new CopyMoveVisitor(before, after, beforeIsDir ? paths.relativeTo(before) : null, overwrite, isCopy));
    } catch (FileAlreadyExistsException e) {
        throw new ValidationException("Cannot move file to '%s' because it already exists", e.getFile());
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ValidationException(com.google.copybara.exception.ValidationException) NonReversibleValidationException(com.google.copybara.NonReversibleValidationException)

Example 3 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class GithubUtil method getProjectNameFromUrl.

/**
 * Given a url that represents a GitHub repository, return the project name.
 */
public static String getProjectNameFromUrl(String url) throws ValidationException {
    if (url.startsWith(GIT_GITHUB_PROTOCOL)) {
        return url.substring(GIT_GITHUB_PROTOCOL.length()).replaceAll("([.]git|/)$", "");
    }
    URI uri;
    try {
        uri = URI.create(url);
    } catch (IllegalArgumentException e) {
        throw new ValidationException("Cannot find project name from url " + url);
    }
    if (uri.getScheme() == null) {
        uri = URI.create("notimportant://" + url);
    }
    if (!Objects.equals(uri.getHost(), GITHUB_HOST)) {
        throw new ValidationException("Not a github url: " + url);
    }
    String name = uri.getPath().replaceAll("^/", "").replaceAll("([.]git|/)$", "");
    if (Strings.isNullOrEmpty(name)) {
        throw new ValidationException("Cannot find project name from url " + url);
    }
    return name;
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) URI(java.net.URI)

Example 4 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class PatchTransformation method transform.

@Override
public void transform(TransformWork work) throws ValidationException, IOException {
    for (int i = 0; i < patches.size(); i++) {
        ConfigFile<?> patch = patches.get(i);
        work.getConsole().info(String.format("Applying patch %d/%d: '%s'.", i + 1, patches.size(), patch.path()));
        try {
            DiffUtil.patch(work.getCheckoutDir(), patch.content(), excludedPaths, SLASHES_TO_STRIP, options.isVerbose(), reverse, options.getEnvironment());
        } catch (IOException ioException) {
            work.getConsole().error("Error applying patch: " + ioException.getMessage());
            throw new ValidationException(ioException, "Error applying patch.");
        } catch (InsideGitDirException e) {
            throw new ValidationException("Cannot use patch.apply because Copybara temporary directory (%s) is inside a git" + " directory (%s). Please remove the git repository or use %s flag.", e.getPath(), e.getGitDirPath(), OUTPUT_ROOT_FLAG);
        }
    }
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) IOException(java.io.IOException) InsideGitDirException(com.google.copybara.util.InsideGitDirException)

Example 5 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class Main method runInternal.

/**
 * Runs the command and returns the {@link ExitCode}.
 *
 * <p>This method is also responsible for the exception handling/logging.
 */
private CommandResult runInternal(String[] args, Console console, FileSystem fs) {
    CommandEnv commandEnv = null;
    CopybaraCmd subcommand = null;
    try {
        ModuleSet moduleSet = newModuleSet(environment, fs, console);
        final MainArguments mainArgs = new MainArguments();
        Options options = moduleSet.getOptions();
        jCommander = new JCommander(ImmutableList.builder().addAll(options.getAll()).add(mainArgs).build());
        jCommander.setProgramName("copybara");
        String version = getVersion();
        logger.atInfo().log("Copybara version: %s", version);
        jCommander.parse(args);
        ConfigLoaderProvider configLoaderProvider = newConfigLoaderProvider(moduleSet);
        ImmutableMap<String, CopybaraCmd> commands = Maps.uniqueIndex(getCommands(moduleSet, configLoaderProvider, jCommander), CopybaraCmd::name);
        // generating the usage info.
        for (Map.Entry<String, CopybaraCmd> cmd : commands.entrySet()) {
            jCommander.addCommand(cmd.getKey(), cmd.getValue());
        }
        CommandWithArgs cmdToRun = mainArgs.parseCommand(commands, commands.get("migrate"));
        subcommand = cmdToRun.getSubcommand();
        initEnvironment(options, cmdToRun.getSubcommand(), ImmutableList.copyOf(args));
        GeneralOptions generalOptions = options.get(GeneralOptions.class);
        Path baseWorkdir = mainArgs.getBaseWorkdir(generalOptions, generalOptions.getFileSystem());
        commandEnv = new CommandEnv(baseWorkdir, options, cmdToRun.getArgs());
        generalOptions.console().progressFmt("Running %s", subcommand.name());
        // TODO(malcon): Remove this after 2019-09-15, once tested that temp features work.
        logger.atInfo().log("Temporary features test: %s", options.get(GeneralOptions.class).isTemporaryFeature("TEST_TEMP_FEATURES", true));
        ExitCode exitCode = subcommand.run(commandEnv);
        return new CommandResult(exitCode, subcommand, commandEnv);
    } catch (CommandLineException | ParameterException e) {
        printCauseChain(Level.WARNING, console, args, e);
        console.error("Try 'copybara help'.");
        return new CommandResult(ExitCode.COMMAND_LINE_ERROR, subcommand, commandEnv);
    } catch (RepoException e) {
        printCauseChain(Level.SEVERE, console, args, e);
        // have to do this hack.
        if (e.getCause() instanceof InterruptedException) {
            return new CommandResult(ExitCode.INTERRUPTED, subcommand, commandEnv);
        }
        return new CommandResult(ExitCode.REPOSITORY_ERROR, subcommand, commandEnv);
    } catch (EmptyChangeException e) {
        // This is not necessarily an error. Maybe the tool was run previously and there are no new
        // changes to import.
        console.warn(e.getMessage());
        return new CommandResult(ExitCode.NO_OP, subcommand, commandEnv);
    } catch (ValidationException e) {
        printCauseChain(Level.WARNING, console, args, e);
        return new CommandResult(ExitCode.CONFIGURATION_ERROR, subcommand, commandEnv);
    } catch (IOException e) {
        handleUnexpectedError(console, e.getMessage(), args, e);
        return new CommandResult(ExitCode.ENVIRONMENT_ERROR, subcommand, commandEnv);
    } catch (RuntimeException e) {
        // This usually indicates a serious programming error that will require Copybara team
        // intervention. Print stack trace without concern for presentation.
        e.printStackTrace();
        handleUnexpectedError(console, "Unexpected error (please file a bug against copybara): " + e.getMessage(), args, e);
        return new CommandResult(ExitCode.INTERNAL_ERROR, subcommand, commandEnv);
    }
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) ExitCode(com.google.copybara.util.ExitCode) CommandLineException(com.google.copybara.exception.CommandLineException) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) Path(java.nio.file.Path) RepoException(com.google.copybara.exception.RepoException) IOException(java.io.IOException) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) CommandWithArgs(com.google.copybara.MainArguments.CommandWithArgs) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

ValidationException (com.google.copybara.exception.ValidationException)178 Test (org.junit.Test)125 Path (java.nio.file.Path)33 RepoException (com.google.copybara.exception.RepoException)29 NonReversibleValidationException (com.google.copybara.exception.NonReversibleValidationException)26 ImmutableList (com.google.common.collect.ImmutableList)21 IOException (java.io.IOException)19 Console (com.google.copybara.util.console.Console)16 EmptyChangeException (com.google.copybara.exception.EmptyChangeException)14 DummyRevision (com.google.copybara.testing.DummyRevision)14 Glob (com.google.copybara.util.Glob)14 ProfilerTask (com.google.copybara.profiler.Profiler.ProfilerTask)13 Nullable (javax.annotation.Nullable)13 Migration (com.google.copybara.config.Migration)11 TestingConsole (com.google.copybara.util.console.testing.TestingConsole)11 Iterables (com.google.common.collect.Iterables)10 Change (com.google.copybara.Change)10 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)10 Collectors (java.util.stream.Collectors)10 WriterContext (com.google.copybara.WriterContext)9