Example usage for org.eclipse.jgit.lib ObjectId fromString

List of usage examples for org.eclipse.jgit.lib ObjectId fromString

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId fromString.

Prototype

public static ObjectId fromString(String str) 

Source Link

Document

Convert an ObjectId from hex characters.

Usage

From source file:com.bacoder.scmtools.git.test.TestRepository1.java

License:Apache License

public void testMaster() throws InitializationException, ProcessingException {
    GitRepository gitRepository = new GitRepository(uri,
            new GitConfig().setCommitRevision(ObjectId.fromString("f28590f812223d3e62586473cbc46e675e83fbc7")));
    gitRepository.process(new GitEntryProcessor() {
        @Override//from w ww.  ja v  a 2 s  . c  o m
        public void process(GitEntry entry) throws IOException {
            writeln(String.format("*** %s @ %s ***", new File(entry.getSubmodulePrefix(), entry.getPath()),
                    entry.getObjectId().name()));
            writeln(entry.open().getBytes());
        }
    });
    verify(getOutput(),
            getClass().getClassLoader().getResourceAsStream("TestRepository1/TestRepository1Master.txt"));
}

From source file:com.benhumphreys.jgitcassandra.store.RefStore.java

License:Apache License

/**
 * Parses a Cassandra refs table row and converts it to a Ref
 *
 * @param row a single Cassandra row to parse
 * @return a ref, or null if the "row" parameter is null
 * @throws IOException           if an exception occurs when communicating to the
 *                               database
 * @throws IllegalStateException if the "type" field read back from the
 *                               database is not one of the four handled
 *                               types (@see RefType).
 *///  w ww.ja v  a 2  s  .  c  om
private Ref rowToRef(Row row) throws IOException {
    if (row == null) {
        return null;
    }

    final String name = row.getString("name");
    final String value = row.getString("value");
    final int refType = row.getInt("type");

    if (refType == RefType.PEELED_NONTAG.getValue()) {
        return new ObjectIdRef.PeeledNonTag(Ref.Storage.NETWORK, name, ObjectId.fromString(value));
    } else if (refType == RefType.PEELED_TAG.getValue()) {
        final String auxValue = row.getString("aux_value");
        return new ObjectIdRef.PeeledTag(Ref.Storage.NETWORK, name, ObjectId.fromString(value),
                ObjectId.fromString(auxValue));
    } else if (refType == RefType.UNPEELED.getValue()) {
        return new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, name, ObjectId.fromString(value));
    } else if (refType == RefType.SYMBOLIC.getValue()) {
        return new SymbolicRef(name, get(value));
    } else {
        throw new IllegalStateException("Unhandled ref type: " + refType);
    }
}

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

License:Apache License

private static RevCommit buildRevCommit(Repository repository, String commit) throws IOException {
    // a RevWalk allows to walk over commits based on some filtering that is defined
    try (RevWalk revWalk = new RevWalk(repository)) {
        return revWalk.parseCommit(ObjectId.fromString(commit));
    }//ww  w .  j  av  a 2s  .  co  m
}

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

License:Apache License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
        try (ObjectReader oldReader = repository.newObjectReader()) {
            oldTreeParser.reset(oldReader, tree.getId());
        }//from   w  w w  . ja  v a  2 s . co m

        walk.dispose();

        return oldTreeParser;
    }
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public long getCommitTime(String commitId) throws Exception {
    try (RevWalk revWalk = new RevWalk(localRepo)) {
        return revWalk.parseCommit(ObjectId.fromString(commitId)).getCommitterIdent().getWhen().getTime();
    }/*from  ww w .  j a  v  a2  s. c o m*/
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public byte[] readFromCommit(String commitId, String path) throws Exception {
    try (RevWalk revWalk = new RevWalk(localRepo)) {
        RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitId));
        // use commit's tree find the path
        RevTree tree = commit.getTree();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (TreeWalk treeWalk = new TreeWalk(localRepo)) {
            treeWalk.addTree(tree);// ww  w . j a  v  a2 s. c o  m
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(path));
            if (!treeWalk.next()) {
                return null;
            }

            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = localRepo.open(objectId);

            loader.copyTo(baos);
        }
        revWalk.dispose();
        return baos.toByteArray();
    }
}

From source file:com.cloudbees.eclipse.dev.scm.egit.ForgeEGitSync.java

License:Open Source License

private boolean openRemoteFile_(final String repo, final ChangeSetPathItem item,
        final IProgressMonitor monitor) {
    try {/*from   w  w w  . j  av  a 2  s  .  c  om*/
        // TODO extract repo search into separate method
        RepositoryCache repositoryCache = org.eclipse.egit.core.Activator.getDefault().getRepositoryCache();
        Repository repository = null;
        URIish proposal = new URIish(repo);
        List<String> reps = Activator.getDefault().getRepositoryUtil().getConfiguredRepositories();
        all: for (String rep : reps) {
            try {

                Repository fr = repositoryCache.lookupRepository(new File(rep));
                List<RemoteConfig> allRemotes = RemoteConfig.getAllRemoteConfigs(fr.getConfig());
                for (RemoteConfig remo : allRemotes) {
                    List<URIish> uris = remo.getURIs();
                    for (URIish uri : uris) {
                        CloudBeesDevCorePlugin.getDefault().getLogger()
                                .info("Checking URI: " + uri + " - " + proposal.equals(uri));
                        if (proposal.equals(uri)) {
                            repository = fr;
                            break all;
                        }
                    }
                }
            } catch (Exception e) {
                CloudBeesDevCorePlugin.getDefault().getLogger().error(e);
            }
        }

        CloudBeesDevCorePlugin.getDefault().getLogger().info("Repo: " + repository);

        if (repository == null) {
            throw new CloudBeesException("Failed to find mapped repository for " + repo);
        }

        ObjectId commitId = ObjectId.fromString(item.parent.id);
        RevWalk rw = new RevWalk(repository);
        RevCommit rc = rw.parseCommit(commitId);
        final IFileRevision rev = CompareUtils.getFileRevision(item.path, rc, repository, null);

        final IEditorPart[] editor = new IEditorPart[1];

        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
            @Override
            public void run() {
                IWorkbenchPage activePage = CloudBeesUIPlugin.getActiveWindow().getActivePage();
                try {
                    editor[0] = Utils.openEditor(activePage, rev, monitor);
                } catch (CoreException e) {
                    e.printStackTrace(); // TODO
                }
            }
        });

        return editor[0] != null;
    } catch (Exception e) {
        CloudBeesDevCorePlugin.getDefault().getLogger().error(e); // TODO handle better?
        return false;
    }
}

From source file:com.GitAnalytics.CommitInfo.java

public static List<CommitInfo> getCommits(Repository repo, Iterable<RevCommit> commits, List<Ref> tags)
        throws Exception {
    List<CommitInfo> list = new LinkedList<>();

    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
    df.setRepository(repo);//from w  ww.  j a  v  a2  s .  co  m
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);

    RevWalk rw = new RevWalk(repo);

    for (RevCommit commit : commits) {
        List<String> curTags = new LinkedList<>();

        tags.stream().filter((tag) -> (tag.getObjectId().equals(ObjectId.fromString(commit.getName()))))
                .forEachOrdered((tag) -> {
                    curTags.add(tag.getName());
                });

        list.add(new CommitInfo(df, rw, commit, curTags));
    }

    return list;
}

From source file:com.gitblit.git.PatchsetCommand.java

License:Apache License

public PatchsetCommand(String username, Patchset patchset) {
    super(patchset.isFF() ? ObjectId.fromString(patchset.parent) : ObjectId.zeroId(),
            ObjectId.fromString(patchset.tip), null);
    this.change = new Change(username);
    this.change.patchset = patchset;
}

From source file:com.gitblit.git.PatchsetReceivePack.java

License:Apache License

/**
 * Merge the specified patchset to the integration branch.
 *
 * @param ticket//www. j  a va2 s.  c  o m
 * @param patchset
 * @return true, if successful
 */
public MergeStatus merge(TicketModel ticket) {
    PersonIdent committer = new PersonIdent(user.getDisplayName(),
            StringUtils.isEmpty(user.emailAddress) ? (user.username + "@gitblit") : user.emailAddress);
    Patchset patchset = ticket.getCurrentPatchset();
    String message = MessageFormat.format("Merged #{0,number,0} \"{1}\"", ticket.number, ticket.title);
    Ref oldRef = null;
    try {
        oldRef = getRepository().findRef(ticket.mergeTo);
    } catch (IOException e) {
        LOGGER.error("failed to get ref for " + ticket.mergeTo, e);
    }
    MergeResult mergeResult = JGitUtils.merge(getRepository(), patchset.tip, ticket.mergeTo,
            getRepositoryModel().mergeType, committer, message);

    if (StringUtils.isEmpty(mergeResult.sha)) {
        LOGGER.error("FAILED to merge {} to {} ({})",
                new Object[] { patchset, ticket.mergeTo, mergeResult.status.name() });
        return mergeResult.status;
    }
    Change change = new Change(user.username);
    change.setField(Field.status, Status.Merged);
    change.setField(Field.mergeSha, mergeResult.sha);
    change.setField(Field.mergeTo, ticket.mergeTo);

    if (StringUtils.isEmpty(ticket.responsible)) {
        // unassigned tickets are assigned to the closer
        change.setField(Field.responsible, user.username);
    }

    long ticketId = ticket.number;
    ticket = ticketService.updateTicket(repository, ticket.number, change);
    if (ticket != null) {
        ticketNotifier.queueMailing(ticket);

        if (oldRef != null) {
            ReceiveCommand cmd = new ReceiveCommand(oldRef.getObjectId(), ObjectId.fromString(mergeResult.sha),
                    oldRef.getName());
            cmd.setResult(Result.OK);
            List<ReceiveCommand> commands = Arrays.asList(cmd);

            logRefChange(commands);
            updateIncrementalPushTags(commands);
            updateGitblitRefLog(commands);
        }

        // call patchset hooks
        for (PatchsetHook hook : gitblit.getExtensions(PatchsetHook.class)) {
            try {
                hook.onMergePatchset(ticket);
            } catch (Exception e) {
                LOGGER.error("Failed to execute extension", e);
            }
        }
        return mergeResult.status;
    } else {
        LOGGER.error("FAILED to resolve ticket {} by merge from web ui", ticketId);
    }
    return mergeResult.status;
}