/** * Returns a RefModel for the refs/meta/gitblit/tickets branch in the repository. If the branch * can not be found, null is returned. * * @return a refmodel for the gitblit tickets branch or null */ private RefModel getTicketsBranch(Repository db) { List<RefModel> refs = JGitUtils.getRefs(db, "refs/"); Ref oldRef = null; for (RefModel ref : refs) { if (ref.reference.getName().equals(BRANCH)) { return ref; } else if (ref.reference.getName().equals("refs/gitblit/tickets")) { oldRef = ref.reference; } } if (oldRef != null) { // rename old ref to refs/meta/gitblit/tickets RefRename cmd; try { cmd = db.renameRef(oldRef.getName(), BRANCH); cmd.setRefLogIdent(new PersonIdent("Gitblit", "gitblit@localhost")); cmd.setRefLogMessage("renamed " + oldRef.getName() + " => " + BRANCH); Result res = cmd.rename(); switch (res) { case RENAMED: log.info(db.getDirectory() + " " + cmd.getRefLogMessage()); return getTicketsBranch(db); default: log.error( "failed to rename " + oldRef.getName() + " => " + BRANCH + " (" + res.name() + ")"); } } catch (IOException e) { log.error("failed to rename tickets branch", e); } } return null; }
@Test public void logAllCommits() throws Exception { List<RevCommit> commits = new ArrayList<RevCommit>(); Git git = Git.wrap(db); writeTrashFile("Test.txt", "Hello world"); git.add().addFilepattern("Test.txt").call(); commits.add(git.commit().setMessage("initial commit").call()); git.branchCreate().setName("branch1").call(); Ref checkedOut = git.checkout().setName("branch1").call(); assertEquals("refs/heads/branch1", checkedOut.getName()); writeTrashFile("Test1.txt", "Hello world!"); git.add().addFilepattern("Test1.txt").call(); commits.add(git.commit().setMessage("branch1 commit").call()); checkedOut = git.checkout().setName("master").call(); assertEquals("refs/heads/master", checkedOut.getName()); writeTrashFile("Test2.txt", "Hello world!!"); git.add().addFilepattern("Test2.txt").call(); commits.add(git.commit().setMessage("branch1 commit").call()); Iterator<RevCommit> log = git.log().all().call().iterator(); assertTrue(log.hasNext()); assertTrue(commits.contains(log.next())); assertTrue(log.hasNext()); assertTrue(commits.contains(log.next())); assertTrue(log.hasNext()); assertTrue(commits.contains(log.next())); assertFalse(log.hasNext()); }
private void revalidate(RepositorySelection repoSelection, List<Ref> branches, Ref head) { if (repoSelection.equals(validatedRepoSelection) && branches.equals(validatedSelectedBranches) && head.equals(validatedHEAD)) { checkPage(); return; } if (!repoSelection.equals(validatedRepoSelection)) { validatedRepoSelection = repoSelection; // update repo-related selection only if it changed final String n = validatedRepoSelection.getURI().getHumanishName(); setDescription(NLS.bind(UIText.CloneDestinationPage_description, n)); directoryText.setText( new File(ResourcesPlugin.getWorkspace().getRoot().getRawLocation().toFile(), n) .getAbsolutePath()); } validatedSelectedBranches = branches; validatedHEAD = head; initialBranch.removeAll(); final Ref actHead = head; int newix = 0; for (final Ref r : branches) { String name = r.getName(); if (name.startsWith(Constants.R_HEADS)) name = name.substring((Constants.R_HEADS).length()); if (actHead != null && actHead.getName().equals(r.getName())) newix = initialBranch.getItemCount(); initialBranch.add(name); } initialBranch.select(newix); checkPage(); }
@Override public void create() { super.create(); setTitle(UIText.BranchRenameDialog_Title); String oldName = branchToRename.getName(); String prefix; if (oldName.startsWith(Constants.R_HEADS)) prefix = Constants.R_HEADS; else if (oldName.startsWith(Constants.R_REMOTES)) prefix = Constants.R_REMOTES; else prefix = null; String shortName = null; if (prefix != null) { shortName = Repository.shortenRefName(branchToRename.getName()); setMessage(NLS.bind(UIText.BranchRenameDialog_Message, shortName)); } else setErrorMessage(NLS.bind(UIText.BranchRenameDialog_WrongPrefixErrorMessage, oldName)); if (shortName != null) { name.setText(shortName); name.setSelection(0, shortName.length()); } final IInputValidator inputValidator = ValidationUtils.getRefNameInputValidator(repository, prefix, true); name.addModifyListener( new ModifyListener() { public void modifyText(ModifyEvent e) { String error = inputValidator.isValid(name.getText()); setErrorMessage(error); getButton(OK).setEnabled(error == null); } }); getButton(OK).setEnabled(false); }
private Ref resolve( final Ref ref, int depth, String prefix, RefList<LooseRef> loose, RefList<Ref> packed) throws IOException { if (ref.isSymbolic()) { Ref dst = ref.getTarget(); if (MAX_SYMBOLIC_REF_DEPTH <= depth) return null; // claim it doesn't exist // If the cached value can be assumed to be current due to a // recent scan of the loose directory, use it. if (loose != null && dst.getName().startsWith(prefix)) { int idx; if (0 <= (idx = loose.find(dst.getName()))) dst = loose.get(idx); else if (0 <= (idx = packed.find(dst.getName()))) dst = packed.get(idx); else return ref; } else { dst = readRef(dst.getName(), packed); if (dst == null) return ref; } dst = resolve(dst, depth + 1, prefix, loose, packed); if (dst == null) return null; return new SymbolicRef(ref.getName(), dst); } return ref; }
private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException, IOException { try (RevWalk rw = new RevWalk(getRepository())) { RevObject obj = rw.parseAny(leaf.getObjectId()); if (obj instanceof RevTag) { return new ObjectIdRef.PeeledTag( leaf.getStorage(), leaf.getName(), leaf.getObjectId(), rw.peel(obj).copy()); } else { return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf.getName(), leaf.getObjectId()); } } }
/** * Constructs this page. * * <p>If a base branch is provided, the drop down will be selected accordingly * * @param repo the repository * @param baseRef the branch or tag to base the new branch on, may be null */ public CreateBranchPage(Repository repo, Ref baseRef) { super(CreateBranchPage.class.getName()); this.myRepository = repo; if (baseRef != null) this.myBaseRef = baseRef.getName(); else this.myBaseRef = null; this.myBaseCommit = null; this.myValidator = ValidationUtils.getRefNameInputValidator(myRepository, Constants.R_HEADS, false); if (baseRef != null) this.upstreamConfig = UpstreamConfig.getDefault(repo, baseRef.getName()); else this.upstreamConfig = UpstreamConfig.NONE; setTitle(UIText.CreateBranchPage_Title); setMessage(UIText.CreateBranchPage_ChooseBranchAndNameMessage); }
// build both the allBranches sorted arrayList and the branches map private void buildBranchesMap(int size) throws GitAPIException { if (branches != null) { System.err.println( "GitMIner ( " + name + " -- " + id + " ) ERROR : the map of the branches has already been built!"); return; } branches = new LinkedHashMap<String, ArrayList<BranchRef>>(size, 1); allBranches = new ArrayList<BranchRef>(); ArrayList<BranchRef> temp = null; BranchRef br; Ref r; ArrayList<Ref> all = (ArrayList<Ref>) git.branchList().setListMode(ListMode.REMOTE).call(); Iterator<Ref> allBs = all.iterator(); String bName = ""; allBranches.ensureCapacity(all.size()); // int j = 0; while (allBs.hasNext()) { /**/ // System.err.println("###### Iteration " + (++j)); r = allBs.next(); if (!(r.getName().split("/")[2]).equals(bName)) { bName = r.getName().split("/")[2]; // getName() format: // refs/remotes/<remote-name>/<branch-name> if (temp != null) temp.trimToSize(); temp = new ArrayList<BranchRef>(); branches.put(bName, temp); } br = new BranchRef(r); temp.add(br); allBranches.add(br); } allBranches.trimToSize(); Collections.sort(allBranches); for (int i = 0; i < allBranches.size(); i++) { allBranches.get(i).index = i; } // Entry<String, ArrayList<BranchRef>> e; // Iterator<Entry<String, ArrayList<BranchRef>>> eit = branches.entrySet().iterator(); // while (eit.hasNext()) { // e = eit.next(); // System.out.println("\t" + e.getKey() + ":\n"); // printAny(e.getValue(), System.out); // } // printArray(allBranches, System.out); }
private Ref resolve(Ref ref, int depth, RefList<Ref> loose) throws IOException { if (!ref.isSymbolic()) return ref; Ref dst = ref.getTarget(); if (MAX_SYMBOLIC_REF_DEPTH <= depth) return null; // claim it doesn't exist dst = loose.get(dst.getName()); if (dst == null) return ref; dst = resolve(dst, depth + 1, loose); if (dst == null) return null; return new SymbolicRef(ref.getName(), dst); }
/** * Make sure a ref is peeled and has the Storage PACKED. If the given ref has this attributes * simply return it. Otherwise create a new peeled {@link ObjectIdRef} where Storage is set to * PACKED. * * @param f * @return a ref for Storage PACKED having the same name, id, peeledId as f * @throws MissingObjectException * @throws IOException */ private Ref peeledPackedRef(Ref f) throws MissingObjectException, IOException { if (f.getStorage().isPacked() && f.isPeeled()) { return f; } if (!f.isPeeled()) { f = peel(f); } ObjectId peeledObjectId = f.getPeeledObjectId(); if (peeledObjectId != null) { return new ObjectIdRef.PeeledTag(PACKED, f.getName(), f.getObjectId(), peeledObjectId); } else { return new ObjectIdRef.PeeledNonTag(PACKED, f.getName(), f.getObjectId()); } }
@Test public void test() throws Exception { GitService git = lookup(GitService.class); File gitDir = git.getWorkingDir(); String tag = "mock-1.0" + System.currentTimeMillis(); VersionContext context = new VersionContext(0, tag, "test", "test", "test"); git.setup(context); git.pull(context); git.clearWorkingDir(context); downloadAndExtractTo(tag, gitDir); ObjectId objId = git.commit(context); git.push(context); Collection<Ref> refs = git.lsRemote(); boolean tagExist = false; boolean commitSuccess = false; if (refs != null) { for (Ref ref : refs) { if (ref.getName().equals(REFS_TAGS + tag)) { tagExist = true; } if (ref.getObjectId().getName().equals(objId.getName())) { commitSuccess = true; } } } Assert.assertTrue(tagExist); Assert.assertTrue(commitSuccess); git.removeTag(context); refs = git.lsRemote(); tagExist = false; if (refs != null) { for (Ref ref : refs) { if (ref.getName().equals(REFS_TAGS + tag)) { tagExist = true; } } } Assert.assertFalse(tagExist); }
private boolean isLocalBranch(Git git, String branch) throws GitAPIException { List<Ref> branches = git.branchList().call(); for (Ref ref : branches) { if (Repository.shortenRefName(ref.getName()).equals(branch)) return true; } return false; }
private Iterable<ChangeData> byCommitsOnBranchNotMergedFromDatabase( Repository repo, ReviewDb db, Branch.NameKey branch, List<String> hashes) throws OrmException, IOException { Set<Change.Id> changeIds = Sets.newHashSetWithExpectedSize(hashes.size()); String lastPrefix = null; for (Ref ref : repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES).values()) { String r = ref.getName(); if ((lastPrefix != null && r.startsWith(lastPrefix)) || !hashes.contains(ref.getObjectId().name())) { continue; } Change.Id id = Change.Id.fromRef(r); if (id == null) { continue; } if (changeIds.add(id)) { lastPrefix = r.substring(0, r.lastIndexOf('/')); } } List<ChangeData> cds = new ArrayList<>(hashes.size()); for (Change c : db.changes().get(changeIds)) { if (c.getDest().equals(branch) && c.getStatus() != Change.Status.MERGED) { cds.add(changeDataFactory.create(db, c)); } } return cds; }
private static Ref recreate(final Ref old, final ObjectIdRef leaf) { if (old.isSymbolic()) { Ref dst = recreate(old.getTarget(), leaf); return new SymbolicRef(old.getName(), dst); } return leaf; }
private Iterable<RevCommit> getCommitsFromTag(String treeName) { try { List<Ref> call = git.tagList().call(); Iterable<RevCommit> logs = null; for (Ref ref : call) { if (ref.getName().equals(treeName)) { LogCommand log = git.log(); Ref peeledRef = repository.peel(ref); if (peeledRef.getPeeledObjectId() != null) { log.add(peeledRef.getPeeledObjectId()); } else { log.add(ref.getObjectId()); } logs = log.call(); return logs; } } return null; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (MissingObjectException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (IncorrectObjectTypeException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
private DhtRef doPeel(final Ref leaf) throws MissingObjectException, IOException { RevWalk rw = new RevWalk(getRepository()); try { DhtReader ctx = (DhtReader) rw.getObjectReader(); RevObject obj = rw.parseAny(leaf.getObjectId()); RefData.Builder d = RefData.newBuilder(((DhtRef) leaf).getRefData()); ChunkKey oKey = ctx.findChunk(leaf.getObjectId()); if (oKey != null) d.getTargetBuilder().setChunkKey(oKey.asString()); else d.getTargetBuilder().clearChunkKey(); if (obj instanceof RevTag) { ObjectId pId = rw.peel(obj); d.getPeeledBuilder().setObjectName(pId.name()); ChunkKey pKey = ctx.findChunk(pId); if (pKey != null) d.getPeeledBuilder().setChunkKey(pKey.asString()); else d.getPeeledBuilder().clearChunkKey(); } else { d.clearPeeled(); } d.setIsPeeled(true); d.setSequence(d.getSequence() + 1); return new DhtObjectIdRef(leaf.getName(), d.build()); } finally { rw.release(); } }
@Override public Map<String, Ref> getRefs(String prefix) throws IOException { final RefList<LooseRef> oldLoose = looseRefs.get(); LooseScanner scan = new LooseScanner(oldLoose); scan.scan(prefix); final RefList<Ref> packed = getPackedRefs(); RefList<LooseRef> loose; if (scan.newLoose != null) { scan.newLoose.sort(); loose = scan.newLoose.toRefList(); if (looseRefs.compareAndSet(oldLoose, loose)) modCnt.incrementAndGet(); } else loose = oldLoose; fireRefsChanged(); RefList.Builder<Ref> symbolic = scan.symbolic; for (int idx = 0; idx < symbolic.size(); ) { final Ref symbolicRef = symbolic.get(idx); final Ref resolvedRef = resolve(symbolicRef, 0, prefix, loose, packed); if (resolvedRef != null && resolvedRef.getObjectId() != null) { symbolic.set(idx, resolvedRef); idx++; } else { // A broken symbolic reference, we have to drop it from the // collections the client is about to receive. Should be a // rare occurrence so pay a copy penalty. symbolic.remove(idx); final int toRemove = loose.find(symbolicRef.getName()); if (0 <= toRemove) loose = loose.remove(toRemove); } } symbolic.sort(); return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList()); }
private void doCheckout(final Ref branch) throws IOException { if (branch == null) throw die(CLIText.get().cannotChekoutNoHeadsAdvertisedByRemote); if (!Constants.HEAD.equals(branch.getName())) { RefUpdate u = db.updateRef(Constants.HEAD); u.disableRefLog(); u.link(branch.getName()); } final RevCommit commit = parseCommit(branch); final RefUpdate u = db.updateRef(Constants.HEAD); u.setNewObjectId(commit); u.forceUpdate(); DirCache dc = db.lockDirCache(); DirCacheCheckout co = new DirCacheCheckout(db, dc, commit.getTree()); co.checkout(); }
@Override protected Result doDelete(Result desiredResult) throws IOException { if (getRefDatabase().compareAndRemove(dstRef)) { getRefDatabase().removed(dstRef.getName()); return desiredResult; } return Result.LOCK_FAILURE; }
boolean performClone() { final URIish uri = cloneSource.getSelection().getURI(); setWindowTitle(NLS.bind(UIText.GitCloneWizard_jobName, uri.toString())); final boolean allSelected; final Collection<Ref> selectedBranches; if (validSource.isSourceRepoEmpty()) { // fetch all branches of empty repo allSelected = true; selectedBranches = Collections.emptyList(); } else { allSelected = validSource.isAllSelected(); selectedBranches = validSource.getSelectedBranches(); } final File workdir = cloneDestination.getDestinationFile(); final Ref ref = cloneDestination.getInitialBranch(); final String remoteName = cloneDestination.getRemote(); boolean created = workdir.exists(); if (!created) created = workdir.mkdirs(); if (!created || !workdir.isDirectory()) { final String errorMessage = NLS.bind(UIText.GitCloneWizard_errorCannotCreate, workdir.getPath()); ErrorDialog.openError( getShell(), getWindowTitle(), UIText.GitCloneWizard_failed, new Status(IStatus.ERROR, Activator.getPluginId(), 0, errorMessage, null)); // let's give user a chance to fix this minor problem return false; } int timeout = Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT); final CloneOperation op = new CloneOperation( uri, allSelected, selectedBranches, workdir, ref != null ? ref.getName() : null, remoteName, timeout); if (gerritConfiguration.configureGerrit()) doGerritConfiguration(remoteName, op); UserPasswordCredentials credentials = cloneSource.getCredentials(); if (credentials != null) op.setCredentialsProvider( new UsernamePasswordCredentialsProvider( credentials.getUser(), credentials.getPassword())); alreadyClonedInto = workdir.getPath(); cloneSource.saveUriInPrefs(); if (!callerRunsCloneOperation) runAsJob(uri, op); else cloneOperation = op; return true; }
@Override protected Result doUpdate(Result desiredResult) throws IOException { ObjectIdRef newRef; RevObject obj = rw.parseAny(getNewObjectId()); if (obj instanceof RevTag) { newRef = new ObjectIdRef.PeeledTag( Storage.PACKED, dstRef.getName(), getNewObjectId(), rw.peel(obj).copy()); } else { newRef = new ObjectIdRef.PeeledNonTag(Storage.PACKED, dstRef.getName(), getNewObjectId()); } if (getRefDatabase().compareAndPut(dstRef, newRef)) { getRefDatabase().stored(newRef); return desiredResult; } return Result.LOCK_FAILURE; }
private List<String> getTags() { RevCommit commit = getCommit().getRevCommit(); Repository repository = getCommit().getRepository(); List<String> tags = new ArrayList<String>(); for (Ref tag : repository.getTags().values()) if (commit.equals(repository.peel(tag).getPeeledObjectId())) tags.add(Repository.shortenRefName(tag.getName())); Collections.sort(tags); return tags; }
@NotNull public RepositoryStateData getCurrentState(@NotNull GitVcsRoot gitRoot) throws VcsException { String refInRoot = gitRoot.getRef(); String fullRef = GitUtils.expandRef(refInRoot); Map<String, String> branchRevisions = new HashMap<String, String>(); for (Ref ref : getRemoteRefs(gitRoot.getOriginalRoot()).values()) { if (!ref.getName().startsWith("ref")) continue; if (!gitRoot.isReportTags() && isTag(ref) && !fullRef.equals(ref.getName())) continue; branchRevisions.put(ref.getName(), getRevision(ref)); } if (branchRevisions.get(fullRef) == null && !gitRoot.isIgnoreMissingDefaultBranch()) { throw new VcsException( "Cannot find revision of the default branch '" + refInRoot + "' of vcs root " + LogUtil.describe(gitRoot)); } return RepositoryStateData.createVersionState(fullRef, branchRevisions); }
public static void main(String[] args) throws IOException, GitAPIException { Repository repository = CookbookHelper.openJGitCookbookRepository(); List<Ref> refs = new Git(repository).branchList().call(); for (Ref ref : refs) { System.out.println( "Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); listReflog(repository, ref); } List<Ref> call = new Git(repository).tagList().call(); for (Ref ref : call) { System.out.println("Tag: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName()); listReflog(repository, ref); } repository.close(); }
@Override protected Result doLink(String target) throws IOException { final SymbolicRef newRef = new SymbolicRef(dstRef.getName(), new ObjectIdRef.Unpeeled(Storage.NEW, target, null)); if (getRefDatabase().compareAndPut(dstRef, newRef)) { getRefDatabase().stored(newRef); if (dstRef.getStorage() == Ref.Storage.NEW) return Result.NEW; return Result.FORCED; } return Result.LOCK_FAILURE; }
/** * Obtain a modified copy of the cache with a ref stored. * * <p>This cache instance is not modified by this method. * * @param ref reference to add or replace. * @return a copy of this cache, with the reference added or replaced. */ public RefCache put(Ref ref) { RefList<Ref> newIds = this.ids.put(ref); RefList<Ref> newSym = this.sym; if (ref.isSymbolic()) { newSym = newSym.put(ref); } else { int p = newSym.find(ref.getName()); if (0 <= p) newSym = newSym.remove(p); } return new RefCache(newIds, newSym); }
private static Ref guessHEAD(final FetchResult result) { final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD); Ref head = null; for (final Ref r : result.getAdvertisedRefs()) { final String n = r.getName(); if (!n.startsWith(Constants.R_HEADS)) continue; if (idHEAD == null || head != null) continue; if (r.getObjectId().equals(idHEAD.getObjectId())) head = r; } if (idHEAD != null && head == null) head = idHEAD; return head; }
public static JSONArray getListEntries( TreeWalk treeWalk, Repository repo, Git git, Ref head, String filePath, String projectName) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { JSONArray contents = new JSONArray(); do { if (treeWalk.isSubtree()) { String test = new String(treeWalk.getRawPath()); if (test.length() /*treeWalk.getPathLength()*/ > filePath.length()) { listEntry( treeWalk.getNameString(), "dir", "0", treeWalk.getPathString(), projectName, head.getName(), git, contents); } if (test.length() /*treeWalk.getPathLength()*/ <= filePath.length()) { treeWalk.enterSubtree(); } } else { ObjectId objId = treeWalk.getObjectId(0); ObjectLoader loader = repo.open(objId); long size = loader.getSize(); listEntry( treeWalk.getNameString(), "file", Long.toString(size), treeWalk.getPathString(), projectName, head.getName(), git, contents); } } while (treeWalk.next()); return contents; }
public static Ref checkout( final Git git, final Ref localRef, final boolean createBranch, final SetupUpstreamMode mode, final boolean force) throws GitAPIException { CheckoutCommand checkout = git.checkout(); checkout.setName(Repository.shortenRefName(localRef.getName())); checkout.setForce(force); checkout.setUpstreamMode(mode); return checkout.call(); }
private Ref readRef(final TreeMap<String, Ref> avail, final String rn) throws TransportException { final String s; String ref = ROOT_DIR + rn; try { final BufferedReader br = openReader(ref); try { s = br.readLine(); } finally { br.close(); } } catch (FileNotFoundException noRef) { return null; } catch (IOException err) { throw new TransportException(getURI(), "read " + ref, err); } if (s == null) throw new TransportException(getURI(), "Empty ref: " + rn); if (s.startsWith("ref: ")) { final String target = s.substring("ref: ".length()); Ref r = avail.get(target); if (r == null) r = readRef(avail, target); if (r == null) return null; r = new Ref(r.getStorage(), rn, r.getObjectId(), r.getPeeledObjectId(), r.isPeeled()); avail.put(r.getName(), r); return r; } if (ObjectId.isId(s)) { final Ref r = new Ref(loose(avail.get(rn)), rn, ObjectId.fromString(s)); avail.put(r.getName(), r); return r; } throw new TransportException(getURI(), "Bad ref: " + rn + ": " + s); }