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

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

Introduction

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

Prototype

public DeleteBranchCommand branchDelete() 

Source Link

Document

Return a command object used to delete branches

Usage

From source file:br.com.metricminer2.scm.GitRepository.java

License:Apache License

private void deleteMMBranch(Git git)
        throws GitAPIException, NotMergedException, CannotDeleteCurrentBranchException {
    List<Ref> refs = git.branchList().call();
    for (Ref r : refs) {
        if (r.getName().endsWith("mm")) {
            git.branchDelete().setBranchNames("mm").setForce(true).call();
            break;
        }/*  w w  w .ja v a 2s . co  m*/
    }
}

From source file:br.com.metricminer2.scm.GitRepository.java

License:Apache License

public void reset() {
    Git git = null;
    try {/*from ww  w . j  a va2  s.  c  o  m*/
        git = Git.open(new File(path));

        git.checkout().setName("master").setForce(true).call();
        git.branchDelete().setBranchNames("mm").setForce(true).call();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (git != null)
            git.close();
    }

}

From source file:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

/**
 * Use with care!//  w w  w .  j  a v a 2 s . c  o  m
 */
public boolean deleteBranch() {
    if (!branch.startsWith("feature/")) {
        throw new GitException("Can only delete feature branch.");
    }
    try {

        final Git git = gitOpen();
        git.checkout().setCreateBranch(true).setName("feature/temp_" + UUID.randomUUID()).call();
        List<String> deletedBranches = git.branchDelete().setBranchNames(branch).setForce(true).call();
        if (deletedBranches.size() == 1) {
            // delete branch 'branchToDelete' on remote 'origin'
            RefSpec refSpec = new RefSpec().setSource(null).setDestination("refs/heads/" + branch);
            Iterable<PushResult> results = git.push().setCredentialsProvider(credentialsProvider())
                    .setRefSpecs(refSpec).setRemote("origin").call();
            for (PushResult result : results) {
                RemoteRefUpdate myUpdate = result.getRemoteUpdate("refs/heads/" + branch);
                if (myUpdate.isDelete() && myUpdate.getStatus() == RemoteRefUpdate.Status.OK) {
                    return true;
                }
            }
        }
        return false;
    } catch (IOException | GitAPIException e) {
        throw new GitException("Delete branch failed", e);
    }
}

From source file:com.door43.translationstudio.tasks.PullTargetTranslationTask.java

private void createBackupBranch(Repo repo) {
    try {//from  www.  j a  va2s. c  om
        Git git = repo.getGit();
        DeleteBranchCommand deleteBranchCommand = git.branchDelete();
        deleteBranchCommand.setBranchNames("backup-master").setForce(true).call();
        CreateBranchCommand createBranchCommand = git.branchCreate();
        createBranchCommand.setName("backup-master").setForce(true).call();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

private void testRefChange(AccessPermission permission, Status expectedCreate, Status expectedDelete,
        Status expectedRewind) throws Exception {

    final String originName = "ticgit.git";
    final String forkName = "refchecks/ticgit.git";
    final String workingCopy = "refchecks/ticgit-wc";

    // lower access restriction on origin repository
    RepositoryModel origin = repositories().getRepositoryModel(originName);
    origin.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(origin.name, origin, false);

    UserModel user = getUser();//from   www .  j  a  v  a  2 s  . com
    delete(user);

    CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password);

    // fork from original to a temporary bare repo
    File refChecks = new File(GitBlitSuite.REPOSITORIES, forkName);
    if (refChecks.exists()) {
        FileUtils.delete(refChecks, FileUtils.RECURSIVE);
    }
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(url + "/" + originName);
    clone.setDirectory(refChecks);
    clone.setBare(true);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    // elevate repository to clone permission
    RepositoryModel model = repositories().getRepositoryModel(forkName);
    switch (permission) {
    case VIEW:
        model.accessRestriction = AccessRestrictionType.CLONE;
        break;
    case CLONE:
        model.accessRestriction = AccessRestrictionType.CLONE;
        break;
    default:
        model.accessRestriction = AccessRestrictionType.PUSH;
    }
    model.authorizationControl = AuthorizationControl.NAMED;

    // grant user specified
    user.setRepositoryPermission(model.name, permission);

    gitblit().addUser(user);
    repositories().updateRepositoryModel(model.name, model, false);

    // clone temp bare repo to working copy
    File local = new File(GitBlitSuite.REPOSITORIES, workingCopy);
    if (local.exists()) {
        FileUtils.delete(local, FileUtils.RECURSIVE);
    }
    clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, model.name));
    clone.setDirectory(local);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);

    try {
        GitBlitSuite.close(clone.call());
    } catch (GitAPIException e) {
        if (permission.atLeast(AccessPermission.CLONE)) {
            throw e;
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            // user does not have clone permission
            assertTrue(e.getMessage(), e.getMessage().contains("not permitted"));
            return;
        }
    }

    Git git = Git.open(local);

    // commit a file and push it
    File file = new File(local, "PUSHCHK");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("push test").call();
    Iterable<PushResult> results = null;
    try {
        results = git.push().setCredentialsProvider(cp).setRemote("origin").call();
    } catch (GitAPIException e) {
        if (permission.atLeast(AccessPermission.PUSH)) {
            throw e;
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            // user does not have push permission
            assertTrue(e.getMessage(), e.getMessage().contains("not permitted"));
            GitBlitSuite.close(git);
            return;
        }
    }

    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (permission.atLeast(AccessPermission.PUSH)) {
            assertTrue("User failed to push commit?! " + status.name(), Status.OK.equals(status));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            assertTrue("User was able to push commit! " + status.name(),
                    Status.REJECTED_OTHER_REASON.equals(status));
            GitBlitSuite.close(git);
            // skip delete test
            return;
        }
    }

    // create a local branch and push the new branch back to the origin
    git.branchCreate().setName("protectme").call();
    RefSpec refSpec = new RefSpec("refs/heads/protectme:refs/heads/protectme");
    results = git.push().setCredentialsProvider(cp).setRefSpecs(refSpec).setRemote("origin").call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/protectme");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedCreate)) {
            assertTrue("User failed to push creation?! " + status.name(), status.equals(expectedCreate));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            assertTrue("User was able to push ref creation! " + status.name(), status.equals(expectedCreate));
            GitBlitSuite.close(git);
            // skip delete test
            return;
        }
    }

    // delete the branch locally
    git.branchDelete().setBranchNames("protectme").call();

    // push a delete ref command
    refSpec = new RefSpec(":refs/heads/protectme");
    results = git.push().setCredentialsProvider(cp).setRefSpecs(refSpec).setRemote("origin").call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/protectme");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedDelete)) {
            assertTrue("User failed to push ref deletion?! " + status.name(), status.equals(Status.OK));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            assertTrue("User was able to push ref deletion?! " + status.name(), status.equals(expectedDelete));
            GitBlitSuite.close(git);
            // skip rewind test
            return;
        }
    }

    // rewind master by two commits
    git.reset().setRef("HEAD~2").setMode(ResetType.HARD).call();

    // commit a change on this detached HEAD
    file = new File(local, "REWINDCHK");
    os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    RevCommit commit = git.commit().setMessage("rewind master and new commit").call();

    // Reset master to our new commit now we our local branch tip is no longer
    // upstream of the remote branch tip.  It is an alternate tip of the branch.
    JGitUtils.setBranchRef(git.getRepository(), "refs/heads/master", commit.getName());

    // Try pushing our new tip to the origin.
    // This requires the server to "rewind" it's master branch and update it
    // to point to our alternate tip.  This leaves the original master tip
    // unreferenced.
    results = git.push().setCredentialsProvider(cp).setRemote("origin").setForce(true).call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedRewind)) {
            assertTrue("User failed to rewind master?! " + status.name(), status.equals(expectedRewind));
        } else {
            assertTrue("User was able to rewind master?! " + status.name(), status.equals(expectedRewind));
        }
    }
    GitBlitSuite.close(git);

    // close serving repository
    GitBlitSuite.close(refChecks);

    delete(user);
}

From source file:com.hazelcast.utils.GitUtils.java

License:Open Source License

public static void cleanupBranch(String branchName, Git git) throws GitAPIException {
    git.checkout().setName("master").call();

    if (branchName != null) {
        git.branchDelete().setBranchNames(branchName).setForce(true).call();
    }/* ww w .j  a  v  a2s .  c om*/
}

From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

@Secured({ Role.User })
@Override//from   w  w w.  j a va2  s  .  c  o m
public void deleteBranch(String repoName, String branchName) throws EntityNotFoundException {
    try {
        Repository r = findRepositoryByName(repoName);
        Git git = Git.wrap(r);
        DeleteBranchCommand command = git.branchDelete();
        command.setBranchNames(branchName);
        command.setForce(true);
        command.call();
        r.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Delete a branch in the local git repository
 * (git branch -d branchname) and finally pushes new branch on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication/*from   w ww  .j  a  va  2 s  .co  m*/
 * @param message   the commit message to be used    
 */
public static void deleteBranch(@NonNull File directory, String branchName, String username, String password,
        String message) {

    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);

        DeleteBranchCommand deleteBranchCommand = git.branchDelete();

        deleteBranchCommand.setBranchNames(branchName);
        deleteBranchCommand.call();
        log.info("Develop branch deleted");

        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info(message);

        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");

    } catch (final GitAPIException | IOException e) {
        log.error(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;//w  w  w  .j av  a  2  s  .  c o  m
    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;/*from w ww. ja v a2  s . c  o m*/
    }

    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;
}