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:com.microsoft.gittf.core.tasks.CloneTaskTest.java

License:Open Source License

@Test
public void testShallowCloneFilesAndFolders() throws Exception {
    URI projectCollectionURI = new URI("http://fakeCollection:8080/tfs/DefaultCollection"); //$NON-NLS-1$
    String tfsPath = "$/project"; //$NON-NLS-1$
    String gitRepositoryPath = Util.getRepositoryFile(getName()).getAbsolutePath();

    final MockVersionControlService mockVersionControlService = new MockVersionControlService();

    mockVersionControlService.AddFile("$/project/folder/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file0.txt", 1); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 2); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file2.txt", 3); //$NON-NLS-1$

    Calendar date = Calendar.getInstance();
    date.set(2012, 11, 12, 18, 15);/*from w  ww  . ja  va 2  s .  c o m*/

    MockChangesetProperties changesetProperties = new MockChangesetProperties("ownerDisplayName", //$NON-NLS-1$
            "ownerName", //$NON-NLS-1$
            "committerDisplayName", //$NON-NLS-1$
            "committerName", //$NON-NLS-1$
            "comment", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties, 3);

    final Repository repository = RepositoryUtil.createNewRepository(gitRepositoryPath, false);
    final boolean defaultDeep = repository.getConfig().getInt(ConfigurationConstants.CONFIGURATION_SECTION,
            ConfigurationConstants.GENERAL_SUBSECTION, ConfigurationConstants.DEPTH,
            GitTFConstants.GIT_TF_SHALLOW_DEPTH) > 1;

    CloneTask cloneTask = new CloneTask(projectCollectionURI, mockVersionControlService, tfsPath, repository);
    TaskStatus cloneTaskStatus = cloneTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(cloneTaskStatus.isOK());

    // Load Git Repo
    Git git = new Git(repository);
    git.checkout().setName("master").call(); //$NON-NLS-1$

    // Verify Changeset 1
    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder/file0.txt"), //$NON-NLS-1$
            "$/project/folder/file0.txt", //$NON-NLS-1$
            1));

    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder2/file0.txt"), //$NON-NLS-1$
            "$/project/folder2/file0.txt", //$NON-NLS-1$
            1));

    assertTrue(mockVersionControlService.verifyFileContent(
            new File(gitRepositoryPath, "folder/nestedFolder/file0.txt"), //$NON-NLS-1$
            "$/project/folder/nestedFolder/file0.txt", //$NON-NLS-1$
            1));

    // Verify Changeset 2
    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder/file1.txt"), //$NON-NLS-1$
            "$/project/folder/file1.txt", //$NON-NLS-1$
            2));

    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder2/file1.txt"), //$NON-NLS-1$
            "$/project/folder2/file1.txt", //$NON-NLS-1$
            2));

    assertTrue(mockVersionControlService.verifyFileContent(
            new File(gitRepositoryPath, "folder/nestedFolder/file1.txt"), //$NON-NLS-1$
            "$/project/folder/nestedFolder/file1.txt", //$NON-NLS-1$
            2));

    // Verify Changeset 3
    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder/file2.txt"), //$NON-NLS-1$
            "$/project/folder/file2.txt", //$NON-NLS-1$
            3));

    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder2/file2.txt"), //$NON-NLS-1$
            "$/project/folder2/file2.txt", //$NON-NLS-1$
            3));

    assertTrue(mockVersionControlService.verifyFileContent(
            new File(gitRepositoryPath, "folder/nestedFolder/file2.txt"), //$NON-NLS-1$
            "$/project/folder/nestedFolder/file2.txt", //$NON-NLS-1$
            3));

    // Verify Git Repo configuration
    GitTFConfiguration gitRepoServerConfig = GitTFConfiguration.loadFrom(repository);

    assertEquals(gitRepoServerConfig.getServerURI(), projectCollectionURI);
    assertEquals(gitRepoServerConfig.getServerPath(), tfsPath);
    assertEquals(gitRepoServerConfig.getDeep(), defaultDeep);

    // Verify the number of commits
    Iterable<RevCommit> commits = git.log().call();

    assertNotNull(commits);

    int commitCounter = 0;
    for (RevCommit commit : commits) {
        assertEquals(commit.getFullMessage(), "comment"); //$NON-NLS-1$

        PersonIdent ownwer = commit.getAuthorIdent();
        assertEquals(ownwer.getEmailAddress(), "ownerName"); //$NON-NLS-1$
        assertEquals(ownwer.getName(), "ownerDisplayName"); //$NON-NLS-1$

        PersonIdent committer = commit.getCommitterIdent();
        assertEquals(committer.getEmailAddress(), "committerName"); //$NON-NLS-1$
        assertEquals(committer.getName(), "committerDisplayName"); //$NON-NLS-1$

        commitCounter++;
    }

    assertEquals(commitCounter, 1);

    // Verify the tags
    List<Ref> tags = git.tagList().call();
    assertEquals(1, tags.size());
}

From source file:com.microsoft.gittf.core.tasks.CloneTaskTest.java

License:Open Source License

@Test
public void testDeepCloneFilesAndFoldersSimple() throws Exception {
    URI projectCollectionURI = new URI("http://fakeCollection:8080/tfs/DefaultCollection"); //$NON-NLS-1$
    String tfsPath = "$/project"; //$NON-NLS-1$
    String gitRepositoryPath = Util.getRepositoryFile(getName()).getAbsolutePath();

    final MockVersionControlService mockVersionControlService = new MockVersionControlService();

    mockVersionControlService.AddFile("$/project/folder/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file0.txt", 1); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 2); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file2.txt", 3); //$NON-NLS-1$

    Calendar date = Calendar.getInstance();
    date.set(2012, 11, 12, 18, 15);/*w  w  w  .java2  s .  co m*/

    MockChangesetProperties changesetProperties = new MockChangesetProperties("ownerDisplayName1", //$NON-NLS-1$
            "ownerName1", //$NON-NLS-1$
            "committerDisplayName1", //$NON-NLS-1$
            "committerName1", //$NON-NLS-1$
            "comment1", //$NON-NLS-1$
            date);

    mockVersionControlService.updateChangesetInformation(changesetProperties, 1);

    changesetProperties = new MockChangesetProperties("ownerDisplayName2", //$NON-NLS-1$
            "ownerName2", //$NON-NLS-1$
            "committerDisplayName2", //$NON-NLS-1$
            "committerName2", //$NON-NLS-1$
            "comment2", //$NON-NLS-1$
            date);

    mockVersionControlService.updateChangesetInformation(changesetProperties, 2);

    changesetProperties = new MockChangesetProperties("ownerDisplayName3", //$NON-NLS-1$
            "ownerName3", //$NON-NLS-1$
            "committerDisplayName3", //$NON-NLS-1$
            "committerName3", //$NON-NLS-1$
            "comment3", //$NON-NLS-1$
            date);

    mockVersionControlService.updateChangesetInformation(changesetProperties, 3);

    final Repository repository = RepositoryUtil.createNewRepository(gitRepositoryPath, false);
    final boolean defaultDeep = repository.getConfig().getInt(ConfigurationConstants.CONFIGURATION_SECTION,
            ConfigurationConstants.GENERAL_SUBSECTION, ConfigurationConstants.DEPTH,
            GitTFConstants.GIT_TF_SHALLOW_DEPTH) > 1;

    CloneTask cloneTask = new CloneTask(projectCollectionURI, mockVersionControlService, tfsPath, repository);
    cloneTask.setDepth(10);

    TaskStatus cloneTaskStatus = cloneTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(cloneTaskStatus.isOK());

    // Load Git Repo
    Git git = new Git(repository);
    git.checkout().setName("master").call(); //$NON-NLS-1$

    // Verify Changeset 1
    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder/file0.txt"), //$NON-NLS-1$
            "$/project/folder/file0.txt", //$NON-NLS-1$
            1));

    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder2/file0.txt"), //$NON-NLS-1$
            "$/project/folder2/file0.txt", //$NON-NLS-1$
            1));

    assertTrue(mockVersionControlService.verifyFileContent(
            new File(gitRepositoryPath, "folder/nestedFolder/file0.txt"), //$NON-NLS-1$
            "$/project/folder/nestedFolder/file0.txt", //$NON-NLS-1$
            1));

    // Verify Changeset 2
    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder/file1.txt"), //$NON-NLS-1$
            "$/project/folder/file1.txt", //$NON-NLS-1$
            2));

    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder2/file1.txt"), //$NON-NLS-1$
            "$/project/folder2/file1.txt", //$NON-NLS-1$
            2));

    assertTrue(mockVersionControlService.verifyFileContent(
            new File(gitRepositoryPath, "folder/nestedFolder/file1.txt"), //$NON-NLS-1$
            "$/project/folder/nestedFolder/file1.txt", //$NON-NLS-1$
            2));

    // Verify Changeset 3
    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder/file2.txt"), //$NON-NLS-1$
            "$/project/folder/file2.txt", //$NON-NLS-1$
            3));

    assertTrue(mockVersionControlService.verifyFileContent(new File(gitRepositoryPath, "folder2/file2.txt"), //$NON-NLS-1$
            "$/project/folder2/file2.txt", //$NON-NLS-1$
            3));

    assertTrue(mockVersionControlService.verifyFileContent(
            new File(gitRepositoryPath, "folder/nestedFolder/file2.txt"), //$NON-NLS-1$
            "$/project/folder/nestedFolder/file2.txt", //$NON-NLS-1$
            3));

    // Verify Git Repo configuration
    GitTFConfiguration gitRepoServerConfig = GitTFConfiguration.loadFrom(repository);

    assertEquals(gitRepoServerConfig.getServerURI(), projectCollectionURI);
    assertEquals(gitRepoServerConfig.getServerPath(), tfsPath);
    assertEquals(gitRepoServerConfig.getDeep(), defaultDeep);

    // Verify the number of commits
    Iterable<RevCommit> commits = git.log().call();

    assertNotNull(commits);

    int commitCounter = 3;
    for (RevCommit commit : commits) {
        assertEquals(commit.getFullMessage(), "comment" + Integer.toString(commitCounter)); //$NON-NLS-1$

        PersonIdent ownwer = commit.getAuthorIdent();
        assertEquals(ownwer.getEmailAddress(), "ownerName" + Integer.toString(commitCounter)); //$NON-NLS-1$
        assertEquals(ownwer.getName(), "ownerDisplayName" + Integer.toString(commitCounter)); //$NON-NLS-1$

        PersonIdent committer = commit.getCommitterIdent();
        assertEquals(committer.getEmailAddress(), "committerName" + Integer.toString(commitCounter)); //$NON-NLS-1$
        assertEquals(committer.getName(), "committerDisplayName" + Integer.toString(commitCounter)); //$NON-NLS-1$

        commitCounter--;
    }

    assertEquals(commitCounter, 0);

    // Verify the tags
    List<Ref> tags = git.tagList().call();
    assertEquals(3, tags.size());
}

From source file:com.mortardata.git.GitUtil.java

License:Apache License

/**
 * Checkout a branch, tracking remote branch if it exists.
 *  //  w  w w .j a v  a  2s  .  c  o m
 * @param git Git repository
 * @param branch Name of branch to checkout
 * @throws GitAPIException if error running git command
 */
public void checkout(Git git, String branch) throws GitAPIException {
    List<Ref> branches = getBranches(git);

    CheckoutCommand checkout = git.checkout().setName(branch);

    String localBranchRefName = "refs/heads/" + branch;
    String remoteBranchName = "origin/" + branch;
    String remoteBranchRefName = "refs/remotes/" + remoteBranchName;
    if (containsRef(branches, localBranchRefName)) {
        logger.debug("git checkout " + branch);
        // local branch exists: no create branch
        checkout.setCreateBranch(false);
    } else if (containsRef(branches, remoteBranchRefName)) {
        logger.debug("git checkout --set-upstream -b " + branch + " " + remoteBranchName);
        // remote branch exists: track existing branch
        checkout.setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
                .setStartPoint(remoteBranchName);
    } else {
        // no remote branch exists: create a new branch, no tracking
        logger.debug("git checkout -b " + branch);
        checkout.setCreateBranch(true);
    }

    checkout.call();
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Checkout specific branch or tag.// w  w  w  .  ja va  2  s.c o  m
 * 
 * @param localPath
 * @param name
 * @throws GitError
 */
public static void checkout(String localPath, String name) throws GitError {
    try {
        Git git = Git.open(new File(localPath));
        CheckoutCommand co = git.checkout();
        co.setName(name);
        co.call();
    } catch (Exception e) {
        GittApp.saveErrorTrace(e);
        throw new GitError();
    }
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

License:Open Source License

public static LocalRepoBean createTestRepoMultipleBranches() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();/*w ww  .ja  va2 s .  co m*/
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);

    final Git git = new Git(repo);

    // add some files to some branches
    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("branch1").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch1" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();
    git.checkout().setName("branch2").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch2" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    repo.close();
    return repoBean;
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

License:Open Source License

public static LocalRepoBean createTestRepo() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();//from   w  w  w. j  a  v a  2 s.c  o  m
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);
    repoBean.setSourcePartner("partner");

    final Git git = new Git(repo);

    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();

    repo.close();
    return repoBean;
}

From source file:com.tenxdev.ovcs.command.InitCommand.java

License:Open Source License

private void initGitRepo(final Path workingDir, final String remoteUri, final String connectionString)
        throws OvcsException {
    try {//from   ww w . ja  v a2s.  c o m
        System.out.println("Cloning git repo");
        Git.cloneRepository().setDirectory(workingDir.toFile()).setCloneAllBranches(true).setRemote("origin")
                .setURI(remoteUri).setProgressMonitor(new TextProgressMonitor()).call();
        final Git git = Git.open(workingDir.toFile());
        final StoredConfig config = git.getRepository().getConfig();
        config.setString("database", null, "connectionString", connectionString);
        config.save();
        git.checkout().setName("master").setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    } catch (GitAPIException | IOException e) {
        throw new OvcsException("Unable to initialize Git repo: " + e.getMessage(), e);
    }
}

From source file:de.blizzy.documentr.page.CherryPicker.java

License:Open Source License

private List<CommitCherryPickResult> cherryPick(String projectName, String branchName, String path,
        List<String> commits, String targetBranch, Set<CommitCherryPickConflictResolve> conflictResolves,
        boolean dryRun, User user, Locale locale) throws IOException, GitAPIException {

    ILockedRepository repo = null;/*from w w w . ja v a 2s  . c om*/
    List<CommitCherryPickResult> cherryPickResults = Lists.newArrayList();
    boolean hadConflicts = false;
    boolean failed = false;
    try {
        repo = globalRepositoryManager.getProjectBranchRepository(projectName, targetBranch);

        String tempBranchName = "_temp_" + String.valueOf((long) (Math.random() * Long.MAX_VALUE)); //$NON-NLS-1$
        Git git = Git.wrap(repo.r());

        git.branchCreate().setName(tempBranchName).setStartPoint(targetBranch).call();

        git.checkout().setName(tempBranchName).call();

        for (String commit : commits) {
            PageVersion pageVersion = PageUtil.toPageVersion(CommitUtils.getCommit(repo.r(), commit));
            if (!hadConflicts) {
                CommitCherryPickResult singleCherryPickResult = cherryPick(repo, branchName, path, pageVersion,
                        targetBranch, conflictResolves, user, locale);
                if (singleCherryPickResult != null) {
                    cherryPickResults.add(singleCherryPickResult);
                    if (singleCherryPickResult.getStatus() == CommitCherryPickResult.Status.CONFLICT) {
                        hadConflicts = true;
                    }
                } else {
                    failed = true;
                    break;
                }
            } else {
                cherryPickResults
                        .add(new CommitCherryPickResult(pageVersion, CommitCherryPickResult.Status.UNKNOWN));
            }
        }

        if (hadConflicts || failed) {
            git.reset().setMode(ResetCommand.ResetType.HARD).call();
        }

        git.checkout().setName(targetBranch).call();

        if (!dryRun && !hadConflicts && !failed) {
            git.merge().include(repo.r().resolve(tempBranchName)).call();
        }

        git.branchDelete().setBranchNames(tempBranchName).setForce(true).call();

        if (failed) {
            throw new IOException("cherry-picking failed"); //$NON-NLS-1$
        }
    } finally {
        Closeables.closeQuietly(repo);
    }

    if (!dryRun && !hadConflicts && !failed) {
        eventBus.post(new PageChangedEvent(projectName, targetBranch, path));
    }

    return cherryPickResults;
}

From source file:de.blizzy.documentr.page.PageStore.java

License:Open Source License

private MergeConflict savePageInternal(String projectName, String branchName, String path, String suffix,
        Page page, String baseCommit, String rootDir, User user, ILockedRepository repo, boolean push)
        throws IOException, GitAPIException {

    Git git = Git.wrap(repo.r());

    String headCommit = CommitUtils.getHead(repo.r()).getName();
    if ((baseCommit != null) && headCommit.equals(baseCommit)) {
        baseCommit = null;//  w w  w.ja v  a2 s.c om
    }

    String editBranchName = "_edit_" + String.valueOf((long) (Math.random() * Long.MAX_VALUE)); //$NON-NLS-1$
    if (baseCommit != null) {
        git.branchCreate().setName(editBranchName).setStartPoint(baseCommit).call();

        git.checkout().setName(editBranchName).call();
    }

    Map<String, Object> metaMap = new HashMap<String, Object>();
    metaMap.put(TITLE, page.getTitle());
    metaMap.put(CONTENT_TYPE, page.getContentType());
    if (!page.getTags().isEmpty()) {
        metaMap.put(TAGS, page.getTags());
    }
    metaMap.put(VIEW_RESTRICTION_ROLE, page.getViewRestrictionRole());
    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    String json = gson.toJson(metaMap);
    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File pagesDir = new File(workingDir, rootDir);
    File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.META_SUFFIX);
    FileUtils.write(workingFile, json, Charsets.UTF_8);

    PageData pageData = page.getData();
    if (pageData != null) {
        workingFile = Util.toFile(pagesDir, path + suffix);
        FileUtils.writeByteArrayToFile(workingFile, pageData.getData());
    }

    AddCommand addCommand = git.add().addFilepattern(rootDir + "/" + path + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$
    if (pageData != null) {
        addCommand.addFilepattern(rootDir + "/" + path + suffix); //$NON-NLS-1$
    }
    addCommand.call();

    PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
    git.commit().setAuthor(ident).setCommitter(ident).setMessage(rootDir + "/" + path + suffix).call(); //$NON-NLS-1$

    MergeConflict conflict = null;

    if (baseCommit != null) {
        git.rebase().setUpstream(branchName).call();

        if (repo.r().getRepositoryState() != RepositoryState.SAFE) {
            String text = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
            conflict = new MergeConflict(text, headCommit);

            git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
        }

        git.checkout().setName(branchName).call();

        if (conflict == null) {
            git.merge().include(repo.r().resolve(editBranchName)).call();
        }

        git.branchDelete().setBranchNames(editBranchName).setForce(true).call();
    }

    if (push && (conflict == null)) {
        git.push().call();
    }

    page.setParentPagePath(getParentPagePath(path, repo.r()));

    if (conflict == null) {
        PageUtil.updateProjectEditTime(projectName);
    }

    return conflict;
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

ILockedRepository createBranchRepository(String branchName, String startingBranch)
        throws IOException, GitAPIException {
    Assert.hasLength(branchName);/*from   w  w w. j a v a 2s.  c  o m*/
    if (startingBranch != null) {
        Assert.hasLength(startingBranch);
    }

    File repoDir = new File(reposDir, branchName);
    if (repoDir.isDirectory()) {
        throw new IllegalStateException("repository already exists: " + repoDir.getAbsolutePath()); //$NON-NLS-1$
    }

    List<String> branches = listBranches();
    if (branches.contains(branchName)) {
        throw new IllegalArgumentException("branch already exists: " + branchName); //$NON-NLS-1$
    }

    if ((startingBranch == null) && !branches.isEmpty()) {
        throw new IllegalArgumentException("must specify a starting branch"); //$NON-NLS-1$
    }

    ILock lock = lockManager.lockAll();
    try {
        Repository centralRepo = null;
        File centralRepoGitDir;
        try {
            centralRepo = getCentralRepositoryInternal(true);
            centralRepoGitDir = centralRepo.getDirectory();
        } finally {
            RepositoryUtil.closeQuietly(centralRepo);
            centralRepo = null;
        }

        Repository repo = null;
        try {
            repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString()).setDirectory(repoDir)
                    .call().getRepository();

            try {
                centralRepo = getCentralRepositoryInternal(true);
                if (!RepositoryUtils.getBranches(centralRepo).contains(branchName)) {
                    CreateBranchCommand createBranchCommand = Git.wrap(centralRepo).branchCreate();
                    if (startingBranch != null) {
                        createBranchCommand.setStartPoint(startingBranch);
                    }
                    createBranchCommand.setName(branchName).call();
                }
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            Git git = Git.wrap(repo);
            RefSpec refSpec = new RefSpec("refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
            git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
            git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
            git.checkout().setName(branchName).call();
        } finally {
            RepositoryUtil.closeQuietly(repo);
        }
    } finally {
        lockManager.unlock(lock);
    }

    return getBranchRepository(branchName);
}