Example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder

List of usage examples for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder

Introduction

In this page you can find the example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder.

Prototype

FileRepositoryBuilder

Source Link

Usage

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String upgrade(String path) throws Exception {
    //staticDir.mkdirs();
    Repository repository = null;/*from   ww  w . j  a  v  a2s. c o  m*/
    try {
        String logFile = "output.log";
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        File output = new File(installLogDir, logFile);
        String gitPath = github + path + ".git";
        logger.debug("Updating from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        Git git = null;
        try {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            repository = builder.setGitDir(new File(destDir, "/.git")).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();
            git = new Git(repository);
            PullResult result = git.pull().call();
            FileUtils.writeStringToFile(output, result.getMergeResult().toString(), true);
            logger.debug("DONE: Updated " + gitPath + " repository: " + result.getMergeResult().toString());

            //now run npm install
            //runNpmInstall(output, destDir);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        } finally {
            if (git != null)
                git.close();
            if (repository != null)
                repository.close();
        }
        return logFile;

    } finally {
        if (repository != null)
            repository.close();
    }

}

From source file:org.abratuhi.camel.GitLogProducer.java

License:Apache License

public void process(Exchange exchange) throws Exception {
    String repo = endpoint.getEndpointUri().substring("git://".length());
    FileRepositoryBuilder frb = new FileRepositoryBuilder();
    FileRepository fr = frb.setGitDir(new File(repo)).readEnvironment().build();
    Git git = new Git(fr);
    Iterable<RevCommit> commits = git.log().call();

    StringBuffer sb = new StringBuffer();
    for (RevCommit rc : commits) {
        sb.append(rc.getShortMessage() + "\n");
    }/*from w w  w . j av a 2s . c  o  m*/

    GitLogMessage msg = new GitLogMessage();
    msg.setBody(sb.toString());

    exchange.setOut(msg);
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

/**
 * Open a Git repository using the specified directory.
 * @param gitProjectRootDir a root directory of a Git project
 * @return created Repository/*from   ww w  . j  a v  a  2 s. com*/
 * @throws IOException thrown when the specified directory does not exist,
 * does not have read/write privilege or not containing .git directory
 */
private Repository openRepository(final File gitProjectRootDir) throws IOException {

    // Instead of using FileUtils.ensureDirectoryExistAndCanReadAndWrite, check availability manually here.
    // Because the util will try to create a dir if not exist.
    // The git dir should be initialized and configured by users.
    if (!gitProjectRootDir.isDirectory()) {
        throw new IOException(format("'%s' is not a directory or does not exist.", gitProjectRootDir));
    }

    if (!(gitProjectRootDir.canRead() && gitProjectRootDir.canWrite())) {
        throw new IOException(format("Directory '%s' does not have read/write privilege.", gitProjectRootDir));
    }

    // Search .git dir but avoid searching parent directories.
    final FileRepositoryBuilder builder = new FileRepositoryBuilder().readEnvironment().setMustExist(true)
            .addCeilingDirectory(gitProjectRootDir).findGitDir(gitProjectRootDir);

    if (builder.getGitDir() == null) {
        throw new IOException(format("Directory '%s' does not contain a .git directory."
                + " Please init and configure the directory with 'git init' command before using it from NiFi Registry.",
                gitProjectRootDir));
    }

    return builder.build();
}

From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java

License:Apache License

private static void initializeGitRepository() throws ServletException {
    XacmlAdminUI.repositoryPath = Paths
            .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY));
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {/*from   www.  j  a v a2 s.  c o  m*/
        XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment()
                .findGitDir().setBare().build();
        if (Files.notExists(XacmlAdminUI.repositoryPath)
                || Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) {
            //
            // Create it if it doesn't exist. As a bare repository
            //
            logger.info("Creating bare git repository: " + XacmlAdminUI.repositoryPath.toString());
            XacmlAdminUI.repository.create();
            //
            // Add the magic file so remote works.
            //
            Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok");
            Files.createFile(daemon);
        }
    } catch (IOException e) {
        logger.error("Failed to build repository: " + repository, e);
        throw new ServletException(e.getMessage(), e.getCause());
    }
    //
    // Make sure the workspace directory is created
    //
    Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE));
    workspace = workspace.toAbsolutePath();
    if (Files.notExists(workspace)) {
        try {
            Files.createDirectory(workspace);
        } catch (IOException e) {
            logger.error("Failed to build workspace: " + workspace, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Create the user workspace directory
    //
    workspace = Paths.get(workspace.toString(), "pe");
    if (Files.notExists(workspace)) {
        try {
            Files.createDirectory(workspace);
        } catch (IOException e) {
            logger.error("Failed to create directory: " + workspace, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Get the path to where the repository is going to be
    //
    Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
    if (Files.notExists(gitPath)) {
        try {
            Files.createDirectory(gitPath);
        } catch (IOException e) {
            logger.error("Failed to create directory: " + gitPath, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Initialize the domain structure
    //
    String base = null;
    String domain = XacmlAdminUI.getDomain();
    if (domain != null) {
        for (String part : Splitter.on(':').trimResults().split(domain)) {
            if (base == null) {
                base = part;
            }
            Path subdir = Paths.get(gitPath.toString(), part);
            if (Files.notExists(subdir)) {
                try {
                    Files.createDirectory(subdir);
                    Files.createFile(Paths.get(subdir.toString(), ".svnignore"));
                } catch (IOException e) {
                    logger.error("Failed to create: " + subdir, e);
                    throw new ServletException(e.getMessage(), e.getCause());
                }
            }
        }
    } else {
        try {
            Files.createFile(Paths.get(workspace.toString(), ".svnignore"));
            base = ".svnignore";
        } catch (IOException e) {
            logger.error("Failed to create file", e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    try {
        //
        // These are the sequence of commands that must be done initially to
        // finish setting up the remote bare repository.
        //
        Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call();
        git.add().addFilepattern(base).call();
        git.commit().setMessage("Initialize Bare Repository").call();
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString());
        config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
        config.save();
        git.push().setRemote("origin").add("master").call();
        /*
         * This will not work unless git.push().setRemote("origin").add("master").call();
         * is called first. Otherwise it throws an exception. However, if the push() is
         * called then calling this function seems to add nothing.
         * 
        git.branchCreate().setName("master")
           .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
           .setStartPoint("origin/master").setForce(true).call();
        */
    } catch (GitAPIException | IOException e) {
        logger.error(e);
        throw new ServletException(e.getMessage(), e.getCause());
    }
}

From source file:org.basinmc.maven.plugins.minecraft.patch.GeneratePatchesMojo.java

License:Apache License

/**
 * {@inheritDoc}/*ww w . j a va  2s  . c  o  m*/
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    super.execute();

    this.getLog().info("Purging previous patch files");

    try {
        Files.walk(this.getPatchDirectory().toPath())
                .filter((p) -> p.getFileName().toString().endsWith(".patch")).forEach((p) -> {
                    try {
                        Files.delete(p);
                    } catch (IOException ex) {
                        throw new WrappedException(ex);
                    }
                });
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to access patch directory: " + ex.getMessage(), ex);
    } catch (WrappedException ex) {
        if (ex.getCause() instanceof IOException) {
            throw new MojoFailureException("Failed to delete patch file: " + ex.getMessage(), ex);
        }

        throw new MojoFailureException("Caught unexpected exception: " + ex.getMessage(), ex);
    }

    try {
        Repository repository = new FileRepositoryBuilder().setWorkTree(this.getSourceDirectory())
                .setMustExist(true).build();

        Git git = new Git(repository);

        if (!git.status().call().isClean()) {
            this.getLog().warn("One or more uncommited changes present within source directory\n");
            this.getLog().warn("Only commited changes will be considered in patch generation");
        }
    } catch (GitAPIException ex) {
        throw new MojoFailureException("Failed to invoke git: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoFailureException("Could not access module repository: " + ex.getMessage(), ex);
    }

    Path workingDirectory = this.getSourceDirectory().toPath().toAbsolutePath();
    Path relativePatchDirectory = workingDirectory.relativize(this.getPatchDirectory().toPath());

    try {
        if (this.execute(new ProcessBuilder()
                .command("git", "format-patch", "--minimal", "--no-stat", "-N", "-o",
                        relativePatchDirectory.toString(), "upstream")
                .directory(this.getSourceDirectory().getAbsoluteFile())) != 0) {
            throw new MojoFailureException("Git reported an unexpected error");
        }
    } catch (InterruptedException ex) {
        throw new MojoFailureException("Interrupted while awaiting git result: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to invoke git: " + ex.getMessage(), ex);
    }
}

From source file:org.basinmc.maven.plugins.minecraft.patch.SafeguardMojo.java

License:Apache License

/**
 * {@inheritDoc}/*from www .j av  a2  s .com*/
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    this.verifyProperties("sourceDirectory", "force");

    this.getLog().info("Running repository safeguard checks");

    if (this.isForced()) {
        this.getLog().warn("Skipping safeguard - Override is enabled\n" + "\n"
                + "+--------------------------------------+\n" + "|                                      |\n"
                + "|    THIS MAY CAUSE LOSS OF CHANGES    |\n" + "|         USE AT YOUR OWN RISK         |\n"
                + "|                                      |\n" + "+--------------------------------------+\n");
        return;
    }

    try {
        Repository repository = new FileRepositoryBuilder().setWorkTree(this.getSourceDirectory()).build();

        if (!repository.getObjectDatabase().exists()) {
            this.getLog().info("Skipping safeguard - No repository in source path");
            return;
        }

        Git git = new Git(repository);

        if (!git.status().call().isClean()) {
            this.getLog().error(
                    "The repository at " + this.getSourceDirectory().toString() + " is not in a clean state");
            this.getLog().error(
                    "As such the build will be halted - Please verify that all changes you wish to retain have been commited and turned into patch files");
            this.getLog().error(
                    "If you wish to override this behavior, start the build by passing -Dminecraft.force=true");

            throw new MojoFailureException("Repository is in a dirty state");
        }

        // TODO: Compare number of commits since first commit against amount of patches to
        // prevent accidental loss of changes due to the pending git reset operation
    } catch (GitAPIException ex) {
        throw new MojoFailureException("Failed to execute git command: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoFailureException("Could not access source repository: " + ex.getMessage(), ex);
    }
}

From source file:org.codehaus.mojo.versions.BumpMojo.java

License:Apache License

public void init() throws MojoExecutionException {
    try {/*from   ww w. ja v  a 2 s  .  c  o m*/
        NetRCCredentialsProvider.install();

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.findGitDir().readEnvironment().findGitDir().build();
        git = new Git(repository);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.codice.git.GitHandler.java

License:Open Source License

public GitHandler(File basedir) throws IOException {
    super(basedir);
    this.repo = new FileRepositoryBuilder().findGitDir().readEnvironment().findGitDir().build();
}

From source file:org.codice.git.GitHandler.java

License:Open Source License

public GitHandler(File cwd, File basedir) throws IOException {
    super(basedir);
    this.repo = new FileRepositoryBuilder().findGitDir(cwd).readEnvironment().findGitDir().build();
}

From source file:org.commonjava.aprox.subsys.git.GitManager.java

License:Apache License

public GitManager(final GitConfig config) throws GitSubsystemException {
    this.config = config;
    rootDir = config.getContentDir();/*  w ww. j  a  v a2s  .c  o m*/
    final String cloneUrl = config.getCloneFrom();

    boolean checkUpdate = false;
    if (cloneUrl != null) {
        logger.info("Cloning: {} into: {}", cloneUrl, rootDir);
        if (rootDir.isDirectory()) {
            checkUpdate = true;
        } else {
            final boolean mkdirs = rootDir.mkdirs();
            logger.info("git dir {} (mkdir result: {}; is directory? {}) contains:\n  {}", rootDir, mkdirs,
                    rootDir.isDirectory(), join(rootDir.listFiles(), "\n  "));
            try {
                Git.cloneRepository().setURI(cloneUrl).setDirectory(rootDir).setRemote("origin").call();
            } catch (final GitAPIException e) {
                throw new GitSubsystemException("Failed to clone remote URL: {} into: {}. Reason: {}", e,
                        cloneUrl, rootDir, e.getMessage());
            }
        }
    }

    final File dotGitDir = new File(rootDir, ".git");

    logger.info("Setting up git manager for: {}", dotGitDir);
    try {
        repo = new FileRepositoryBuilder().readEnvironment().setGitDir(dotGitDir).build();
    } catch (final IOException e) {
        throw new GitSubsystemException("Failed to create Repository instance for: {}. Reason: {}", e,
                dotGitDir, e.getMessage());
    }

    String[] preExistingFromCreate = null;
    if (!dotGitDir.isDirectory()) {
        preExistingFromCreate = rootDir.list();

        try {
            repo.create();
        } catch (final IOException e) {
            throw new GitSubsystemException("Failed to create git repo: {}. Reason: {}", e, rootDir,
                    e.getMessage());
        }
    }

    String originUrl = repo.getConfig().getString("remote", "origin", "url");
    if (originUrl == null) {
        originUrl = cloneUrl;
        logger.info("Setting origin URL: {}", originUrl);

        repo.getConfig().setString("remote", "origin", "url", originUrl);

        repo.getConfig().setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    }

    String email = repo.getConfig().getString("user", null, "email");

    if (email == null) {
        email = config.getUserEmail();
    }

    if (email == null) {
        try {
            email = "aprox@" + InetAddress.getLocalHost().getCanonicalHostName();

        } catch (final UnknownHostException e) {
            throw new GitSubsystemException("Failed to resolve 'localhost'. Reason: {}", e, e.getMessage());
        }
    }

    if (repo.getConfig().getString("user", null, "email") == null) {
        repo.getConfig().setString("user", null, "email", email);
    }

    this.email = email;

    git = new Git(repo);

    if (preExistingFromCreate != null && preExistingFromCreate.length > 0) {
        addAndCommitPaths(new ChangeSummary(ChangeSummary.SYSTEM_USER, "Committing pre-existing files."),
                preExistingFromCreate);
    }

    if (checkUpdate) {
        pullUpdates();
    }
}