Java Code Examples for org.eclipse.jgit.lib.Repository#newObjectReader()

The following examples show how to use org.eclipse.jgit.lib.Repository#newObjectReader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Source File: GitNoteWriter.java    From git-appraise-eclipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Private ctor. Use the static factory methods.
 */
private GitNoteWriter(String reviewHash, final Repository repo, String ref, PersonIdent author) {
  this.ref = ref;
  this.repo = repo;
  this.author = author;

  revWalk = new RevWalk(repo);
  inserter = repo.newObjectInserter();
  reader = repo.newObjectReader();

  try {
    ObjectId reviewRefObjId = repo.resolve(reviewHash);
    this.reviewCommit = revWalk.parseCommit(reviewRefObjId);
  } catch (Exception e) {
    logger.log(Level.SEVERE, "Failed to init note writer for commit " + reviewHash, e);
    throw new RuntimeException(e);
  }
}
 
Example 3
Source File: GitUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings(value={"RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification="JDK11 produces different bytecode - https://github.com/spotbugs/spotbugs/issues/756")
static byte[] readFile(Repository repository, String ref, String filePath) {
    try (ObjectReader reader = repository.newObjectReader()) {
        ObjectId branchRef = repository.resolve(ref); // repository.exactRef(ref);
        if (branchRef != null) { // for empty repositories, branchRef may be null
            RevWalk revWalk = new RevWalk(repository);
            RevCommit commit = revWalk.parseCommit(branchRef);
            // and using commit's tree find the path
            RevTree tree = commit.getTree();
            TreeWalk treewalk = TreeWalk.forPath(reader, filePath, tree);
            if (treewalk != null) {
                // use the blob id to read the file's data
                return reader.open(treewalk.getObjectId(0)).getBytes();
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return null;
}
 
Example 4
Source File: RewordActionHandler.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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;
    }
}
 
Example 5
Source File: JGitTemplate.java    From piper with Apache License 2.0 6 votes vote down vote up
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);
    if(id == null) {
      return List.of();
    }
    RevCommit commit = walk.parseCommit(id);
    RevTree tree = commit.getTree();
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
      String path = treeWalk.getPathString();        
      if(!path.startsWith(".") && (searchPaths == null || searchPaths.size() == 0 || 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);
  } 
}
 
Example 6
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private boolean 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();
        
        if (diffs.isEmpty()) {
            System.out.println("No diff");
            return false;
        }else{
            return true;
        }
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }return true;//assume true
}
 
Example 7
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static List<DiffEntry> diff(Repository repository, AnyObjectId oldRevId, AnyObjectId newRevId) {
	List<DiffEntry> diffs = new ArrayList<>();
	try (	DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);
			RevWalk revWalk = new RevWalk(repository);
			ObjectReader reader = repository.newObjectReader();) {
    	diffFormatter.setRepository(repository);
    	diffFormatter.setDetectRenames(true);
    	diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
    	
    	CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    	if (!oldRevId.equals(ObjectId.zeroId()))
    		oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree());
    	
    	CanonicalTreeParser newTreeParser = new CanonicalTreeParser();
    	if (!newRevId.equals(ObjectId.zeroId()))
    		newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree());
    	
    	for (DiffEntry entry: diffFormatter.scan(oldTreeParser, newTreeParser)) {
    		if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
    				|| !Objects.equal(entry.getOldMode(), entry.getNewMode())
    				|| entry.getOldId()==null || !entry.getOldId().isComplete()
    				|| entry.getNewId()== null || !entry.getNewId().isComplete()
    				|| !entry.getOldId().equals(entry.getNewId())) {
    			diffs.add(entry);
    		}
    	}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}			
	return diffs;
}
 
Example 8
Source File: PGA.java    From coming with MIT License 5 votes vote down vote up
private 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
    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(repository.resolve(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());

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

    walk.dispose();

    return treeParser;
}
 
Example 9
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator getTreeIterator(Repository db, String name) throws IOException {
	final ObjectId id = db.resolve(name);
	if (id == null)
		throw new IllegalArgumentException(name);
	final CanonicalTreeParser p = new CanonicalTreeParser();
	final ObjectReader or = db.newObjectReader();
	try {
		p.reset(or, new RevWalk(db).parseTree(id));
		return p;
	} finally {
		or.close();
	}
}
 
Example 10
Source File: JGitTemplate.java    From piper with Apache License 2.0 5 votes vote down vote up
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);
    }
    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));
  }
}
 
Example 11
Source File: GitRepoMetaData.java    From GitFx with Apache License 2.0 5 votes vote down vote up
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException,
        MissingObjectException,
        IncorrectObjectTypeException {
    RevWalk walk = new RevWalk(repository) ;
    RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());
    CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    ObjectReader oldReader = repository.newObjectReader();
    oldTreeParser.reset(oldReader, tree.getId());
    walk.dispose();
    return oldTreeParser;
}
 
Example 12
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public DiffConflictedFile getDiffForConflictedFile(String siteId, String path)
        throws ServiceLayerException, CryptoException {
    DiffConflictedFile diffResult = new DiffConflictedFile();
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    try (Git git = new Git(repo)) {
        List<ObjectId> mergeHeads = repo.readMergeHeads();
        ObjectId mergeCommitId = mergeHeads.get(0);
        logger.debug("Get content for studio version of conflicted file " + path + " for site " + siteId);
        InputStream studioVersionIs = contentRepository.getContentVersion(siteId, path, Constants.HEAD);
        diffResult.setStudioVersion(IOUtils.toString(studioVersionIs));
        logger.debug("Get content for remote version of conflicted file " + path + " for site " + siteId);
        InputStream remoteVersionIs = contentRepository.getContentVersion(siteId, path, mergeCommitId.getName());
        diffResult.setRemoteVersion(IOUtils.toString(remoteVersionIs));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        logger.debug("Get diff between studio and remote version of conflicted file " + path + " for site "
                + siteId);
        RevTree headTree = helper.getTreeForCommit(repo, Constants.HEAD);
        RevTree remoteTree = helper.getTreeForCommit(repo, mergeCommitId.getName());

        try (ObjectReader reader = repo.newObjectReader()) {
            CanonicalTreeParser headCommitTreeParser = new CanonicalTreeParser();
            CanonicalTreeParser remoteCommitTreeParser = new CanonicalTreeParser();
            headCommitTreeParser.reset(reader, headTree.getId());
            remoteCommitTreeParser.reset(reader, remoteTree.getId());

            // Diff the two commit Ids
            git.diff()
                    .setPathFilter(PathFilter.create(helper.getGitPath(path)))
                    .setOldTree(headCommitTreeParser)
                    .setNewTree(remoteCommitTreeParser)
                    .setOutputStream(baos)
                    .call();
            diffResult.setDiff(baos.toString());
        }


    } catch (IOException | GitAPIException e) {
        logger.error("Error while getting diff for conflicting file " + path + " site " + siteId);
        throw new ServiceLayerException("Error while getting diff for conflicting file " + path + " site " + siteId);
    }
    return diffResult;
}
 
Example 13
Source File: CherryPickCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void applySteps (List<RebaseTodoLine> steps, boolean skipFirstStep) throws GitAPIException, IOException {
    Repository repository = getRepository();
    ObjectReader or = repository.newObjectReader();
    CherryPickResult res = null;
    boolean skipped = false;
    List<Ref> cherryPickedRefs = new ArrayList<>();
    for (Iterator<RebaseTodoLine> it = steps.iterator(); it.hasNext();) {
        RebaseTodoLine step = it.next();
        if (step.getAction() == RebaseTodoLine.Action.PICK) {
            if (skipFirstStep && !skipped) {
                it.remove();
                writeTodoFile(repository, steps);
                skipped = true;
                continue;
            }
            Collection<ObjectId> ids = or.resolve(step.getCommit());
            if (ids.size() != 1) {
                throw new JGitInternalException("Could not resolve uniquely the abbreviated object ID");
            }
            org.eclipse.jgit.api.CherryPickCommand command = new Git(repository).cherryPick();
            command.include(ids.iterator().next());
            if (workAroundStrategyIssue) {
                command.setStrategy(new FailuresDetectRecurciveStrategy());
            }
            res = command.call();
            if (res.getStatus() == CherryPickResult.CherryPickStatus.OK) {
                it.remove();
                writeTodoFile(repository, steps);
                cherryPickedRefs.addAll(res.getCherryPickedRefs());
            } else {
                break;
            }
        } else {
            it.remove();
        }
    }
    if (res == null) {
        result = createCustomResult(GitCherryPickResult.CherryPickStatus.OK, cherryPickedRefs);
    } else {
        result = createResult(res, cherryPickedRefs);
    }
    if (steps.isEmpty()) {
        // sequencer no longer needed
        Utils.deleteRecursively(getSequencerFolder());
    }
}
 
Example 14
Source File: ExportDiffCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
  protected void run() throws GitException {
      Repository repository = getRepository();
      String workTreePath = repository.getWorkTree().getAbsolutePath();
      try (DiffFormatter formatter = new DiffFormatter(out);
          ObjectReader or = repository.newObjectReader()) {
          formatter.setRepository(repository);
          Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots);
          if (!pathFilters.isEmpty()) {
              formatter.setPathFilter(PathFilterGroup.create(pathFilters));
          }
          if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
              // work-around for autocrlf
              formatter.setDiffComparator(new AutoCRLFComparator());
          }
          AbstractTreeIterator firstTree = getIterator(firstCommit, or);
          AbstractTreeIterator secondTree = getIterator(secondCommit, or);
          List<DiffEntry> diffEntries;
          if (secondTree instanceof WorkingTreeIterator) {
              // remote when fixed in JGit, see ExportDiffTest.testDiffRenameDetectionProblem
              formatter.setDetectRenames(false);
              diffEntries = formatter.scan(firstTree, secondTree);
              formatter.setDetectRenames(true);
              RenameDetector detector = formatter.getRenameDetector();
              detector.reset();
              detector.addAll(diffEntries);
diffEntries = detector.compute(new ContentSource.Pair(ContentSource.create(or), ContentSource.create((WorkingTreeIterator) secondTree)), NullProgressMonitor.INSTANCE);
          } else {
              formatter.setDetectRenames(true);
              diffEntries = formatter.scan(firstTree, secondTree);
          }
          for (DiffEntry ent : diffEntries) {
              if (monitor.isCanceled()) {
                  break;
              }
              listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath());
              formatter.format(ent);
          }
          formatter.flush();
      } catch (IOException ex) {
          throw new GitException(ex);
      }
  }
 
Example 15
Source File: GitServiceImpl.java    From apidiff with MIT License 4 votes vote down vote up
@Override
public Map<ChangeType, List<GitFile>> fileTreeDiff(Repository repository, RevCommit commitNew) throws Exception {
       
	Map<ChangeType, List<GitFile>> mapDiff = new HashMap<ChangeType, List<GitFile>>();
	mapDiff.put(ChangeType.ADD, new ArrayList<>());
	mapDiff.put(ChangeType.COPY, new ArrayList<>());
	mapDiff.put(ChangeType.DELETE, new ArrayList<>());
	mapDiff.put(ChangeType.MODIFY, new ArrayList<>());
	mapDiff.put(ChangeType.RENAME, new ArrayList<>());
	
	if(commitNew.getParentCount() == 0){
		this.logger.warn("Commit don't have parent [commitId="+commitNew.getId().getName()+"]");
		return mapDiff;
	}
      
	ObjectId headOld = commitNew.getParent(0).getTree(); //Commit pai no grafo.
	ObjectId headNew = commitNew.getTree(); //Commit corrente.

       // prepare the two iterators to compute the diff between
	ObjectReader reader = repository.newObjectReader();
	
	CanonicalTreeParser treeRepositoryOld = new CanonicalTreeParser();
	treeRepositoryOld.reset(reader, headOld);
	
	CanonicalTreeParser treeRepositoryNew = new CanonicalTreeParser();
	treeRepositoryNew.reset(reader, headNew);
	
	// finally get the list of changed files
	List<DiffEntry> diffs = new Git(repository).diff()
	                    .setNewTree(treeRepositoryNew)
	                    .setOldTree(treeRepositoryOld)
	                    .setShowNameAndStatusOnly(true)
	                    .call();
	
       for (DiffEntry entry : diffs) {
       	if(UtilTools.isJavaFile(entry.getOldPath()) || UtilTools.isJavaFile(entry.getNewPath())) {
       		String pathNew =  "/dev/null".equals(entry.getNewPath())?null:entry.getNewPath();
       		String pathOld =  "/dev/null".equals(entry.getOldPath())?null:entry.getOldPath();
       		GitFile file = new GitFile(pathOld, pathNew, entry.getChangeType());
       		mapDiff.get(entry.getChangeType()).add(file);
       	}
       }
       return mapDiff;
}
 
Example 16
Source File: ObjectWalk.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Create a new revision and object walker for a given repository.
 *
 * @param repo
 *            the repository the walker will obtain data from.
 */
public ObjectWalk(Repository repo) {
	this(repo.newObjectReader());
}
 
Example 17
Source File: RevWalk.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Create a new revision walker for a given repository.
 *
 * @param repo
 *            the repository the walker will obtain data from. An
 *            ObjectReader will be created by the walker, and will be closed
 *            when the walker is closed.
 */
public RevWalk(Repository repo) {
	this(repo.newObjectReader(), true);
}