Example usage for org.eclipse.jgit.lib Repository resolve

List of usage examples for org.eclipse.jgit.lib Repository resolve

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository resolve.

Prototype

@Nullable
public ObjectId resolve(String revstr)
        throws AmbiguousObjectException, IncorrectObjectTypeException, RevisionSyntaxException, IOException 

Source Link

Document

Parse a git revision string and return an object id.

Usage

From source file:net.morimekta.gittool.GitTool.java

License:Apache License

public Optional<RevCommit> commitOf(Repository repository, String branch) throws IOException {
    try (RevWalk revWalk = new RevWalk(repository)) {
        ObjectId oid = repository.resolve(refName(branch));
        revWalk.markStart(revWalk.parseCommit(oid));
        revWalk.sort(RevSort.COMMIT_TIME_DESC);
        return Optional.ofNullable(ImmutableList.copyOf(revWalk).get(0));
    }/*from ww  w.j  ava2s  .c o  m*/
}

From source file:net.morimekta.idltool.IdlUtils.java

License:Apache License

public static Meta getMetaInRegistry(Repository repo) throws IOException, GitAPIException {
    // use tree and meta.json file to show available services.
    ObjectId lastCommitId = repo.resolve(Constants.HEAD);
    // now we have to get the commit
    RevWalk revWalk = new RevWalk(repo);
    RevCommit commit = revWalk.parseCommit(lastCommitId);
    // and using commit's tree find the path
    RevTree tree = commit.getTree();/* w  w  w .j  a  v  a  2  s. co m*/
    TreeWalk treeWalk = new TreeWalk(repo);

    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.create(Idl_Constants.META_JSON));
    if (!treeWalk.next()) {
        throw new RuntimeException("No registry meta file found, should be at "
                + new File(repo.getDirectory(), Idl_Constants.META_JSON).getCanonicalFile().getAbsolutePath());
    }
    ObjectId objectId = treeWalk.getObjectId(0);
    ObjectLoader loader = repo.open(objectId);

    // and then one can use either
    InputStream in = loader.openStream();

    return new JsonSerializer().deserialize(in, Meta.kDescriptor);
}

From source file:net.polydawn.mdm.commands.MdmReleaseCommand.java

License:Open Source License

/**
 * Check that nothing that would get in the way of a version name is present in
 * the repository.//from w  ww  .  j a  va  2 s.c  o  m
 * <p>
 * Checks performed include tags, branches, and paths committed to the master
 * branch. This is good coverage against local conflicts, but it's worth noting
 * that there's all sorts of problems that could well come up from having
 * incomplete local state and then trying to push what turns out to be a coliding
 * branch name, and so on.
 *
 * @param relModule
 * @param version
 * @throws MdmExitMessage
 * @throws IOException
 */
static void assertReleaseRepoDoesntAlreadyContain(MdmModuleRelease relModule, String version)
        throws MdmExitMessage, IOException {
    Repository relRepo = relModule.getRepo();

    // part 1: check branch for version name doesn't already exist
    if (relRepo.getRef("refs/heads/mdm/release/" + version) != null)
        throw new MdmExitMessage(":'(",
                "the releases repo already has a release point branch labeled version " + version + " !");

    // part 2: check tag for version name doesn't already exist
    if (relRepo.getRef("refs/tags/release/" + version) != null)
        throw new MdmExitMessage(":'(",
                "the releases repo already has a release point tag labeled version " + version + " !");

    // part 3: make sure there's nothing in the version-named directory in master.
    RevTree tree = new RevWalk(relRepo).parseCommit(relRepo.resolve("refs/heads/master")).getTree();
    TreeWalk treeWalk = new TreeWalk(relRepo);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.create(version));
    if (treeWalk.next())
        throw new MdmExitMessage(":'(",
                "the releases repo already has files committed in the master branch where version " + version
                        + " should go!");
}

From source file:net.polydawn.mdm.MdmModule.java

License:Open Source License

/**
 * @param repo/*from   w  w w .  j av  a 2 s.co  m*/
 *                required.
 *
 *                well, unless you're about to create one, in which case not even.
 * @param handle
 *                required.
 * @param parent
 *                null if repository stands alone, otherwise if we are a submodule
 *                required.
 * @param gitmodulesCfg
 *                ignored if parent null, otherwise required.
 * @param indexId
 *                ignored if parent null, otherwise will be automatically loaded
 *                if not provided.
 *
 *                the commit hash known to the parent repo index for this
 *                submodule (or null if it's not handy; we'll load it in that
 *                case).
 *
 * @throws MdmModuleTypeException
 *                 if the {@code gitmodulesCfg} entries for {@code handle} don't
 *                 concur with the {@code type} expected.
 * @throws MdmRepositoryIOException
 *                 if disks reject our advances
 */
protected MdmModule(Repository repo, String handle, Repository parent, Config gitmodulesCfg, ObjectId indexId)
        throws MdmRepositoryIOException, MdmModuleTypeException {
    handle = (File.separatorChar != '/') ? handle.replace(File.separatorChar, '/') : handle;
    this.handle = handle;
    this.repo = repo;

    if (repo == null) {
        this.headId = null;
        this.dirtyFiles = false;
    } else {
        try {
            this.headId = repo.resolve(Constants.HEAD);
        } catch (IOException e) {
            throw new MdmRepositoryIOException(false, handle, e);
        }

        boolean dirtyFiles;
        try {
            dirtyFiles = !new Git(repo).status().call().isClean();
        } catch (NoWorkTreeException e) {
            throw new RuntimeException("wat", e);
        } catch (GitAPIException e) {
            dirtyFiles = false;
        }
        this.dirtyFiles = dirtyFiles;
    }

    if (parent != null) {
        // sanity check the expected module type if we're a submodule (if we're not a submodule, we can't make any such check since there's no gitmodules file to refer to).
        MdmModuleType type = getType();
        MdmModuleType type_configured = MdmModuleType
                .fromString(gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                        MdmConfigConstants.Module.MODULE_TYPE.toString()));
        if (type == null)
            throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle
                    + ", but gitmodules file has no known type for this module.");
        if (type != type_configured)
            throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle
                    + ", but gitmodules file states this is a " + type_configured + " module.");

        // load real path from gitmodule config (probably same as handle, but theoretically allowed to be different)
        String path = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                ConfigConstants.CONFIG_KEY_PATH);
        this.path = (File.separatorChar != '/') ? path.replace(File.separatorChar, '/') : path;

        // load remote urls
        this.urlHistoric = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                ConfigConstants.CONFIG_KEY_URL);
        this.urlLocal = parent.getConfig().getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                ConfigConstants.CONFIG_KEY_URL);

        // load indexId the parent expects the submodule to be at (if not already provided)
        if (indexId != null)
            this.indexId = indexId;
        else
            try {
                SubmoduleWalk generator = SubmoduleWalk.forIndex(parent).setFilter(PathFilter.create(path));
                this.indexId = generator.next() ? generator.getObjectId() : null;
            } catch (IOException e) {
                throw new MdmRepositoryIOException(false, parent.getWorkTree().getPath(), e);
            }

        // review the submodule and summarize a status.
        SubmoduleStatusType statusType;
        if (path == null)
            // jgit report SubmoduleStatusType.MISSING if no path in .gitmodules file, but I don't even want to deal with that.
            throw new MdmModuleTypeException("no path for module " + handle + " listed in gitmodules file.");
        else if (urlLocal == null)
            // Report uninitialized if no URL in config file
            statusType = SubmoduleStatusType.UNINITIALIZED;
        else if (repo == null)
            // Report uninitialized if no submodule repository
            statusType = SubmoduleStatusType.UNINITIALIZED;
        else if (headId == null)
            // Report uninitialized if no HEAD commit in submodule repository
            statusType = SubmoduleStatusType.UNINITIALIZED;
        else if (!headId.equals(indexId))
            // Report checked out if HEAD commit is different than index commit
            statusType = SubmoduleStatusType.REV_CHECKED_OUT;
        else
            // Report initialized if HEAD commit is the same as the index commit
            statusType = SubmoduleStatusType.INITIALIZED;
        this.status = new SubmoduleStatus(statusType, path, indexId, headId);
    } else {
        this.path = handle;
        this.indexId = null;
        this.urlHistoric = null;
        this.urlLocal = null;
        this.status = null;
    }
}

From source file:net.riezebos.thoth.content.impl.GitContentManager.java

License:Apache License

@Override
protected synchronized String cloneOrPull() throws ContentManagerException {
    StringBuilder log = new StringBuilder();
    try {/*from  w w w .  ja va 2  s . c  om*/
        Configuration config = getConfiguration();
        RepositoryDefinition repositoryDefinition = getContextDefinition().getRepositoryDefinition();
        String repositoryUrl = repositoryDefinition.getLocation();
        String workspaceLocation = config.getWorkspaceLocation();
        if (StringUtils.isBlank(workspaceLocation))
            throw new IllegalArgumentException("No environment variable or system variable named "
                    + Configuration.WORKSPACELOCATION + " was set");
        File file = new File(workspaceLocation);
        if (!file.isDirectory()) {
            severe(log, "The library path " + workspaceLocation
                    + " does not exist. Cannot initialize content manager");
        } else {
            try {
                String contextFolder = getContextFolder();
                File target = new File(contextFolder);
                CredentialsProvider credentialsProvider = getCredentialsProvider();

                if (target.isDirectory()) {
                    try (Git repos = getRepository()) {

                        Repository repository = repos.getRepository();
                        ObjectId oldHead = repository.resolve(HEAD_TREE);

                        PullResult pullResult = repos.pull().setCredentialsProvider(credentialsProvider).call();
                        ObjectId newHead = repository.resolve(HEAD_TREE);
                        boolean changes = (oldHead == null && newHead != null)//
                                || (oldHead != null && !oldHead.equals(newHead));
                        if (changes)
                            notifyContextContentsChanged();

                        String message = pullResult.isSuccessful() ? ": Pull successful, "
                                : ": Pull of failed, ";
                        message += changes ? CHANGES_DETECTED_MSG : NO_CHANGES_DETECTED_MSG;
                        info(log, getContextName() + message);

                        setLatestRefresh(new Date());
                    } catch (Exception e) {
                        severe(log, e);
                    }
                } else {
                    info(log, getContextName() + ": Cloning from " + repositoryUrl + " to " + contextFolder);
                    target.mkdirs();
                    try (Git result = Git.cloneRepository()//
                            .setURI(repositoryUrl)//
                            .setBranch(getBranch())//
                            .setCredentialsProvider(credentialsProvider)//
                            .setDirectory(target).call()) {
                        info(log, getContextName() + ": Cloned repository: "
                                + result.getRepository().getDirectory());
                        setLatestRefresh(new Date());
                        notifyContextContentsChanged();
                    } catch (Exception e) {
                        severe(log, e);
                    }
                }
            } catch (Exception e) {
                severe(log, e);
            }
        }

    } catch (Exception e) {
        throw new ContentManagerException(e);
    }

    return log.toString().trim();
}

From source file:net.sf.authorship.strategies.GitStrategy.java

License:Open Source License

public Set<Author> getAuthors() throws AuthorshipException {

    try {/*from  www . ja v a  2  s. co m*/
        this.cloneRepository(this.readOnlyUrl, this.folder);
    } catch (IOException ioe) {
        throw new AuthorshipException("Failed to clone git repository [" + this.readOnlyUrl + "]", ioe);
    }

    final Set<Author> authorEmails = new HashSet<Author>();
    final File directory = new File(this.folder);
    try {
        final Repository repository;
        try {
            repository = RepositoryCache.open(RepositoryCache.FileKey.lenient(directory, FS.DETECTED), true);
        } catch (IOException ioe) {
            throw new AuthorshipException("Failed to open git repository [" + this.readOnlyUrl
                    + "] cloned into local repository [" + this.folder + "]", ioe);
        }

        final RevWalk walk;
        try {
            walk = new RevWalk(repository);
            if (StringUtils.isNotBlank(this.fromRevision)) {
                this.fromRevision = Constants.HEAD;
            }
            ObjectId revId = repository.resolve(this.fromRevision);
            RevCommit root = walk.parseCommit(revId);
            walk.markStart(root);
            if (StringUtils.isNotBlank(this.toRevision)) {
                ObjectId to = repository.resolve(this.toRevision);
                RevCommit end = walk.parseCommit(to);
                walk.markUninteresting(end);
            }
        } catch (IOException ioe) {
            throw new AuthorshipException("Failed to analyse revisions from git repository [" + this.folder
                    + "]: " + ioe.getMessage(), ioe);
        }

        for (RevCommit commit : walk) {
            Author author = new Author(null, commit.getAuthorIdent().getName(),
                    commit.getAuthorIdent().getEmailAddress(), null);
            authorEmails.add(author);
        }
        walk.dispose();
    } finally {
        try {
            if (!directory.delete()) {
                directory.deleteOnExit();
            }
        } catch (RuntimeException re) {
            LOGGER.warning(re.getMessage());
        }
    }

    return authorEmails;
}

From source file:net.tietema.versioning.GitJavaVersioning.java

License:Apache License

public String getRevision(File projectDir) throws MojoExecutionException {
    // XXX we use our own findGitDir because they JGit one doesn't find the git dir in a multi project build
    File gitDir = findGitDir(projectDir);
    String revision = "Unknown";
    if (gitDir == null)
        return revision;

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = null;
    try {//from w w w .  jav a  2s  .co  m
        repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir(projectDir) // scan up the file system tree
                .build();

        log.info("Git dir: " + gitDir.toString());
        RepositoryState state = repository.getRepositoryState();
        log.info(state.getDescription());
        String branch = repository.getBranch();
        log.info("Branch is: " + branch);
        Git git = new Git(repository);
        String fullBranch = repository.getFullBranch();
        log.info("Full branch is: " + fullBranch);
        ObjectId id = repository.resolve(fullBranch);
        log.info("Branch " + repository.getBranch() + " points to " + id.name());

        Status status = git.status().call();
        boolean strictClean = status.isClean();
        // no untracked files
        boolean loseClean = status.getAdded().isEmpty() && status.getChanged().isEmpty()
                && status.getConflicting().isEmpty() && status.getMissing().isEmpty()
                && status.getModified().isEmpty() && status.getRemoved().isEmpty();

        StringWriter buffer = new StringWriter();
        JavaWriter writer = new JavaWriter(buffer);
        writer.emitPackage(packageName)
                .beginType(packageName + "." + className, "class", Modifier.PUBLIC | Modifier.FINAL)
                .emitField("String", "BRANCH", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", branch))
                .emitField("String", "REVISION", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", id.name()))
                .emitField("String", "REVISION_SHORT", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", id.name().substring(0, 8)))
                .emitJavadoc("Strict Clean means no changes, not even untracked files")
                .emitField("boolean", "STRICT_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        (strictClean ? "true" : "false"))
                .emitJavadoc("Lose Clean means no changes except untracked files.")
                .emitField("boolean", "LOSE_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        (loseClean ? "true" : "false"))
                .endType();
        revision = buffer.toString();

        return revision;
    } catch (IOException e) {
        log.error(e);
        throw new MojoExecutionException(e.getMessage());
    } catch (GitAPIException e) {
        log.error(e);
        throw new MojoExecutionException(e.getMessage());
    } finally {
        if (repository != null)
            repository.close();
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitLog.java

License:Apache License

/**
 * Gets the commit log and stores it in a project property as configured.
 *//*www  . java2  s.  c  o  m*/
@TaskAction
public void reset() {
    final LogCommand cmd = getGit().log();
    Repository repo = getGit().getRepository();
    if (includes != null) {
        for (String include : includes) {
            try {
                ObjectId commit = repo.resolve(include);
                if (commit == null) {
                    throw new GradleException("No commit found for revision string: " + include);
                } else {
                    cmd.add(commit);
                }
            } catch (AmbiguousObjectException e) {
                throw new GradleException("Revision string is ambiguous: " + include, e);
            } catch (MissingObjectException e) {
                throw new GradleException("Commit could not be found in repository: " + include, e);
            } catch (IncorrectObjectTypeException e) {
                throw new GradleException("Revision string did not point to a commit: " + include, e);
            } catch (IOException e) {
                throw new GradleException("Problem resolving revision string: " + include, e);
            }
        }
    }
    if (excludes != null) {
        for (String exclude : excludes) {
            try {
                ObjectId commit = repo.resolve(exclude);
                if (commit == null) {
                    throw new GradleException("No commit found for revision string: " + exclude);
                } else {
                    cmd.add(commit);
                }
            } catch (AmbiguousObjectException e) {
                throw new GradleException("Revision string is ambiguous: " + exclude, e);
            } catch (MissingObjectException e) {
                throw new GradleException("Commit could not be found in repository: " + exclude, e);
            } catch (IncorrectObjectTypeException e) {
                throw new GradleException("Revision string did not point to a commit: " + exclude, e);
            } catch (IOException e) {
                throw new GradleException("Problem resolving revision string: " + exclude, e);
            }
        }
    }
    cmd.setSkip(skipCommits);
    cmd.setMaxCount(maxCommits);

    try {
        Iterable<RevCommit> commits = cmd.call();
        List<Commit> tempLog = new ArrayList<Commit>();
        for (RevCommit commit : commits) {
            tempLog.add(GitUtil.revCommitToCommit(commit));
        }
        this.log = Collections.unmodifiableList(tempLog);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with log.", e);
    }
    //TODO add progress monitor to log progress to Gradle status bar
}

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

License:Apache License

private RevCommit getHeadCommit(Repository repository) throws Exception {
    RevWalk rw = new RevWalk(repository);
    AnyObjectId headId = repository.resolve(Constants.HEAD);
    RevCommit head = rw.parseCommit(headId);
    rw.release();//from   w w w  .j  a va2s .com
    return head;
}

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

License:Apache License

private AbstractTreeIterator getTreeIterator(Repository repo, String name) throws IOException {
    final ObjectId id = repo.resolve(name);
    if (id == null) {
        throw new IllegalArgumentException(name);
    }//from ww  w .  j  av  a 2  s . c  o m
    final CanonicalTreeParser p = new CanonicalTreeParser();
    final ObjectReader or = repo.newObjectReader();
    try {
        p.reset(or, new RevWalk(repo).parseTree(id));
        return p;
    } finally {
        or.release();
    }
}