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

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

Introduction

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

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:org.apache.maven.scm.provider.git.jgit.command.diff.JGitDiffCommand.java

License:Apache License

@Override
protected DiffScmResult executeDiffCommand(ScmProviderRepository repository, ScmFileSet fileSet,
        ScmVersion startRevision, ScmVersion endRevision) throws ScmException {

    Git git = null;/*from  www .  jav a2 s  .  c om*/
    try {
        git = Git.open(fileSet.getBasedir());
        DiffScmResult diff = callDiff(git, startRevision, endRevision);
        git.getRepository().close();
        return diff;
    } catch (Exception e) {
        throw new ScmException("JGit diff failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.info.JGitInfoCommand.java

License:Apache License

@Override
protected ScmResult executeCommand(ScmProviderRepository repository, ScmFileSet fileSet,
        CommandParameters parameters) throws ScmException {
    Git git = null;/*  ww  w .  j a  va2  s  . c o  m*/
    try {
        File basedir = fileSet.getBasedir();

        git = Git.open(basedir);

        ObjectId objectId = git.getRepository().resolve("HEAD");

        InfoItem infoItem = new InfoItem();
        infoItem.setRevision(StringUtils.trim(objectId.name()));
        infoItem.setURL(basedir.getPath());

        return new InfoScmResult(Collections.singletonList(infoItem),
                new ScmResult("JGit.resolve(HEAD)", "", objectId.toString(), true));
    } catch (Exception e) {
        throw new ScmException("JGit resolve failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.list.JGitListCommand.java

License:Apache License

@Override
protected ListScmResult executeListCommand(ScmProviderRepository repo, ScmFileSet fileSet, boolean recursive,
        ScmVersion scmVersion) throws ScmException {

    Git git = null;/*from   w  ww.java 2 s .c  o m*/
    try {
        git = Git.open(fileSet.getBasedir());
        CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git,
                (GitScmProviderRepository) repo);

        List<ScmFile> list = new ArrayList<ScmFile>();
        Collection<Ref> lsResult = git.lsRemote().setCredentialsProvider(credentials).call();
        for (Ref ref : lsResult) {
            getLogger().debug(ref.getObjectId().getName() + "  " + ref.getTarget().getName());
            list.add(new ScmFile(ref.getName(), ScmFileStatus.CHECKED_IN));
        }

        return new ListScmResult("JGit ls-remote", list);
    } catch (Exception e) {
        throw new ScmException("JGit ls-remote failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.remoteinfo.JGitRemoteInfoCommand.java

License:Apache License

@Override
public RemoteInfoScmResult executeRemoteInfoCommand(ScmProviderRepository repository, ScmFileSet fileSet,
        CommandParameters parameters) throws ScmException {

    GitScmProviderRepository repo = (GitScmProviderRepository) repository;
    Git git = null;/*from   w ww .j  a  v  a 2  s . com*/
    try {
        git = Git.open(fileSet.getBasedir());
        CredentialsProvider credentials = JGitUtils.getCredentials(repo);

        LsRemoteCommand lsCommand = git.lsRemote().setRemote(repo.getPushUrl())
                .setCredentialsProvider(credentials);

        Map<String, String> tag = new HashMap<String, String>();
        Collection<Ref> allTags = lsCommand.setHeads(false).setTags(true).call();
        for (Ref ref : allTags) {
            tag.put(Repository.shortenRefName(ref.getName()), ref.getObjectId().name());
        }

        Map<String, String> heads = new HashMap<String, String>();
        Collection<Ref> allHeads = lsCommand.setHeads(true).setTags(false).call();
        for (Ref ref : allHeads) {
            heads.put(Repository.shortenRefName(ref.getName()), ref.getObjectId().name());
        }

        return new RemoteInfoScmResult("JGit remoteinfo", heads, tag);
    } catch (Exception e) {
        throw new ScmException("JGit remoteinfo failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.status.JGitStatusCommand.java

License:Apache License

/**
 * {@inheritDoc}/*from   w w  w  . ja  v a2  s  .com*/
 */
protected StatusScmResult executeStatusCommand(ScmProviderRepository repo, ScmFileSet fileSet)
        throws ScmException {
    Git git = null;
    try {
        git = Git.open(fileSet.getBasedir());
        Status status = git.status().call();
        List<ScmFile> changedFiles = getFileStati(status);

        return new StatusScmResult("JGit status", changedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit status failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.tag.JGitTagCommand.java

License:Apache License

/**
 * {@inheritDoc}/*from   w ww  . jav  a 2  s .c  o  m*/
 */
public ScmResult executeTagCommand(ScmProviderRepository repo, ScmFileSet fileSet, String tag,
        ScmTagParameters scmTagParameters) throws ScmException {
    if (tag == null || StringUtils.isEmpty(tag.trim())) {
        throw new ScmException("tag name must be specified");
    }

    if (!fileSet.getFileList().isEmpty()) {
        throw new ScmException("This provider doesn't support tagging subsets of a directory");
    }

    String escapedTagName = tag.trim().replace(' ', '_');

    Git git = null;
    try {
        git = Git.open(fileSet.getBasedir());

        // tag the revision
        String tagMessage = scmTagParameters.getMessage();
        Ref tagRef = git.tag().setName(escapedTagName).setMessage(tagMessage).setForceUpdate(false).call();

        if (repo.isPushChanges()) {
            getLogger().info("push tag [" + escapedTagName + "] to remote...");
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo,
                    new RefSpec(Constants.R_TAGS + escapedTagName));
        }

        // search for the tagged files
        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(tagRef.getObjectId());
        revWalk.release();

        final TreeWalk walk = new TreeWalk(git.getRepository());
        walk.reset(); // drop the first empty tree, which we do not need here
        walk.setRecursive(true);
        walk.addTree(commit.getTree());

        List<ScmFile> taggedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            taggedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        return new TagScmResult("JGit tag", taggedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit tag failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

License:Apache License

protected void pushChanges(final File target) {
    try {/*from   w w w .j a  v a2  s  .c  om*/
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        final String base;
        Status status;
        if (target == null) {
            base = ".";
        } else {
            Path relativePath = repoPath.relativize(Paths.get(target.getPath()));
            base = relativePath.toString();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
        //
        // Check if its clean
        //
        if (status.isClean()) {
            //
            // Its clean
            //
            AdminNotification.warn(target.getName() + " is clean!");
            return;
        }
        //
        // Create the window
        //
        final GitPushWindow window = new GitPushWindow(git, target, status);
        window.setCaption("Push Changes");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {
            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                if (window.isSaved() == false) {
                    return;
                }
                try {
                    //
                    // Needs to be added first
                    //
                    DirCache cache = git.add().addFilepattern(base).call();
                    for (int i = 0; i < cache.getEntryCount(); i++) {
                        DirCacheEntry entry = cache.getEntry(i);
                        if (logger.isDebugEnabled()) {
                            logger.debug("Entry: " + entry);
                        }
                    }
                    //
                    // Next they need to be committed
                    //
                    RevCommit rev = git.commit().setMessage(window.getComment()).call();
                    if (logger.isDebugEnabled()) {
                        logger.debug("RevCommit: " + rev);
                    }
                    //
                    // Now we can push changes to the Git repository
                    //
                    Iterable<PushResult> results = git.push().call();
                    for (PushResult result : results) {
                        logger.info(result);
                    }
                    //
                    // Have the container fire an item set change notification
                    //
                    self.treeContainer.updateItem(target);
                } catch (NoWorkTreeException | GitAPIException e1) {
                    logger.error(e);
                    AdminNotification.error("Exception occurred while trying to push: " + e1);
                }
            }

        });
        window.center();
        UI.getCurrent().addWindow(window);
    } catch (IOException | GitAPIException e) {
        logger.error(e);
        AdminNotification.error("Exception occurred while trying to get status: " + e);
    }
}

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

License:Apache License

protected void openPolicyTab(File policy, boolean readOnly) {
    ////  www. jav a  2  s  .  co m
    // Sanity check
    //
    assert policy != null;
    assert policy.isFile();
    if (policy == null || !policy.isFile()) {
        throw new IllegalArgumentException("You must specify a file.");
    }
    Status status;
    Path relativePath;
    String base;
    try {
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        relativePath = repoPath.relativize(Paths.get(policy.getPath()));
        base = relativePath.toString();
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
    } catch (NoWorkTreeException | IOException | GitAPIException e) {
        logger.error("Failed to get status on " + policy + " " + e);
        AdminNotification.error("Could not get Git status on the file.");
        return;
    }
    //
    // Check if its clean
    //
    if (status.isClean() == false) {
        //
        // Check if its conflicting
        //
        for (String conflict : status.getConflicting()) {
            if (conflict.equals(base)) {
                //
                // Yes - we won't be able to edit it
                //
                AdminNotification.error("Policy has conflicts with master, please synchronize the repository.");
                return;
            }
        }
    }
    //
    // Check to see if there already is a tab open
    //
    Iterator<Component> iter = self.tabSheet.iterator();
    while (iter.hasNext()) {
        Component c = iter.next();
        if (c instanceof PolicyEditor) {
            Object data = ((PolicyEditor) c).getData();
            if (data != null && data instanceof File && ((File) data).equals(policy)) {
                self.tabSheet.setSelectedTab(c);
                return;
            }
        }
    }
    //
    // No tab is open, create a new one
    //
    PolicyEditor editor = null;
    try {
        editor = new PolicyEditor(policy, this.treeContainer, readOnly);
    } catch (IOException e) {
        logger.error("Failed to open policy");
        editor = null;
    }
    if (editor != null) {
        editor.setWidth("100%");
        Tab tab = self.tabSheet.addTab(editor);
        editor.setTab(tab);
        tab.setClosable(true);

        self.tabSheet.setSelectedTab(editor);
    } else {
        AdminNotification.error("The Policy File is not a Xacml 3.0 policy.");
    }
}

From source file:org.apache.openaz.xacml.admin.view.windows.GitPushWindow.java

License:Apache License

protected void refreshStatus() {
    try {//from   w  w  w  .ja  v  a 2 s  .c  o  m
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        final String base;
        Status status;
        if (target == null) {
            base = ".";
        } else {
            Path relativePath = repoPath.relativize(Paths.get(target.getPath()));
            base = relativePath.toString();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
        //
        // Pass it to our container
        //
        this.container.refreshStatus(status);
        this.tableChanges.refreshRowCache();
    } catch (NoWorkTreeException | IOException | GitAPIException e) {
        String error = "Failed to refresh status: " + e.getLocalizedMessage();
        logger.error(error);
    }
}

From source file:org.apache.openaz.xacml.admin.view.windows.GitSynchronizeWindow.java

License:Apache License

protected void synchronize() {
    ////www  . ja  v a  2  s .  c  o  m
    // Grab our working repository
    //
    Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
    try {
        final Git git = Git.open(repoPath.toFile());

        PullResult result = git.pull().call();
        // FetchResult fetch = result.getFetchResult();
        // MergeResult merge = result.getMergeResult();
        // RebaseResult rebase = result.getRebaseResult();
        if (result.isSuccessful()) {
            //
            // TODO add more notification
            //
            this.textAreaResults.setValue("Successful!");
        } else {
            //
            // TODO
            //
            this.textAreaResults.setValue("Failed.");
        }
    } catch (IOException | GitAPIException e) {
        e.printStackTrace();
    }
    this.buttonSynchronize.setCaption("Ok");
}