Java Code Examples for org.eclipse.jgit.lib.Ref#getName()

The following examples show how to use org.eclipse.jgit.lib.Ref#getName() . 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: GitServiceImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
public RevWalk createAllRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getRefDatabase().getRefs()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			if (branch == null || refName.endsWith("/" + branch)) {
				currentRemoteRefs.add(ref.getObjectId());
			}
		}
	}
	
	RevWalk walk = new RevWalk(repository);
	for (ObjectId newRef : currentRemoteRefs) {
		walk.markStart(walk.parseCommit(newRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 2
Source File: GfsCheckout.java    From ParallelGit with Apache License 2.0 6 votes vote down vote up
private void prepareTarget() throws IOException {
  if(target == null)
    throw new NoBranchException();
  if(!detach) {
    if(BranchUtils.branchExists(target, repo)) {
      Ref branchRef = RefUtils.getBranchRef(target, repo);
      targetBranch = branchRef.getName();
      targetCommit = CommitUtils.getCommit(targetBranch, repo);
    }
  }
  if(targetCommit == null) {
    if(CommitUtils.exists(target, repo))
      targetCommit = CommitUtils.getCommit(target, repo);
    else
      throw new NoSuchBranchException(target);
  }
}
 
Example 3
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getRefDatabase().getRefs()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			currentRemoteRefs.add(ref.getObjectId());
		}
	}
	
	List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);
	
	RevWalk walk = new RevWalk(repository);
	for (TrackingRefUpdate newRef : newRemoteRefs) {
		if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
			walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
		}
	}
	for (ObjectId oldRef : currentRemoteRefs) {
		walk.markUninteresting(walk.parseCommit(oldRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 4
Source File: GitServiceImpl.java    From apidiff with MIT License 6 votes vote down vote up
@Override
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			currentRemoteRefs.add(ref.getObjectId());
		}
	}
	
	List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);
	
	RevWalk walk = new RevWalk(repository);
	for (TrackingRefUpdate newRef : newRemoteRefs) {
		if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
			walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
		}
	}
	for (ObjectId oldRef : currentRemoteRefs) {
		walk.markUninteresting(walk.parseCommit(oldRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 5
Source File: GitServiceImpl.java    From apidiff with MIT License 6 votes vote down vote up
public RevWalk createAllRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			if (branch == null || refName.endsWith("/" + branch)) {
				currentRemoteRefs.add(ref.getObjectId());
			}
		}
	}
	
	RevWalk walk = new RevWalk(repository);
	for (ObjectId newRef : currentRemoteRefs) {
		walk.markStart(walk.parseCommit(newRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 6
Source File: DeleteTagCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    Ref currentRef = repository.getTags().get(tagName);
    if (currentRef == null) {
        throw new GitException.MissingObjectException(tagName, GitObjectType.TAG);
    }
    String fullName = currentRef.getName();
    try {
        RefUpdate update = repository.updateRef(fullName);
        update.setRefLogMessage("tag deleted", false);
        update.setForceUpdate(true);
        Result deleteResult = update.delete();

        switch (deleteResult) {
            case IO_FAILURE:
            case LOCK_FAILURE:
            case REJECTED:
                throw new GitException.RefUpdateException("Cannot delete tag " + tagName, GitRefUpdateResult.valueOf(deleteResult.name()));
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    
}
 
Example 7
Source File: GfsCheckout.java    From ParallelGit with Apache License 2.0 6 votes vote down vote up
private void prepareTarget() throws IOException {
  if(target == null)
    throw new NoBranchException();
  if(!detach) {
    if(BranchUtils.branchExists(target, repo)) {
      Ref branchRef = RefUtils.getBranchRef(target, repo);
      targetBranch = branchRef.getName();
      targetCommit = CommitUtils.getCommit(targetBranch, repo);
    }
  }
  if(targetCommit == null) {
    if(CommitUtils.exists(target, repo))
      targetCommit = CommitUtils.getCommit(target, repo);
    else
      throw new NoSuchBranchException(target);
  }
}
 
Example 8
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Override
public String createBranch(String commitId, String branchName) {
    
    Ref result = null;
    CreateBranchCommand branchCreate = _git.branchCreate();
    branchCreate.setName(branchName);
    branchCreate.setStartPoint(commitId);
    try {
        result = branchCreate.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format(
                "Failed creating branch: %s for commit [%s]",
                branchName,
                commitId), e);
    }
    
    return result.getName();
}
 
Example 9
Source File: GitUtil.java    From apigee-deploy-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
	 * IMP NOTE: Tag number will be displayed only if git tags are peeled manually using the command "git gc"
	 * @return
	 */
	public  String getTagNameForWorkspaceHeadRevision() {
		String headRevision = getWorkspaceHeadRevisionString();
		
		Map<String, Ref> tags = git.getRepository().getAllRefs();
		for (Ref tagRef : tags.values()) {
			String tagName = tagRef.getName();
			ObjectId obj = tagRef.getPeeledObjectId();
			if (obj == null) obj = tagRef.getObjectId();
//			 System.out.println(">>>>>>>>>>>>>>>>>" + tagRef.getName() + "," +
//			 obj.getName() +"," + headRevision  );
			if (headRevision.equals(obj.getName())) {
				if (tagName.contains("/tags/")) {
					int lastSlashIndex = tagName.lastIndexOf("/");
					if (lastSlashIndex > 0) {
						tagName = tagName.substring(lastSlashIndex + 1);
						return tagName;
					}
				}
			}

		}
		return null;
	}
 
Example 10
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected ObjectId getBranchObjectId(Git git) {
    Ref branchRef = null;
    try {
        String branchRevName = "refs/heads/" + branch;
        List<Ref> branches = git.branchList().call();
        for (Ref ref : branches) {
            String revName = ref.getName();
            if (Objects.equals(branchRevName, revName)) {
                branchRef = ref;
                break;
            }
        }
    } catch (GitAPIException e) {
        LOG.warn("Failed to find branches " + e, e);
    }

    ObjectId branchObjectId = null;
    if (branchRef != null) {
        branchObjectId = branchRef.getObjectId();
    }
    return branchObjectId;
}
 
Example 11
Source File: GitCloner.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private void checkoutAllBranches(Repository repository) throws GitAPIException {
    final Git git = Git.wrap(repository);
    for (final Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call()) {
        final String refName = ref.getName();
        final String branchName = refName.substring(refName.lastIndexOf('/') + 1);
        try {
            git.checkout().setCreateBranch(true).setName(branchName).setStartPoint("origin/" + branchName).call();
        } catch (RefAlreadyExistsException e) {
            LOGGER.warning("Already exists, so ignoring " + e.getMessage());
        }
    }
}
 
Example 12
Source File: Reactor.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
private static Collection<Long> getRemoteBuildNumbers(LocalGitRepo gitRepo, String artifactId, String versionWithoutBuildNumber, VersionNamer versionNamer) throws GitAPIException {
    Collection<Ref> remoteTagRefs = gitRepo.allTags();
    Collection<Long> remoteBuildNumbers = new ArrayList<Long>();
    String tagWithoutBuildNumber = artifactId + "-" + versionWithoutBuildNumber;
    AnnotatedTagFinder annotatedTagFinder = new AnnotatedTagFinder(versionNamer);
    for (Ref remoteTagRef : remoteTagRefs) {
        String remoteTagName = remoteTagRef.getName();
        Long buildNumber = annotatedTagFinder.buildNumberOf(tagWithoutBuildNumber, remoteTagName);
        if (buildNumber != null) {
            remoteBuildNumbers.add(buildNumber);
        }
    }
    return remoteBuildNumbers;
}
 
Example 13
Source File: GitVcsRepository.java    From gradle-golang-plugin with Mozilla Public License 2.0 5 votes vote down vote up
@Override
@Nonnull
protected VcsFullReference downloadToInternal(@Nonnull Path targetDirectory, @Nullable ProgressMonitor progressMonitor) throws VcsException {
    Ref ref = null;
    final GitVcsUri uri = gitVcsUriFor(getReference());
    final Git git;
    try {
        ref = resolveRemoteRef();
        if (ref == null) {
            throw new VcsValidationException("Could not find ref " + uri + "@" + getReference().getRef() + ".");
        }
        final String refName = ref.getName();
        LOGGER.debug("Clone remote refs from {}@{} to {}...", uri, refName, targetDirectory);
        git = Git.cloneRepository()
            .setProgressMonitor(toGitProgressMonitor(progressMonitor))
            .setURI(uri.getUri().toString())
            .setDirectory(targetDirectory.toFile())
            .setBranch(refName)
            .call();
        LOGGER.debug("Clone remote refs from {}@{} to {}... DONE!", uri, refName, targetDirectory);
    } catch (final GitAPIException e) {
        throw new VcsException("Cannot clone " + uri + "@" + (ref != null ? ref.getName() : "unresolved") + " to " + targetDirectory + ".", e);
    }
    final String fullRevision = fullRevisionOf(git);
    removeGitDirectoryIfNeeded(targetDirectory, git);
    return new VcsFullReference(getReference(), fullRevision);
}
 
Example 14
Source File: RefComparator.java    From gradle-golang-plugin with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public int compare(Ref o1, Ref o2) {
    if (o1 == null && o2 == null) {
        return 0;
    }
    if (o1 == null) {
        return 1;
    }
    if (o2 == null) {
        return -1;
    }
    final String n1 = o1.getName();
    final String n2 = o2.getName();
    if ("HEAD".equals(n1) && !"HEAD".equals(n2)) {
        return -1;
    }
    if (!"HEAD".equals(n1) && "HEAD".equals(n2)) {
        return 1;
    }
    if (n1.startsWith("refs/tags/") && !n2.startsWith("refs/tags/")) {
        return -1;
    }
    if (!n1.startsWith("refs/tags/") && n2.startsWith("refs/tags/")) {
        return 1;
    }
    if (n1.startsWith("refs/heads/") && !n2.startsWith("refs/heads/")) {
        return -1;
    }
    if (!n1.startsWith("refs/heads/") && n2.startsWith("refs/heads/")) {
        return 1;
    }
    return n1.compareTo(n2);
}
 
Example 15
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected List<String> doListBranches(Git git) throws Exception {
    SortedSet<String> names = new TreeSet<String>();
    List<Ref> call = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    for (Ref ref : call) {
        String name = ref.getName();
        int idx = name.lastIndexOf('/');
        if (idx >= 0) {
            name = name.substring(idx + 1);
        }
        if (name.length() > 0) {
            names.add(name);
        }
    }
    return new ArrayList<String>(names);
}
 
Example 16
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
private List<Ref> getAllBranchRefs(boolean originBranches) {
    List<Ref> branches = new ArrayList<>();
    try (Repository repo = getRepository()) {
        for (Ref r : repo.getAllRefs().values()) {
            final String branchName = r.getName();
            if (branchName.startsWith(R_HEADS)
                    || (originBranches && branchName.startsWith(R_REMOTES))) {
                branches.add(r);
            }
        }
    }
    return branches;
}
 
Example 17
Source File: JgitTests.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
protected static String getBranchName(Ref ref) {
    String name = ref.getName();
    if ("HEAD".equals(trimToEmpty(name))) {
        ObjectId objectId = ref.getObjectId();
        name = objectId.getName();
    } else {
        int index = name.lastIndexOf("/");
        name = name.substring(index + 1);
    }
    return name;
}
 
Example 18
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Map<String, ObjectId> getRemoteReferences(String url, String pattern, boolean headsOnly, boolean tagsOnly)
        throws GitException, InterruptedException {
    Map<String, ObjectId> references = new HashMap<>();
    String regexPattern = null;
    if (pattern != null) {
        regexPattern = createRefRegexFromGlob(pattern);
    }
    try (Repository repo = openDummyRepository()) {
        LsRemoteCommand lsRemote = new LsRemoteCommand(repo);
        if (headsOnly) {
            lsRemote.setHeads(headsOnly);
        }
        if (tagsOnly) {
            lsRemote.setTags(tagsOnly);
        }
        lsRemote.setRemote(url);
        lsRemote.setCredentialsProvider(getProvider());
        Collection<Ref> refs = lsRemote.call();
            for (final Ref r : refs) {
                final String refName = r.getName();
                final ObjectId refObjectId =
                        r.getPeeledObjectId() != null ? r.getPeeledObjectId() : r.getObjectId();
                if (regexPattern != null) {
                    if (refName.matches(regexPattern)) {
                        references.put(refName, refObjectId);
                    }
                } else {
                    references.put(refName, refObjectId);
                }
            }
    } catch (JGitInternalException | GitAPIException | IOException e) {
        throw new GitException(e);
    }
    return references;
}
 
Example 19
Source File: Git.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
public String getCommitId()
    throws GitAPIException, DockerException, IOException, MojoExecutionException {

  if (repo == null) {
    throw new MojoExecutionException(
        "Cannot tag with git commit ID because directory not a git repo");
  }

  final StringBuilder result = new StringBuilder();

  try {
    // get the first 7 characters of the latest commit
    final ObjectId head = repo.resolve("HEAD");
    if (head == null || isNullOrEmpty(head.getName())) {
      return null;
    }

    result.append(head.getName().substring(0, 7));
    final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo);

    // append first git tag we find
    for (final Ref gitTag : git.tagList().call()) {
      if (gitTag.getObjectId().equals(head)) {
        // name is refs/tag/name, so get substring after last slash
        final String name = gitTag.getName();
        result.append(".");
        result.append(name.substring(name.lastIndexOf('/') + 1));
        break;
      }
    }

    // append '.DIRTY' if any files have been modified
    final Status status = git.status().call();
    if (status.hasUncommittedChanges()) {
      result.append(".DIRTY");
    }
  } finally {
    repo.close();
  }

  return result.length() == 0 ? null : result.toString();
}
 
Example 20
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<PublishingHistoryItem> getPublishingHistory(String siteId, String environment, String pathRegex,
                                                        String publisher, ZonedDateTime fromDate,
                                                        ZonedDateTime toDate, int limit) {
    List<PublishingHistoryItem> toRet = new ArrayList<PublishingHistoryItem>();
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
        Repository publishedRepo = helper.getRepository(siteId, PUBLISHED);
        if (publishedRepo != null) {
            int counter = 0;
            try (Git git = new Git(publishedRepo)) {
                // List all environments
                List<Ref> environments = git.branchList().call();
                for (int i = 0; i < environments.size() && counter < limit; i++) {
                    Ref env = environments.get(i);
                    String environmentGit = env.getName();
                    environmentGit = environmentGit.replace(R_HEADS, "");
                    if ((StringUtils.isBlank(environment) && !StringUtils.equals(MASTER, environmentGit))
                            || StringUtils.equals(environment, environmentGit)) {
                        List<RevFilter> filters = new ArrayList<RevFilter>();
                        if (fromDate != null) {
                            filters.add(CommitTimeRevFilter.after(fromDate.toInstant().toEpochMilli()));
                        }
                        if (toDate != null) {
                            filters.add(CommitTimeRevFilter.before(toDate.toInstant().toEpochMilli()));
                        } else {
                            filters.add(CommitTimeRevFilter.before(ZonedDateTime.now().toInstant().toEpochMilli()));
                        }
                        filters.add(NotRevFilter.create(MessageRevFilter.create("Initial commit.")));
                        if (StringUtils.isNotEmpty(publisher)) {
                            User user = userServiceInternal.getUserByIdOrUsername(-1, publisher);
                            filters.add(AuthorRevFilter.create(helper.getAuthorIdent(user).getName()));
                        }
                        Iterable<RevCommit> branchLog = git.log()
                                .add(env.getObjectId())
                                .setRevFilter(AndRevFilter.create(filters))
                                .call();

                        Iterator<RevCommit> iterator = branchLog.iterator();
                        while (iterator.hasNext() && counter < limit) {
                            RevCommit revCommit = iterator.next();
                            List<String> files = helper.getFilesInCommit(publishedRepo, revCommit);
                            for (int j = 0; j < files.size() && counter < limit; j++) {
                                String file = files.get(j);
                                Path path = Paths.get(file);
                                String fileName = path.getFileName().toString();
                                if (!ArrayUtils.contains(IGNORE_FILES, fileName)) {
                                    boolean addFile = false;
                                    if (StringUtils.isNotEmpty(pathRegex)) {
                                        Pattern pattern = Pattern.compile(pathRegex);
                                        Matcher matcher = pattern.matcher(file);
                                        addFile = matcher.matches();
                                    } else {
                                        addFile = true;
                                    }
                                    if (addFile) {
                                        PublishingHistoryItem phi = new PublishingHistoryItem();
                                        phi.setSiteId(siteId);
                                        phi.setPath(file);
                                        phi.setPublishedDate(
                                                Instant.ofEpochSecond(revCommit.getCommitTime()).atZone(UTC));
                                        phi.setPublisher(revCommit.getAuthorIdent().getName());
                                        phi.setEnvironment(environmentGit.replace(R_HEADS, ""));
                                        toRet.add(phi);
                                        counter++;
                                    }
                                }
                            }
                        }
                    }
                }
                git.close();
                toRet.sort((o1, o2) -> o2.getPublishedDate().compareTo(o1.getPublishedDate()));
            } catch (IOException | GitAPIException | UserNotFoundException | ServiceLayerException e1) {
                logger.error("Error while getting deployment history for site " + siteId, e1);
            }
        }
    } catch (CryptoException e) {
        e.printStackTrace();
    }
    return toRet;
}