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:com.amd.gerrit.plugins.manifestsubscription.Utilities.java

License:Open Source License

static Manifest getManifest(GitRepositoryManager gitRepoManager, String manifestRepo, String manifestCommitish,
        String manifestPath) throws ManifestReadException, IOException, ConfigInvalidException, JAXBException {

    Project.NameKey p = new Project.NameKey(manifestRepo);
    Repository repo = gitRepoManager.openRepository(p);
    ObjectId commitId = repo.resolve(manifestCommitish);
    VersionedManifests vManifests = new VersionedManifests(manifestCommitish);
    vManifests.load(repo, commitId);/*from  w ww. j a v a2s  . co  m*/
    CanonicalManifest manifests = new CanonicalManifest(vManifests);

    return manifests.getCanonicalManifest(manifestPath);
}

From source file:com.amd.gerrit.plugins.manifestsubscription.Utilities.java

License:Open Source License

static Manifest createNewManifestFromBase(GitRepositoryManager gitRepoManager,
        MetaDataUpdate.Server metaDataUpdateFactory, ChangeHooks changeHooks, String srcManifestRepo,
        String srcManifestCommitish, String manifestRepo, String manifestBranch, String manifestPath,
        String newRef, boolean createSnapShotBranch, Manifest base)
        throws JAXBException, IOException, ConfigInvalidException, GitAPIException {

    // Replace default ref with newly created branch or tag
    Manifest manifest = (Manifest) base.clone();
    final String defaultRef;
    if (manifest.getDefault() != null) {
        defaultRef = manifest.getDefault().getRevision();
    } else {/*w  w  w. j  a  v a  2s .  c o m*/
        defaultRef = null;
    }

    if (manifest.getDefault() != null) {
        ManifestOp op = new ManifestOp() {
            @Override
            public boolean apply(com.amd.gerrit.plugins.manifestsubscription.manifest.Project project,
                    String hash, String name, GitRepositoryManager gitRepoManager)
                    throws GitAPIException, IOException {

                //This is assuming newRef points to the existing hash
                if (project.getRevision() != null && project.getRevision().equals(hash)) {
                    project.setRevision(null);
                } else {
                    project.setRevision(defaultRef);
                }

                return true;
            }
        };

        VersionedManifests.traverseManifestAndApplyOp(gitRepoManager, manifest.getProject(), defaultRef, op,
                null);
    } else {
        manifest.setDefault(new Default());
    }

    manifest.getDefault().setRevision(newRef);

    if (createSnapShotBranch) {
        // Create the snapshot branch and tag it
        // branch name is by convention for the new manifest to be created below

        // current jgit Repository.resolve doesn't seem to resolve short-name
        // properly.  FIXME
        String shortBranch = manifestBranch.replaceFirst("^refs/heads/(.*)", "$1");

        ObjectId oid = Utilities.updateManifest(gitRepoManager, metaDataUpdateFactory, changeHooks,
                srcManifestRepo, ManifestSubscription.STORE_BRANCH_PREFIX + shortBranch + "/" + manifestPath,
                manifest, manifestRepo, "Manifest branched", srcManifestCommitish);

        //      try (Repository db = gitRepoManager.openRepository(new Project.NameKey(srcManifestRepo));
        //           Git git = new Git(db);
        //           RevWalk walk = new RevWalk(db)) {
        //        RevCommit commit = walk.parseCommit(oid);
        //        git.tag().setName(createSnapShotBranch)
        //            .setObjectId(commit).setAnnotated(true).call();
        //      }
    }

    Project.NameKey p = new Project.NameKey(manifestRepo);
    Repository repo = gitRepoManager.openRepository(p);
    ObjectId commitId = repo.resolve(manifestBranch);
    VersionedManifests vManifests;
    MetaDataUpdate update = metaDataUpdateFactory.create(p);
    if (commitId == null) {
        // TODO remove assumption that master branch always exists
        vManifests = new VersionedManifests("refs/heads/master");
        vManifests.load(update);
    } else {
        vManifests = new VersionedManifests(manifestBranch);
        vManifests.load(repo, commitId);
    }

    Map<String, Manifest> entry = Maps.newHashMapWithExpectedSize(1);
    entry.put(manifestPath, manifest);
    vManifests.setManifests(entry);

    RevCommit commit;
    if (commitId == null) {
        commit = vManifests.commitToNewRef(update, manifestBranch);
    } else {
        commit = vManifests.commit(update);
    }

    //TODO
    //if (commit != null) {
    //  changeHooks.doRefUpdatedHook(new Branch.NameKey(p, refName),
    //      commit.getParent(0).getId(),
    //      commit.getId(), null);
    //} else {
    //  log.warn("Failing to create new manifest");
    //}
    return manifest;
}

From source file:com.buildautomation.jgit.api.CreateArchive.java

License:Apache License

private static void write(Repository repository, String suffix, String format)
        throws IOException, GitAPIException {
    // this is the file that we write the archive to
    File file = File.createTempFile("test", suffix);
    try (OutputStream out = new FileOutputStream(file)) {
        // finally call the ArchiveCommand to write out using the various supported formats
        try (Git git = new Git(repository)) {
            git.archive().setTree(repository.resolve("master")).setFormat(format).setOutputStream(out).call();
        }/*w ww.  ja v  a2  s  . c o m*/
    }

    System.out.println("Wrote " + file.length() + " bytes to " + file);
}

From source file:com.buildautomation.jgit.api.GetFileAttributes.java

License:Apache License

private static RevTree getTree(Repository repository) throws IOException {
    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

    // a RevWalk allows to walk over commits based on some filtering
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(lastCommitId);

        System.out.println("Time of commit (seconds since epoch): " + commit.getCommitTime());

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        System.out.println("Having tree: " + tree);
        return tree;
    }//w ww  .j  a v  a2  s.co m
}

From source file:com.creactiviti.piper.core.git.JGitTemplate.java

License:Apache License

private List<IdentifiableResource> getHeadFiles(Repository aRepository, String... aSearchPaths) {
    List<String> searchPaths = Arrays.asList(aSearchPaths);
    List<IdentifiableResource> resources = new ArrayList<>();
    try (ObjectReader reader = aRepository.newObjectReader();
            RevWalk walk = new RevWalk(reader);
            TreeWalk treeWalk = new TreeWalk(aRepository, reader);) {
        final ObjectId id = aRepository.resolve(Constants.HEAD);
        RevCommit commit = walk.parseCommit(id);
        RevTree tree = commit.getTree();
        treeWalk.addTree(tree);//from  w  w w  .  j  a  va2 s.  c o m
        treeWalk.setRecursive(true);
        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            if (searchPaths.stream().anyMatch((sp) -> path.startsWith(sp))) {
                ObjectId objectId = treeWalk.getObjectId(0);
                logger.debug("Loading {} [{}]", path, objectId.name());
                resources.add(readBlob(aRepository, path.substring(0, path.indexOf('.')), objectId.name()));
            }
        }
        return resources;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.creactiviti.piper.core.git.JGitTemplate.java

License:Apache License

private IdentifiableResource readBlob(Repository aRepo, String aPath, String aBlobId) throws Exception {
    try (ObjectReader reader = aRepo.newObjectReader()) {
        if (aBlobId.equals(LATEST)) {
            List<IdentifiableResource> headFiles = getHeadFiles(aRepo, aPath);
            Assert.notEmpty(headFiles, "could not find: " + aPath + ":" + aBlobId);
            return headFiles.get(0);
        }//from  ww w. j  av  a2 s  .  co  m
        ObjectId objectId = aRepo.resolve(aBlobId);
        Assert.notNull(objectId, "could not find: " + aPath + ":" + aBlobId);
        byte[] data = reader.open(objectId).getBytes();
        AbbreviatedObjectId abbreviated = reader.abbreviate(objectId);
        return new IdentifiableResource(aPath + ":" + abbreviated.name(), new ByteArrayResource(data));
    }
}

From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java

License:Open Source License

private void checkout(Git git, Pom pom, GitDependency dependency) throws MojoExecutionException {
    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);

    try {//from w  w  w  .java  2s. c  om
        final Repository repository = git.getRepository();
        final ObjectId rev = repository.resolve(version);
        final RevCommit rc = new RevWalk(repository).parseCommit(rev);
        final CheckoutCommand checkout = git.checkout();

        checkout.setName("maven-gitdep-branch-" + rc.getCommitTime());
        checkout.setStartPoint(rc);
        checkout.setCreateBranch(true);
        checkout.call();

        final Status status = checkout.getResult().getStatus();

        if (status != Status.OK) {
            throw new MojoExecutionException(
                    String.format("Invalid checkout state (%s) of dependency.", status));
        }
    } catch (IOException | InvalidRefNameException | RefAlreadyExistsException | RefNotFoundException ex) {
        throw new MojoExecutionException(String.format("Failed to check out dependency for %s.%s",
                dependency.getGroupId(), dependency.getArtifactId()), ex);
    }
}

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

public static void main(String[] args) {
    Params params = new Params();
    JCommander jc = new JCommander(params);
    try {/*ww w. j a va 2  s .c  o m*/
        jc.parse(args);
    } catch (ParameterException t) {
        System.err.println(t.getMessage());
        jc.usage();
    }

    File source = new File(params.sourceFolder);
    String ghpages = "refs/heads/gh-pages";
    try {
        File gitDir = FileKey.resolve(new File(params.repositoryFolder), FS.DETECTED);
        Repository repository = new FileRepository(gitDir);

        RefModel issuesBranch = JGitUtils.getPagesBranch(repository);
        if (issuesBranch == null) {
            JGitUtils.createOrphanBranch(repository, "gh-pages", null);
        }

        System.out.println("Updating gh-pages branch...");
        ObjectId headId = repository.resolve(ghpages + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            DirCache index = createIndex(repository, headId, source, params.obliterate);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent author = new PersonIdent("Gitblit", "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage("updated pages");
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(ghpages);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            ghpages, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
        System.out.println("gh-pages updated.");
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.gitblit.plugin.flowdock.TicketMessageGenerator.java

License:Apache License

private List<RevCommit> getCommits(String repositoryName, String baseId, String tipId) {
    IRepositoryManager repositoryManager = GitblitContext.getManager(IRepositoryManager.class);
    Repository db = repositoryManager.getRepository(repositoryName);
    List<RevCommit> list = new ArrayList<RevCommit>();
    RevWalk walk = new RevWalk(db);
    walk.reset();//from   www  . j  a  va 2s.c om
    walk.sort(RevSort.TOPO);
    walk.sort(RevSort.REVERSE, true);
    try {
        RevCommit tip = walk.parseCommit(db.resolve(tipId));
        RevCommit base = walk.parseCommit(db.resolve(baseId));
        walk.markStart(tip);
        walk.markUninteresting(base);
        for (;;) {
            RevCommit c = walk.next();
            if (c == null) {
                break;
            }
            list.add(c);
        }
    } catch (IOException e) {
        // Should never happen, the core receive process would have
        // identified the missing object earlier before we got control.
        log.error("failed to get commits", e);
    } finally {
        walk.release();
        db.close();
    }
    return list;
}

From source file:com.gitblit.servlet.BranchGraphServlet.java

License:Eclipse Distribution License

@Override
protected long getLastModified(HttpServletRequest req) {
    String repository = req.getParameter("r");
    if (StringUtils.isEmpty(repository)) {
        return 0;
    }//from  w  w  w.  ja  v  a  2  s  .  co  m
    String objectId = req.getParameter("h");
    Repository r = null;
    try {
        r = repositoryManager.getRepository(repository);
        if (StringUtils.isEmpty(objectId)) {
            objectId = JGitUtils.getHEADRef(r);
        }
        ObjectId id = r.resolve(objectId);
        if (id == null) {
            return 0;
        }
        RevCommit commit = JGitUtils.getCommit(r, objectId);
        return JGitUtils.getCommitDate(commit).getTime();
    } catch (Exception e) {
        log.error("Failed to determine last modified", e);
        return 0;
    } finally {
        if (r != null) {
            r.close();
        }
    }
}