Example usage for org.eclipse.jgit.api Git Git

List of usage examples for org.eclipse.jgit.api Git Git

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git Git.

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

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();/*from  w  ww . ja v a  2s  .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();
    }
}

From source file:org.commonjava.gitwrap.BareGitRepository.java

License:Open Source License

protected BareGitRepository(final File gitDir, final boolean create, final File workDir) throws IOException {
    this.gitDir = gitDir;
    this.workDir = workDir;

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.setGitDir(gitDir);/*from w  ww  .j a  v a2  s . c  o m*/
    if (workDir != null) {
        builder.setWorkTree(workDir);
    }

    builder.setup();

    repository = new FileRepository(builder);

    if (create && !gitDir.exists()) {
        final File objectsDir = new File(gitDir, "objects");
        final File refsDir = new File(gitDir, "refs");

        refsDir.mkdirs();
        objectsDir.mkdirs();

        repository.create(workDir == null);
        final FileBasedConfig config = repository.getConfig();

        config.setInt("core", null, "repositoryformatversion", 0);
        config.setBoolean("core", null, "filemode", true);
        config.setBoolean("core", null, "bare", workDir == null);
        config.setBoolean("core", null, "logallrefupdates", true);
        config.setBoolean("core", null, "ignorecase", true);

        config.save();
    }

    git = new Git(repository);
}

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

License:Apache License

public GitManager(final GitConfig config) throws GitSubsystemException {
    this.config = config;
    rootDir = config.getContentDir();/*from   ww w  .j  av  a 2  s. co  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 = "indy@" + 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) {
        addPaths(new ChangeSummary(SYSTEM_USER, "Committing pre-existing files."), preExistingFromCreate);
        commit();
    }

    if (checkUpdate) {
        pullUpdates();
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;//w  ww  .  j av a 2 s  .  c o  m
    try {
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void pushChanges(Repository repository) {
    Git git = new Git(repository);
    try {/*w w w. j a va2 s .c o  m*/
        git.add().addFilepattern(".").call();
        git.commit().setMessage("deployment to environment store").call();
        git.push().call();
    } catch (GitAPIException e) {
        logger.error("Error while pushing workflow changes.", e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private boolean createEnvironmentStoreRepository(String site) {
    boolean success = true;
    Path siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment);
    try {//from w w  w  .j  a  v a2  s.  com
        Files.deleteIfExists(siteEnvironmentStoreRepoPath);
        siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment, ".git");
        Repository repository = FileRepositoryBuilder.create(siteEnvironmentStoreRepoPath.toFile());
        repository.create();

        Git git = new Git(repository);
        git.add().addFilepattern(".").call();
        RevCommit commit = git.commit().setMessage("initial content").setAllowEmpty(true).call();
    } catch (IOException | GitAPIException e) {
        logger.error("Error while creating repository for site " + site, e);
        success = false;
    }
    return success;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void addWorkAreaRemote(String site, Repository envStoreRepo) {
    envStoreRepo.getRemoteName("work-area");
    Git git = new Git(envStoreRepo);
    StoredConfig config = git.getRepository().getConfig();
    Path siteRepoPath = Paths.get(rootPath, "sites", site, ".git");
    config.setString("remote", "work-area", "url", siteRepoPath.normalize().toAbsolutePath().toString());
    try {//from   www  .j  a  v  a 2s.c o m
        config.save();
    } catch (IOException e) {
        logger.error("Error adding work area as remote for environment store.", e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

@Override
public void deleteFile(String site, String path) {
    try {/*www.  ja v  a  2s.  c  o  m*/
        Repository repo = getEnvironmentStoreRepositoryInstance(site);
        Git git = new Git(repo);
        git.rm().addFilepattern(getGitPath(path)).setCached(false).call();

        RevCommit commit = git.commit().setOnly(getGitPath(path)).setMessage(StringUtils.EMPTY).call();
    } catch (GitAPIException | IOException | JGitInternalException e) {
        logger.error("Error while deleting content from environment store for site: " + site + " path: " + path
                + " environment: " + environment, e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitDeployer.java

License:Open Source License

@Override
public void deployFile(String site, String path) {
    try (Repository envStoreRepo = getEnvironmentStoreRepositoryInstance(site)) {
        fetchFromRemote(site, envStoreRepo);
        createPatch(envStoreRepo, site, path);
        Git git = new Git(envStoreRepo);
        applyPatch(envStoreRepo, site);/*from  ww w  .  j  ava2s . c om*/
        git.add().addFilepattern(".").call();
        git.commit().setMessage("deployment").call();

    } catch (IOException | GitAPIException e) {
        logger.error("Error while deploying file for site: " + site + " path: " + path, e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String createFolder(String site, String path, String name) {
    // SJ: Git doesn't care about empty folders, so we will create the folders and put a 0 byte file in them
    String commitId = null;/*from   www . jav a 2s.c o  m*/
    boolean result;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Path emptyFilePath = Paths.get(path, name, EMPTY_FILE);
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        try {
            // Create basic file
            File file = new File(repo.getDirectory().getParent(), emptyFilePath.toString());

            // Create parent folders
            File folder = file.getParentFile();
            if (folder != null) {
                if (!folder.exists()) {
                    folder.mkdirs();
                }
            }

            // Create the file
            if (!file.createNewFile()) {
                logger.error("error writing file: site: " + site + " path: " + emptyFilePath);
                result = false;
            } else {
                // Add the file to git
                try (Git git = new Git(repo)) {
                    git.add().addFilepattern(helper.getGitPath(emptyFilePath.toString())).call();

                    git.close();
                    result = true;
                } catch (GitAPIException e) {
                    logger.error("error adding file to git: site: " + site + " path: " + emptyFilePath, e);
                    result = false;
                }
            }
        } catch (IOException e) {
            logger.error("error writing file: site: " + site + " path: " + emptyFilePath, e);
            result = false;
        }

        if (result) {
            commitId = helper.commitFile(repo, site, emptyFilePath.toString(),
                    "Created folder site: " + site + " " + "path: " + path, helper.getCurrentUserIdent());
        }
    }

    return commitId;
}