/// <summary> /// Compute the tracking status for the <code>branchName</code> in /// <code>repository</code>. /// </summary> /// <remarks> /// Compute the tracking status for the <code>branchName</code> in /// <code>repository</code>. /// </remarks> /// <param name="repository">the git repository to compute the status from</param> /// <param name="branchName">the local branch</param> /// <returns>the tracking status, or null if it is not known</returns> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public static NGit.BranchTrackingStatus Of(Repository repository, string branchName ) { BranchConfig branchConfig = new BranchConfig(repository.GetConfig(), branchName); string trackingBranch = branchConfig.GetTrackingBranch(); if (trackingBranch == null) { return null; } Ref tracking = repository.GetRef(trackingBranch); if (tracking == null) { return null; } Ref local = repository.GetRef(branchName); if (local == null) { return null; } RevWalk walk = new RevWalk(repository); RevCommit localCommit = walk.ParseCommit(local.GetObjectId()); RevCommit trackingCommit = walk.ParseCommit(tracking.GetObjectId()); walk.SetRevFilter(RevFilter.MERGE_BASE); walk.MarkStart(localCommit); walk.MarkStart(trackingCommit); RevCommit mergeBase = walk.Next(); walk.Reset(); walk.SetRevFilter(RevFilter.ALL); int aheadCount = RevWalkUtils.Count(walk, localCommit, mergeBase); int behindCount = RevWalkUtils.Count(walk, trackingCommit, mergeBase); return new NGit.BranchTrackingStatus(trackingBranch, aheadCount, behindCount); }
public InitialGenerator(RevWalk w, Generator s, BoundaryGenerator parent) // [henon] parent needed because we cannot access outer instances in C# { _walk = w; _held = new FIFORevQueue(); _source = s; _source.shareFreeList(_held); _parent = parent; }
/// <exception cref="NGit.Errors.StopWalkException"></exception> /// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> public override bool Include(RevWalk walker, RevCommit cmit) { if (skip > count++) { return false; } return true; }
public void parseCanonical(RevWalk walk, byte[] raw) { MutableObjectId idBuffer = walk.idBuffer; idBuffer.FromString(raw, 5); tree = walk.lookupTree(idBuffer); int ptr = 46; if (parents == null) { RevCommit[] pList = new RevCommit[1]; int nParents = 0; for (; ; ) { if (raw[ptr] != (byte)'p') break; idBuffer.FromString(raw, ptr + 7); RevCommit p = walk.lookupCommit(idBuffer); if (nParents == 0) pList[nParents++] = p; else if (nParents == 1) { pList = new RevCommit[] { pList[0], p }; nParents = 2; } else { if (pList.Length <= nParents) { RevCommit[] old = pList; pList = new RevCommit[pList.Length + 32]; Array.Copy(old, 0, pList, 0, nParents); } pList[nParents++] = p; } ptr += 48; } if (nParents != pList.Length) { RevCommit[] old = pList; pList = new RevCommit[nParents]; Array.Copy(old, 0, pList, 0, nParents); } parents = pList; } // extract time from "committer " ptr = RawParseUtils.committer(raw, ptr); if (ptr > 0) { ptr = RawParseUtils.nextLF(raw, ptr, (byte)'>'); // In 2038 commitTime will overflow unless it is changed to long. commitTime = RawParseUtils.parseBase10(raw, ptr, null); } buffer = raw; flags |= PARSED; }
/// <exception cref="NGit.Errors.StopWalkException"></exception> /// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> public override bool Include(RevWalk walker, RevCommit cmit) { count++; if (count > maxCount) { throw StopWalkException.INSTANCE; } return true; }
public RebaseOperation (NGit.Repository repo, string upstreamRef, IProgressMonitor monitor) { this.monitor = monitor; this.repo = repo; this.upstreamRef = upstreamRef; rw = new RevWalk (repo); branch = repo.GetBranch (); starting = true; }
internal override void parseBody(RevWalk walk) { if (_buffer == null) { _buffer = loadCanonical(walk); if ((Flags & PARSED) == 0) parseCanonical(walk, _buffer); } }
public virtual void TestTaggingOnHead() { Git git = new Git(db); RevCommit commit = git.Commit().SetMessage("initial commit").Call(); Ref tagRef = git.Tag().SetName("tag").Call(); NUnit.Framework.Assert.AreEqual(commit.Id, db.Peel(tagRef).GetPeeledObjectId()); RevWalk walk = new RevWalk(db); NUnit.Framework.Assert.AreEqual("tag", walk.ParseTag(tagRef.GetObjectId()).GetTagName ()); }
internal override void parse(RevWalk walk) { ObjectLoader ldr = walk.db.openObject(walk.curs, this); if (ldr == null) throw new MissingObjectException(this, TYPE_COMMIT); byte[] data = ldr.getCachedBytes(); if (Constants.OBJ_COMMIT != ldr.getType()) throw new IncorrectObjectTypeException(this, TYPE_COMMIT); parseCanonical(walk, data); }
public string GetFullMessage(string hash) { var walk = new RevWalk(this.git.GetRepository()); RevCommit commit = walk.ParseCommit(ObjectId.FromString(hash)); walk.Dispose(); return commit.GetFullMessage(); }
public IEnumerable<CommitInfo> ListCommits() { using(var repository = new GitSharp.Repository(FullPath)) { var w = new RevWalk(repository); w.markStart(((GitSharp.Core.Repository)repository).getAllRefsByPeeledObjectId().Keys.Select(w.parseCommit)); return w.Select(t => new CommitInfo { Id = t.getId().Name, Date = t.AsCommit(w).Author.When.MillisToDateTimeOffset(t.AsCommit(w).Author.TimeZoneOffset), Message = t.getShortMessage() }).ToArray(); } }
public RefAdvertiser(PacketLineOut o, RevWalk.RevWalk protoWalk, RevFlag advertisedFlag) { _tmpLine = new StringBuilder(100); _tmpId = new char[2 * Constants.OBJECT_ID_LENGTH]; _capabilities = new List<string>(); _first = true; _pckOut = o; _walk = protoWalk; ADVERTISED = advertisedFlag; }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> internal override void ParseHeaders(RevWalk walk) { if (walk.reader.Has(this)) { flags |= PARSED; } else { throw new MissingObjectException(this, Type); } }
public RepositoryWalker(CoreRepository repo) { if (repo == null) { throw new ArgumentNullException(nameof(repo)); } _walker = new RevWalk(repo); _assistantWalker = new RevWalk(repo); _initCommit = new RevCommit(repo.Head.ObjectId); }
/// <exception cref="System.Exception"></exception> public virtual void Setup(int count) { Git git = new Git(db); for (int i = 0; i < count; i++) { git.Commit().SetCommitter(committer).SetAuthor(author).SetMessage("commit " + i). Call(); } list = new RevCommitList<RevCommit>(); RevWalk w = new RevWalk(db); w.MarkStart(w.LookupCommit(db.Resolve(Constants.HEAD))); list.Source(w); }
public ActionResult FileDiff(string path, string fromSha1,string toSha1) { var nGit = TM_UserData_Git.Current.NGit; Func<Repository, string, string, string, string> getDiff = (gitRepo, repoPath, fromCommitId, toCommitId) => { var fromCommit = gitRepo.Resolve(fromCommitId); var toCommit = gitRepo.Resolve(toCommitId); var outputStream = "Sharpen.dll".assembly().type("ByteArrayOutputStream").ctor(new object[0]).cast<OutputStream>(); //return "diffing from {0} to {1}".format(fromCommit, toCommit); var diffFormater = new DiffFormatter(outputStream); var pathFilter = PathFilter.Create(repoPath); diffFormater.SetRepository(gitRepo); diffFormater.SetPathFilter(pathFilter); //diffFormater.Format(refLog.GetNewId(), refLog.GetOldId()); diffFormater.Format(fromCommit, toCommit); return "result: " + outputStream.str(); }; Func<Repository, string, string, string> getFistValue = (gitRepo, commitSha1, repoPath) => { var revCommit = nGit.commit(commitSha1); var outputStream = "Sharpen.dll".assembly().type("ByteArrayOutputStream").ctor(new object[0]).cast<OutputStream>(); var diffFormater = new DiffFormatter(outputStream); var pathFilter = PathFilter.Create(repoPath); diffFormater.SetRepository(gitRepo); diffFormater.SetPathFilter(pathFilter); var revWalk = new RevWalk(gitRepo); var canonicalTreeParser = new CanonicalTreeParser(null, revWalk.GetObjectReader(), revCommit.Tree); diffFormater.Format(new EmptyTreeIterator(), canonicalTreeParser); return outputStream.str().fix_CRLF(); }; var rawDiff = fromSha1 == NGit_Consts.EMPTY_SHA1 ? getFistValue(nGit.repository(), fromSha1, path) : getDiff(nGit.repository(), path, fromSha1, toSha1); var viewFile = new View_GitFileDiff() { FilePath = path, FromSha1 = fromSha1, ToSha1 = toSha1, Diff = rawDiff }; return View(viewFile); }
/// <exception cref="System.InvalidOperationException"></exception> /// <exception cref="System.IO.IOException"></exception> private void CheckoutCommit(RevCommit commit) { RevWalk walk = new RevWalk(db); RevCommit head = walk.ParseCommit(db.Resolve(Constants.HEAD)); DirCacheCheckout dco = new DirCacheCheckout(db, head.Tree, db.LockDirCache(), commit .Tree); dco.SetFailOnConflict(true); dco.Checkout(); walk.Release(); // update the HEAD RefUpdate refUpdate = db.UpdateRef(Constants.HEAD, true); refUpdate.SetNewObjectId(commit); refUpdate.ForceUpdate(); }
public void parseCanonical(RevWalk walk, byte[] rawTag) { MutableInteger pos = new MutableInteger(); int oType; pos.value = 53; // "@object $sha1\ntype " oType = Constants.decodeTypeString(this, rawTag, (byte)'\n', pos); walk.idBuffer.FromString(rawTag, 7); @object = walk.lookupAny(walk.idBuffer, oType); int p = pos.value += 4; // "tag " int nameEnd = RawParseUtils.nextLF(rawTag, p) - 1; name = RawParseUtils.decode(Constants.CHARSET, rawTag, p, nameEnd); buffer = rawTag; flags |= PARSED; }
public void parseCanonical(RevWalk walk, byte[] rawTag) { var pos = new MutableInteger { value = 53 }; int oType = Constants.decodeTypeString(this, rawTag, (byte)'\n', pos); walk.IdBuffer.FromString(rawTag, 7); _object = walk.lookupAny(walk.IdBuffer, oType); int p = pos.value += 4; // "tag " int nameEnd = RawParseUtils.nextLF(rawTag, p) - 1; _tagName = RawParseUtils.decode(Constants.CHARSET, rawTag, p, nameEnd); if (walk.isRetainBody()) _buffer = rawTag; Flags |= PARSED; }
private RevWalk CreateRevWalker() { var repository = _git.GetRepository(); try { var revWalk = new RevWalk(repository); foreach (var reference in repository.GetAllRefs()) { revWalk.MarkStart(revWalk.ParseCommit(reference.Value.GetObjectId())); } return revWalk; } finally { repository.Close(); } }
public override CommitInfo GetLatestCommit() { using (var repository = GetRepository()) { var repo = (FileRepository)repository; var branch = repo.GetBranch(); if (branch == null) return null; var objId = repo.Resolve(branch); if (objId == null) return null; RevWalk walk = new RevWalk(repo); RevCommit commit = walk.ParseCommit(objId); if (commit == null) return null; return new CommitInfo { Message = commit.GetFullMessage(), Date = commit.GetCommitterIdent().GetWhen().ToLocalTime() }; } }
public virtual void TestEquals() { RevCommit a1 = Commit(); RevCommit b1 = Commit(); NUnit.Framework.Assert.IsTrue(a1.Equals(a1)); NUnit.Framework.Assert.IsTrue(a1.Equals((object)a1)); NUnit.Framework.Assert.IsFalse(a1.Equals(b1)); NUnit.Framework.Assert.IsTrue(a1.Equals(a1)); NUnit.Framework.Assert.IsTrue(a1.Equals((object)a1)); NUnit.Framework.Assert.IsFalse(a1.Equals(string.Empty)); RevWalk rw2 = new RevWalk(db); RevCommit a2 = rw2.ParseCommit(a1); RevCommit b2 = rw2.ParseCommit(b1); NUnit.Framework.Assert.AreNotSame(a1, a2); NUnit.Framework.Assert.AreNotSame(b1, b2); NUnit.Framework.Assert.IsTrue(a1.Equals(a2)); NUnit.Framework.Assert.IsTrue(b1.Equals(b2)); NUnit.Framework.Assert.AreEqual(a1.GetHashCode(), a2.GetHashCode()); NUnit.Framework.Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); NUnit.Framework.Assert.IsTrue(AnyObjectId.Equals(a1, a2)); NUnit.Framework.Assert.IsTrue(AnyObjectId.Equals(b1, b2)); }
/// <param name="w"></param> /// <param name="s">Parent generator</param> /// <exception cref="NGit.Errors.MissingObjectException">NGit.Errors.MissingObjectException /// </exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException">NGit.Errors.IncorrectObjectTypeException /// </exception> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> internal DepthGenerator(DepthWalk w, Generator s) { pending = new FIFORevQueue(); walk = (RevWalk)w; this.depth = w.GetDepth(); this.UNSHALLOW = w.GetUnshallowFlag(); this.REINTERESTING = w.GetReinterestingFlag(); s.ShareFreeList(pending); // Begin by sucking out all of the source's commits, and // adding them to the pending queue for (; ;) { RevCommit c = s.Next(); if (c == null) { break; } if (((NGit.Revwalk.Depthwalk.Commit)c).GetDepth() == 0) { pending.Add(c); } } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> private ObjectIdRef DoPeel(Ref leaf) { RevWalk rw = new RevWalk(GetRepository()); try { RevObject obj = rw.ParseAny(leaf.GetObjectId()); if (obj is 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 ())); } } finally { rw.Release(); } }
public static API_NGit files(this API_NGit nGit,string commitId, Action<TreeWalk> onTreeWalk) { try { var headCommit = nGit.Repository.Resolve(commitId); if (commitId.notNull()) { var revWalk = new RevWalk(nGit.Repository); var commit = revWalk.ParseCommit(headCommit); var treeWalk = new TreeWalk(nGit.Repository); var tree = commit.Tree; treeWalk.AddTree(tree); treeWalk.Recursive = true; while (treeWalk.Next()) onTreeWalk(treeWalk); } } catch (Exception ex) { ex.log("[API_NGit][getRepoFiles]"); } return nGit ; }
private void InitRevPool(bool reverse) { if (queue != null) { throw new InvalidOperationException(); } if (revPool != null) { revPool.Release(); } if (reverse) { revPool = new ReverseWalk(GetRepository()); } else { revPool = new RevWalk(GetRepository()); } revPool.SetRetainBody(true); SEEN = revPool.NewFlag("SEEN"); reader = revPool.GetObjectReader(); treeWalk = new TreeWalk(reader); treeWalk.Recursive = true; }
public virtual void TestEquals() { RevCommit a1 = Commit(); RevCommit b1 = Commit(); NUnit.Framework.Assert.IsTrue(a1.Equals(a1)); NUnit.Framework.Assert.IsTrue(a1.Equals((object)a1)); NUnit.Framework.Assert.IsFalse(a1.Equals(b1)); NUnit.Framework.Assert.IsTrue(a1.Equals(a1)); NUnit.Framework.Assert.IsTrue(a1.Equals((object)a1)); NUnit.Framework.Assert.IsFalse(a1.Equals(string.Empty)); RevWalk rw2 = new RevWalk(db); RevCommit a2 = rw2.ParseCommit(a1); RevCommit b2 = rw2.ParseCommit(b1); NUnit.Framework.Assert.AreNotSame(a1, a2); NUnit.Framework.Assert.AreNotSame(b1, b2); NUnit.Framework.Assert.IsTrue(a1.Equals(a2)); NUnit.Framework.Assert.IsTrue(b1.Equals(b2)); NUnit.Framework.Assert.AreEqual(a1.GetHashCode(), a2.GetHashCode()); NUnit.Framework.Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode()); NUnit.Framework.Assert.IsTrue(AnyObjectId.Equals(a1, a2)); NUnit.Framework.Assert.IsTrue(AnyObjectId.Equals(b1, b2)); }
/// <summary>Set the revision walker this list populates itself from.</summary> /// <remarks>Set the revision walker this list populates itself from.</remarks> /// <param name="w">the walker to populate from.</param> /// <seealso cref="RevCommitList{E}.FillTo(int)">RevCommitList<E>.FillTo(int)</seealso> public virtual void Source(RevWalk w) { walker = w; }
/// <exception cref="NGit.Api.Errors.NotMergedException"> /// when trying to delete a branch which has not been merged into /// the currently checked out branch without force /// </exception> /// <exception cref="NGit.Api.Errors.CannotDeleteCurrentBranchException">NGit.Api.Errors.CannotDeleteCurrentBranchException /// </exception> /// <returns>the list with the (full) names of the deleted branches</returns> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override IList <string> Call() { CheckCallable(); IList <string> result = new AList <string>(); if (branchNames.IsEmpty()) { return(result); } try { string currentBranch = repo.GetFullBranch(); if (!force) { // check if the branches to be deleted // are all merged into the current branch RevWalk walk = new RevWalk(repo); RevCommit tip = walk.ParseCommit(repo.Resolve(Constants.HEAD)); foreach (string branchName in branchNames) { if (branchName == null) { continue; } Ref currentRef = repo.GetRef(branchName); if (currentRef == null) { continue; } RevCommit @base = walk.ParseCommit(repo.Resolve(branchName)); if (!walk.IsMergedInto(@base, tip)) { throw new NotMergedException(); } } } SetCallable(false); foreach (string branchName_1 in branchNames) { if (branchName_1 == null) { continue; } Ref currentRef = repo.GetRef(branchName_1); if (currentRef == null) { continue; } string fullName = currentRef.GetName(); if (fullName.Equals(currentBranch)) { throw new CannotDeleteCurrentBranchException(MessageFormat.Format(JGitText.Get(). cannotDeleteCheckedOutBranch, branchName_1)); } RefUpdate update = repo.UpdateRef(fullName); update.SetRefLogMessage("branch deleted", false); update.SetForceUpdate(true); RefUpdate.Result deleteResult = update.Delete(); bool ok = true; switch (deleteResult) { case RefUpdate.Result.IO_FAILURE: case RefUpdate.Result.LOCK_FAILURE: case RefUpdate.Result.REJECTED: { ok = false; break; } default: { break; break; } } if (ok) { result.AddItem(fullName); if (fullName.StartsWith(Constants.R_HEADS)) { string shortenedName = Sharpen.Runtime.Substring(fullName, Constants.R_HEADS.Length ); // remove upstream configuration if any StoredConfig cfg = repo.GetConfig(); cfg.UnsetSection(ConfigConstants.CONFIG_BRANCH_SECTION, shortenedName); cfg.Save(); } } else { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().deleteBranchUnexpectedResult , deleteResult.ToString())); } } return(result); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> internal abstract void ParseBody(RevWalk walk);
/// <summary>Update the type of this command by checking for fast-forward.</summary> /// <remarks> /// Update the type of this command by checking for fast-forward. /// <p> /// If the command's current type is UPDATE, a merge test will be performed /// using the supplied RevWalk to determine if /// <see cref="GetOldId()">GetOldId()</see> /// is fully /// merged into /// <see cref="GetNewId()">GetNewId()</see> /// . If some commits are not merged the /// update type is changed to /// <see cref="Type.UPDATE_NONFASTFORWARD">Type.UPDATE_NONFASTFORWARD</see> /// . /// </remarks> /// <param name="walk"> /// an instance to perform the merge test with. The caller must /// allocate and release this object. /// </param> /// <exception cref="System.IO.IOException"> /// either oldId or newId is not accessible in the repository /// used by the RevWalk. This usually indicates data corruption, /// and the command cannot be processed. /// </exception> public virtual void UpdateType(RevWalk walk) { if (typeIsCorrect) { return; } if (type == ReceiveCommand.Type.UPDATE && !AnyObjectId.Equals(oldId, newId)) { RevObject o = walk.ParseAny(oldId); RevObject n = walk.ParseAny(newId); if (!(o is RevCommit) || !(n is RevCommit) || !walk.IsMergedInto((RevCommit)o, (RevCommit )n)) { SetType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD); } } typeIsCorrect = true; }
/// <exception cref="System.InvalidOperationException"></exception> /// <exception cref="System.IO.IOException"></exception> protected internal virtual void CheckoutBranch(string branchName) { RevWalk walk = new RevWalk(db); RevCommit head = walk.ParseCommit(db.Resolve(Constants.HEAD)); RevCommit branch = walk.ParseCommit(db.Resolve(branchName)); DirCacheCheckout dco = new DirCacheCheckout(db, head.Tree.Id, db.LockDirCache(), branch.Tree.Id); dco.SetFailOnConflict(true); dco.Checkout(); walk.Release(); // update the HEAD RefUpdate refUpdate = db.UpdateRef(Constants.HEAD); refUpdate.Link(branchName); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> internal override void ParseHeaders(RevWalk walk) { ParseCanonical(walk, walk.GetCachedBytes(this)); }
protected internal override IDictionary <string, Ref> GetAdvertisedRefs(Repository r, RevWalk revWalk) { IDictionary <string, Ref> refs = new Dictionary <string, Ref>(r.GetAllRefs()); NUnit.Framework.Assert.IsNotNull(Sharpen.Collections.Remove(refs, R_PRIVATE)); return(refs); }
/// <param name="repo"></param> protected internal RebaseCommand(Repository repo) : base(repo) { walk = new RevWalk(repo); rebaseDir = new FilePath(repo.Directory, REBASE_MERGE); }
/// <exception cref="System.Exception"></exception> public override void SetUp() { base.SetUp(); util = new TestRepository <Repository>(db, CreateRevWalk()); rw = util.GetRevWalk(); }
/// <summary> /// Executes the /// <code>revert</code> /// command with all the options and parameters /// collected by the setter methods (e.g. /// <see cref="Include(NGit.Ref)">Include(NGit.Ref)</see> /// of this /// class. Each instance of this class should only be used for one invocation /// of the command. Don't call this method twice on an instance. /// </summary> /// <returns> /// on success the /// <see cref="NGit.Revwalk.RevCommit">NGit.Revwalk.RevCommit</see> /// pointed to by the new HEAD is /// returned. If a failure occurred during revert <code>null</code> /// is returned. The list of successfully reverted /// <see cref="NGit.Ref">NGit.Ref</see> /// 's can /// be obtained by calling /// <see cref="GetRevertedRefs()">GetRevertedRefs()</see> /// </returns> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override RevCommit Call() { RevCommit newHead = null; CheckCallable(); RevWalk revWalk = new RevWalk(repo); try { // get the head commit Ref headRef = repo.GetRef(Constants.HEAD); if (headRef == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId()); newHead = headCommit; // loop through all refs to be reverted foreach (Ref src in commits) { // get the commit to be reverted // handle annotated tags ObjectId srcObjectId = src.GetPeeledObjectId(); if (srcObjectId == null) { srcObjectId = src.GetObjectId(); } RevCommit srcCommit = revWalk.ParseCommit(srcObjectId); // get the parent of the commit to revert if (srcCommit.ParentCount != 1) { throw new MultipleParentsNotAllowedException(JGitText.Get().canOnlyRevertCommitsWithOneParent ); } RevCommit srcParent = srcCommit.GetParent(0); revWalk.ParseHeaders(srcParent); ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger (repo)); merger.SetWorkingTreeIterator(new FileTreeIterator(repo)); merger.SetBase(srcCommit.Tree); if (merger.Merge(headCommit, srcParent)) { if (AnyObjectId.Equals(headCommit.Tree.Id, merger.GetResultTreeId())) { continue; } DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), merger.GetResultTreeId()); dco.SetFailOnConflict(true); dco.Checkout(); string newMessage = "Revert \"" + srcCommit.GetShortMessage() + "\"" + "\n\n" + "This reverts commit " + srcCommit.Id.GetName() + "\n"; newHead = new Git(GetRepository()).Commit().SetMessage(newMessage).Call(); revertedRefs.AddItem(src); } else { return(null); } } } catch (IOException e) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionCaughtDuringExecutionOfRevertCommand , e), e); } finally { revWalk.Release(); } return(newHead); }
internal virtual void ParseCanonical(RevWalk walk, byte[] raw) { MutableObjectId idBuffer = walk.idBuffer; idBuffer.FromString(raw, 5); tree = walk.LookupTree(idBuffer); int ptr = 46; if (parents == null) { NGit.Revwalk.RevCommit[] pList = new NGit.Revwalk.RevCommit[1]; int nParents = 0; for (; ;) { if (raw[ptr] != 'p') { break; } idBuffer.FromString(raw, ptr + 7); NGit.Revwalk.RevCommit p = walk.LookupCommit(idBuffer); if (nParents == 0) { pList[nParents++] = p; } else { if (nParents == 1) { pList = new NGit.Revwalk.RevCommit[] { pList[0], p }; nParents = 2; } else { if (pList.Length <= nParents) { NGit.Revwalk.RevCommit[] old = pList; pList = new NGit.Revwalk.RevCommit[pList.Length + 32]; System.Array.Copy(old, 0, pList, 0, nParents); } pList[nParents++] = p; } } ptr += 48; } if (nParents != pList.Length) { NGit.Revwalk.RevCommit[] old = pList; pList = new NGit.Revwalk.RevCommit[nParents]; System.Array.Copy(old, 0, pList, 0, nParents); } parents = pList; } // extract time from "committer " ptr = RawParseUtils.Committer(raw, ptr); if (ptr > 0) { ptr = RawParseUtils.NextLF(raw, ptr, '>'); // In 2038 commitTime will overflow unless it is changed to long. commitTime = RawParseUtils.ParseBase10(raw, ptr, null); } if (walk.IsRetainBody()) { buffer = raw; } flags |= PARSED; }
internal MergeBaseGenerator(RevWalk w) { walker = w; pending = new DateRevQueue(); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> public override bool Include(RevWalk walker, RevCommit c) { return(c.HasAny(flags)); }
/// <summary> /// Find commits that are reachable from <code>start</code> until a commit /// that is reachable from <code>end</code> is encountered. /// </summary> /// <remarks> /// Find commits that are reachable from <code>start</code> until a commit /// that is reachable from <code>end</code> is encountered. In other words, /// Find of commits that are in <code>start</code>, but not in /// <code>end</code>. /// <p> /// Note that this method calls /// <see cref="RevWalk.Reset()">RevWalk.Reset()</see> /// at the beginning. /// Also note that the existing rev filter on the walk is left as-is, so be /// sure to set the right rev filter before calling this method. /// </remarks> /// <param name="walk">the rev walk to use</param> /// <param name="start">the commit to start counting from</param> /// <param name="end"> /// the commit where counting should end, or null if counting /// should be done until there are no more commits /// </param> /// <returns>the commits found</returns> /// <exception cref="NGit.Errors.MissingObjectException">NGit.Errors.MissingObjectException /// </exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException">NGit.Errors.IncorrectObjectTypeException /// </exception> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public static IList<RevCommit> Find(RevWalk walk, RevCommit start, RevCommit end) { walk.Reset(); walk.MarkStart(start); if (end != null) { walk.MarkUninteresting(end); } IList<RevCommit> commits = new AList<RevCommit>(); foreach (RevCommit c in walk) { commits.AddItem(c); } return commits; }
public override void Clear() { base.Clear(); walker = null; }
public override bool include(RevWalk walker, RevCommit c) { // Reset the tree filter to scan this commit and parents. // RevCommit[] pList = c.Parents; int nParents = pList.Length; TreeWalk.TreeWalk tw = _pathFilter; var trees = new ObjectId[nParents + 1]; for (int i = 0; i < nParents; i++) { RevCommit p = c.Parents[i]; if ((p.Flags & Parsed) == 0) { p.parseHeaders(walker); } trees[i] = p.Tree; } trees[nParents] = c.Tree; tw.reset(trees); if (nParents == 1) { // We have exactly one parent. This is a very common case. // int chgs = 0, adds = 0; while (tw.next()) { chgs++; if (tw.getRawMode(0) == 0 && tw.getRawMode(1) != 0) { adds++; } else { break; // no point in looking at this further. } } if (chgs == 0) { // No changes, so our tree is effectively the same as // our parent tree. We pass the buck to our parent. // c.Flags |= Rewrite; return(false); } // We have interesting items, but neither of the special // cases denoted above. // return(true); } if (nParents == 0) { // We have no parents to compare against. Consider us to be // Rewrite only if we have no paths matching our filter. // if (tw.next()) { return(true); } c.Flags |= Rewrite; return(false); } // We are a merge commit. We can only be Rewrite if we are same // to _all_ parents. We may also be able to eliminate a parent if // it does not contribute changes to us. Such a parent may be an // uninteresting side branch. // var chgs_ = new int[nParents]; var adds_ = new int[nParents]; while (tw.next()) { int myMode = tw.getRawMode(nParents); for (int i = 0; i < nParents; i++) { int pMode = tw.getRawMode(i); if (myMode == pMode && tw.idEqual(i, nParents)) { continue; } chgs_[i]++; if (pMode == 0 && myMode != 0) { adds_[i]++; } } } bool same = false; bool diff = false; for (int i = 0; i < nParents; i++) { if (chgs_[i] == 0) { // No changes, so our tree is effectively the same as // this parent tree. We pass the buck to only this one // parent commit. // RevCommit p = pList[i]; if ((p.Flags & Uninteresting) != 0) { // This parent was marked as not interesting by the // application. We should look for another parent // that is interesting. // same = true; continue; } c.Flags |= Rewrite; c.Parents = new[] { p }; return(false); } if (chgs_[i] == adds_[i]) { // All of the differences from this parent were because we // added files that they did not have. This parent is our // "empty tree root" and thus their history is not relevant. // Cut our grandparents to be an empty list. // pList[i].Parents = RevCommit.NoParents; } // We have an interesting difference relative to this parent. // diff = true; } if (diff && !same) { // We did not abort above, so we are different in at least one // way from all of our parents. We have to take the blame for // that difference. // return(true); } // We are the same as all of our parents. We must keep them // as they are and allow those parents to flow into pending // for further scanning. // c.Flags |= Rewrite; return(false); }
// TODO not implemented yet // TODO not implemented yet /// <summary> /// Executes the /// <code>Reset</code> /// command. Each instance of this class should /// only be used for one invocation of the command. Don't call this method /// twice on an instance. /// </summary> /// <returns>the Ref after reset</returns> /// <exception cref="System.IO.IOException"></exception> public override Ref Call() { CheckCallable(); Ref r; RevCommit commit; try { RepositoryState state = repo.GetRepositoryState(); bool merging = state.Equals(RepositoryState.MERGING) || state.Equals(RepositoryState .MERGING_RESOLVED); bool cherryPicking = state.Equals(RepositoryState.CHERRY_PICKING) || state.Equals (RepositoryState.CHERRY_PICKING_RESOLVED); // resolve the ref to a commit ObjectId commitId; try { commitId = repo.Resolve(@ref); } catch (IOException e) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().cannotRead, @ref ), e); } RevWalk rw = new RevWalk(repo); try { commit = rw.ParseCommit(commitId); } catch (IOException e) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().cannotReadCommit , commitId.ToString()), e); } finally { rw.Release(); } if (!filepaths.IsEmpty()) { // reset [commit] -- paths ResetIndexForPaths(commit); SetCallable(false); return(repo.GetRef(Constants.HEAD)); } // write the ref RefUpdate ru = repo.UpdateRef(Constants.HEAD); ru.SetNewObjectId(commitId); string refName = Repository.ShortenRefName(@ref); string message = refName + ": updating " + Constants.HEAD; //$NON-NLS-1$ ru.SetRefLogMessage(message, false); if (ru.ForceUpdate() == RefUpdate.Result.LOCK_FAILURE) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().cannotLock, ru .GetName())); } switch (mode) { case ResetCommand.ResetType.HARD: { CheckoutIndex(commit); break; } case ResetCommand.ResetType.MIXED: { ResetIndex(commit); break; } case ResetCommand.ResetType.SOFT: { // do nothing, only the ref was changed break; } case ResetCommand.ResetType.KEEP: case ResetCommand.ResetType.MERGE: { // TODO // TODO throw new NotSupportedException(); } } if (mode != ResetCommand.ResetType.SOFT) { if (merging) { ResetMerge(); } else { if (cherryPicking) { ResetCherryPick(); } } } SetCallable(false); r = ru.GetRef(); } catch (IOException e) { throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfResetCommand , e); } return(r); }
public RewriteTreeFilter(RevWalk walker, TreeFilter t) { _pathFilter = new TreeWalk.TreeWalk(walker.Repository); _pathFilter.setFilter(t); _pathFilter.Recursive = t.shouldBeRecursive(); }
/// <exception cref="NGit.Api.Errors.RefAlreadyExistsException"> /// when trying to create (without force) a branch with a name /// that already exists /// </exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException">if the start point or branch can not be found /// </exception> /// <exception cref="NGit.Api.Errors.InvalidRefNameException"> /// if the provided name is <code>null</code> or otherwise /// invalid /// </exception> /// <returns>the newly created branch</returns> /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception> public override Ref Call() { CheckCallable(); ProcessOptions(); try { if (createBranch) { Git git = new Git(repo); CreateBranchCommand command = git.BranchCreate(); command.SetName(name); command.SetStartPoint(GetStartPoint().Name); if (upstreamMode != null) { command.SetUpstreamMode(upstreamMode); } command.Call(); } Ref headRef = repo.GetRef(Constants.HEAD); string refLogMessage = "checkout: moving from " + headRef.GetTarget().GetName(); ObjectId branch = repo.Resolve(name); if (branch == null) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved , name)); } RevWalk revWalk = new RevWalk(repo); AnyObjectId headId = headRef.GetObjectId(); RevCommit headCommit = headId == null ? null : revWalk.ParseCommit(headId); RevCommit newCommit = revWalk.ParseCommit(branch); RevTree headTree = headCommit == null ? null : headCommit.Tree; DirCacheCheckout dco = new DirCacheCheckout(repo, headTree, repo.LockDirCache(), newCommit.Tree); dco.SetFailOnConflict(true); try { dco.Checkout(); } catch (NGit.Errors.CheckoutConflictException e) { status = new CheckoutResult(CheckoutResult.Status.CONFLICTS, dco.GetConflicts()); throw; } Ref @ref = repo.GetRef(name); if (@ref != null && [email protected]().StartsWith(Constants.R_HEADS)) { @ref = null; } RefUpdate refUpdate = repo.UpdateRef(Constants.HEAD, @ref == null); refUpdate.SetForceUpdate(force); refUpdate.SetRefLogMessage(refLogMessage + " to " + newCommit.GetName(), false); RefUpdate.Result updateResult; if (@ref != null) { updateResult = refUpdate.Link(@ref.GetName()); } else { refUpdate.SetNewObjectId(newCommit); updateResult = refUpdate.ForceUpdate(); } SetCallable(false); bool ok = false; switch (updateResult) { case RefUpdate.Result.NEW: { ok = true; break; } case RefUpdate.Result.NO_CHANGE: case RefUpdate.Result.FAST_FORWARD: case RefUpdate.Result.FORCED: { ok = true; break; } default: { break; break; } } if (!ok) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().checkoutUnexpectedResult , updateResult.ToString())); } if (!dco.GetToBeDeleted().IsEmpty()) { status = new CheckoutResult(CheckoutResult.Status.NONDELETED, dco.GetToBeDeleted( )); } else { status = CheckoutResult.OK_RESULT; } return(@ref); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } finally { if (status == null) { status = CheckoutResult.ERROR_RESULT; } } }
public override string GetTextAtRevision (FilePath repositoryPath, Revision revision) { var repository = GetRepository (repositoryPath); ObjectId id = repository.Resolve (revision.ToString ()); RevWalk rw = new RevWalk (repository); RevCommit c = rw.ParseCommit (id); if (c == null) return string.Empty; else return GetCommitTextContent (c, repositoryPath); }
public override bool include(RevWalk walker, RevCommit c) { return(!_a.include(walker, c)); }
public override bool include(RevWalk walker, RevCommit cmit) { return(cmit.hasAny(_flags)); }
/// <param name="repo"></param> protected internal LogCommand(Repository repo) : base(repo) { walk = new RevWalk(repo); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> public override bool Include(RevWalk walker, RevCommit cmit) { return pattern.Match(Text(cmit)) >= 0; }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> public override bool Include(RevWalk walker, RevCommit c) { return(a.Include(walker, c) && b.Include(walker, c)); }
public static RevCommit[] Blame(NGit.Repository repo, RevCommit commit, string file) { string localFile = ToGitPath(repo, file); TreeWalk tw = TreeWalk.ForPath(repo, localFile, commit.Tree); if (tw == null) { return(new RevCommit [0]); } int totalLines = GetFileLineCount(repo, tw); int lineCount = totalLines; RevCommit[] lines = new RevCommit [lineCount]; RevWalk revWalker = new RevWalk(repo); revWalker.MarkStart(commit); List <RevCommit> commitHistory = new List <RevCommit>(); FilePath localCpath = FromGitPath(repo, localFile); foreach (RevCommit ancestorCommit in revWalker) { foreach (Change change in GetCommitChanges(repo, ancestorCommit)) { FilePath cpath = FromGitPath(repo, change.Path); if (change.ChangeType != ChangeType.Deleted && (localCpath == cpath || cpath.IsChildPathOf(localCpath))) { commitHistory.Add(ancestorCommit); break; } } } int historySize = commitHistory.Count; if (historySize > 1) { RevCommit recentCommit = commitHistory[0]; RawText latestRawText = GetRawText(repo, localFile, recentCommit); for (int i = 1; i < historySize; i++) { RevCommit ancestorCommit = commitHistory[i]; RawText ancestorRawText = GetRawText(repo, localFile, ancestorCommit); lineCount -= SetBlameLines(repo, lines, recentCommit, latestRawText, ancestorRawText); recentCommit = ancestorCommit; if (lineCount <= 0) { break; } } if (lineCount > 0) { RevCommit firstCommit = commitHistory[historySize - 1]; for (int i = 0; i < totalLines; i++) { if (lines[i] == null) { lines[i] = firstCommit; } } } } else if (historySize == 1) { RevCommit firstCommit = commitHistory[0]; for (int i = 0; i < totalLines; i++) { lines[i] = firstCommit; } } return(lines); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception> /// <exception cref="System.IO.IOException"></exception> internal abstract void ParseHeaders(RevWalk walk);
// Utility class /// <summary> /// Count the number of commits that are reachable from <code>start</code> /// until a commit that is reachable from <code>end</code> is encountered. /// </summary> /// <remarks> /// Count the number of commits that are reachable from <code>start</code> /// until a commit that is reachable from <code>end</code> is encountered. In /// other words, count the number of commits that are in <code>start</code>, /// but not in <code>end</code>. /// <p> /// Note that this method calls /// <see cref="RevWalk.Reset()">RevWalk.Reset()</see> /// at the beginning. /// Also note that the existing rev filter on the walk is left as-is, so be /// sure to set the right rev filter before calling this method. /// </remarks> /// <param name="walk">the rev walk to use</param> /// <param name="start">the commit to start counting from</param> /// <param name="end"> /// the commit where counting should end, or null if counting /// should be done until there are no more commits /// </param> /// <returns>the number of commits</returns> /// <exception cref="NGit.Errors.MissingObjectException">NGit.Errors.MissingObjectException /// </exception> /// <exception cref="NGit.Errors.IncorrectObjectTypeException">NGit.Errors.IncorrectObjectTypeException /// </exception> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public static int Count(RevWalk walk, RevCommit start, RevCommit end) { return Find(walk, start, end).Count; }
public static MergeCommandResult MergeTrees(ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult) { RevCommit newHead; RevWalk revWalk = new RevWalk(repo); try { // get the head commit Ref headRef = repo.GetRef(Constants.HEAD); if (headRef == null) { throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported ); } RevCommit headCommit = revWalk.ParseCommit(headRef.GetObjectId()); ResolveMerger merger = (ResolveMerger)((ThreeWayMerger)MergeStrategy.RESOLVE.NewMerger (repo)); merger.SetWorkingTreeIterator(new FileTreeIterator(repo)); merger.SetBase(srcBase); bool noProblems; IDictionary <string, MergeResult <Sequence> > lowLevelResults = null; IDictionary <string, ResolveMerger.MergeFailureReason> failingPaths = null; IList <string> modifiedFiles = null; ResolveMerger resolveMerger = merger; resolveMerger.SetCommitNames(new string[] { "BASE", "HEAD", sourceDisplayName }); noProblems = merger.Merge(headCommit, srcCommit); lowLevelResults = resolveMerger.GetMergeResults(); modifiedFiles = resolveMerger.GetModifiedFiles(); failingPaths = resolveMerger.GetFailingPaths(); if (monitor != null) { monitor.Update(50); } if (noProblems) { if (modifiedFiles != null && modifiedFiles.Count == 0) { return(new MergeCommandResult(headCommit, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.ALREADY_UP_TO_DATE, MergeStrategy.RESOLVE, null, null)); } DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.Tree, repo.LockDirCache (), merger.GetResultTreeId()); dco.SetFailOnConflict(true); dco.Checkout(); if (commitResult) { newHead = new NGit.Api.Git(repo).Commit().SetMessage(srcCommit.GetFullMessage() ).SetAuthor(srcCommit.GetAuthorIdent()).Call(); return(new MergeCommandResult(newHead.Id, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.MERGED, MergeStrategy.RESOLVE, null, null)); } else { return(new MergeCommandResult(headCommit, null, new ObjectId[] { headCommit.Id, srcCommit .Id }, MergeStatus.MERGED, MergeStrategy.RESOLVE, null, null)); } } else { if (failingPaths != null) { return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] { headCommit.Id, srcCommit.Id }, MergeStatus.FAILED, MergeStrategy.RESOLVE, lowLevelResults , failingPaths, null)); } else { return(new MergeCommandResult(null, merger.GetBaseCommit(0, 1), new ObjectId[] { headCommit.Id, srcCommit.Id }, MergeStatus.CONFLICTING, MergeStrategy.RESOLVE, lowLevelResults , null)); } } } finally { revWalk.Release(); } }
/// <exception cref="NGit.Api.Errors.RefAlreadyExistsException"> /// when trying to create (without force) a branch with a name /// that already exists /// </exception> /// <exception cref="NGit.Api.Errors.RefNotFoundException">if the start point can not be found /// </exception> /// <exception cref="NGit.Api.Errors.InvalidRefNameException"> /// if the provided name is <code>null</code> or otherwise /// invalid /// </exception> /// <returns>the newly created branch</returns> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override Ref Call() { CheckCallable(); ProcessOptions(); RevWalk revWalk = new RevWalk(repo); try { Ref refToCheck = repo.GetRef(name); bool exists = refToCheck != null && refToCheck.GetName().StartsWith(Constants.R_HEADS ); if (!force && exists) { throw new RefAlreadyExistsException(MessageFormat.Format(JGitText.Get().refAlreadyExists1 , name)); } ObjectId startAt = GetStartPoint(); string startPointFullName = null; if (startPoint != null) { Ref baseRef = repo.GetRef(startPoint); if (baseRef != null) { startPointFullName = baseRef.GetName(); } } // determine whether we are based on a commit, // a branch, or a tag and compose the reflog message string refLogMessage; string baseBranch = string.Empty; if (startPointFullName == null) { string baseCommit; if (startCommit != null) { baseCommit = startCommit.GetShortMessage(); } else { RevCommit commit = revWalk.ParseCommit(repo.Resolve(startPoint)); baseCommit = commit.GetShortMessage(); } if (exists) { refLogMessage = "branch: Reset start-point to commit " + baseCommit; } else { refLogMessage = "branch: Created from commit " + baseCommit; } } else { if (startPointFullName.StartsWith(Constants.R_HEADS) || startPointFullName.StartsWith (Constants.R_REMOTES)) { baseBranch = startPointFullName; if (exists) { refLogMessage = "branch: Reset start-point to branch " + startPointFullName; } else { // TODO refLogMessage = "branch: Created from branch " + baseBranch; } } else { startAt = revWalk.Peel(revWalk.ParseAny(startAt)); if (exists) { refLogMessage = "branch: Reset start-point to tag " + startPointFullName; } else { refLogMessage = "branch: Created from tag " + startPointFullName; } } } RefUpdate updateRef = repo.UpdateRef(Constants.R_HEADS + name); updateRef.SetNewObjectId(startAt); updateRef.SetRefLogMessage(refLogMessage, false); RefUpdate.Result updateResult; if (exists && force) { updateResult = updateRef.ForceUpdate(); } else { updateResult = updateRef.Update(); } SetCallable(false); bool ok = false; switch (updateResult) { case RefUpdate.Result.NEW: { ok = !exists; break; } case RefUpdate.Result.NO_CHANGE: case RefUpdate.Result.FAST_FORWARD: case RefUpdate.Result.FORCED: { ok = exists; break; } default: { break; break; } } if (!ok) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().createBranchUnexpectedResult , updateResult.ToString())); } Ref result = repo.GetRef(name); if (result == null) { throw new JGitInternalException(JGitText.Get().createBranchFailedUnknownReason); } if (baseBranch.Length == 0) { return(result); } // if we are based on another branch, see // if we need to configure upstream configuration: first check // whether the setting was done explicitly bool doConfigure; if (upstreamMode == CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM || upstreamMode == CreateBranchCommand.SetupUpstreamMode.TRACK) { // explicitly set to configure doConfigure = true; } else { if (upstreamMode == CreateBranchCommand.SetupUpstreamMode.NOTRACK) { // explicitly set to not configure doConfigure = false; } else { // if there was no explicit setting, check the configuration string autosetupflag = repo.GetConfig().GetString(ConfigConstants.CONFIG_BRANCH_SECTION , null, ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE); if ("false".Equals(autosetupflag)) { doConfigure = false; } else { if ("always".Equals(autosetupflag)) { doConfigure = true; } else { // in this case, the default is to configure // only in case the base branch was a remote branch doConfigure = baseBranch.StartsWith(Constants.R_REMOTES); } } } } if (doConfigure) { StoredConfig config = repo.GetConfig(); string[] tokens = baseBranch.RegexSplit("/", 4); bool isRemote = tokens[1].Equals("remotes"); if (isRemote) { // refs/remotes/<remote name>/<branch> string remoteName = tokens[2]; string branchName = tokens[3]; config.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE , remoteName); config.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE , Constants.R_HEADS + branchName); } else { // set "." as remote config.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE , "."); config.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE , baseBranch); } config.Save(); } return(result); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } finally { revWalk.Release(); } }
public static List <RevObject> objects(this RevWalk revWalk) { var revObjects = (ObjectIdOwnerMap <RevObject>)revWalk.field("objects"); return(revObjects.toList()); }
protected override Revision GetHeadRevision () { GitRepository repo2 = (GitRepository)repo; RevWalk rw = new RevWalk (repo2.RootRepository); ObjectId headId = repo2.RootRepository.Resolve (Constants.HEAD); if (headId == null) return null; RevCommit commit = rw.ParseCommit (headId); GitRevision rev = new GitRevision (repo, repo2.RootRepository, commit.Id.Name); rev.Commit = commit; return rev; }
public static RevObject object_Get(this RevWalk revWalk, string objectId) { return(revWalk.object_Get(objectId.objectId())); }