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

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

Introduction

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

Prototype

public CheckoutCommand checkout() 

Source Link

Document

Return a command object to execute a checkout command

Usage

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

/**   Creates new Git Support module */
public GitSupport(String login, String password, String repository, String projectPath, String tempFolder,
        String initBranch) {/*ww  w  . ja  v a  2  s.  c om*/

    final String home = System.getProperty("user.home");
    if (login == null || login.isEmpty()) {
        mSshConfigCallback = new SSHConfigCallback(home + Path.SEPARATOR + ".ssh" + Path.SEPARATOR + "id_rsa",
                new CredentialsProvider(password));
        mHttpsCredentialsProvider = null;
    } else {
        mSshConfigCallback = null;
        mHttpsCredentialsProvider = new UsernamePasswordCredentialsProvider(login, password);
    }

    try {
        final CloneCommand cloneCommand = Git.cloneRepository().setURI(repository)
                .setDirectory(new File(tempFolder));

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

        final Git mGit = cloneCommand.call();

        try {
            mGit.checkout().setCreateBranch(true).setName(initBranch).call();
        } catch (RefNotFoundException e) {
            e.printStackTrace();
            final StoredConfig config = mGit.getRepository().getConfig();
            config.setString("remote", "origin", "url", repository);
            config.save();
        }

        mGit.close();

        move(new File(tempFolder + "/.git"), new File(projectPath + "/.git"));
        move(new File(tempFolder + "/README.md"), new File(projectPath + "/README.md"));
        move(new File(tempFolder + "/LICENSE"), new File(projectPath + "/LICENSE"));
        move(new File(tempFolder + "/.gitignore"), new File(projectPath + "/.gitignore"));

        new File(tempFolder).delete();
        mProjectPath = projectPath;

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

}

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

License:Apache License

/**
 * Link and fetch from remote.//  w  w w  .ja  v a2 s  . c om
 *
 * @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:util.DifferenceComputer.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    ////* w  ww  . j  a  v  a  2 s  .  c om*/
    String coreRepoPath = "/Users/Onekin/Desktop/VODPlayer-CoreAssets-2";//args[0];
    String branchToLookInto = "develop.coreAssets";
    try {
        Git git = Git.open(new File(coreRepoPath));
        Repository repository = git.getRepository();
        Ref ref = repository.findRef(branchToLookInto);
        if (ref == null) {
            ref = git.checkout().setCreateBranch(true).setName(branchToLookInto)
                    .setUpstreamMode(SetupUpstreamMode.TRACK).setStartPoint("origin/" + branchToLookInto)
                    .call();
        }

        ObjectId parentCommit = repository
                .resolve(repository.findRef(branchToLookInto).getObjectId().getName() + "^^{commit}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String)
        ObjectId currentCommit = repository
                .resolve(repository.findRef(branchToLookInto).getObjectId().getName() + "^{commit}");

        List<DiffEntry> listOfChangedFiles = getChangedFilesBetweenTwoCommits(coreRepoPath, currentCommit,
                parentCommit);
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }

}

From source file:util.Util.java

public static void extractInformation(Git git, Project project) throws IOException, DatabaseException {

    DaoCommit daoCommit = new DaoCommit();

    List<RevCommit> revs = empilharRevs(git, project);
    RevCommit rev = revs.remove(0);//  www .  ja v  a  2s .co m

    Commit commit = new Commit();
    commit.setAuthor(rev.getAuthorIdent().getName());
    commit.setDate(rev.getAuthorIdent().getWhen());
    commit.setMessage(rev.getShortMessage());
    commit.setProject(project);
    commit.setSha(rev.getName());
    commit.setNumberFileErros(fileErros);
    fileErros = 0;

    List<File> files = getFilesInFolder(new File(project.getAbsolutePath()));

    commit.setNumberFileChanges(files.size());
    daoCommit.insert(commit);
    for (File file : files) {
        extractAllMetrics(file, commit);
    }
    int con = 0;
    while (!revs.isEmpty()) {
        rev = revs.remove(0);
        try {
            git.checkout().setName(rev.getName()).call();
            System.out.println("Checkout... " + con++);

            commit = new Commit();
            commit.setAuthor(rev.getAuthorIdent().getName());
            commit.setDate(rev.getAuthorIdent().getWhen());
            commit.setMessage(rev.getShortMessage());
            commit.setProject(project);
            commit.setSha(rev.getName());
            commit.setNumberFileErros(fileErros);
            fileErros = 0;
            files = listFilesChanges(git, rev, project);
            commit.setNumberFileChanges(files.size());

            daoCommit.insert(commit);
            for (File file : files) {
                extractAllMetrics(file, commit);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}