org.eclipse.jgit.lib.Ref Java Examples
The following examples show how to use
org.eclipse.jgit.lib.Ref.
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: JgitTests.java From super-cloudops with Apache License 2.0 | 6 votes |
@Test public void tagListTest() throws IOException, GitAPIException { Git git = Git.open(new File(gitPath)); /*ListTagCommand listTagCommand = git.tagList(); List<Ref> call = listTagCommand.call(); for(Ref ref : call){ System.out.println(ref.getName()); }*/ // FetchCommand fetchCommand = git.fetch().setTagOpt(TagOpt.FETCH_TAGS); fetchCommand.setCredentialsProvider(usernamePasswordCredentialsProvider); fetchCommand.call(); List<Ref> tags = git.tagList().call(); if(tags != null && tags.size() > 0) { for(Ref tag : tags) { System.out.println(tag.getName()); } } }
Example #2
Source File: ConfigRepositoryTest.java From gocd with Apache License 2.0 | 6 votes |
@Test public void shouldThrowExceptionWhenThereIsMergeConflict() throws Exception { String original = "first\nsecond\n"; String nextUpdate = "1st\nsecond\n"; String latestUpdate = "2nd\nsecond\n"; configRepo.checkin(goConfigRevision(original, "md5-1")); configRepo.checkin(goConfigRevision(nextUpdate, "md5-2")); RevCommit currentRevCommitOnMaster = configRepo.getCurrentRevCommit(); try { configRepo.getConfigMergedWithLatestRevision(goConfigRevision(latestUpdate, "md5-3"), "md5-1"); fail("should have bombed for merge conflict"); } catch (ConfigMergeException e) { assertThat(e.getMessage(), is(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH)); } List<Ref> branches = getAllBranches(); assertThat(branches.size(), is(1)); assertThat(branches.get(0).getName().endsWith("master"), is(true)); assertThat(configRepo.getCurrentRevCommit(), is(currentRevCommitOnMaster)); }
Example #3
Source File: JGitOperator.java From verigreen with Apache License 2.0 | 6 votes |
boolean isRefBehind( Ref behind, Ref tracking ) throws IOException { RevWalk walk = new RevWalk( _git.getRepository() ); try { RevCommit behindCommit = walk.parseCommit( behind.getObjectId() ); RevCommit trackingCommit = walk.parseCommit( tracking.getObjectId() ); walk.setRevFilter( RevFilter.MERGE_BASE ); walk.markStart( behindCommit ); walk.markStart( trackingCommit ); RevCommit mergeBase = walk.next(); walk.reset(); walk.setRevFilter( RevFilter.ALL ); int aheadCount = RevWalkUtils.count( walk, behindCommit, mergeBase ); int behindCount = RevWalkUtils.count( walk, trackingCommit, mergeBase ); return behindCount > aheadCount ? true:false; } catch (Throwable e) { throw new RuntimeException(String.format( "Failed to check if [%s] behind [%s]", behind, tracking), e); } finally { walk.dispose(); } }
Example #4
Source File: RemoteBranch.java From orion.server with Eclipse Public License 1.0 | 6 votes |
private Ref findRef() { try { Set<String> configNames = getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION); for (String configName : configNames) { if (configName.equals(remote.getName())) { final String fullName = getName(true, false); Ref ref = db.getRefDatabase().getRef(fullName); if (ref != null && !ref.isSymbolic()) { return ref; } } } } catch (IOException e) { // ignore, return null } return null; }
Example #5
Source File: JGitAPIImpl.java From git-client-plugin with MIT License | 6 votes |
/** {@inheritDoc} */ @Override public Set<String> getRefNames(String refPrefix) throws GitException, InterruptedException { if (refPrefix.isEmpty()) { refPrefix = RefDatabase.ALL; } else { refPrefix = refPrefix.replace(' ', '_'); } try (Repository repo = getRepository()) { List<Ref> refList = repo.getRefDatabase().getRefsByPrefix(refPrefix); Set<String> refs = new HashSet<>(refList.size()); for (Ref ref : refList) { refs.add(ref.getName()); } return refs; } catch (IOException e) { throw new GitException("Error retrieving refs with prefix " + refPrefix, e); } }
Example #6
Source File: JGitAPIImpl.java From git-client-plugin with MIT License | 6 votes |
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error") private Set<String> listRemoteBranches(String remote) throws NotSupportedException, TransportException, URISyntaxException { Set<String> branches = new HashSet<>(); try (final Repository repo = getRepository()) { StoredConfig config = repo.getConfig(); try (final Transport tn = Transport.open(repo, new URIish(config.getString("remote",remote,"url")))) { tn.setCredentialsProvider(getProvider()); try (final FetchConnection c = tn.openFetch()) { for (final Ref r : c.getRefs()) { if (r.getName().startsWith(R_HEADS)) branches.add("refs/remotes/"+remote+"/"+r.getName().substring(R_HEADS.length())); } } } } return branches; }
Example #7
Source File: CliGitAPIImpl.java From git-client-plugin with MIT License | 6 votes |
/** * Returns the remote branches defined in this repository. * * @return {@link java.util.Set} of remote branches in this repository * @throws hudson.plugins.git.GitException if underlying git operation fails * @throws java.lang.InterruptedException if interrupted */ @Override public Set<Branch> getRemoteBranches() throws GitException, InterruptedException { try (Repository db = getRepository()) { Map<String, Ref> refs = db.getAllRefs(); Set<Branch> branches = new HashSet<>(); for(Ref candidate : refs.values()) { if(candidate.getName().startsWith(Constants.R_REMOTES)) { Branch buildBranch = new Branch(candidate); if (!GitClient.quietRemoteBranches) { listener.getLogger().println("Seen branch in repository " + buildBranch.getName()); } branches.add(buildBranch); } } if (branches.size() == 1) { listener.getLogger().println("Seen 1 remote branch"); } else { listener.getLogger().println(MessageFormat.format("Seen {0} remote branches", branches.size())); } return branches; } }
Example #8
Source File: GitWrapper.java From Stringlate with MIT License | 6 votes |
public static ArrayList<String> getBranches(final File repo) { try { final List<Ref> refs = Git.open(repo) .branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call(); final ArrayList<String> result = new ArrayList<>(); for (Ref ref : refs) result.add(ref.getName()); return result; } catch (GitAPIException | IOException e) { e.printStackTrace(); } return new ArrayList<>(); }
Example #9
Source File: JGitOperator.java From verigreen with Apache License 2.0 | 6 votes |
@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 #10
Source File: GitClient.java From cf-butler with Apache License 2.0 | 6 votes |
public RevCommit getLatestCommit(Repository repo) throws IOException, GitAPIException { RevCommit latestCommit = null; int inc = 0; try( Git git = new Git(repo); RevWalk walk = new RevWalk(repo); ) { List<Ref> branches = git.branchList().call(); for(Ref branch : branches) { RevCommit commit = walk.parseCommit(branch.getObjectId()); if (inc == 0) latestCommit = commit; if(commit.getAuthorIdent().getWhen().compareTo(latestCommit.getAuthorIdent().getWhen()) > 0) latestCommit = commit; inc++; } } return latestCommit; }
Example #11
Source File: GitService.java From Refactoring-Bot with MIT License | 6 votes |
/** * This method creates a new branch. * * @param gitConfig * @param branchName * @param origin * @throws BotRefactoringException * @throws GitWorkflowException */ public void createBranch(GitConfiguration gitConfig, String branchName, String newBranch, String origin) throws BotRefactoringException, GitWorkflowException { try (Git git = Git.open(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))) { // Try to create new branch @SuppressWarnings("unused") Ref ref = git.checkout().setCreateBranch(true).setName(newBranch) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint(origin + "/" + branchName).call(); // Pull data git.pull(); // If branch already exists } catch (RefAlreadyExistsException r) { logger.error(r.getMessage(), r); throw new BotRefactoringException( "Issue was already refactored in the past! The bot database might have been resetted but not the fork itself."); } catch (Exception e) { logger.error(e.getMessage(), e); throw new GitWorkflowException("Branch with the name " + "'" + newBranch + "' could not be created!"); } }
Example #12
Source File: GitRepo.java From spring-cloud-release-tools with Apache License 2.0 | 6 votes |
/** * Look for a tag with the given name, and if not found looks for a branch. */ private Optional<Ref> findTagOrBranchHeadRevision(Git git, String tagOrBranch) throws GitAPIException, IOException { if (tagOrBranch.equals("HEAD")) { return Optional.of(git.getRepository().exactRef(Constants.HEAD).getTarget()); } final Optional<Ref> tag = git.tagList().call().stream() .filter(ref -> ref.getName().equals("refs/tags/" + tagOrBranch)) .findFirst(); if (tag.isPresent()) { return tag; } return git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call() .stream().filter(ref -> ref.getName().equals("refs/heads/" + tagOrBranch)) .findFirst(); }
Example #13
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 6 votes |
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 #14
Source File: RevisionSelector.java From onedev with MIT License | 6 votes |
public RevisionSelector(String id, IModel<Project> projectModel, @Nullable String revision, boolean canCreateRef) { super(id); Preconditions.checkArgument(revision!=null || !canCreateRef); this.projectModel = projectModel; this.revision = revision; if (canCreateRef) { Project project = projectModel.getObject(); canCreateBranch = SecurityUtils.canCreateBranch(project, Constants.R_HEADS); canCreateTag = SecurityUtils.canCreateTag(project, Constants.R_TAGS); } else { canCreateBranch = false; canCreateTag = false; } if (revision != null) { Ref ref = projectModel.getObject().getRef(revision); branchesActive = ref == null || GitUtils.ref2tag(ref.getName()) == null; } else { branchesActive = true; } refs = findRefs(); }
Example #15
Source File: RepositoryManagementServiceInternalImpl.java From studio with GNU General Public License v3.0 | 6 votes |
private Map<String, List<String>> getRemoteBranches(Git git) throws GitAPIException { List<Ref> resultRemoteBranches = git.branchList() .setListMode(ListBranchCommand.ListMode.REMOTE) .call(); Map<String, List<String>> remoteBranches = new HashMap<String, List<String>>(); for (Ref remoteBranchRef : resultRemoteBranches) { String branchFullName = remoteBranchRef.getName().replace(Constants.R_REMOTES, ""); String remotePart = StringUtils.EMPTY; String branchNamePart = StringUtils.EMPTY; int slashIndex = branchFullName.indexOf("/"); if (slashIndex > 0) { remotePart = branchFullName.substring(0, slashIndex); branchNamePart = branchFullName.substring(slashIndex + 1); } if (!remoteBranches.containsKey(remotePart)) { remoteBranches.put(remotePart, new ArrayList<String>()); } remoteBranches.get(remotePart).add(branchNamePart); } return remoteBranches; }
Example #16
Source File: GitServiceImpl.java From apidiff with MIT License | 6 votes |
@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 #17
Source File: CreateTagAction.java From onedev with MIT License | 6 votes |
@Override public void execute(Build build) { PersonIdent tagIdent = OneDev.getInstance(UserManager.class).getSystem().asPerson(); Project project = build.getProject(); String tagName = getTagName(); CreateTagAction instance = new CreateTagAction(); instance.setTagName(tagName); if (project.getBuildSetting().isActionAuthorized(build, instance)) { Ref tagRef = project.getTagRef(tagName); if (tagRef != null) { OneDev.getInstance(ProjectManager.class).deleteTag(project, tagName); project.createTag(tagName, build.getCommitHash(), tagIdent, getTagMessage()); } else { project.createTag(tagName, build.getCommitHash(), tagIdent, getTagMessage()); } } else { throw new OneException("Creating tag '" + tagName + "' is not allowed in this build"); } }
Example #18
Source File: PullCommand.java From netbeans with Apache License 2.0 | 6 votes |
private String findRemoteBranchName () throws GitException { Ref ref = null; try { ref = getRepository().findRef(branchToMerge); } catch (IOException ex) { throw new GitException(ex); } if (ref != null) { for (String s : refSpecs) { RefSpec spec = new RefSpec(s); if (spec.matchDestination(ref)) { spec = spec.expandFromDestination(ref); String refName = spec.getSource(); if (refName.startsWith(Constants.R_HEADS)) { return refName.substring(Constants.R_HEADS.length()); } } } } return branchToMerge; }
Example #19
Source File: UpdaterGenerator.java From neembuu-uploader with GNU General Public License v3.0 | 6 votes |
/** * Clone GIT repository from sourceforge. * * @param gitDirectory The directory of Git. */ private void gitClone(File gitDirectory) { try { git = Git.cloneRepository() .setDirectory(gitDirectory) .setURI("http://git.code.sf.net/p/neembuuuploader/gitcode") .setProgressMonitor(new TextProgressMonitor()).call(); for (Ref f : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { git.checkout().setName(f.getName()).call(); System.out.println("checked out branch " + f.getName() + ". HEAD: " + git.getRepository().getRef("HEAD")); } // try to checkout branches by specifying abbreviated names git.checkout().setName("master").call(); } catch (GitAPIException | IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }
Example #20
Source File: Project.java From onedev with MIT License | 6 votes |
public RevCommit getLastCommit() { if (lastCommitHolder == null) { RevCommit lastCommit = null; try { for (Ref ref: getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS)) { RevCommit commit = getRevCommit(ref.getObjectId(), false); if (commit != null) { if (lastCommit != null) { if (commit.getCommitTime() > lastCommit.getCommitTime()) lastCommit = commit; } else { lastCommit = commit; } } } } catch (IOException e) { throw new RuntimeException(e); } lastCommitHolder = Optional.fromNullable(lastCommit); } return lastCommitHolder.orNull(); }
Example #21
Source File: DefaultCommitInfoManager.java From onedev with MIT License | 6 votes |
private void collect(Project project) { List<CollectingWork> works = new ArrayList<>(); try (RevWalk revWalk = new RevWalk(project.getRepository())) { Collection<Ref> refs = new ArrayList<>(); refs.addAll(project.getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS)); refs.addAll(project.getRepository().getRefDatabase().getRefsByPrefix(Constants.R_TAGS)); for (Ref ref: refs) { RevObject revObj = revWalk.peel(revWalk.parseAny(ref.getObjectId())); if (revObj instanceof RevCommit) works.add(new CollectingWork(PRIORITY, (RevCommit) revObj, ref.getName())); } } catch (IOException e) { throw new RuntimeException(e); } Collections.sort(works, new CommitTimeComparator()); for (CollectingWork work: works) batchWorkManager.submit(getBatchWorker(project.getId()), work); }
Example #22
Source File: VersionStrategy.java From jgitver with Apache License 2.0 | 6 votes |
protected Version getBaseVersionAndRegisterMetadata(Commit base, Ref tagToUse) { Version baseVersion = Version.DEFAULT_VERSION; if (tagToUse != null) { String tagName = GitUtils.tagNameFromRef(tagToUse); baseVersion = versionFromTag(tagToUse); TagType tagType = computeTagType(tagToUse, maxVersionTag(base.getAnnotatedTags()).orElse(null)); getRegistrar().registerMetadata(Metadatas.BASE_TAG_TYPE, tagType.name()); getRegistrar().registerMetadata(Metadatas.BASE_TAG, tagName); } getRegistrar().registerMetadata(Metadatas.BASE_VERSION, baseVersion.toString()); getRegistrar().registerMetadata(Metadatas.CURRENT_VERSION_MAJOR, Integer.toString(baseVersion.getMajor())); getRegistrar().registerMetadata(Metadatas.CURRENT_VERSION_MINOR, Integer.toString(baseVersion.getMinor())); getRegistrar().registerMetadata(Metadatas.CURRENT_VERSION_PATCH, Integer.toString(baseVersion.getPatch())); return baseVersion; }
Example #23
Source File: GitRepository.java From centraldogma with Apache License 2.0 | 6 votes |
@VisibleForTesting static void doRefUpdate(org.eclipse.jgit.lib.Repository jGitRepository, RevWalk revWalk, String ref, ObjectId commitId) throws IOException { if (ref.startsWith(Constants.R_TAGS)) { final Ref oldRef = jGitRepository.exactRef(ref); if (oldRef != null) { throw new StorageException("tag ref exists already: " + ref); } } final RefUpdate refUpdate = jGitRepository.updateRef(ref); refUpdate.setNewObjectId(commitId); final Result res = refUpdate.update(revWalk); switch (res) { case NEW: case FAST_FORWARD: // Expected break; default: throw new StorageException("unexpected refUpdate state: " + res); } }
Example #24
Source File: CreateBranchCommand.java From netbeans with Apache License 2.0 | 5 votes |
private void setupRebaseFlag (Repository repository) throws IOException { Ref baseRef = repository.findRef(revision); if (baseRef != null && baseRef.getName().startsWith(Constants.R_REMOTES)) { StoredConfig config = repository.getConfig(); String autosetupRebase = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE); boolean rebase = ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase) || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase); if (rebase && !config.getNames(ConfigConstants.CONFIG_BRANCH_SECTION, branchName).isEmpty()) { config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE, rebase); config.save(); } } }
Example #25
Source File: RepositoryUtilsSetRepositoryHeadTest.java From ParallelGit with Apache License 2.0 | 5 votes |
@Test public void setHeadToTag_theRepositoryHeadShouldDetachToTheTaggedCommit() throws IOException { writeSomethingToCache(); AnyObjectId commitId = commitToMaster(); Ref tagRef = TagUtils.tagCommit("test_tag", commitId, repo); RepositoryUtils.setRepositoryHead(repo, tagRef.getName()); assertEquals(commitId.getName(), repo.getBranch()); }
Example #26
Source File: GitVersionCalculatorImpl.java From jgitver with Apache License 2.0 | 5 votes |
private ObjectId latestObjectIdOfTags(List<Ref> reachableTags, Function<Ref, ObjectId> refToObjectIdFunction) { try (TagDateExtractor dateExtractor = new TagDateExtractor(repository)) { return reachableTags.stream() .map(r -> new Pair<Ref, Date>(r, dateExtractor.dateOfRef(r))) .max(Comparator.comparing(p -> ((Date) p.getRight()))) .map(p -> (Ref) p.getLeft()) .map(refToObjectIdFunction) .orElseThrow(() -> new IllegalStateException(String.format("could not find most recent tag"))); } }
Example #27
Source File: GitConfigurationSource.java From cfg4j with Apache License 2.0 | 5 votes |
private boolean anyRefMatches(List<Ref> refList, String branch) { for (Ref ref : refList) { if (ref.getName().replace("refs/heads/", "").equals(branch)) { return true; } } return false; }
Example #28
Source File: GHRule.java From github-integration-plugin with MIT License | 5 votes |
public void commitFileToBranch(String branch, String fileName, String content, String commitMessage) throws IOException, GitAPIException { final String beforeBranch = git.getRepository().getBranch(); final List<Ref> refList = git.branchList().call(); boolean exist = false; for (Ref ref : refList) { if (ref.getName().endsWith(branch)) { exist = true; break; } } if (!exist) { git.branchCreate().setName(branch).call(); } git.checkout().setName(branch).call(); writeStringToFile(new File(gitRootDir, fileName), content); git.add().addFilepattern(".").call(); git.commit().setAll(true).setMessage(commitMessage).call(); git.push() .setPushAll() .setProgressMonitor(new TextProgressMonitor()) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GH_TOKEN, "")) .call(); git.checkout().setName(beforeBranch).call(); await().pollInterval(3, SECONDS) .timeout(120, SECONDS) .until(ghBranchAppeared(getGhRepo(), branch)); }
Example #29
Source File: GitUtilsTest.java From submarine with Apache License 2.0 | 5 votes |
@Test public void branchCreateAndCheckout() { if (token == null) { LOG.warn("Token not set!"); return; } else { gitUtils.commit(LOCALPATH, "add new file."); Ref ref = gitUtils.branchCreate(LOCALPATH, BRANCHNAME); assertEquals(true, ref.getName().endsWith(BRANCHNAME)); ref = gitUtils.checkout(LOCALPATH, BRANCHNAME); assertEquals(true, ref.getName().endsWith(BRANCHNAME)); } }
Example #30
Source File: JGitAPIImpl.java From git-client-plugin with MIT License | 5 votes |
/** {@inheritDoc} */ @Override public Set<GitObject> getTags() throws GitException, InterruptedException { Set<GitObject> peeledTags = new HashSet<>(); Set<String> tagNames = new HashSet<>(); try (Repository repo = getRepository()) { Map<String, Ref> tagsRead = repo.getTags(); for (Map.Entry<String, Ref> entry : tagsRead.entrySet()) { /* Prefer peeled ref if available (for tag commit), otherwise take first tag reference seen */ String tagName = entry.getKey(); Ref tagRef = entry.getValue(); if (!tagRef.isPeeled()) { Ref peeledRef = repo.peel(tagRef); if (peeledRef.getPeeledObjectId() != null) { tagRef = peeledRef; // Use peeled ref instead of annotated ref } } /* Packed lightweight (non-annotated) tags can wind up peeled with no peeled obj ID */ if (tagRef.isPeeled() && tagRef.getPeeledObjectId() != null) { peeledTags.add(new GitObject(tagName, tagRef.getPeeledObjectId())); } else if (!tagNames.contains(tagName)) { peeledTags.add(new GitObject(tagName, tagRef.getObjectId())); } tagNames.add(tagName); } } return peeledTags; }