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

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

Introduction

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

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java

License:Apache License

private UserInfo getCommitter(ScmProviderRepository repo, Git git) {
    boolean forceMvnUser = git.getRepository().getConfig().getBoolean(GIT_MAVEN_SECTION, GIT_FORCE, false);

    // git config
    UserConfig user = git.getRepository().getConfig().get(UserConfig.KEY);
    String committerName = null;/*w w w .j av a2s.co m*/
    if (!forceMvnUser && !user.isCommitterNameImplicit()) {
        committerName = user.getCommitterName();
    }

    // mvn parameter
    if (StringUtils.isBlank(committerName)) {
        committerName = repo.getUser();
    }

    // git default
    if (StringUtils.isBlank(committerName)) {
        committerName = user.getCommitterName();
    }

    // git config
    String committerMail = null;
    if (!user.isCommitterEmailImplicit()) {
        committerMail = user.getCommitterEmail();
    }

    if (StringUtils.isBlank(committerMail)) {
        String defaultDomain = git.getRepository().getConfig().getString(GIT_MAVEN_SECTION, null,
                GIT_MAILDOMAIN);
        defaultDomain = StringUtils.isNotBlank(defaultDomain) ? defaultDomain : getHostname();

        // mvn parameter (constructed with username) or git default
        committerMail = StringUtils.isNotBlank(repo.getUser()) ? repo.getUser() + "@" + defaultDomain
                : user.getCommitterEmail();
    }

    return new UserInfo(committerName, committerMail);
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java

License:Apache License

private UserInfo getAuthor(ScmProviderRepository repo, Git git) {
    boolean forceMvnUser = git.getRepository().getConfig().getBoolean(GIT_MAVEN_SECTION, GIT_FORCE, false);

    // git config
    UserConfig user = git.getRepository().getConfig().get(UserConfig.KEY);
    String authorName = null;//from   w w w .  j  a  va 2s  . c  o  m
    if (!forceMvnUser && !user.isAuthorNameImplicit()) {
        authorName = user.getAuthorName();
    }

    // mvn parameter
    if (StringUtils.isBlank(authorName)) {
        authorName = repo.getUser();
    }

    // git default
    if (StringUtils.isBlank(authorName)) {
        authorName = user.getAuthorName();
    }

    // git config
    String authorMail = null;
    if (!user.isAuthorEmailImplicit()) {
        authorMail = user.getAuthorEmail();
    }

    if (StringUtils.isBlank(authorMail)) {
        String defaultDomain = git.getRepository().getConfig().getString(GIT_MAVEN_SECTION, null,
                GIT_MAILDOMAIN);
        defaultDomain = StringUtils.isNotBlank(defaultDomain) ? defaultDomain : getHostname();

        // mvn parameter (constructed with username) or git default
        authorMail = StringUtils.isNotBlank(repo.getUser()) ? repo.getUser() + "@" + defaultDomain
                : user.getAuthorEmail();
    }

    return new UserInfo(authorName, authorMail);
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommandCommitterAuthorTckTest.java

License:Apache License

@Override
public void testCheckInCommandTest() throws Exception {
    File fooJava = new File(getWorkingCopy(), "src/main/java/Foo.java");
    assertFalse("check Foo.java doesn't yet exist", fooJava.canRead());

    Git git = Git.open(getWorkingCopy());

    RevCommit head = getHeadCommit(git.getRepository());
    // Mark created the test repo...
    assertEquals("Mark Struberg", head.getCommitterIdent().getName());
    JGitUtils.closeRepo(git);/*w w w .  j  av a 2s. c  o m*/

    createAndCommitFile(fooJava, null);

    // change user in config
    git = Git.open(getWorkingCopy());
    StoredConfig config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString("user", null, "name", "Dominik");
    config.setString("user", null, "email", "domi@mycomp.com");
    config.save();

    // make a commit
    createAndCommitFile(fooJava, null);

    // check new commit is done with new user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("Dominik", head.getCommitterIdent().getName());
    assertEquals("Dominik", head.getAuthorIdent().getName());
    assertEquals("domi@mycomp.com", head.getAuthorIdent().getEmailAddress());
    assertEquals("domi@mycomp.com", head.getCommitterIdent().getEmailAddress());
    JGitUtils.closeRepo(git);

    // change user in config
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString("user", null, "name", "dbartholdi");
    config.save();

    // make a change
    createAndCommitFile(fooJava, null);

    // check new commit is done with new user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dbartholdi", head.getCommitterIdent().getName());
    assertFalse("no mail domain is configured, git system default should be used",
            head.getCommitterIdent().getEmailAddress().contains("dbartholdi"));
    JGitUtils.closeRepo(git);

    // unset a user and maven user but set default mail domain
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN, "comp.com");
    config.save();

    // make a change with an user on the commandline
    createAndCommitFile(fooJava, "dude");

    // check new commit is done with new maven user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dude", head.getCommitterIdent().getName());
    assertEquals("dude@comp.com", head.getCommitterIdent().getEmailAddress());
    assertEquals("dude", head.getAuthorIdent().getName());
    assertEquals("dude@comp.com", head.getAuthorIdent().getEmailAddress());
    JGitUtils.closeRepo(git);

    // unset a user and maven user but set default mail domain
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString("user", null, "name", "dbartholdi");
    config.setBoolean(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_FORCE, true);
    config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN,
            "anycomp.com");
    config.save();

    // make a change with an user on the commandline
    createAndCommitFile(fooJava, "dude");

    // check new commit is done with new maven user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dude", head.getCommitterIdent().getName());
    assertEquals("dude@anycomp.com", head.getCommitterIdent().getEmailAddress());
    assertEquals("dude", head.getAuthorIdent().getName());
    assertEquals("dude@anycomp.com", head.getAuthorIdent().getEmailAddress());
    JGitUtils.closeRepo(git);

    // unset a user and maven user but set default mail domain
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN,
            "anycomp.com");
    config.save();

    // make a change with no username given
    createAndCommitFile(fooJava, null);

    // check new commit does not contain the configured email domain
    head = getHeadCommit(git.getRepository());
    assertFalse(head.getCommitterIdent().getEmailAddress().contains("anycomp.com"));
    assertFalse(head.getAuthorIdent().getEmailAddress().contains("anycomp.com"));
    JGitUtils.closeRepo(git);

    // unset a user and full maven section
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.save();

    // make a change with an user on the commandline
    createAndCommitFile(fooJava, "dundy");

    // check new commit is done with new maven user in config
    head = getHeadCommit(git.getRepository());
    assertEquals("dundy", head.getCommitterIdent().getName());
    assertEquals("dundy", head.getAuthorIdent().getName());
    assertTrue(
            "the maven user (from parameter) name must be in the committer mail when nothing else is configured",
            head.getCommitterIdent().getEmailAddress().contains("dundy"));
    assertTrue("the user name (from parameter) must be in the author mail when nothing else is configured",
            head.getAuthorIdent().getEmailAddress().contains("dundy"));
    JGitUtils.closeRepo(git);

    // unset all configs
    git = Git.open(getWorkingCopy());
    config = git.getRepository().getConfig();
    unsetConfig(config);
    config.save();

    // make a change with no user on the commandline
    createAndCommitFile(fooJava, null);

    // check new commit is has a committer/author with email set
    head = getHeadCommit(git.getRepository());
    assertNotNull(head.getCommitterIdent().getName());
    assertNotNull(head.getAuthorIdent().getName());
    assertNotNull(head.getCommitterIdent().getEmailAddress());
    assertNotNull(head.getAuthorIdent().getEmailAddress());
    JGitUtils.closeRepo(git);
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java

License:Apache License

/**
 * For git, the given repository is a remote one. We have to clone it first if the working directory does not
 * contain a git repo yet, otherwise we have to git-pull it.
 * <p/>/*from   w  w  w.j  a v a 2  s .  c o  m*/
 * {@inheritDoc}
 */
protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet,
        ScmVersion version, boolean recursive) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol())
            && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }

    Git git = null;
    try {

        ProgressMonitor monitor = JGitUtils.getMonitor(getLogger());

        String branch = version != null ? version.getName() : null;

        if (StringUtils.isBlank(branch)) {
            branch = Constants.MASTER;
        }

        getLogger().debug("try checkout of branch: " + branch);

        if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) {
            if (fileSet.getBasedir().exists()) {
                // git refuses to clone otherwise
                fileSet.getBasedir().delete();
            }

            // FIXME only if windauze
            WindowCacheConfig cfg = new WindowCacheConfig();
            cfg.setPackedGitMMAP(false);
            cfg.install();

            // no git repo seems to exist, let's clone the original repo
            CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo);
            getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir());
            CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl());
            command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir());
            command.setProgressMonitor(monitor);
            git = command.call();
        }

        JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand();
        remoteInfoCommand.setLogger(getLogger());
        RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null);

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

        if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists()
                && result.getBranches().size() > 0) {
            // git repo exists, so we must git-pull the changes
            CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository);

            if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) {
                // A tag will not be pulled but we only fetch all the commits from the upstream repo
                // This is done because checking out a tag might not happen on the current branch
                // but create a 'detached HEAD'.
                // In fact, a tag in git may be in multiple branches. This occurs if
                // you create a branch after the tag has been created
                getLogger().debug("fetch...");
                git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            } else {
                getLogger().debug("pull...");
                git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            }
        }

        Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git);
        if (version instanceof ScmTag) {
            getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else if (localBranchNames.contains(branch)) {
            getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else {
            getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).setCreateBranch(true)
                    .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call();
        }

        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD));
        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> listedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        getLogger().debug("current branch: " + git.getRepository().getBranch());

        return new CheckOutScmResult("checkout via JGit", listedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkout failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

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;
    try {/*from   w  w w .  j a v  a2s.  c o  m*/
        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.diff.JGitDiffCommand.java

License:Apache License

public DiffScmResult callDiff(Git git, ScmVersion startRevision, ScmVersion endRevision)
        throws IOException, GitAPIException, ScmException {

    AbstractTreeIterator oldTree = null;
    if (startRevision != null && StringUtils.isNotEmpty(startRevision.getName().trim())) {
        String startRev = startRevision.getName().trim();
        oldTree = getTreeIterator(git.getRepository(), startRev);
    }//www  .j a  va2s .  c om

    AbstractTreeIterator newTree = null;
    if (endRevision != null && StringUtils.isNotEmpty(endRevision.getName().trim())) {
        String endRev = endRevision.getName().trim();
        newTree = getTreeIterator(git.getRepository(), endRev);
    }

    OutputStream out = new ByteArrayOutputStream();

    git.diff().setOutputStream(out).setOldTree(oldTree).setNewTree(newTree).setCached(false).call();
    git.diff().setOutputStream(out).setOldTree(oldTree).setNewTree(newTree).setCached(true).call();

    out.flush();

    GitDiffConsumer consumer = new GitDiffConsumer(getLogger(), null);
    String fullDiff = out.toString();
    out.close();

    String[] lines = fullDiff.split("\n");
    for (String aLine : lines) {
        consumer.consumeLine(aLine);
    }

    return new DiffScmResult("JGit diff", consumer.getChangedFiles(), consumer.getDifferences(),
            consumer.getPatch());
}

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;
    try {/*from w w w. j  a  v  a  2 s. c o  m*/
        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.JGitUtils.java

License:Apache License

/**
 * Closes the repository wrapped by the passed git object
 * @param git /*w w w  . j  a v a 2s . c  om*/
 */
public static void closeRepo(Git git) {
    if (git != null && git.getRepository() != null) {
        git.getRepository().close();
    }
}

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

License:Apache License

/**
 * Prepares the in memory configuration of git to connect to the configured
 * repository. It configures the following settings in memory: <br />
 * <li>push url</li> <li>fetch url</li>
 * <p/>//from   ww  w .j  a v  a 2s. c  o  m
 *
 * @param logger     used to log some details
 * @param git        the instance to configure (only in memory, not saved)
 * @param repository the repo config to be used
 * @return {@link CredentialsProvider} in case there are credentials
 *         informations configured in the repository.
 */
public static CredentialsProvider prepareSession(ScmLogger logger, Git git,
        GitScmProviderRepository repository) {
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", repository.getFetchUrl());
    config.setString("remote", "origin", "pushURL", repository.getPushUrl());

    // make sure we do not log any passwords to the output
    String password = StringUtils.isNotBlank(repository.getPassword()) ? repository.getPassword().trim()
            : "no-pwd-defined";
    logger.info("fetch url: " + repository.getFetchUrl().replace(password, "******"));
    logger.info("push url: " + repository.getPushUrl().replace(password, "******"));
    return getCredentials(repository);
}

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

License:Apache License

/**
 * {@inheritDoc}//  ww  w. j a  v  a  2s  .c  om
 */
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);
    }
}