Exemplo n.º 1
0
 public void test001_NewIdent()
 {
     PersonIdent p = new PersonIdent("A U Thor", "*****@*****.**", 1142878501L, 0);
     Assert.AreEqual("A U Thor", p.Name);
     Assert.AreEqual("*****@*****.**", p.EmailAddress);
     Assert.AreEqual(1142878501L, p.When.ToGitInternalTime());
     Assert.AreEqual("A U Thor <*****@*****.**> 1142878501 +0000", p.ToExternalString());
 }
Exemplo n.º 2
0
 public void test002_ParseIdent()
 {
     string i = "A U Thor <*****@*****.**> 1142878501 -0500";
     var p = new PersonIdent(i);
     Assert.AreEqual(i, p.ToExternalString());
     Assert.AreEqual("A U Thor", p.Name);
     Assert.AreEqual("*****@*****.**", p.EmailAddress);
     Assert.AreEqual(1142878501000L, p.When);
 }
Exemplo n.º 3
0
 public void test001_NewIdent()
 {
     var p = new PersonIdent("A U Thor", "*****@*****.**", 1142878501L.UnixTimeToDateTime(),
                             TimeZoneInfo.FindSystemTimeZoneById("US/Eastern"));
     Assert.AreEqual("A U Thor", p.Name);
     Assert.AreEqual("*****@*****.**", p.EmailAddress);
     Assert.AreEqual(1142878501000L, p.When);
     Assert.AreEqual("A U Thor <*****@*****.**> 1142878501 -0500", p
                                                                           .ToExternalString());
 }
Exemplo n.º 4
0
 /// <summary>Sets default values for not explicitly specified options.</summary>
 /// <remarks>
 /// Sets default values for not explicitly specified options. Then validates
 /// that all required data has been provided.
 /// </remarks>
 /// <param name="state">the state of the repository we are working on</param>
 /// <exception cref="NGit.Api.Errors.InvalidTagNameException">if the tag name is null or invalid
 ///     </exception>
 /// <exception cref="System.NotSupportedException">if the tag is signed (not supported yet)
 ///     </exception>
 private void ProcessOptions(RepositoryState state)
 {
     if (tagger == null)
     {
         tagger = new PersonIdent(repo);
     }
     if (name == null || !Repository.IsValidRefName(Constants.R_TAGS + name))
     {
         throw new InvalidTagNameException(MessageFormat.Format(JGitText.Get().tagNameInvalid
                                                                , name == null ? "<null>" : name));
     }
     if (signed)
     {
         throw new NotSupportedException(JGitText.Get().signingNotSupportedOnTag);
     }
 }
Exemplo n.º 5
0
        static TestRepository()
        {
            MockSystemReader m   = new MockSystemReader();
            long             now = m.getCurrentTime();
            int tz = m.getTimezone(now);

            String an = "J. Author";
            String ae = "*****@*****.**";

            author = new PersonIdent(an, ae, now, tz);

            String cn = "J. Committer";
            String ce = "*****@*****.**";

            committer = new PersonIdent(cn, ce, now, tz);
        }
Exemplo n.º 6
0
        /// <exception cref="System.IO.IOException"></exception>
        private RebaseResult Stop(RevCommit commitToPick)
        {
            PersonIdent author       = commitToPick.GetAuthorIdent();
            string      authorScript = ToAuthorScript(author);

            CreateFile(rebaseDir, AUTHOR_SCRIPT, authorScript);
            CreateFile(rebaseDir, MESSAGE, commitToPick.GetFullMessage());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DiffFormatter         df  = new DiffFormatter(bos);

            df.SetRepository(repo);
            df.Format(commitToPick.GetParent(0), commitToPick);
            CreateFile(rebaseDir, PATCH, Sharpen.Runtime.GetStringForBytes(bos.ToByteArray(),
                                                                           Constants.CHARACTER_ENCODING));
            CreateFile(rebaseDir, STOPPED_SHA, repo.NewObjectReader().Abbreviate(commitToPick
                                                                                 ).Name);
            return(new RebaseResult(commitToPick));
        }
        public virtual void TestParseAllFields()
        {
            ObjectId      treeId      = Id("9788669ad918b6fcce64af8882fc9a81cb6aba67");
            string        name        = "v1.2.3.4.5";
            string        taggerName  = "A U. Thor";
            string        taggerEmail = "*****@*****.**";
            int           taggerTime  = 1218123387;
            StringBuilder body        = new StringBuilder();

            body.Append("object ");
            body.Append(treeId.Name);
            body.Append("\n");
            body.Append("type tree\n");
            body.Append("tag ");
            body.Append(name);
            body.Append("\n");
            body.Append("tagger ");
            body.Append(taggerName);
            body.Append(" <");
            body.Append(taggerEmail);
            body.Append("> ");
            body.Append(taggerTime);
            body.Append(" +0700\n");
            body.Append("\n");
            RevWalk rw = new RevWalk(db);
            RevTag  c;

            c = new RevTag(Id("9473095c4cb2f12aefe1db8a355fe3fafba42f67"));
            NUnit.Framework.Assert.IsNull(c.GetObject());
            NUnit.Framework.Assert.IsNull(c.GetTagName());
            c.ParseCanonical(rw, Sharpen.Runtime.GetBytesForString(body.ToString(), "UTF-8"));
            NUnit.Framework.Assert.IsNotNull(c.GetObject());
            NUnit.Framework.Assert.AreEqual(treeId, c.GetObject().Id);
            NUnit.Framework.Assert.AreSame(rw.LookupTree(treeId), c.GetObject());
            NUnit.Framework.Assert.IsNotNull(c.GetTagName());
            NUnit.Framework.Assert.AreEqual(name, c.GetTagName());
            NUnit.Framework.Assert.AreEqual(string.Empty, c.GetFullMessage());
            PersonIdent cTagger = c.GetTaggerIdent();

            NUnit.Framework.Assert.IsNotNull(cTagger);
            NUnit.Framework.Assert.AreEqual(taggerName, cTagger.GetName());
            NUnit.Framework.Assert.AreEqual(taggerEmail, cTagger.GetEmailAddress());
        }
        public virtual void RefLogIncludesCommitMessage()
        {
            PersonIdent who = new PersonIdent("user", "*****@*****.**");

            DeleteTrashFile("file.txt");
            RevCommit stashed = git.StashCreate().SetPerson(who).Call();

            NUnit.Framework.Assert.IsNotNull(stashed);
            NUnit.Framework.Assert.AreEqual("content", Read(committedFile));
            ValidateStashedCommit(stashed);
            ReflogReader reader = new ReflogReader(git.GetRepository(), Constants.R_STASH);
            ReflogEntry  entry  = reader.GetLastEntry();

            NUnit.Framework.Assert.IsNotNull(entry);
            NUnit.Framework.Assert.AreEqual(ObjectId.ZeroId, entry.GetOldId());
            NUnit.Framework.Assert.AreEqual(stashed, entry.GetNewId());
            NUnit.Framework.Assert.AreEqual(who, entry.GetWho());
            NUnit.Framework.Assert.AreEqual(stashed.GetFullMessage(), entry.GetComment());
        }
Exemplo n.º 9
0
        /// <exception cref="System.IO.IOException"></exception>
        private void UpdateStashRef(ObjectId commitId, PersonIdent refLogIdent, string refLogMessage
                                    )
        {
            Ref       currentRef = repo.GetRef(@ref);
            RefUpdate refUpdate  = repo.UpdateRef(@ref);

            refUpdate.SetNewObjectId(commitId);
            refUpdate.SetRefLogIdent(refLogIdent);
            refUpdate.SetRefLogMessage(refLogMessage, false);
            if (currentRef != null)
            {
                refUpdate.SetExpectedOldObjectId(currentRef.GetObjectId());
            }
            else
            {
                refUpdate.SetExpectedOldObjectId(ObjectId.ZeroId);
            }
            refUpdate.ForceUpdate();
        }
Exemplo n.º 10
0
 /// <summary>Sets default values for not explicitly specified options.</summary>
 /// <remarks>
 /// Sets default values for not explicitly specified options. Then validates
 /// that all required data has been provided.
 /// </remarks>
 /// <param name="state">the state of the repository we are working on</param>
 /// <exception cref="NGit.Api.Errors.NoMessageException">if the commit message has not been specified
 ///     </exception>
 private void ProcessOptions(RepositoryState state)
 {
     if (committer == null)
     {
         committer = new PersonIdent(repo);
     }
     if (author == null)
     {
         author = committer;
     }
     // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
     if (state == RepositoryState.MERGING_RESOLVED)
     {
         try
         {
             parents = repo.ReadMergeHeads();
         }
         catch (IOException e)
         {
             throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionOccurredDuringReadingOfGIT_DIR
                                                                  , Constants.MERGE_HEAD, e), e);
         }
         if (message == null)
         {
             try
             {
                 message = repo.ReadMergeCommitMsg();
             }
             catch (IOException e)
             {
                 throw new JGitInternalException(MessageFormat.Format(JGitText.Get().exceptionOccurredDuringReadingOfGIT_DIR
                                                                      , Constants.MERGE_MSG, e), e);
             }
         }
     }
     if (message == null)
     {
         // as long as we don't suppport -C option we have to have
         // an explicit message
         throw new NoMessageException(JGitText.Get().commitMessageNotSpecified);
     }
 }
Exemplo n.º 11
0
        private void commit(Core.Tree t, string commitMsg, PersonIdent author,
                            PersonIdent committer)
        {
            Core.Commit commit = new Core.Commit(db);
            commit.Author    = (author);
            commit.Committer = (committer);
            commit.Message   = (commitMsg);
            commit.TreeEntry = (t);
            //ObjectWriter writer = new ObjectWriter(db);
            //commit.CommitId = (writer.WriteCommit(commit));
            commit.Save();

            int       nl = commitMsg.IndexOf('\n');
            RefUpdate ru = db.UpdateRef(Constants.HEAD);

            ru.NewObjectId = (commit.CommitId);
            ru.SetRefLogMessage("commit : "
                                + ((nl == -1) ? commitMsg : commitMsg.Slice(0, nl)), false);
            ru.ForceUpdate();
        }
Exemplo n.º 12
0
        public virtual void TestSomeCommits()
        {
            // do 4 commits
            Git git = new Git(db);

            git.Commit().SetMessage("initial commit").Call();
            git.Commit().SetMessage("second commit").SetCommitter(committer).Call();
            git.Commit().SetMessage("third commit").SetAuthor(author).Call();
            git.Commit().SetMessage("fourth commit").SetAuthor(author).SetCommitter(committer
                                                                                    ).Call();
            Iterable <RevCommit> commits = git.Log().Call();
            // check that all commits came in correctly
            PersonIdent defaultCommitter = new PersonIdent(db);

            PersonIdent[] expectedAuthors = new PersonIdent[] { defaultCommitter, committer,
                                                                author, author };
            PersonIdent[] expectedCommitters = new PersonIdent[] { defaultCommitter, committer
                                                                   , defaultCommitter, committer };
            string[] expectedMessages = new string[] { "initial commit", "second commit", "third commit"
                                                       , "fourth commit" };
            int l = expectedAuthors.Length - 1;

            foreach (RevCommit c in commits)
            {
                NUnit.Framework.Assert.AreEqual(expectedAuthors[l].GetName(), c.GetAuthorIdent().
                                                GetName());
                NUnit.Framework.Assert.AreEqual(expectedCommitters[l].GetName(), c.GetCommitterIdent
                                                    ().GetName());
                NUnit.Framework.Assert.AreEqual(c.GetFullMessage(), expectedMessages[l]);
                l--;
            }
            NUnit.Framework.Assert.AreEqual(l, -1);
            ReflogReader reader = db.GetReflogReader(Constants.HEAD);

            NUnit.Framework.Assert.IsTrue(reader.GetLastEntry().GetComment().StartsWith("commit:"
                                                                                        ));
            reader = db.GetReflogReader(db.GetBranch());
            NUnit.Framework.Assert.IsTrue(reader.GetLastEntry().GetComment().StartsWith("commit:"
                                                                                        ));
        }
Exemplo n.º 13
0
        public virtual void CommitAmendWithoutAuthorShouldSetOriginalAuthorAndAuthorTime(
            )
        {
            Git git = new Git(db);

            WriteTrashFile("file1", "file1");
            git.Add().AddFilepattern("file1").Call();
            string      authorName  = "First Author";
            string      authorEmail = "*****@*****.**";
            DateTime    authorDate  = Sharpen.Extensions.CreateDate(1349621117000L);
            PersonIdent firstAuthor = new PersonIdent(authorName, authorEmail, authorDate, Sharpen.Extensions.GetTimeZone
                                                          ("UTC"));

            git.Commit().SetMessage("initial commit").SetAuthor(firstAuthor).Call();
            RevCommit   amended       = git.Commit().SetAmend(true).SetMessage("amend commit").Call();
            PersonIdent amendedAuthor = amended.GetAuthorIdent();

            NUnit.Framework.Assert.AreEqual(authorName, amendedAuthor.GetName());
            NUnit.Framework.Assert.AreEqual(authorEmail, amendedAuthor.GetEmailAddress());
            NUnit.Framework.Assert.AreEqual(authorDate.GetTime(), amendedAuthor.GetWhen().GetTime
                                                ());
        }
Exemplo n.º 14
0
 internal virtual long Timeof(RevObject o)
 {
     if (o is RevCommit)
     {
         return(((RevCommit)o).CommitTime);
     }
     if (o is RevTag)
     {
         RevTag tag = (RevTag)o;
         try
         {
             this._enclosing.ParseBody(tag);
         }
         catch (IOException)
         {
             return(0);
         }
         PersonIdent who = tag.GetTaggerIdent();
         return(who != null?who.GetWhen().GetTime() : 0);
     }
     return(0);
 }
Exemplo n.º 15
0
        public virtual void TestTimeAltersId()
        {
            PersonIdent oldAuthor    = author;
            PersonIdent oldCommitter = committer;

            NUnit.Framework.Assert.AreEqual("a\n" + "\n" + "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n"
                                            , Call("a\n"));
            //
            //
            //
            Tick();
            NUnit.Framework.Assert.AreEqual("a\n" + "\n" + "Change-Id: I3251906b99dda598a58a6346d8126237ee1ea800\n"
                                            , Call("a\n"));
            //
            //
            //
            Tick();
            NUnit.Framework.Assert.AreEqual("a\n" + "\n" + "Change-Id: I69adf9208d828f41a3d7e41afbca63aff37c0c5c\n"
                                            , Call("a\n"));

            author    = oldAuthor;
            committer = oldCommitter;
        }
Exemplo n.º 16
0
        internal virtual string ToAuthorScript(PersonIdent author)
        {
            StringBuilder sb = new StringBuilder(100);

            sb.Append(GIT_AUTHOR_NAME);
            sb.Append("='");
            sb.Append(author.GetName());
            sb.Append("'\n");
            sb.Append(GIT_AUTHOR_EMAIL);
            sb.Append("='");
            sb.Append(author.GetEmailAddress());
            sb.Append("'\n");
            // the command line uses the "external String"
            // representation for date and timezone
            sb.Append(GIT_AUTHOR_DATE);
            sb.Append("='");
            string externalString = author.ToExternalString();

            sb.Append(Sharpen.Runtime.Substring(externalString, externalString.LastIndexOf('>'
                                                                                           ) + 2));
            sb.Append("'\n");
            return(sb.ToString());
        }
Exemplo n.º 17
0
        public virtual void TestAuthorScriptConverter()
        {
            // -1 h timezone offset
            PersonIdent ident = new PersonIdent("Author name", "*****@*****.**", 123456789123L
                                                , -60);
            string convertedAuthor = git.Rebase().ToAuthorScript(ident);

            string[] lines = convertedAuthor.Split("\n");
            NUnit.Framework.Assert.AreEqual("GIT_AUTHOR_NAME='Author name'", lines[0]);
            NUnit.Framework.Assert.AreEqual("GIT_AUTHOR_EMAIL='*****@*****.**'", lines[1]);
            NUnit.Framework.Assert.AreEqual("GIT_AUTHOR_DATE='123456789 -0100'", lines[2]);
            PersonIdent parsedIdent = git.Rebase().ParseAuthor(Sharpen.Runtime.GetBytesForString
                                                                   (convertedAuthor, "UTF-8"));

            NUnit.Framework.Assert.AreEqual(ident.GetName(), parsedIdent.GetName());
            NUnit.Framework.Assert.AreEqual(ident.GetEmailAddress(), parsedIdent.GetEmailAddress
                                                ());
            // this is rounded to the last second
            NUnit.Framework.Assert.AreEqual(123456789000L, parsedIdent.GetWhen().GetTime());
            NUnit.Framework.Assert.AreEqual(ident.GetTimeZoneOffset(), parsedIdent.GetTimeZoneOffset
                                                ());
            // + 9.5h timezone offset
            ident           = new PersonIdent("Author name", "*****@*****.**", 123456789123L, +570);
            convertedAuthor = git.Rebase().ToAuthorScript(ident);
            lines           = convertedAuthor.Split("\n");
            NUnit.Framework.Assert.AreEqual("GIT_AUTHOR_NAME='Author name'", lines[0]);
            NUnit.Framework.Assert.AreEqual("GIT_AUTHOR_EMAIL='*****@*****.**'", lines[1]);
            NUnit.Framework.Assert.AreEqual("GIT_AUTHOR_DATE='123456789 +0930'", lines[2]);
            parsedIdent = git.Rebase().ParseAuthor(Sharpen.Runtime.GetBytesForString(convertedAuthor
                                                                                     , "UTF-8"));
            NUnit.Framework.Assert.AreEqual(ident.GetName(), parsedIdent.GetName());
            NUnit.Framework.Assert.AreEqual(ident.GetEmailAddress(), parsedIdent.GetEmailAddress
                                                ());
            NUnit.Framework.Assert.AreEqual(123456789000L, parsedIdent.GetWhen().GetTime());
            NUnit.Framework.Assert.AreEqual(ident.GetTimeZoneOffset(), parsedIdent.GetTimeZoneOffset
                                                ());
        }
        public virtual void SetUp()
        {
            lock (this)
            {
                if (shutdownHook == null)
                {
                    shutdownHook = new _Thread_117(this);
                    // On windows accidentally open files or memory
                    // mapped regions may prevent files from being deleted.
                    // Suggesting a GC increases the likelihood that our
                    // test repositories actually get removed after the
                    // tests, even in the case of failure.
                    Runtime.GetRuntime().AddShutdownHook(shutdownHook);
                }
            }
            RecursiveDelete(TestId(), trash, true, false);
            mockSystemReader = new MockSystemReader();
            mockSystemReader.userGitConfig = new FileBasedConfig(new FilePath(trash, "usergitconfig"
                                                                              ), FS.DETECTED);
            CeilTestDirectories(GetCeilings());
            SystemReader.SetInstance(mockSystemReader);
            long now = mockSystemReader.GetCurrentTime();
            int  tz  = mockSystemReader.GetTimezone(now);

            author    = new PersonIdent("J. Author", "*****@*****.**");
            author    = new PersonIdent(author, now, tz);
            committer = new PersonIdent("J. Committer", "*****@*****.**");
            committer = new PersonIdent(committer, now, tz);
            WindowCacheConfig c = new WindowCacheConfig();

            c.SetPackedGitLimit(128 * WindowCacheConfig.KB);
            c.SetPackedGitWindowSize(8 * WindowCacheConfig.KB);
            c.SetPackedGitMMAP(useMMAP);
            c.SetDeltaBaseCacheLimit(8 * WindowCacheConfig.KB);
            WindowCache.Reconfigure(c);
        }
Exemplo n.º 19
0
 private string iso(PersonIdent id)
 {
     return id.When.UnixTimeToDateTimeOffset(id.TimeZoneOffset).ToIsoDateFormat();
 }
Exemplo n.º 20
0
 public void test007_ParseIdent()
 {
     string i = "A U Thor<*****@*****.**>1142878501 +0230 ";
     var p = new PersonIdent(i);
     Assert.AreEqual("A U Thor", p.Name);
     Assert.AreEqual("*****@*****.**", p.EmailAddress);
     Assert.AreEqual(1142878501000L, p.When);
 }
Exemplo n.º 21
0
 public void setRefLogIdent(PersonIdent pi)
 {
     refLogIdent = pi;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Format committer, author or tagger ident according to this formatter's
        /// specification.
        /// </summary>
        /// <remarks>
        /// Format committer, author or tagger ident according to this formatter's
        /// specification.
        /// </remarks>
        /// <param name="ident"></param>
        /// <returns>formatted version of date, time and time zone</returns>
        public virtual string FormatDate(PersonIdent ident)
        {
            TimeZoneInfo tz;

            switch (format)
            {
            case GitDateFormatter.Format.RAW:
            {
                int    offset = ident.GetTimeZoneOffset();
                string sign   = offset < 0 ? "-" : "+";
                int    offset2;
                if (offset < 0)
                {
                    offset2 = -offset;
                }
                else
                {
                    offset2 = offset;
                }
                int hours   = offset2 / 60;
                int minutes = offset2 % 60;
                return(string.Format("%d %s%02d%02d", ident.GetWhen().GetTime() / 1000, sign, hours
                                     , minutes));
            }

            case GitDateFormatter.Format.RELATIVE:
            {
                return(RelativeDateFormatter.Format(ident.GetWhen()));
            }

            case GitDateFormatter.Format.LOCALELOCAL:
            case GitDateFormatter.Format.LOCAL:
            {
                dateTimeInstance.SetTimeZone(SystemReader.GetInstance().GetTimeZone());
                return(dateTimeInstance.Format(ident.GetWhen()));
            }

            case GitDateFormatter.Format.LOCALE:
            {
                tz = ident.GetTimeZone();
                if (tz == null)
                {
                    tz = SystemReader.GetInstance().GetTimeZone();
                }
                dateTimeInstance.SetTimeZone(tz);
                dateTimeInstance2.SetTimeZone(tz);
                return(dateTimeInstance.Format(ident.GetWhen()) + " " + dateTimeInstance2.Format(
                           ident.GetWhen()));
            }

            default:
            {
                tz = ident.GetTimeZone();
                if (tz == null)
                {
                    tz = SystemReader.GetInstance().GetTimeZone();
                }
                dateTimeInstance.SetTimeZone(ident.GetTimeZone());
                return(dateTimeInstance.Format(ident.GetWhen()));

                break;
            }
            }
        }
Exemplo n.º 23
0
 public void test004_ParseIdent()
 {
     String i = "A U Thor<*****@*****.**> 1142878501 +0230";
     PersonIdent p = new PersonIdent(i);
     Assert.AreEqual("A U Thor", p.Name);
     Assert.AreEqual("*****@*****.**", p.EmailAddress);
     Assert.AreEqual(1142878501L, p.When.ToGitInternalTime());
 }
Exemplo n.º 24
0
 public API_NGit()
 {
     Author    = new PersonIdent(NGit_Consts.DEFAULT_COMMIT_NAME, NGit_Consts.DEFAULT_COMMIT_EMAIL);
     Committer = new PersonIdent("FluentSharp NGit", "*****@*****.**");
 }
Exemplo n.º 25
0
 public static ObjectId CreateCommit(NGit.Repository rep, string message, IList <ObjectId> parents, ObjectId indexTreeId, PersonIdent author, PersonIdent committer)
 {
     try {
         ObjectInserter odi = rep.NewObjectInserter();
         try {
             // Create a Commit object, populate it and write it
             NGit.CommitBuilder commit = new NGit.CommitBuilder();
             commit.Committer = committer;
             commit.Author    = author;
             commit.Message   = message;
             commit.SetParentIds(parents);
             commit.TreeId = indexTreeId;
             ObjectId commitId = odi.Insert(commit);
             odi.Flush();
             return(commitId);
         } finally {
             odi.Release();
         }
     } catch (UnmergedPathException) {
         // since UnmergedPathException is a subclass of IOException
         // which should not be wrapped by a JGitInternalException we
         // have to catch and re-throw it here
         throw;
     } catch (IOException e) {
         throw new JGitInternalException("Commit failed", e);
     }
 }
Exemplo n.º 26
0
 /// <summary>Set the person to use as the author and committer in the commits made</summary>
 /// <param name="person"></param>
 /// <returns>
 ///
 /// <code>this</code>
 /// </returns>
 public virtual NGit.Api.StashCreateCommand SetPerson(PersonIdent person)
 {
     this.person = person;
     return(this);
 }
Exemplo n.º 27
0
        public Stash Create(ProgressMonitor monitor, string message)
        {
            if (monitor != null)
            {
                monitor.Start(1);
                monitor.BeginTask("Stashing changes", 100);
            }

            UserConfig config = _repo.GetConfig().Get(UserConfig.KEY);
            RevWalk    rw     = new RevWalk(_repo);
            ObjectId   headId = _repo.Resolve(Constants.HEAD);
            var        parent = rw.ParseCommit(headId);

            PersonIdent author = new PersonIdent(config.GetAuthorName() ?? "unknown", config.GetAuthorEmail() ?? "unknown@(none).");

            if (string.IsNullOrEmpty(message))
            {
                // Use the commit summary as message
                message = parent.Abbreviate(7) + " " + parent.GetShortMessage();
                int i = message.IndexOfAny(new char[] { '\r', '\n' });
                if (i != -1)
                {
                    message = message.Substring(0, i);
                }
            }

            // Create the index tree commit
            ObjectInserter inserter = _repo.NewObjectInserter();
            DirCache       dc       = _repo.ReadDirCache();

            if (monitor != null)
            {
                monitor.Update(10);
            }

            var tree_id = dc.WriteTree(inserter);

            inserter.Release();

            if (monitor != null)
            {
                monitor.Update(10);
            }

            string   commitMsg   = "index on " + _repo.GetBranch() + ": " + message;
            ObjectId indexCommit = GitUtil.CreateCommit(_repo, commitMsg + "\n", new ObjectId[] { headId }, tree_id, author, author);

            if (monitor != null)
            {
                monitor.Update(20);
            }

            // Create the working dir commit
            tree_id   = WriteWorkingDirectoryTree(parent.Tree, dc);
            commitMsg = "WIP on " + _repo.GetBranch() + ": " + message;
            var wipCommit = GitUtil.CreateCommit(_repo, commitMsg + "\n", new ObjectId[] { headId, indexCommit }, tree_id, author, author);

            if (monitor != null)
            {
                monitor.Update(20);
            }

            string   prevCommit = null;
            FileInfo sf         = StashRefFile;

            if (sf.Exists)
            {
                prevCommit = File.ReadAllText(sf.FullName).Trim(' ', '\t', '\r', '\n');
            }

            Stash s = new Stash(prevCommit, wipCommit.Name, author, commitMsg);

            FileInfo stashLog = StashLogFile;

            File.AppendAllText(stashLog.FullName, s.FullLine + "\n");
            File.WriteAllText(sf.FullName, s.CommitId + "\n");

            if (monitor != null)
            {
                monitor.Update(5);
            }

            // Wipe all local changes
            GitUtil.HardReset(_repo, Constants.HEAD);

            monitor.EndTask();
            s.StashCollection = this;
            return(s);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Sets the committer for this
 /// <code>commit</code>
 /// . If no committer is explicitly
 /// specified because this method is never called or called with
 /// <code>null</code>
 /// value then the committer will be deduced from config info in repository,
 /// with current time.
 /// </summary>
 /// <param name="committer">
 /// the committer used for the
 /// <code>commit</code>
 /// </param>
 /// <returns>
 ///
 /// <code>this</code>
 /// </returns>
 public virtual NGit.Api.CommitCommand SetCommitter(PersonIdent committer)
 {
     CheckCallable();
     this.committer = committer;
     return(this);
 }
Exemplo n.º 29
0
 /// <summary>
 /// Sets the author for this
 /// <code>commit</code>
 /// . If no author is explicitly
 /// specified because this method is never called or called with
 /// <code>null</code>
 /// value then the author will be set to the committer or to the original
 /// author when amending.
 /// </summary>
 /// <param name="author">
 /// the author used for the
 /// <code>commit</code>
 /// </param>
 /// <returns>
 ///
 /// <code>this</code>
 /// </returns>
 public virtual NGit.Api.CommitCommand SetAuthor(PersonIdent author)
 {
     CheckCallable();
     this.author = author;
     return(this);
 }
Exemplo n.º 30
0
        /// <summary>
        /// Executes the
        /// <code>commit</code>
        /// command with all the options and parameters
        /// collected by the setter methods of this class. Each instance of this
        /// class should only be used for one invocation of the command (means: one
        /// call to
        /// <see cref="Call()">Call()</see>
        /// )
        /// </summary>
        /// <returns>
        /// a
        /// <see cref="NGit.Revwalk.RevCommit">NGit.Revwalk.RevCommit</see>
        /// object representing the successful commit.
        /// </returns>
        /// <exception cref="NGit.Api.Errors.NoHeadException">when called on a git repo without a HEAD reference
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.NoMessageException">when called without specifying a commit message
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.UnmergedPathsException">when the current index contained unmerged paths (conflicts)
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException">
        /// when HEAD or branch ref is updated concurrently by someone
        /// else
        /// </exception>
        /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">when repository is not in the right state for committing
        ///     </exception>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        public override RevCommit Call()
        {
            CheckCallable();
            RepositoryState state = repo.GetRepositoryState();

            if (!state.CanCommit())
            {
                throw new WrongRepositoryStateException(MessageFormat.Format(JGitText.Get().cannotCommitOnARepoWithState
                                                                             , state.Name()));
            }
            ProcessOptions(state);
            try
            {
                if (all && !repo.IsBare && repo.WorkTree != null)
                {
                    Git git = new Git(repo);
                    try
                    {
                        git.Add().AddFilepattern(".").SetUpdate(true).Call();
                    }
                    catch (NoFilepatternException e)
                    {
                        // should really not happen
                        throw new JGitInternalException(e.Message, e);
                    }
                }
                Ref head = repo.GetRef(Constants.HEAD);
                if (head == null)
                {
                    throw new NoHeadException(JGitText.Get().commitOnRepoWithoutHEADCurrentlyNotSupported
                                              );
                }
                // determine the current HEAD and the commit it is referring to
                ObjectId headId = repo.Resolve(Constants.HEAD + "^{commit}");
                if (headId == null && amend)
                {
                    throw new WrongRepositoryStateException(JGitText.Get().commitAmendOnInitialNotPossible
                                                            );
                }
                if (headId != null)
                {
                    if (amend)
                    {
                        RevCommit   previousCommit = new RevWalk(repo).ParseCommit(headId);
                        RevCommit[] p = previousCommit.Parents;
                        for (int i = 0; i < p.Length; i++)
                        {
                            parents.Add(0, p[i].Id);
                        }
                        if (author == null)
                        {
                            author = previousCommit.GetAuthorIdent();
                        }
                    }
                    else
                    {
                        parents.Add(0, headId);
                    }
                }
                // lock the index
                DirCache index = repo.LockDirCache();
                try
                {
                    if (!only.IsEmpty())
                    {
                        index = CreateTemporaryIndex(headId, index);
                    }
                    ObjectInserter odi = repo.NewObjectInserter();
                    try
                    {
                        // Write the index as tree to the object database. This may
                        // fail for example when the index contains unmerged paths
                        // (unresolved conflicts)
                        ObjectId indexTreeId = index.WriteTree(odi);
                        if (insertChangeId)
                        {
                            InsertChangeId(indexTreeId);
                        }
                        // Create a Commit object, populate it and write it
                        NGit.CommitBuilder commit = new NGit.CommitBuilder();
                        commit.Committer = committer;
                        commit.Author    = author;
                        commit.Message   = message;
                        commit.SetParentIds(parents);
                        commit.TreeId = indexTreeId;
                        ObjectId commitId = odi.Insert(commit);
                        odi.Flush();
                        RevWalk revWalk = new RevWalk(repo);
                        try
                        {
                            RevCommit revCommit = revWalk.ParseCommit(commitId);
                            RefUpdate ru        = repo.UpdateRef(Constants.HEAD);
                            ru.SetNewObjectId(commitId);
                            if (reflogComment != null)
                            {
                                ru.SetRefLogMessage(reflogComment, false);
                            }
                            else
                            {
                                string prefix = amend ? "commit (amend): " : "commit: ";
                                ru.SetRefLogMessage(prefix + revCommit.GetShortMessage(), false);
                            }
                            if (headId != null)
                            {
                                ru.SetExpectedOldObjectId(headId);
                            }
                            else
                            {
                                ru.SetExpectedOldObjectId(ObjectId.ZeroId);
                            }
                            RefUpdate.Result rc = ru.ForceUpdate();
                            switch (rc)
                            {
                            case RefUpdate.Result.NEW:
                            case RefUpdate.Result.FORCED:
                            case RefUpdate.Result.FAST_FORWARD:
                            {
                                SetCallable(false);
                                if (state == RepositoryState.MERGING_RESOLVED)
                                {
                                    // Commit was successful. Now delete the files
                                    // used for merge commits
                                    repo.WriteMergeCommitMsg(null);
                                    repo.WriteMergeHeads(null);
                                }
                                else
                                {
                                    if (state == RepositoryState.CHERRY_PICKING_RESOLVED)
                                    {
                                        repo.WriteMergeCommitMsg(null);
                                        repo.WriteCherryPickHead(null);
                                    }
                                }
                                return(revCommit);
                            }

                            case RefUpdate.Result.REJECTED:
                            case RefUpdate.Result.LOCK_FAILURE:
                            {
                                throw new ConcurrentRefUpdateException(JGitText.Get().couldNotLockHEAD, ru.GetRef
                                                                           (), rc);
                            }

                            default:
                            {
                                throw new JGitInternalException(MessageFormat.Format(JGitText.Get().updatingRefFailed
                                                                                     , Constants.HEAD, commitId.ToString(), rc));
                            }
                            }
                        }
                        finally
                        {
                            revWalk.Release();
                        }
                    }
                    finally
                    {
                        odi.Release();
                    }
                }
                finally
                {
                    index.Unlock();
                }
            }
            catch (UnmergedPathException e)
            {
                throw new UnmergedPathsException(e);
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfCommitCommand
                                                , e);
            }
        }
Exemplo n.º 31
0
 /// <summary>Create a command to stash changes in the working directory and index</summary>
 /// <param name="repo"></param>
 protected internal StashCreateCommand(Repository repo) : base(repo)
 {
     person = new PersonIdent(repo);
 }
Exemplo n.º 32
0
 private static Person ToPerson(PersonIdent ident)
 {
     return(new Person(ident.GetName(), ident.GetEmailAddress()));
 }
Exemplo n.º 33
0
        //
        //
        //
        //
        //
        //
        /// <summary>Compute a Change-Id.</summary>
        /// <remarks>Compute a Change-Id.</remarks>
        /// <param name="treeId">The id of the tree that would be committed</param>
        /// <param name="firstParentId">parent id of previous commit or null</param>
        /// <param name="author">
        /// the
        /// <see cref="NGit.PersonIdent">NGit.PersonIdent</see>
        /// for the presumed author and time
        /// </param>
        /// <param name="committer">
        /// the
        /// <see cref="NGit.PersonIdent">NGit.PersonIdent</see>
        /// for the presumed committer and time
        /// </param>
        /// <param name="message">The commit message</param>
        /// <returns>
        /// the change id SHA1 string (without the 'I') or null if the
        /// message is not complete enough
        /// </returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public static ObjectId ComputeChangeId(ObjectId treeId, ObjectId firstParentId, PersonIdent
                                               author, PersonIdent committer, string message)
        {
            string cleanMessage = Clean(message);

            if (cleanMessage.Length == 0)
            {
                return(null);
            }
            StringBuilder b = new StringBuilder();

            b.Append("tree ");
            b.Append(ObjectId.ToString(treeId));
            b.Append("\n");
            if (firstParentId != null)
            {
                b.Append("parent ");
                b.Append(ObjectId.ToString(firstParentId));
                b.Append("\n");
            }
            b.Append("author ");
            b.Append(author.ToExternalString());
            b.Append("\n");
            b.Append("committer ");
            b.Append(committer.ToExternalString());
            b.Append("\n\n");
            b.Append(cleanMessage);
            return(new ObjectInserter.Formatter().IdFor(Constants.OBJ_COMMIT, Sharpen.Runtime.GetBytesForString
                                                            (b.ToString(), Constants.CHARACTER_ENCODING)));
        }
Exemplo n.º 34
0
        public static RevCommit       commit(this API_NGit nGit, string commitMessage, PersonIdent author, PersonIdent committer)
        {
            if (commitMessage.valid())
            {
                "[API_NGit] commit: {0}".debug(commitMessage);
                var commit_Command = nGit.Git.Commit();
                commit_Command.SetMessage(commitMessage);
                commit_Command.SetAuthor(author);
                commit_Command.SetCommitter(committer);
                return(commit_Command.Call());
            }

            "[API_NGit] commit was called with no commitMessage".error();
            return(null);
        }
Exemplo n.º 35
0
 /// <summary>Write the given entry information to the ref's log</summary>
 /// <param name="refName"></param>
 /// <param name="oldId"></param>
 /// <param name="newId"></param>
 /// <param name="ident"></param>
 /// <param name="message"></param>
 /// <returns>this writer</returns>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public virtual NGit.Storage.File.ReflogWriter Log(string refName, ObjectId oldId,
                                                   ObjectId newId, PersonIdent ident, string message)
 {
     byte[] encoded = Encode(oldId, newId, ident, message);
     return(Log(refName, encoded));
 }
Exemplo n.º 36
0
 public void setRefLogIdent(PersonIdent pi)
 {
     refLogIdent = pi;
 }
Exemplo n.º 37
0
 /// <summary>Sets the tagger of the tag.</summary>
 /// <remarks>
 /// Sets the tagger of the tag. If the tagger is null, a PersonIdent will be
 /// created from the info in the repository.
 /// </remarks>
 /// <param name="tagger"></param>
 /// <returns>
 ///
 /// <code>this</code>
 /// </returns>
 public virtual NGit.Api.TagCommand SetTagger(PersonIdent tagger)
 {
     this.tagger = tagger;
     return(this);
 }
Exemplo n.º 38
0
 private String iso(PersonIdent id)
 {
     return id.When.UnixTimeToDateTimeOffset(id.TimeZoneOffset).ToString("yyyy-MM-dd'T'HH:mm:ss");
     return id.When.ToString("yyyy-MM-dd'T'HH:mm:ss");
     //SimpleDateFormat fmt;
     //fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
     //fmt.setTimeZone(id.TimeZoneOffset);
     //return fmt.format(id.When);
 }