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

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

Introduction

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

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String deleteContent(String site, String path) {
    String commitId = null;//from   w  w w.ja  v a2 s.c o m

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        try (Git git = new Git(repo)) {
            git.rm().addFilepattern(helper.getGitPath(path)).setCached(false).call();

            // TODO: SJ: we need to define messages in a string table of sorts
            commitId = helper.commitFile(repo, site, path, "Delete file " + path, helper.getCurrentUserIdent());

            git.close();
        } catch (GitAPIException e) {
            logger.error("Error while deleting content for site: " + site + " path: " + path, e);
        }
    }

    return commitId;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String moveContent(String site, String fromPath, String toPath, String newName) {
    String commitId = null;/*from   w  ww .j a v  a  2s  .  c  o  m*/

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        String gitFromPath = helper.getGitPath(fromPath);
        String gitToPath = helper.getGitPath(toPath + newName);

        try (Git git = new Git(repo)) {
            // Check if destination is a file, then this is a rename operation
            // Perform rename and exit
            Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath);
            File sourceFile = sourcePath.toFile();
            Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath);
            File targetFile = targetPath.toFile();
            if (targetFile.isFile()) {
                if (sourceFile.isFile()) {
                    sourceFile.renameTo(targetFile);
                } else {
                    // This is not a valid operation
                    logger.error("Invalid move operation: Trying to rename a directory to a file for site: "
                            + site + " fromPath: " + fromPath + " toPath: " + toPath + " newName: " + newName);
                }
            } else if (sourceFile.isDirectory()) {
                // Check if we're moving a single file or whole subtree
                FileUtils.moveToDirectory(sourceFile, targetFile, true);
            }

            // The operation is done on disk, now it's time to commit
            git.add().addFilepattern(gitToPath).call();
            RevCommit commit = git.commit().setOnly(gitFromPath).setOnly(gitToPath)
                    .setAuthor(helper.getCurrentUserIdent()).setCommitter(helper.getCurrentUserIdent())
                    .setMessage("Moving " + fromPath + " to " + toPath + newName).call();
            commitId = commit.getName();

            git.close();
        } catch (IOException | GitAPIException e) {
            logger.error("Error while moving content for site: " + site + " fromPath: " + fromPath + " toPath: "
                    + toPath + " newName: " + newName);
        }
    }

    return commitId;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String copyContent(String site, String fromPath, String toPath) {
    String commitId = null;/*from  ww w.j ava  2  s  . co  m*/

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        String gitFromPath = helper.getGitPath(fromPath);
        String gitToPath = helper.getGitPath(toPath);

        try (Git git = new Git(repo)) {
            Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath);
            File sourceFile = sourcePath.toFile();
            Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath);
            File targetFile = targetPath.toFile();

            // Check if we're copying a single file or whole subtree
            FileUtils.copyDirectory(sourceFile, targetFile);

            // The operation is done on disk, now it's time to commit
            git.add().addFilepattern(gitToPath).call();
            RevCommit commit = git.commit().setOnly(gitFromPath).setOnly(gitToPath)
                    .setAuthor(helper.getCurrentUserIdent()).setCommitter(helper.getCurrentUserIdent())
                    .setMessage("Copying " + fromPath + " to " + toPath).call();
            commitId = commit.getName();

            git.close();
        } catch (IOException | GitAPIException e) {
            logger.error("Error while copying content for site: " + site + " fromPath: " + fromPath + " toPath:"
                    + " " + toPath + " newName: ");
        }
    }

    return commitId;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public VersionTO[] getContentVersionHistory(String site, String path) {
    List<VersionTO> versionHistory = new ArrayList<VersionTO>();

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        try {// ww  w.j a va  2 s  .c om
            ObjectId head = repo.resolve(Constants.HEAD);
            String gitPath = helper.getGitPath(path);
            try (Git git = new Git(repo)) {
                Iterable<RevCommit> commits = git.log().add(head).addPath(gitPath).call();
                Iterator<RevCommit> iterator = commits.iterator();
                while (iterator.hasNext()) {
                    RevCommit revCommit = iterator.next();
                    VersionTO versionTO = new VersionTO();
                    versionTO.setVersionNumber(revCommit.getName());
                    versionTO.setLastModifier(revCommit.getAuthorIdent().getName());
                    versionTO.setLastModifiedDate(new Date(revCommit.getCommitTime() * 1000));
                    versionTO.setComment(revCommit.getFullMessage());
                    versionHistory.add(versionTO);
                }

                git.close();
            } catch (IOException e) {
                logger.error("error while getting history for content item " + path);
            }
        } catch (IOException | GitAPIException e) {
            logger.error("Failed to create Git repo for site: " + site + " path: " + path, e);
        }
    }

    VersionTO[] toRet = new VersionTO[versionHistory.size()];
    return versionHistory.toArray(toRet);
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String createVersion(String site, String path, String comment, boolean majorVersion) {
    // SJ: Will ignore minor revisions since git handles that via write/commit
    // SJ: Major revisions become git tags
    // TODO: SJ: Redesign/refactor the whole approach in 3.1+
    String toReturn = StringUtils.EMPTY;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : PUBLISHED)) {
        if (majorVersion) {
            Repository repo = helper.getRepository(site,
                    StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.PUBLISHED);
            // Tag the repository with a date-time based version label
            String gitPath = helper.getGitPath(path);

            try (Git git = new Git(repo)) {
                PersonIdent currentUserIdent = helper.getCurrentUserIdent();
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                String versionLabel = dateFormat.format(cal);

                TagCommand tagCommand = git.tag().setName(versionLabel).setMessage(comment)
                        .setTagger(currentUserIdent);

                tagCommand.call();//  w w  w.  j  av  a  2s  . c o m

                toReturn = versionLabel;

                git.close();
            } catch (GitAPIException err) {
                logger.error("error creating new version for site:  " + site + " path: " + path, err);
            }
        } else {
            logger.info("request to create minor revision ignored for site: " + site + " path: " + path);
        }
    }

    return toReturn;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

/**
 * bootstrap the repository/*from  w  ww  .j  a v  a 2 s  .co m*/
 */
public void bootstrap() throws Exception {
    // Initialize the helper
    helper = new GitContentRepositoryHelper(studioConfiguration, securityProvider);

    if (Boolean.parseBoolean(studioConfiguration.getProperty(BOOTSTRAP_REPO))) {
        if (helper.createGlobalRepo()) {
            // Copy the global config defaults to the global site
            // Build a path to the bootstrap repo (the repo that ships with Studio)
            String bootstrapFolderPath = this.ctx.getRealPath(
                    File.separator + BOOTSTRAP_REPO_PATH + File.separator + BOOTSTRAP_REPO_GLOBAL_PATH);
            Path source = java.nio.file.FileSystems.getDefault().getPath(bootstrapFolderPath);

            logger.info("Bootstrapping with baseline @ " + source.toFile().toString());

            // Copy the bootstrap repo to the global repo
            Path globalConfigPath = helper.buildRepoPath(GitRepositories.GLOBAL);
            TreeCopier tc = new TreeCopier(source, globalConfigPath);
            EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            Files.walkFileTree(source, opts, Integer.MAX_VALUE, tc);

            Repository globalConfigRepo = helper.getRepository(StringUtils.EMPTY, GitRepositories.GLOBAL);
            try (Git git = new Git(globalConfigRepo)) {

                Status status = git.status().call();

                if (status.hasUncommittedChanges() || !status.isClean()) {
                    // Commit everything
                    // TODO: Consider what to do with the commitId in the future
                    git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call();
                    git.commit().setMessage(INITIAL_COMMIT).call();
                }

                git.close();
            } catch (GitAPIException err) {
                logger.error("error creating initial commit for global configuration", err);
            }
        }
    }

    // Create global repository object
    if (!helper.buildGlobalRepo()) {
        logger.error("Failed to create global repository!");
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public void publish(String site, List<String> commitIds, String environment, String author, String comment) {
    Repository repo = helper.getRepository(site, GitRepositories.PUBLISHED);

    synchronized (helper.getRepository(site, GitRepositories.PUBLISHED)) {
        try (Git git = new Git(repo)) {
            // fetch "origin/master"
            FetchResult fetchResult = git.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call();

            // checkout environment branch
            Ref checkoutResult = git.checkout().setCreateBranch(true).setName(environment).call();

            // cherry pick all commit ids
            CherryPickCommand cherryPickCommand = git.cherryPick().setStrategy(MergeStrategy.THEIRS);
            for (String commitId : commitIds) {
                ObjectId objectId = ObjectId.fromString(commitId);
                cherryPickCommand.include(objectId);
            }//from w  ww.jav  a  2  s .  co m
            CherryPickResult cherryPickResult = cherryPickCommand.call();

            // tag
            PersonIdent authorIdent = helper.getAuthorIdent(author);
            Ref tagResult = git.tag().setTagger(authorIdent).setMessage(comment).call();
        } catch (GitAPIException e) {
            logger.error("Error when publishing site " + site + " to environment " + environment, e);
        }
    }

}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public List<RepoOperationTO> getOperations(String site, String commitIdFrom, String commitIdTo) {
    List<RepoOperationTO> operations = new ArrayList<>();

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        try {/*w w w  . j  a  v a2  s.c om*/
            // Get the sandbox repo, and then get a reference to the commitId we received and another for head
            Repository repo = helper.getRepository(site, SANDBOX);
            ObjectId objCommitIdFrom = repo.resolve(commitIdFrom);
            ObjectId objCommitIdTo = repo.resolve(commitIdTo);

            // If the commitIdFrom is the same as commitIdTo, there is nothing to calculate, otherwise, let's do it
            if (!objCommitIdFrom.equals(objCommitIdTo)) {
                // Compare HEAD with commitId we're given
                // Get list of commits between commitId and HEAD in chronological order
                try (Git git = new Git(repo)) {
                    // Get the log of all the commits between commitId and head
                    Iterable<RevCommit> commits = git.log().addRange(objCommitIdFrom, objCommitIdTo).call();

                    // Loop through through the commits and diff one from the next util head
                    ObjectId prevCommitId = objCommitIdFrom;
                    ObjectId nextCommitId = objCommitIdFrom;

                    Iterator<RevCommit> iterator = commits.iterator();
                    while (iterator.hasNext()) {
                        RevCommit commit = iterator.next();
                        nextCommitId = commit.getId();

                        RevTree prevTree = helper.getTreeForCommit(repo, prevCommitId.getName());
                        RevTree nextTree = helper.getTreeForCommit(repo, nextCommitId.getName());

                        try (ObjectReader reader = repo.newObjectReader()) {
                            CanonicalTreeParser prevCommitTreeParser = new CanonicalTreeParser();
                            CanonicalTreeParser nextCommitTreeParser = new CanonicalTreeParser();
                            prevCommitTreeParser.reset(reader, prevTree.getId());
                            nextCommitTreeParser.reset(reader, nextTree.getId());

                            // Diff the two commit Ids
                            List<DiffEntry> diffEntries = git.diff().setOldTree(prevCommitTreeParser)
                                    .setNewTree(nextCommitTreeParser).call();

                            // Now that we have a diff, let's itemize the file changes, pack them into a TO
                            // and add them to the list of RepoOperations to return to the caller
                            // also include date/time of commit by taking number of seconds and multiply by 1000 and
                            // convert to java date before sending over
                            operations.addAll(
                                    processDiffEntry(diffEntries, new Date(commit.getCommitTime() * 1000)));
                            prevCommitId = nextCommitId;
                        }
                    }
                } catch (GitAPIException e) {
                    logger.error("Error getting operations for site " + site + " from commit ID: "
                            + commitIdFrom + " to commit ID: " + commitIdTo, e);
                }
            }
        } catch (IOException e) {
            logger.error("Error getting operations for site " + site + " from commit ID: " + commitIdFrom
                    + " to commit ID: " + commitIdTo, e);
        }
    }

    return operations;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

License:Open Source License

/**
 * Perform an initial commit after large changes to a site. Will not work against the global config repo.
 * @param site//from  ww  w. jav  a2s  . co m
 * @param message
 * @return true if successful, false otherwise
 */
public boolean performInitialCommit(String site, String message) {
    boolean toReturn = true;

    try {
        Repository repo = getRepository(site, GitRepositories.SANDBOX);

        Git git = new Git(repo);

        Status status = git.status().call();

        if (status.hasUncommittedChanges() || !status.isClean()) {
            DirCache dirCache = git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call();
            RevCommit commit = git.commit().setMessage(message).call();
            // TODO: SJ: Do we need the commit id?
            // commitId = commit.getName();
        }
    } catch (GitAPIException err) {
        logger.error("error creating initial commit for site:  " + site, err);
        toReturn = false;
    }

    return toReturn;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

License:Open Source License

public boolean writeFile(Repository repo, String site, String path, InputStream content) {
    boolean result;

    try {//ww w  . jav  a2 s.  c o  m
        // Create basic file
        File file = new File(repo.getDirectory().getParent(), path);

        // Create parent folders
        File folder = file.getParentFile();
        if (folder != null) {
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }

        // Create the file if it doesn't exist already
        if (!file.createNewFile()) {
            logger.error("error creating file: site: " + site + " path: " + path);
            result = false;
        } else {
            // Write the bits
            FileChannel outChannel = new FileOutputStream(file.getPath()).getChannel();
            logger.debug("created the file output channel");
            ReadableByteChannel inChannel = Channels.newChannel(content);
            logger.debug("created the file input channel");
            long amount = 1024 * 1024; // 1MB at a time
            long count;
            long offset = 0;
            while ((count = outChannel.transferFrom(inChannel, offset, amount)) > 0) {
                logger.debug("writing the bits: offset = " + offset + " count: " + count);
                offset += count;
            }

            // Add the file to git
            try (Git git = new Git(repo)) {
                git.add().addFilepattern(getGitPath(path)).call();

                git.close();
                result = true;
            } catch (GitAPIException e) {
                logger.error("error adding file to git: site: " + site + " path: " + path, e);
                result = false;
            }
        }
    } catch (IOException e) {
        logger.error("error writing file: site: " + site + " path: " + path, e);
        result = false;
    }

    return result;
}