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

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

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Free resources associated with this instance.

Usage

From source file:ru.nikitenkogleb.androidtools.newappwizard.GitSupport.java

/**   Send changes to remote repository */
final void close(String userName, String userEmail, String initMessage) {
    if (!isSuccessful())
        return;/*from www . ja v  a2  s. c o m*/
    FileRepository mRepository = null;
    Git mGit = null;
    try {

        mRepository = new FileRepository(new File(mProjectPath, ".git"));
        mGit = new Git(mRepository);

        mGit.add().addFilepattern(".").call();
        mGit.commit().setAll(true).setAuthor(userName, userEmail).setCommitter(userName, userEmail)
                .setMessage(initMessage).call();
        final PushCommand pushCommand = mGit.push().setRemote("origin").setPushAll();

        if (mSshConfigCallback != null)
            pushCommand.setTransportConfigCallback(mSshConfigCallback);
        else
            pushCommand.setCredentialsProvider(mHttpsCredentialsProvider);

        pushCommand.call();
    } catch (GitAPIException | IOException e) {
        e.printStackTrace();
    }

    if (mGit != null)
        mGit.close();
    if (mRepository != null)
        mRepository.close();
}

From source file:se.kth.karamel.backend.github.GithubApi.java

/**
 * Clone an existing github repo.//from www . j a v a2  s. c  om
 *
 * @param owner
 * @param repoName
 * @throws se.kth.karamel.common.exception.KaramelException
 */
public synchronized static void cloneRepo(String owner, String repoName) throws KaramelException {
    Git result = null;
    try {
        RepositoryService rs = new RepositoryService(client);
        Repository r = rs.getRepository(owner, repoName);

        String cloneURL = r.getSshUrl();
        // prepare a new folder for the cloned repository
        File localPath = new File(Settings.COOKBOOKS_PATH + File.separator + repoName);
        if (localPath.isDirectory() == false) {
            localPath.mkdirs();
        } else {
            throw new KaramelException("Local directory already exists. Delete it first: " + localPath);
        }

        logger.debug("Cloning from " + cloneURL + " to " + localPath);
        result = Git.cloneRepository().setURI(cloneURL).setDirectory(localPath).call();
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        logger.debug("Cloned repository: " + result.getRepository().getDirectory());
    } catch (IOException | GitAPIException ex) {
        throw new KaramelException("Problem cloning repo: " + ex.getMessage());
    } finally {
        if (result != null) {
            result.close();
        }
    }

}

From source file:se.kth.karamel.backend.github.GithubApi.java

/**
 * Adds a file to the Github repo's index. If the file already exists, it will delete it and replace its contents with
 * the new contents. You wil subsequenty need to commit the change and push the commit to github.
 *
 * @param owner/*from w w w  . ja v a2  s  . com*/
 * @param repoName
 * @param fileName
 * @param contents
 * @throws KaramelException
 */
public synchronized static void addFile(String owner, String repoName, String fileName, String contents)
        throws KaramelException {
    File repoDir = getRepoDirectory(repoName);
    Git git = null;
    try {
        git = Git.open(repoDir);

        new File(repoDir + File.separator + fileName).delete();
        new File(repoDir + File.separator + fileName).getParentFile().mkdirs();
        try (PrintWriter out = new PrintWriter(repoDir + File.separator + fileName)) {
            out.println(contents);
        }
        git.add().addFilepattern(fileName).call();
    } catch (IOException | GitAPIException ex) {
        throw new KaramelException(ex.getMessage());
    } finally {
        if (git != null) {
            git.close();
        }

    }
}

From source file:se.kth.karamel.backend.github.GithubApi.java

public synchronized static void removeFile(String owner, String repoName, String fileName)
        throws KaramelException {
    File repoDir = getRepoDirectory(repoName);
    Git git = null;
    try {//from  ww  w . ja v  a  2s  .  c o  m
        git = Git.open(repoDir);
        new File(repoDir + File.separator + fileName).delete();
        git.add().addFilepattern(fileName).call();
        git.commit().setAuthor(user, email).setMessage("File removed by Karamel.").setAll(true).call();
        git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call();
        RepoItem toRemove = null;
        List<RepoItem> repos = cachedRepos.get(owner);
        for (RepoItem r : repos) {
            if (r.getName().compareToIgnoreCase(repoName) == 0) {
                toRemove = r;
            }
        }
        if (toRemove != null) {
            repos.remove(toRemove);
        }
    } catch (IOException | GitAPIException ex) {
        throw new KaramelException(ex.getMessage());
    } finally {
        if (git != null) {
            git.close();
        }
    }
}

From source file:se.kth.karamel.backend.github.GithubApi.java

/**
 * Scaffolds a Karamel/chef project for an experiment and adds it to the github repo. You still need to commit and
 * push the changes to github.//from  w w  w  .ja  va 2 s . c o m
 *
 * @param repoName
 * @throws KaramelException
 */
public static void scaffoldRepo(String repoName) throws KaramelException {
    File repoDir = getRepoDirectory(repoName);

    Git git = null;
    try {
        git = Git.open(repoDir);

        CookbookScaffolder.create(repoName);

        git.add().addFilepattern("Berksfile").addFilepattern("metadata.rb").addFilepattern("Karamelfile")
                .addFilepattern(".kitchen.yml").addFilepattern("attributes").addFilepattern("recipes")
                .addFilepattern("templates").addFilepattern("README.md").call();

    } catch (IOException | GitAPIException ex) {
        throw new KaramelException("Problem scaffolding a new Repository: " + ex.getMessage());
    } finally {
        if (git != null) {
            git.close();
        }
    }
}

From source file:se.kth.karamel.backend.github.GithubApi.java

/**
 * Synchronizes your updates on your local repository with github.
 *
 * @param owner//  w w  w . j  a  v a  2s  .  c o  m
 * @param repoName
 * @throws KaramelException
 */
public synchronized static void commitPush(String owner, String repoName) throws KaramelException {
    if (email == null || user == null) {
        throw new KaramelException("You forgot to call registerCredentials. You must call this method first.");
    }
    File repoDir = getRepoDirectory(repoName);
    Git git = null;
    try {
        git = Git.open(repoDir);

        git.commit().setAuthor(user, email).setMessage("Code generated by Karamel.").setAll(true).call();
        git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call();
    } catch (IOException | GitAPIException ex) {
        logger.error("error during github push", ex);
        throw new KaramelException(ex.getMessage());
    } finally {
        if (git != null) {
            git.close();
        }

    }
}

From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * Link and fetch from remote./*from  w w w . j  av  a2 s .  c o m*/
 *
 * @param remoteAddress the remote address
 * @param username the username
 * @param password the password
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws AuthenticationException the authentication exception
 * @see sh.isaac.api.sync.SyncFiles#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, char[] password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    LOG.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", this.localFolder,
            remoteAddress, username);

    Repository r = null;
    Git git = null;

    try {
        final File gitFolder = new File(this.localFolder, ".git");

        r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            LOG.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);
        git = new Git(r);

        final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                ((password == null) ? new char[] {} : password));

        LOG.debug("Fetching");

        final FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();

        LOG.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        final Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();

        for (final Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                LOG.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            // we need to fetch and (maybe) merge - get onto origin/master.
            LOG.debug("Fetching from remote");

            final String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();

            LOG.debug("Fetch Result: {}", fetchResult);
            LOG.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            // Get the files from master that we didn't have in our working folder
            LOG.debug("Checking out missing files from origin/master");

            for (final String missing : git.status().call().getMissing()) {
                LOG.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    LOG.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            // just push
            // make sure we have something to push
            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
            }

            git.commit().setMessage("Adding initial files").setAuthor(username, "42").call();
            LOG.debug("Pushing repository");

            for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                LOG.debug("Push Result: {}", pr.getMessages());
            }
        }

        LOG.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (final TransportException te) {
        if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) {
            LOG.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            LOG.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (final GitAPIException e) {
        LOG.error("Unexpected", e);
        throw new IOException("Internal error", e);
    } finally {
        if (git != null) {
            git.close();
        }

        if (r != null) {
            r.close();
        }
    }
}

From source file:to.sauerkraut.krautadmin.core.Toolkit.java

License:Open Source License

public static boolean updateFromGit(final File repositoryDirectory, final URI repositoryUri) throws Exception {
    final String unexpectedExceptionText = "incremental plugin-update from git failed";
    final String upstream = "refs/remotes/origin/master";
    boolean hasUpdated = false;
    Git gitRepo = null;

    try {/*ww  w . j  a va 2s  . c om*/
        gitRepo = Git.open(repositoryDirectory);
        // first reset local changes
        gitRepo.reset().setMode(ResetCommand.ResetType.HARD).call();
        LOG.info("starting incremental plugin-update from git...");
        gitRepo.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call();
        final RebaseResult rebaseResult = gitRepo.rebase().setStrategy(MergeStrategy.THEIRS)
                .setUpstream(upstream).setUpstreamName(upstream).call();
        final Status rebaseStatus = rebaseResult.getStatus();
        if (rebaseStatus.isSuccessful()) {
            if (!(Status.UP_TO_DATE.equals(rebaseStatus))) {
                hasUpdated = true;
            }
        } else {
            throw new WTFException(unexpectedExceptionText);
        }

        if (hasUpdated) {
            LOG.info("incremental plugin-update from git successful");
        } else {
            LOG.info("plugin-files are up-to-date");
        }
    } finally {
        try {
            if (gitRepo != null) {
                gitRepo.close();
            }
        } catch (Exception closex) {
            LOG.debug("closing git repo failed");
        }
    }

    return hasUpdated;
}

From source file:wherehows.common.utils.GitUtil.java

License:Open Source License

/**
 * Cloning the remote git repo to local directory
 * @param remoteUri remote git url e.g. git://gitli.example.com/project/repo.git
 * @param localDir local destination clone directory
 * @throws IOException/* w  w  w.j  a v  a2 s  . co  m*/
 * @throws GitAPIException
 */
public static void clone(String remoteUri, String localDir) throws IOException, GitAPIException {
    //create local git directory
    File localGitRepo = new File(localDir);
    if (localGitRepo.exists()) {
        if (localGitRepo.isDirectory()) {
            // clean up directory
            FileUtils.cleanDirectory(localGitRepo);
        } else {
            throw new IOException("File exists: " + localDir);
        }
    } else {
        localGitRepo.mkdirs();
    }

    Git g = Git.cloneRepository().setURI(remoteUri).setDirectory(localGitRepo).call();
    g.close();
}

From source file:wherehows.common.utils.GitUtil.java

License:Open Source License

/**
 * Fetch all commit metadata from the repo
 * @param repoDir repository directory// w ww.  j a  v  a 2s. c om
 * @return list of commit metadata
 * @throws IOException
 * @throws GitAPIException
 */
public static List<CommitMetadata> getRepoMetadata(String repoDir) throws IOException, GitAPIException {

    List<CommitMetadata> metadataList = new ArrayList<>();

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(repoDir, ".git")).readEnvironment().findGitDir().build();

    // Current branch may not be master. Instead of hard coding determine the current branch
    String currentBranch = repository.getBranch();
    Ref head = repository.getRef("refs/heads/" + currentBranch); // current branch may not be "master"
    if (head == null) {
        return metadataList;
    }

    Git git = new Git(repository);

    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(head.getObjectId());

    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.addTree(commit.getTree());
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
        String filePath = treeWalk.getPathString();
        Iterable<RevCommit> commitLog = git.log().add(repository.resolve(Constants.HEAD)).addPath(filePath)
                .call();
        for (RevCommit r : commitLog) {
            CommitMetadata metadata = new CommitMetadata(r.getName());
            metadata.setFilePath(filePath);
            metadata.setFileName(FilenameUtils.getName(filePath));
            metadata.setMessage(r.getShortMessage().trim());
            // Difference between committer and author
            // refer to: http://git-scm.com/book/ch2-3.html
            PersonIdent committer = r.getCommitterIdent();
            PersonIdent author = r.getAuthorIdent();
            metadata.setAuthor(author.getName());
            metadata.setAuthorEmail(author.getEmailAddress());
            metadata.setCommitter(committer.getName());
            metadata.setCommitterEmail(committer.getEmailAddress());
            metadata.setCommitTime(committer.getWhen());
            metadataList.add(metadata);
        }
    }
    git.close();
    return metadataList;
}