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

The following examples show how to use org.eclipse.jgit.lib.Repository#resolve() . 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: CherryPickCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ObjectId getOriginalCommit () throws GitException {
    Repository repository = getRepository();
    File seqHead = new File(getSequencerFolder(), SEQUENCER_HEAD);
    ObjectId originalCommitId = null;
    if (seqHead.canRead()) {
        try {
            byte[] content = IO.readFully(seqHead);
            if (content.length > 0) {
                originalCommitId = ObjectId.fromString(content, 0);
            }
            if (originalCommitId != null) {
                originalCommitId = repository.resolve(originalCommitId.getName() + "^{commit}");
            }
        } catch (IOException e) {
        }
    }
    return originalCommitId;
}
 
Example 2
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 3
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 4
Source File: GitFXGsonUtil.java    From GitFx with Apache License 2.0 6 votes vote down vote up
public static GitRepoMetaData getGitRepositoryMetaData(String repoPath) {
        try {
            if(!repoPath.endsWith(".git"))
                repoPath = repoPath+File.separator+".git";
            System.out.println("repopath:  "+repoPath);
            GitRepoMetaData gitMetaData = new GitRepoMetaData();
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repository = builder.setGitDir(new File(repoPath))
                    .readEnvironment()
                    .setMustExist(true)
                    .findGitDir()
                    .build();
            RevWalk walk = new RevWalk(repository);
            AnyObjectId id = repository.resolve("HEAD");
            if(id == null)
                return null;//Empty repository
            RevCommit rCommit =walk.parseCommit(id);
            walk.markStart(rCommit);
            gitMetaData.setRepository(repository);
            gitMetaData.setRevWalk(walk);
            return gitMetaData;
        } catch (IOException exception) {
//[LOG]            logger.debug("IOException getGitRepositoryMetaData", exception);
        };
        return null;
    }
 
Example 5
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 6
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 7
Source File: GITStatusCrawler.java    From celerio with Apache License 2.0 5 votes vote down vote up
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
    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    // and using commit's tree find the path
    RevTree tree = commit.getTree();
    return tree;
}
 
Example 8
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getRepoFirstCommitId(final String site) {
    String toReturn = EMPTY;
    Repository repository = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
    if (repository != null) {
        synchronized (repository) {
            Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
            if (repo != null) {
                try (RevWalk rw = new RevWalk(repo)) {
                    ObjectId head = repo.resolve(HEAD);
                    if (head != null) {
                        RevCommit root = rw.parseCommit(head);
                        rw.sort(REVERSE);
                        rw.markStart(root);
                        ObjectId first = rw.next();
                        toReturn = first.getName();
                        logger.debug("getRepoFirstCommitId for site: " + site + " First commit ID: " + toReturn);
                    }
                } catch (IOException e) {
                    logger.error("Error getting first commit ID for site " + site, e);
                }
            }
        }
    }

    return toReturn;
}
 
Example 9
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
private boolean checkoutSandboxBranch(String site, Repository sandboxRepo, String sandboxBranch) {
    String sandboxBranchName = sandboxBranch;
    if (StringUtils.isEmpty(sandboxBranchName)) {
        sandboxBranchName = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
    }
    try (Git git = new Git(sandboxRepo)) {
        if (!StringUtils.equals(sandboxRepo.getBranch(), sandboxBranchName)) {
            List<Ref> branchList = git.branchList().call();
            boolean createBranch = true;
            for (Ref branch : branchList) {
                if (StringUtils.equals(branch.getName(), sandboxBranchName) ||
                        StringUtils.equals(branch.getName(), Constants.R_HEADS + sandboxBranchName)) {
                    createBranch = false;
                    break;
                }
            }
            if (sandboxRepo.isBare() || sandboxRepo.resolve(Constants.HEAD) == null) {
                git.commit()
                        .setAllowEmpty(true)
                        .setMessage(getCommitMessage(REPO_CREATE_SANDBOX_BRANCH_COMMIT_MESSAGE)
                                .replaceAll(PATTERN_SANDBOX, sandboxBranchName))
                        .call();
            }
            git.checkout()
                    .setCreateBranch(createBranch)
                    .setName(sandboxBranchName)
                    .setForce(false)
                    .call();
        }
        return true;
    } catch (GitAPIException | IOException e) {
        logger.error("Error checking out sandbox branch " + sandboxBranchName + " for site " + site, e);
        return false;
    }
}
 
Example 10
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public RevTree getTreeForLastCommit(Repository repository) throws IOException {
    ObjectId lastCommitId = repository.resolve(HEAD);

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

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }
}
 
Example 11
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public RevTree getTreeForCommit(Repository repository, String commitId) throws IOException {
    ObjectId commitObjectId = repository.resolve(commitId);

    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitObjectId);

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }
}
 
Example 12
Source File: DockerBuildInformation.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void updateGitInformation(Log log) {
  try {
    final Repository repo = new Git().getRepo();
    if (repo != null) {
      this.repo   = repo.getConfig().getString("remote", "origin", "url");
      final ObjectId head = repo.resolve("HEAD");
      if (head != null && !isNullOrEmpty(head.getName())) {
        this.commit = head.getName();
      }
    }
  } catch (IOException e) {
    log.error("Failed to read Git information", e);
  }
}
 
Example 13
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 14
Source File: NotesBuilder.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns actual SHA-1 object by commit reference.
 *
 * @param repo git repository.
 * @param ref string representation of commit reference.
 * @return actual SHA-1 object.
 * @throws IOException if an I/O error occurs.
 */
private static ObjectId getActualRefObjectId(Repository repo, String ref) throws IOException {
    final ObjectId actualObjectId;
    final Ref referenceObj = repo.findRef(ref);
    if (referenceObj == null) {
        actualObjectId = repo.resolve(ref);
    }
    else {
        final Ref repoPeeled = repo.peel(referenceObj);
        actualObjectId = Optional.ofNullable(repoPeeled.getPeeledObjectId())
            .orElse(referenceObj.getObjectId());
    }
    return actualObjectId;
}
 
Example 15
Source File: GitProctor.java    From proctor with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Map<String, List<Revision>> getAllHistories() throws StoreException {
    final Repository repository = git.getRepository();
    try {
        final ObjectId head = repository.resolve(Constants.HEAD);
        final GitHistoryParser historyParser =
                GitHistoryParser.fromRepository(git.getRepository(), getTestDefinitionsDirectory());
        return historyParser.parseFromHead(head);
    } catch (final IOException e) {
        throw new StoreException("Could not get history " + getGitCore().getRefName(), e);
    }
}
 
Example 16
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public Iterable<RevCommit> createRevsWalkBetweenCommits(Repository repository, String startCommitId, String endCommitId)
		throws Exception {
	ObjectId from = repository.resolve(startCommitId);
	ObjectId to = repository.resolve(endCommitId);
	try (Git git = new Git(repository)) {
		List<RevCommit> revCommits = StreamSupport.stream(git.log().addRange(from, to).call()
				.spliterator(), false)
				.filter(r -> r.getParentCount() == 1)
		        .collect(Collectors.toList());
		Collections.reverse(revCommits);
		return revCommits;
	}
}
 
Example 17
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 18
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 19
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public RevTree getTreeForLastCommit(Repository repository) throws IOException {
    ObjectId lastCommitId = repository.resolve(Constants.HEAD);
    if (lastCommitId == null) {
        return null;
    }
    // a RevWalk allows to walk over commits based on some filtering
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(lastCommitId);

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }
}
 
Example 20
Source File: RepositoryObjectTreeWalker.java    From writelatex-git-bridge with MIT License 4 votes vote down vote up
public RepositoryObjectTreeWalker(
        Repository repository,
        int fromHead
) throws IOException {
    this(repository, repository.resolve("HEAD~" + fromHead));
}