Java 类org.eclipse.jgit.lib.ObjectReader 实例源码

项目:piper    文件:JGitTemplate.java   
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);
    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);
  } 
}
项目:incubator-netbeans    文件:CheckoutIndex.java   
public void checkoutEntry (Repository repository, File file, DirCacheEntry e, ObjectReader od) throws IOException, GitException {
    // ... create/overwrite this file ...
    if (!ensureParentFolderExists(file.getParentFile())) {
        return;
    }

    boolean exists = file.exists();
    if (exists && e.getFileMode() == FileMode.SYMLINK) {
        monitor.notifyWarning(MessageFormat.format(Utils.getBundle(CheckoutIndex.class).getString("MSG_Warning_SymLink"), file.getAbsolutePath())); //NOI18N
        return;
    }

    if (Utils.isFromNested(e.getFileMode().getBits())) {
        if (!exists) {
            file.mkdirs();
        }
    } else {
        if (exists && file.isDirectory()) {
            monitor.notifyWarning(MessageFormat.format(Utils.getBundle(CheckoutIndex.class).getString("MSG_Warning_ReplacingDirectory"), file.getAbsolutePath())); //NOI18N
            Utils.deleteRecursively(file);
        }
        file.createNewFile();
        if (file.isFile()) {
            DirCacheCheckout.checkoutEntry(repository, file, e, od);
        } else {
            monitor.notifyError(MessageFormat.format(Utils.getBundle(CheckoutIndex.class).getString("MSG_Warning_CannotCreateFile"), file.getAbsolutePath())); //NOI18N
        }
    }
}
项目:incubator-netbeans    文件:AddTest.java   
public void testAddMissingSymlink () throws Exception {
    if (isWindows()) {
        return;
    }
    String path = "folder/file";
    File f = new File(workDir, path);

    // try with commandline client
    File link = new File(workDir, "link");
    Files.createSymbolicLink(Paths.get(link.getAbsolutePath()), Paths.get(path));
    getClient(workDir).add(new File[] { link }, NULL_PROGRESS_MONITOR);
    DirCacheEntry e = repository.readDirCache().getEntry(link.getName());
    assertEquals(FileMode.SYMLINK, e.getFileMode());
    assertEquals(0, e.getLength());
    ObjectReader reader = repository.getObjectDatabase().newReader();
    assertTrue(reader.has(e.getObjectId()));
    byte[] bytes = reader.open(e.getObjectId()).getBytes();
    assertEquals(path, RawParseUtils.decode(bytes));
    reader.release();
}
项目:centraldogma    文件:GitRepository.java   
private Map<String, Change<?>> blockingPreviewDiff(Revision baseRevision, Iterable<Change<?>> changes) {
    requireNonNull(baseRevision, "baseRevision");
    requireNonNull(changes, "changes");
    baseRevision = blockingNormalize(baseRevision);

    try (ObjectReader reader = jGitRepository.newObjectReader();
         RevWalk revWalk = new RevWalk(reader);
         DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE)) {

        final ObjectId baseTreeId = toTreeId(revWalk, baseRevision);
        final DirCache dirCache = DirCache.newInCore();
        final int numEdits = applyChanges(baseRevision, baseTreeId, dirCache, changes);
        if (numEdits == 0) {
            return Collections.emptyMap();
        }

        CanonicalTreeParser p = new CanonicalTreeParser();
        p.reset(reader, baseTreeId);
        diffFormatter.setRepository(jGitRepository);
        List<DiffEntry> result = diffFormatter.scan(p, new DirCacheIterator(dirCache));
        return toChangeMap(result);
    } catch (IOException e) {
        throw new StorageException("failed to perform a dry-run diff", e);
    }
}
项目:pdi-git-plugin    文件:UIGit.java   
private AbstractTreeIterator getTreeIterator( String commitId ) throws Exception {
  if ( commitId == null ) {
    return new EmptyTreeIterator();
  }
  if ( commitId.equals( WORKINGTREE ) ) {
    return new FileTreeIterator( git.getRepository() );
  } else if ( commitId.equals( INDEX ) ) {
    return new DirCacheIterator( git.getRepository().readDirCache() );
  } else {
    ObjectId id = git.getRepository().resolve( commitId );
    if ( id == null ) { // commitId does not exist
      return new EmptyTreeIterator();
    } else {
      CanonicalTreeParser treeIterator = new CanonicalTreeParser();
      try ( RevWalk rw = new RevWalk( git.getRepository() ) ) {
        RevTree tree = rw.parseTree( id );
        try ( ObjectReader reader = git.getRepository().newObjectReader() ) {
          treeIterator.reset( reader, tree.getId() );
        }
      }
      return treeIterator;
    }
  }
}
项目:WebIDE-Backend    文件:RewordActionHandler.java   
@Override
public RebaseResponse extractMessage(Repository repository) throws IOException {
    List<RebaseTodoLine> rebaseTodoLines = repository.readRebaseTodo(getRebasePath(repository, DONE), false);
    // the last rebase_todo_line
    RebaseTodoLine line = rebaseTodoLines.get(rebaseTodoLines.size() - 1);

    try (RevWalk walk = new RevWalk(repository)) {
        ObjectReader or = repository.newObjectReader();
        RevCommit commitToPick = walk.parseCommit(or.resolve(line.getCommit()).iterator().next());

        String oldMessage = commitToPick.getFullMessage();

        RebaseResponse response = new RebaseResponse(false, RebaseResponse.Status.INTERACTIVE_EDIT);
        response.setMessage(oldMessage);

        return response;
    }
}
项目:release-maven-plugin-parent    文件:JGitDiscoveryTest.java   
@Test public void name() throws IOException, GitAPIException {
    ObjectId head = repo.resolve("HEAD^{tree}");
    ObjectId oldHead = repo.resolve("HEAD^^{tree}");


    ObjectReader reader = repo.newObjectReader();

    CanonicalTreeParser prevParser = new CanonicalTreeParser();
    prevParser.reset(reader, oldHead);

    CanonicalTreeParser headParser = new CanonicalTreeParser();
    headParser.reset(reader, head);

    List<DiffEntry> diffs = new Git(repo).diff()
            .setNewTree(headParser)
            .setOldTree(prevParser)
            .call();

    for (DiffEntry entry : diffs)
        System.out.println(entry);
}
项目:sonar-scm-git    文件:GitScmProvider.java   
private AbstractTreeIterator prepareTreeParser(Repository repo, Ref targetRef) throws IOException {
  try (RevWalk walk = newRevWalk(repo)) {
    walk.markStart(walk.parseCommit(targetRef.getObjectId()));
    walk.markStart(walk.parseCommit(repo.exactRef("HEAD").getObjectId()));
    walk.setRevFilter(RevFilter.MERGE_BASE);
    RevCommit base = walk.parseCommit(walk.next());

    CanonicalTreeParser treeParser = new CanonicalTreeParser();
    try (ObjectReader objectReader = repo.newObjectReader()) {
      treeParser.reset(objectReader, base.getTree());
    }

    walk.dispose();

    return treeParser;
  }
}
项目:multi-module-maven-release-plugin    文件:JGitDiscoveryTest.java   
@Test public void name() throws IOException, GitAPIException {
    ObjectId head = repo.resolve("HEAD^{tree}");
    ObjectId oldHead = repo.resolve("HEAD^^{tree}");


    ObjectReader reader = repo.newObjectReader();

    CanonicalTreeParser prevParser = new CanonicalTreeParser();
    prevParser.reset(reader, oldHead);

    CanonicalTreeParser headParser = new CanonicalTreeParser();
    headParser.reset(reader, head);

    List<DiffEntry> diffs = new Git(repo).diff()
            .setNewTree(headParser)
            .setOldTree(prevParser)
            .call();

    for (DiffEntry entry : diffs)
        System.out.println(entry);
}
项目:che    文件:JGitDiffPage.java   
/**
 * Show changes between specified revision and empty tree.
 *
 * @param commitId id of commit
 * @param formatter diff formatter
 * @return list of diff entries
 * @throws IOException if any i/o errors occurs
 */
private List<DiffEntry> emptyToCommit(String commitId, DiffFormatter formatter)
    throws IOException {
  ObjectId commit = repository.resolve(commitId);
  checkArgument(commit != null, "Invalid commit id " + commitId);
  RevTree tree;
  try (RevWalk revWalkA = new RevWalk(repository)) {
    tree = revWalkA.parseTree(commit);
  }

  List<DiffEntry> diff;
  try (ObjectReader reader = repository.newObjectReader()) {
    CanonicalTreeParser iterator = new CanonicalTreeParser();
    iterator.reset(reader, tree);
    diff = formatter.scan(new EmptyTreeIterator(), iterator);
  }
  return diff;
}
项目:GitFx    文件:GitRepoMetaData.java   
public String getDiffBetweenCommits(int commitIndex) throws IOException,GitAPIException{
    if(commitIndex+1==commitCount)
        return "Nothing to Diff. This is first commit";
    AbstractTreeIterator current = prepareTreeParser(repository,commitSHA.get(commitIndex));
    AbstractTreeIterator parent = prepareTreeParser(repository,commitSHA.get(++commitIndex));
    ObjectReader reader = repository.newObjectReader();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    // finally get the list of changed files
    Git git = new Git(repository) ;
    List<DiffEntry> diff = git.diff().
            setOldTree(parent).
            setNewTree(current).
            //TODO Set the path filter to filter out the selected file
            //setPathFilter(PathFilter.create("README.md")).
            call();
    for (DiffEntry entry : diff) {
        System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
        DiffFormatter formatter = new DiffFormatter(byteStream) ;
            formatter.setRepository(repository);
            formatter.format(entry);
        }
   // System.out.println(byteStream.toString());
    String diffContent = byteStream.toString();
    return byteStream.toString();
}
项目:gerrit    文件:PatchListLoader.java   
private Optional<PatchListEntry> getPatchListEntry(
    ObjectReader objectReader,
    DiffFormatter diffFormatter,
    DiffEntry diffEntry,
    RevTree treeA,
    RevTree treeB,
    Set<ContextAwareEdit> editsDueToRebase)
    throws IOException {
  FileHeader fileHeader = toFileHeader(key.getNewId(), diffFormatter, diffEntry);
  long oldSize = getFileSize(objectReader, diffEntry.getOldMode(), diffEntry.getOldPath(), treeA);
  long newSize = getFileSize(objectReader, diffEntry.getNewMode(), diffEntry.getNewPath(), treeB);
  Set<Edit> contentEditsDueToRebase = getContentEdits(editsDueToRebase);
  PatchListEntry patchListEntry =
      newEntry(treeA, fileHeader, contentEditsDueToRebase, newSize, newSize - oldSize);
  // All edits in a file are due to rebase -> exclude the file from the diff.
  if (EditTransformer.toEdits(patchListEntry).allMatch(editsDueToRebase::contains)) {
    return Optional.empty();
  }
  return Optional.of(patchListEntry);
}
项目:gerrit    文件:ReviewNoteMerger.java   
@Override
public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter)
    throws IOException {
  if (ours == null) {
    return theirs;
  }
  if (theirs == null) {
    return ours;
  }
  if (ours.getData().equals(theirs.getData())) {
    return ours;
  }

  ObjectLoader lo = reader.open(ours.getData());
  byte[] sep = new byte[] {'\n'};
  ObjectLoader lt = reader.open(theirs.getData());
  try (ObjectStream os = lo.openStream();
      ByteArrayInputStream b = new ByteArrayInputStream(sep);
      ObjectStream ts = lt.openStream();
      UnionInputStream union = new UnionInputStream(os, b, ts)) {
    ObjectId noteData =
        inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(), union);
    return new Note(ours, noteData);
  }
}
项目:gerrit    文件:RobotCommentNotes.java   
@Override
protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
  metaId = handle.id();
  if (metaId == null) {
    loadDefaults();
    return;
  }
  metaId = metaId.copy();

  RevCommit tipCommit = handle.walk().parseCommit(metaId);
  ObjectReader reader = handle.walk().getObjectReader();
  revisionNoteMap =
      RevisionNoteMap.parseRobotComments(args.noteUtil, reader, NoteMap.read(reader, tipCommit));
  ListMultimap<RevId, RobotComment> cs = MultimapBuilder.hashKeys().arrayListValues().build();
  for (RobotCommentsRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
    for (RobotComment c : rn.getComments()) {
      cs.put(new RevId(c.revId), c);
    }
  }
  comments = ImmutableListMultimap.copyOf(cs);
}
项目:gerrit    文件:DraftCommentNotes.java   
@Override
protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
  ObjectId rev = handle.id();
  if (rev == null) {
    loadDefaults();
    return;
  }

  RevCommit tipCommit = handle.walk().parseCommit(rev);
  ObjectReader reader = handle.walk().getObjectReader();
  revisionNoteMap =
      RevisionNoteMap.parse(
          args.noteUtil,
          getChangeId(),
          reader,
          NoteMap.read(reader, tipCommit),
          PatchLineComment.Status.DRAFT);
  ListMultimap<RevId, Comment> cs = MultimapBuilder.hashKeys().arrayListValues().build();
  for (ChangeRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
    for (Comment c : rn.getComments()) {
      cs.put(new RevId(c.revId), c);
    }
  }
  comments = ImmutableListMultimap.copyOf(cs);
}
项目:gerrit    文件:ChangeNotesParser.java   
private void parseNotes() throws IOException, ConfigInvalidException {
  ObjectReader reader = walk.getObjectReader();
  ChangeNotesCommit tipCommit = walk.parseCommit(tip);
  revisionNoteMap =
      RevisionNoteMap.parse(
          noteUtil,
          id,
          reader,
          NoteMap.read(reader, tipCommit),
          PatchLineComment.Status.PUBLISHED);
  Map<RevId, ChangeRevisionNote> rns = revisionNoteMap.revisionNotes;

  for (Map.Entry<RevId, ChangeRevisionNote> e : rns.entrySet()) {
    for (Comment c : e.getValue().getComments()) {
      comments.put(e.getKey(), c);
    }
  }

  for (PatchSet ps : patchSets.values()) {
    ChangeRevisionNote rn = rns.get(ps.getRevision());
    if (rn != null && rn.getPushCert() != null) {
      ps.setPushCertificate(rn.getPushCert());
    }
  }
}
项目:gerrit    文件:RevisionNoteMap.java   
static RevisionNoteMap<ChangeRevisionNote> parse(
    ChangeNoteUtil noteUtil,
    Change.Id changeId,
    ObjectReader reader,
    NoteMap noteMap,
    PatchLineComment.Status status)
    throws ConfigInvalidException, IOException {
  Map<RevId, ChangeRevisionNote> result = new HashMap<>();
  for (Note note : noteMap) {
    ChangeRevisionNote rn =
        new ChangeRevisionNote(noteUtil, changeId, reader, note.getData(), status);
    rn.parse();
    result.put(new RevId(note.name()), rn);
  }
  return new RevisionNoteMap<>(noteMap, ImmutableMap.copyOf(result));
}
项目:gerrit    文件:CommitReceivedEvent.java   
public CommitReceivedEvent(
    ReceiveCommand command,
    Project project,
    String refName,
    ObjectReader reader,
    ObjectId commitId,
    IdentifiedUser user)
    throws IOException {
  this();
  this.command = command;
  this.project = project;
  this.refName = refName;
  this.revWalk = new RevWalk(reader);
  this.commit = revWalk.parseCommit(commitId);
  this.user = user;
  revWalk.parseBody(commit);
}
项目:gerrit    文件:Files.java   
private List<String> query(RevisionResource resource)
    throws RepositoryNotFoundException, IOException {
  Project.NameKey project = resource.getChange().getProject();
  try (Repository git = gitManager.openRepository(project);
      ObjectReader or = git.newObjectReader();
      RevWalk rw = new RevWalk(or);
      TreeWalk tw = new TreeWalk(or)) {
    RevCommit c =
        rw.parseCommit(ObjectId.fromString(resource.getPatchSet().getRevision().get()));

    tw.addTree(c.getTree());
    tw.setRecursive(true);
    List<String> paths = new ArrayList<>();
    while (tw.next() && paths.size() < 20) {
      String s = tw.getPathString();
      if (s.contains(query)) {
        paths.add(s);
      }
    }
    return paths;
  }
}
项目:gerrit    文件:AbstractQueryChangesTest.java   
protected Change newPatchSet(TestRepository<Repo> repo, Change c) throws Exception {
  // Add a new file so the patch set is not a trivial rebase, to avoid default
  // Code-Review label copying.
  int n = c.currentPatchSetId().get() + 1;
  RevCommit commit =
      repo.parseBody(repo.commit().message("message").add("file" + n, "contents " + n).create());

  PatchSetInserter inserter =
      patchSetFactory
          .create(changeNotesFactory.createChecked(db, c), new PatchSet.Id(c.getId(), n), commit)
          .setNotify(NotifyHandling.NONE)
          .setFireRevisionCreated(false)
          .setValidate(false);
  try (BatchUpdate bu = updateFactory.create(db, c.getProject(), user, TimeUtil.nowTs());
      ObjectInserter oi = repo.getRepository().newObjectInserter();
      ObjectReader reader = oi.newReader();
      RevWalk rw = new RevWalk(reader)) {
    bu.setRepository(repo.getRepository(), rw, oi);
    bu.addOp(c.getId(), inserter);
    bu.execute();
  }

  return inserter.getChange();
}
项目:appformer    文件:ListDiffs.java   
public List<DiffEntry> execute() {
    if (newRef == null || git.getRepository() == null) {
        return emptyList();
    }

    try (final ObjectReader reader = git.getRepository().newObjectReader()) {
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        if (oldRef != null) {
            oldTreeIter.reset(reader,
                              oldRef);
        }
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader,
                          newRef);
        return new CustomDiffCommand(git).setNewTree(newTreeIter).setOldTree(oldTreeIter).setShowNameAndStatusOnly(true).call();
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:neembuu-uploader    文件:UpdaterGenerator.java   
/**
 * Populate all the files to update, if the system should update.
 */
private void populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");

        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();

        pluginsToUpdate = new ArrayList<PluginToUpdate>();

        checkDiffEmpty(diffs);

    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:ninja_chic-    文件:LineContextDiffer.java   
private byte[] open(ObjectReader reader, FileMode mode,
                    AbbreviatedObjectId id) throws IOException {
    if (mode == FileMode.MISSING)
        return new byte[] { };

    if (mode.getObjectType() != Constants.OBJ_BLOB)
        return new byte[] { };

    if (!id.isComplete()) {
        Collection<ObjectId> ids = reader.resolve(id);
        if (ids.size() == 1)
            id = AbbreviatedObjectId.fromObjectId(ids.iterator().next());
        else if (ids.size() == 0)
            throw new MissingObjectException(id, Constants.OBJ_BLOB);
        else
            throw new AmbiguousObjectException(id, ids);
    }

    ObjectLoader ldr = reader.open(id.toObjectId());
    return ldr.getCachedBytes(bigFileThreshold);
}
项目:gitrecommender    文件:UpdateLog.java   
private static AbstractTreeIterator prepareTreeParser(
        Repository repository, RevCommit commit) throws IOException,
        MissingObjectException, IncorrectObjectTypeException {
    // from the commit we can build the tree which allows us to construct
    // the TreeParser
    RevWalk walk = new RevWalk(repository);
    RevTree tree = walk.parseTree(commit.getTree().getId());
    CanonicalTreeParser result = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    try {
        result.reset(reader, tree.getId());
    } finally {
        reader.release();
    }
    walk.dispose();
    return result;
}
项目:gitrecommender    文件:ExtractLog.java   
private static AbstractTreeIterator prepareTreeParser(
        Repository repository, RevCommit commit) throws IOException,
        MissingObjectException, IncorrectObjectTypeException {
    // from the commit we can build the tree which allows us to construct
    // the TreeParser
    RevWalk walk = new RevWalk(repository);
    RevTree tree = walk.parseTree(commit.getTree().getId());
    CanonicalTreeParser result = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    try {
        result.reset(reader, tree.getId());
    } finally {
        reader.release();
    }
    walk.dispose();
    return result;
}
项目:gitiles    文件:LogServlet.java   
private static Optional<ObjectId> getStart(ListMultimap<String, String> params,
    ObjectReader reader) throws IOException {
  List<String> values = params.get(START_PARAM);
  switch (values.size()) {
    case 0:
      return Optional.absent();
    case 1:
      Collection<ObjectId> ids = reader.resolve(AbbreviatedObjectId.fromString(values.get(0)));
      if (ids.size() != 1) {
        return null;
      }
      return Optional.of(Iterables.getOnlyElement(ids));
    default:
      return null;
  }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
public void addNote(String note, String namespace) throws GitException {
    try (Repository repo = getRepository()) {
        ObjectId head = repo.resolve(HEAD); // commit to put a note on

        AddNoteCommand cmd = git(repo).notesAdd();
        cmd.setMessage(normalizeNote(note));
        cmd.setNotesRef(qualifyNotesNamespace(namespace));
        try (ObjectReader or = repo.newObjectReader();
             RevWalk walk = new RevWalk(or)) {
            cmd.setObjectId(walk.parseAny(head));
            cmd.call();
        }
    } catch (GitAPIException | IOException e) {
        throw new GitException(e);
    }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
public void appendNote(String note, String namespace) throws GitException {
    try (Repository repo = getRepository()) {
        ObjectId head = repo.resolve(HEAD); // commit to put a note on

        ShowNoteCommand cmd = git(repo).notesShow();
        cmd.setNotesRef(qualifyNotesNamespace(namespace));
        try (ObjectReader or = repo.newObjectReader();
             RevWalk walk = new RevWalk(or)) {
            cmd.setObjectId(walk.parseAny(head));
            Note n = cmd.call();

            if (n==null) {
                addNote(note,namespace);
            } else {
                ObjectLoader ol = or.open(n.getData());
                StringWriter sw = new StringWriter();
                IOUtils.copy(new InputStreamReader(ol.openStream(),CHARSET),sw);
                sw.write("\n");
                addNote(sw.toString() + normalizeNote(note), namespace);
            }
        }
    } catch (GitAPIException | IOException e) {
        throw new GitException(e);
    }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
public List<IndexEntry> getSubmodules(String treeIsh) throws GitException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk w = new RevWalk(or)) {
        List<IndexEntry> r = new ArrayList<>();

        RevTree t = w.parseTree(repo.resolve(treeIsh));
        SubmoduleWalk walk = new SubmoduleWalk(repo);
        walk.setTree(t);
        walk.setRootTree(t);
        while (walk.next()) {
            r.add(new IndexEntry(walk));
        }

        return r;
    } catch (IOException e) {
        throw new GitException(e);
    }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
@Deprecated
public ObjectId mergeBase(ObjectId id1, ObjectId id2) throws InterruptedException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk walk = new RevWalk(or)) {
        walk.setRetainBody(false);  // we don't need the body for this computation
        walk.setRevFilter(RevFilter.MERGE_BASE);

        walk.markStart(walk.parseCommit(id1));
        walk.markStart(walk.parseCommit(id2));

        RevCommit base = walk.next();
        if (base==null)     return null;    // no common base
        return base.getId();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
@Deprecated
public String getAllLogEntries(String branch) throws InterruptedException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk walk = new RevWalk(or)) {
        StringBuilder w = new StringBuilder();
        markAllRefs(walk);
        walk.setRetainBody(false);

        for (RevCommit c : walk) {
            w.append('\'').append(c.name()).append('#').append(c.getCommitTime()).append("'\n");
        }
        return w.toString().trim();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
@Deprecated
public List<IndexEntry> lsTree(String treeIsh, boolean recursive) throws GitException, InterruptedException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk w = new RevWalk(or)) {
        TreeWalk tree = new TreeWalk(or);
        tree.addTree(w.parseTree(repo.resolve(treeIsh)));
        tree.setRecursive(recursive);

        List<IndexEntry> r = new ArrayList<>();
        while (tree.next()) {
            RevObject rev = w.parseAny(tree.getObjectId(0));
            r.add(new IndexEntry(
                    String.format("%06o", tree.getRawMode(0)),
                    typeString(rev.getType()),
                    tree.getObjectId(0).name(),
                    tree.getNameString()));
        }
        return r;
    } catch (IOException e) {
        throw new GitException(e);
    }
}
项目:jgit-cookbook    文件:DiffFilesInCommit.java   
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(repository.resolve(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader reader = repository.newObjectReader()) {
            treeParser.reset(reader, tree.getId());
        }

        walk.dispose();

        return treeParser;
    }
}
项目:jgit-cookbook    文件:ShowFileDiff.java   
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader reader = repository.newObjectReader()) {
            treeParser.reset(reader, tree.getId());
        }

        walk.dispose();

        return treeParser;
    }
}
项目:jgit-cookbook    文件:ShowBranchDiff.java   
private static AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    Ref head = repository.exactRef(ref);
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(head.getObjectId());
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader reader = repository.newObjectReader()) {
            treeParser.reset(reader, tree.getId());
        }

        walk.dispose();

        return treeParser;
    }
}
项目:jgit-cookbook    文件:DiffRenamedFile.java   
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(repository.resolve(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader reader = repository.newObjectReader()) {
            treeParser.reset(reader, tree.getId());
        }

        walk.dispose();

        return treeParser;
    }
}
项目:jgit-cookbook    文件:JGitBugTest.java   
@Test
public void testRevWalkDisposeClosesReader() throws IOException {
    try (Repository repo = CookbookHelper.openJGitCookbookRepository()) {
        try (ObjectReader reader = repo.newObjectReader()) {
            try (RevWalk walk = new RevWalk(reader)) {
                walk.dispose();

                Ref head = repo.exactRef("refs/heads/master");
                System.out.println("Found head: " + head);

                ObjectLoader loader = reader.open(head.getObjectId());
                assertNotNull(loader);
            }
        }
    }
}
项目:SGit    文件:CommitDiffTask.java   
private AbstractTreeIterator getTreeIterator(Repository repo, String commit) throws IOException {
    if (commit.equals("dircache")) {
        return new DirCacheIterator(repo.readDirCache());
    }
    if (commit.equals("filetree")) {
        return new FileTreeIterator(repo);
    }
    ObjectId treeId = repo.resolve(commit + "^{tree}");

    if (treeId == null) {
        throw new NullPointerException();
    }

    CanonicalTreeParser treeIter = new CanonicalTreeParser();
    ObjectReader reader = repo.newObjectReader();

    treeIter.reset(reader, treeId);
    return treeIter;
}
项目:incubator-netbeans    文件:ExportDiffCommand.java   
private AbstractTreeIterator getIterator (String commit, ObjectReader or) throws IOException, GitException {
    Repository repository = getRepository();
    switch (commit) {
        case Constants.HEAD:
            return getHeadIterator(or);
        case GitClient.INDEX:
            return new DirCacheIterator(repository.readDirCache());
        case GitClient.WORKING_TREE:
            return new FileTreeIterator(repository);
        default:
            CanonicalTreeParser p = new CanonicalTreeParser();
            p.reset(or, Utils.findCommit(repository, commit).getTree());
            return p;
    }
}
项目:incubator-netbeans    文件:CheckoutIndex.java   
public void checkout () throws IOException, GitException {
    TreeWalk treeWalk = new TreeWalk(repository);
    Collection<String> relativePaths = Utils.getRelativePaths(repository.getWorkTree(), roots);
    if (!relativePaths.isEmpty()) {
        treeWalk.setFilter(PathFilterGroup.createFromStrings(relativePaths));
    }
    treeWalk.setRecursive(true);
    treeWalk.reset();
    treeWalk.addTree(new DirCacheIterator(cache));
    treeWalk.addTree(new FileTreeIterator(repository));
    String lastAddedPath = null;
    ObjectReader od = repository.newObjectReader();
    try {
    while (treeWalk.next() && !monitor.isCanceled()) {
        File path = new File(repository.getWorkTree(), treeWalk.getPathString());
        if (treeWalk.getPathString().equals(lastAddedPath)) {
            // skip conflicts
            continue;
        } else {
            lastAddedPath = treeWalk.getPathString();
        }
        DirCacheIterator dit = treeWalk.getTree(0, DirCacheIterator.class);
        FileTreeIterator fit = treeWalk.getTree(1, FileTreeIterator.class);
        if (dit != null && (recursively || directChild(roots, repository.getWorkTree(), path)) && (fit == null || fit.isModified(dit.getDirCacheEntry(), checkContent, od))) {
            // update entry
            listener.notifyFile(path, treeWalk.getPathString());
            checkoutEntry(repository, path, dit.getDirCacheEntry(), od);
        }
    }
    } finally {
        od.release();
        treeWalk.release();
    }
}