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

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

Introduction

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

Prototype

public CommitCommand commit() 

Source Link

Document

Return a command object to execute a Commit command

Usage

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

License:Open Source License

/**
 * Delete a tag in the local git repository
 * (git tag -d tagname) 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  . ja  v  a2 s  .  co  m
 * @param message   the commit message to be used    
 */
public static void deleteTag(@NonNull File directory, String tagName, String username, String password,
        String message) {
    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);
        DeleteTagCommand deleteTagCommand = git.tagDelete();
        deleteTagCommand.setTags(tagName);
        deleteTagCommand.call();
        log.info("Tag 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.access.UserStore.java

License:Open Source License

/**
 * Saves a user.//from w w  w  . j  av  a  2  s  . co m
 *
 * @param user the user to save
 * @param currentUser the user performing the save operation
 */
public void saveUser(User user, User currentUser) throws IOException {
    Assert.notNull(user);
    Assert.notNull(currentUser);

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("loginName", user.getLoginName()); //$NON-NLS-1$
        userMap.put("password", user.getPassword()); //$NON-NLS-1$
        userMap.put("email", user.getEmail()); //$NON-NLS-1$
        userMap.put("disabled", Boolean.valueOf(user.isDisabled())); //$NON-NLS-1$
        if (!user.getOpenIds().isEmpty()) {
            userMap.put("openIds", user.getOpenIds()); //$NON-NLS-1$
        }

        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(userMap);
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        File workingFile = new File(workingDir, user.getLoginName() + USER_SUFFIX);
        FileUtils.write(workingFile, json, Charsets.UTF_8);

        Git git = Git.wrap(repo.r());
        git.add().addFilepattern(user.getLoginName() + USER_SUFFIX).call();
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident).setMessage(user.getLoginName()).call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.access.UserStore.java

License:Open Source License

/**
 * Saves a role.//from  w w w .  j  a  v a2s  .  c o  m
 *
 * @param role the role to save
 * @param currentUser the user performing the save operation
 */
public void saveRole(Role role, User currentUser) throws IOException {
    Assert.notNull(role);
    Assert.notNull(currentUser);

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);

        Map<String, Object> roleMap = new HashMap<String, Object>();
        roleMap.put("name", role.getName()); //$NON-NLS-1$
        Set<String> permissions = Sets.newHashSet();
        for (Permission permission : role.getPermissions()) {
            permissions.add(permission.name());
        }
        roleMap.put("permissions", permissions); //$NON-NLS-1$

        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(roleMap);
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        File workingFile = new File(workingDir, role.getName() + ROLE_SUFFIX);
        FileUtils.write(workingFile, json, Charsets.UTF_8);

        Git git = Git.wrap(repo.r());
        git.add().addFilepattern(role.getName() + ROLE_SUFFIX).call();
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident).setMessage(role.getName()).call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.access.UserStore.java

License:Open Source License

private void saveUserAuthorities(String loginName, Set<RoleGrantedAuthority> authorities,
        ILockedRepository repo, User currentUser, boolean commit) throws IOException, GitAPIException {

    Map<String, Set<String>> authoritiesMap = new HashMap<String, Set<String>>();
    for (RoleGrantedAuthority rga : authorities) {
        GrantedAuthorityTarget target = rga.getTarget();
        String targetStr = target.getType().name() + ":" + target.getTargetId(); //$NON-NLS-1$
        Set<String> roleNames = authoritiesMap.get(targetStr);
        if (roleNames == null) {
            roleNames = Sets.newHashSet();
            authoritiesMap.put(targetStr, roleNames);
        }/*w w w  . j av  a 2 s . c o  m*/
        roleNames.add(rga.getRoleName());
    }

    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    String json = gson.toJson(authoritiesMap);
    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File workingFile = new File(workingDir, loginName + AUTHORITIES_SUFFIX);
    FileUtils.write(workingFile, json, Charsets.UTF_8);

    Git git = Git.wrap(repo.r());
    git.add().addFilepattern(loginName + AUTHORITIES_SUFFIX).call();
    if (commit) {
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident).setMessage(loginName).call();
    }
}

From source file:de.blizzy.documentr.access.UserStore.java

License:Open Source License

public void deleteUser(String loginName, User currentUser) throws IOException {
    Assert.hasLength(loginName);/*www  . j a va  2s  . c om*/
    Assert.notNull(currentUser);

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
        Git git = Git.wrap(repo.r());
        git.rm().addFilepattern(loginName + USER_SUFFIX).call();
        git.rm().addFilepattern(loginName + AUTHORITIES_SUFFIX).call();
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident).setMessage("delete user " + loginName) //$NON-NLS-1$
                .call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.access.UserStore.java

License:Open Source License

public void renameUser(String loginName, String newLoginName, User currentUser) throws IOException {
    Assert.hasLength(loginName);/*from  ww w.  j  a  va2  s  . c o m*/
    Assert.hasLength(newLoginName);
    Assert.notNull(currentUser);
    // check that user exists by trying to load it
    getUser(loginName);
    // check that new user does not exist by trying to load it
    try {
        getUser(newLoginName);
        throw new IllegalArgumentException("user already exists: " + newLoginName); //$NON-NLS-1$
    } catch (UserNotFoundException e) {
        // okay
    }

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);

        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        File file = new File(workingDir, loginName + USER_SUFFIX);
        File newFile = new File(workingDir, newLoginName + USER_SUFFIX);
        FileUtils.copyFile(file, newFile);
        file = new File(workingDir, loginName + AUTHORITIES_SUFFIX);
        newFile = new File(workingDir, newLoginName + AUTHORITIES_SUFFIX);
        FileUtils.copyFile(file, newFile);
        Git git = Git.wrap(repo.r());
        git.rm().addFilepattern(loginName + USER_SUFFIX).call();
        git.rm().addFilepattern(loginName + AUTHORITIES_SUFFIX).call();
        git.add().addFilepattern(newLoginName + USER_SUFFIX).call();
        git.add().addFilepattern(newLoginName + AUTHORITIES_SUFFIX).call();
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident)
                .setMessage("rename user " + loginName + " to " + newLoginName) //$NON-NLS-1$ //$NON-NLS-2$
                .call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.access.UserStore.java

License:Open Source License

public void renameRole(String roleName, String newRoleName, User currentUser) throws IOException {
    Assert.hasLength(roleName);//from   ww w  .  ja  v a2 s  .  c  o  m
    Assert.hasLength(newRoleName);
    Assert.notNull(currentUser);
    // check that role exists by trying to load it
    getRole(roleName);
    // check that new role does not exist by trying to load it
    try {
        getRole(newRoleName);
        throw new IllegalArgumentException("role already exists: " + newRoleName); //$NON-NLS-1$
    } catch (RoleNotFoundException e) {
        // okay
    }

    log.info("renaming role: {} -> {}", roleName, newRoleName); //$NON-NLS-1$

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);

        File workingDir = RepositoryUtil.getWorkingDir(repo.r());

        File file = new File(workingDir, roleName + ROLE_SUFFIX);
        File newFile = new File(workingDir, newRoleName + ROLE_SUFFIX);
        FileUtils.copyFile(file, newFile);
        Git git = Git.wrap(repo.r());
        git.rm().addFilepattern(roleName + ROLE_SUFFIX).call();
        git.add().addFilepattern(newRoleName + ROLE_SUFFIX).call();

        List<String> users = listUsers(repo);
        users.add(ANONYMOUS_USER_LOGIN_NAME);
        for (String user : users) {
            List<RoleGrantedAuthority> authorities = getUserAuthorities(user, repo);
            Set<RoleGrantedAuthority> newAuthorities = Sets.newHashSet();
            for (Iterator<RoleGrantedAuthority> iter = authorities.iterator(); iter.hasNext();) {
                RoleGrantedAuthority rga = iter.next();
                if (rga.getRoleName().equals(roleName)) {
                    RoleGrantedAuthority newRga = new RoleGrantedAuthority(rga.getTarget(), newRoleName);
                    newAuthorities.add(newRga);
                    iter.remove();
                }
            }
            if (!newAuthorities.isEmpty()) {
                authorities.addAll(newAuthorities);
                saveUserAuthorities(user, Sets.newHashSet(authorities), repo, currentUser, false);
            }
        }

        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident)
                .setMessage("rename role " + roleName + " to " + newRoleName) //$NON-NLS-1$ //$NON-NLS-2$
                .call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.access.UserStore.java

License:Open Source License

public void deleteRole(String roleName, User currentUser) throws IOException {
    Assert.hasLength(roleName);//from w  w  w. j ava 2  s  . co m
    Assert.notNull(currentUser);
    // check that role exists by trying to load it
    getRole(roleName);

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
        Git git = Git.wrap(repo.r());

        git.rm().addFilepattern(roleName + ROLE_SUFFIX).call();

        // remove role from all users
        List<String> users = listUsers(repo);
        users.add(ANONYMOUS_USER_LOGIN_NAME);
        for (String user : users) {
            List<RoleGrantedAuthority> authorities = getUserAuthorities(user, repo);
            boolean changed = false;
            for (Iterator<RoleGrantedAuthority> iter = authorities.iterator(); iter.hasNext();) {
                RoleGrantedAuthority rga = iter.next();
                if (rga.getRoleName().equals(roleName)) {
                    iter.remove();
                    changed = true;
                }
            }
            if (changed) {
                saveUserAuthorities(user, Sets.newHashSet(authorities), repo, currentUser, false);
            }
        }

        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident).setMessage("delete role " + roleName) //$NON-NLS-1$
                .call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

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

License:Open Source License

private CommitCherryPickResult tryResolveConflict(ILockedRepository repo, String branchName, String path,
        PageVersion pageVersion, String targetBranch, Set<CommitCherryPickConflictResolve> conflictResolves,
        User user, Locale locale) throws IOException, GitAPIException {

    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File pagesDir = new File(workingDir, DocumentrConstants.PAGES_DIR_NAME);
    File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.PAGE_SUFFIX);

    String resolveText = getCherryPickConflictResolveText(conflictResolves, targetBranch,
            pageVersion.getCommitName());
    CommitCherryPickResult result;//from w w w .  jav  a 2s . c o  m
    if (resolveText != null) {
        if (!CONFLICT_MARKERS_RE.matcher("\n" + resolveText).matches()) { //$NON-NLS-1$
            FileUtils.writeStringToFile(workingFile, resolveText, Charsets.UTF_8.name());
            Git git = Git.wrap(repo.r());
            git.add()
                    .addFilepattern(
                            DocumentrConstants.PAGES_DIR_NAME + "/" + path + DocumentrConstants.PAGE_SUFFIX) //$NON-NLS-1$
                    .call();
            PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
            git.commit().setAuthor(ident).setCommitter(ident)
                    .setMessage(DocumentrConstants.PAGES_DIR_NAME + "/" + path + DocumentrConstants.PAGE_SUFFIX) //$NON-NLS-1$
                    .call();
            result = new CommitCherryPickResult(pageVersion, CommitCherryPickResult.Status.OK);
        } else {
            result = new CommitCherryPickResult(pageVersion, resolveText);
        }
    } else {
        String text = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
        text = StringUtils.replace(text, "<<<<<<< OURS", //$NON-NLS-1$
                "<<<<<<< " + messageSource.getMessage("targetBranchX", new Object[] { targetBranch }, locale)); //$NON-NLS-1$ //$NON-NLS-2$
        text = StringUtils.replace(text, ">>>>>>> THEIRS", //$NON-NLS-1$
                ">>>>>>> " + messageSource.getMessage("sourceBranchX", new Object[] { branchName }, locale)); //$NON-NLS-1$ //$NON-NLS-2$
        result = new CommitCherryPickResult(pageVersion, text);
    }
    return result;
}

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;//ww w  .j  a v  a 2  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;
}