Ejemplo n.º 1
0
        public virtual void TestCreateAndList()
        {
            int localBefore;
            int remoteBefore;
            int allBefore;

            // invalid name not allowed
            try
            {
                git.BranchCreate().SetName("In va lid").Call();
                NUnit.Framework.Assert.Fail("Create branch with invalid ref name should fail");
            }
            catch (InvalidRefNameException)
            {
            }
            // expected
            // existing name not allowed w/o force
            try
            {
                git.BranchCreate().SetName("master").Call();
                NUnit.Framework.Assert.Fail("Create branch with existing ref name should fail");
            }
            catch (RefAlreadyExistsException)
            {
            }
            // expected
            localBefore  = git.BranchList().Call().Count;
            remoteBefore = git.BranchList().SetListMode(ListBranchCommand.ListMode.REMOTE).Call
                               ().Count;
            allBefore = git.BranchList().SetListMode(ListBranchCommand.ListMode.ALL).Call().Count;
            NUnit.Framework.Assert.AreEqual(localBefore + remoteBefore, allBefore);
            Ref newBranch = CreateBranch(git, "NewForTestList", false, "master", null);

            NUnit.Framework.Assert.AreEqual("refs/heads/NewForTestList", newBranch.GetName());
            NUnit.Framework.Assert.AreEqual(1, git.BranchList().Call().Count - localBefore);
            NUnit.Framework.Assert.AreEqual(0, git.BranchList().SetListMode(ListBranchCommand.ListMode
                                                                            .REMOTE).Call().Count - remoteBefore);
            NUnit.Framework.Assert.AreEqual(1, git.BranchList().SetListMode(ListBranchCommand.ListMode
                                                                            .ALL).Call().Count - allBefore);
            // we can only create local branches
            newBranch = CreateBranch(git, "refs/remotes/origin/NewRemoteForTestList", false,
                                     "master", null);
            NUnit.Framework.Assert.AreEqual("refs/heads/refs/remotes/origin/NewRemoteForTestList"
                                            , newBranch.GetName());
            NUnit.Framework.Assert.AreEqual(2, git.BranchList().Call().Count - localBefore);
            NUnit.Framework.Assert.AreEqual(0, git.BranchList().SetListMode(ListBranchCommand.ListMode
                                                                            .REMOTE).Call().Count - remoteBefore);
            NUnit.Framework.Assert.AreEqual(2, git.BranchList().SetListMode(ListBranchCommand.ListMode
                                                                            .ALL).Call().Count - allBefore);
        }
        public virtual void TestPullLocalConflict()
        {
            target.BranchCreate().SetName("basedOnMaster").SetStartPoint("refs/heads/master")
            .SetUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).Call();
            target.GetRepository().UpdateRef(Constants.HEAD).Link("refs/heads/basedOnMaster");
            PullResult res = target.Pull().Call();

            // nothing to update since we don't have different data yet
            NUnit.Framework.Assert.IsNull(res.GetFetchResult());
            NUnit.Framework.Assert.IsTrue(res.GetMergeResult().GetMergeStatus().Equals(MergeStatus
                                                                                       .ALREADY_UP_TO_DATE));
            AssertFileContentsEqual(targetFile, "Hello world");
            // change the file in master
            target.GetRepository().UpdateRef(Constants.HEAD).Link("refs/heads/master");
            WriteToFile(targetFile, "Master change");
            target.Add().AddFilepattern("SomeFile.txt").Call();
            target.Commit().SetMessage("Source change in master").Call();
            // change the file in slave
            target.GetRepository().UpdateRef(Constants.HEAD).Link("refs/heads/basedOnMaster");
            WriteToFile(targetFile, "Slave change");
            target.Add().AddFilepattern("SomeFile.txt").Call();
            target.Commit().SetMessage("Source change in based on master").Call();
            res = target.Pull().Call();
            string sourceChangeString = "Master change\n>>>>>>> branch 'master' of local repository";

            NUnit.Framework.Assert.IsNull(res.GetFetchResult());
            NUnit.Framework.Assert.AreEqual(res.GetMergeResult().GetMergeStatus(), MergeStatus
                                            .CONFLICTING);
            string result = "<<<<<<< HEAD\nSlave change\n=======\n" + sourceChangeString + "\n";

            AssertFileContentsEqual(targetFile, result);
            NUnit.Framework.Assert.AreEqual(RepositoryState.MERGING, target.GetRepository().GetRepositoryState
                                                ());
        }
Ejemplo n.º 3
0
        public virtual void StashChangeInANewSubdirectory()
        {
            string subdir      = "subdir";
            string fname       = "file2.txt";
            string path        = subdir + "/" + fname;
            string otherBranch = "otherbranch";

            WriteTrashFile(subdir, fname, "content2");
            git.Add().AddFilepattern(path).Call();
            RevCommit stashed = git.StashCreate().Call();

            NUnit.Framework.Assert.IsNotNull(stashed);
            NUnit.Framework.Assert.IsTrue(git.Status().Call().IsClean());
            git.BranchCreate().SetName(otherBranch).Call();
            git.Checkout().SetName(otherBranch).Call();
            ObjectId unstashed = git.StashApply().Call();

            NUnit.Framework.Assert.AreEqual(stashed, unstashed);
            Status status = git.Status().Call();

            NUnit.Framework.Assert.IsTrue(status.GetChanged().IsEmpty());
            NUnit.Framework.Assert.IsTrue(status.GetConflicting().IsEmpty());
            NUnit.Framework.Assert.IsTrue(status.GetMissing().IsEmpty());
            NUnit.Framework.Assert.IsTrue(status.GetRemoved().IsEmpty());
            NUnit.Framework.Assert.IsTrue(status.GetModified().IsEmpty());
            NUnit.Framework.Assert.IsTrue(status.GetUntracked().IsEmpty());
            NUnit.Framework.Assert.AreEqual(1, status.GetAdded().Count);
            NUnit.Framework.Assert.IsTrue(status.GetAdded().Contains(path));
        }
Ejemplo n.º 4
0
        public virtual void TestCherryPick()
        {
            Git git = new Git(db);

            WriteTrashFile("a", "first line\nsec. line\nthird line\n");
            git.Add().AddFilepattern("a").Call();
            RevCommit firstCommit = git.Commit().SetMessage("create a").Call();

            WriteTrashFile("b", "content\n");
            git.Add().AddFilepattern("b").Call();
            git.Commit().SetMessage("create b").Call();
            WriteTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
            git.Add().AddFilepattern("a").Call();
            git.Commit().SetMessage("enlarged a").Call();
            WriteTrashFile("a", "first line\nsecond line\nthird line\nfourth line\n");
            git.Add().AddFilepattern("a").Call();
            RevCommit fixingA = git.Commit().SetMessage("fixed a").Call();

            git.BranchCreate().SetName("side").SetStartPoint(firstCommit).Call();
            CheckoutBranch("refs/heads/side");
            WriteTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n");
            git.Add().AddFilepattern("a").Call();
            git.Commit().SetMessage("enhanced a").Call();
            git.CherryPick().Include(fixingA).Call();
            NUnit.Framework.Assert.IsFalse(new FilePath(db.WorkTree, "b").Exists());
            CheckFile(new FilePath(db.WorkTree, "a"), "first line\nsecond line\nthird line\nfeature++\n"
                      );
            Iterator <RevCommit> history = git.Log().Call().Iterator();

            NUnit.Framework.Assert.AreEqual("fixed a", history.Next().GetFullMessage());
            NUnit.Framework.Assert.AreEqual("enhanced a", history.Next().GetFullMessage());
            NUnit.Framework.Assert.AreEqual("create a", history.Next().GetFullMessage());
            NUnit.Framework.Assert.IsFalse(history.HasNext());
        }
Ejemplo n.º 5
0
        public virtual void TestPushRefUpdate()
        {
            Git          git          = new Git(db);
            Git          git2         = new Git(CreateBareRepository());
            StoredConfig config       = git.GetRepository().GetConfig();
            RemoteConfig remoteConfig = new RemoteConfig(config, "test");
            URIish       uri          = new URIish(git2.GetRepository().Directory.ToURI().ToURL());

            remoteConfig.AddURI(uri);
            remoteConfig.AddPushRefSpec(new RefSpec("+refs/heads/*:refs/heads/*"));
            remoteConfig.Update(config);
            config.Save();
            WriteTrashFile("f", "content of f");
            git.Add().AddFilepattern("f").Call();
            RevCommit commit = git.Commit().SetMessage("adding f").Call();

            NUnit.Framework.Assert.AreEqual(null, git2.GetRepository().Resolve("refs/heads/master"
                                                                               ));
            git.Push().SetRemote("test").Call();
            NUnit.Framework.Assert.AreEqual(commit.Id, git2.GetRepository().Resolve("refs/heads/master"
                                                                                    ));
            git.BranchCreate().SetName("refs/heads/test").Call();
            git.Checkout().SetName("refs/heads/test").Call();
            for (int i = 0; i < 6; i++)
            {
                WriteTrashFile("f" + i, "content of f" + i);
                git.Add().AddFilepattern("f" + i).Call();
                commit = git.Commit().SetMessage("adding f" + i).Call();
                git.Push().SetRemote("test").Call();
                git2.GetRepository().GetAllRefs();
                NUnit.Framework.Assert.AreEqual(commit.Id, git2.GetRepository().Resolve("refs/heads/test"
                                                                                        ), "failed to update on attempt " + i);
            }
        }
Ejemplo n.º 6
0
		public virtual void TestCherryPick()
		{
			Git git = new Git(db);
			WriteTrashFile("a", "first line\nsec. line\nthird line\n");
			git.Add().AddFilepattern("a").Call();
			RevCommit firstCommit = git.Commit().SetMessage("create a").Call();
			WriteTrashFile("b", "content\n");
			git.Add().AddFilepattern("b").Call();
			git.Commit().SetMessage("create b").Call();
			WriteTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
			git.Add().AddFilepattern("a").Call();
			git.Commit().SetMessage("enlarged a").Call();
			WriteTrashFile("a", "first line\nsecond line\nthird line\nfourth line\n");
			git.Add().AddFilepattern("a").Call();
			RevCommit fixingA = git.Commit().SetMessage("fixed a").Call();
			git.BranchCreate().SetName("side").SetStartPoint(firstCommit).Call();
			CheckoutBranch("refs/heads/side");
			WriteTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n");
			git.Add().AddFilepattern("a").Call();
			git.Commit().SetMessage("enhanced a").Call();
			git.CherryPick().Include(fixingA).Call();
			NUnit.Framework.Assert.IsFalse(new FilePath(db.WorkTree, "b").Exists());
			CheckFile(new FilePath(db.WorkTree, "a"), "first line\nsecond line\nthird line\nfeature++\n"
				);
			Iterator<RevCommit> history = git.Log().Call().Iterator();
			NUnit.Framework.Assert.AreEqual("fixed a", history.Next().GetFullMessage());
			NUnit.Framework.Assert.AreEqual("enhanced a", history.Next().GetFullMessage());
			NUnit.Framework.Assert.AreEqual("create a", history.Next().GetFullMessage());
			NUnit.Framework.Assert.IsFalse(history.HasNext());
		}
        public virtual void LogAllCommits()
        {
            IList <RevCommit> commits = new AList <RevCommit>();
            Git git = Git.Wrap(db);

            WriteTrashFile("Test.txt", "Hello world");
            git.Add().AddFilepattern("Test.txt").Call();
            commits.AddItem(git.Commit().SetMessage("initial commit").Call());
            git.BranchCreate().SetName("branch1").Call();
            Ref checkedOut = git.Checkout().SetName("branch1").Call();

            NUnit.Framework.Assert.AreEqual("refs/heads/branch1", checkedOut.GetName());
            WriteTrashFile("Test1.txt", "Hello world!");
            git.Add().AddFilepattern("Test1.txt").Call();
            commits.AddItem(git.Commit().SetMessage("branch1 commit").Call());
            checkedOut = git.Checkout().SetName("master").Call();
            NUnit.Framework.Assert.AreEqual("refs/heads/master", checkedOut.GetName());
            WriteTrashFile("Test2.txt", "Hello world!!");
            git.Add().AddFilepattern("Test2.txt").Call();
            commits.AddItem(git.Commit().SetMessage("branch1 commit").Call());
            Iterator <RevCommit> log = git.Log().All().Call().Iterator();

            NUnit.Framework.Assert.IsTrue(log.HasNext());
            NUnit.Framework.Assert.IsTrue(commits.Contains(log.Next()));
            NUnit.Framework.Assert.IsTrue(log.HasNext());
            NUnit.Framework.Assert.IsTrue(commits.Contains(log.Next()));
            NUnit.Framework.Assert.IsTrue(log.HasNext());
            NUnit.Framework.Assert.IsTrue(commits.Contains(log.Next()));
            NUnit.Framework.Assert.IsFalse(log.HasNext());
        }
Ejemplo n.º 8
0
        public virtual void TestUpdateSmudgedEntries()
        {
            git.BranchCreate().SetName("test2").Call();
            RefUpdate rup = db.UpdateRef(Constants.HEAD);

            rup.Link("refs/heads/test2");
            FilePath file  = new FilePath(db.WorkTree, "Test.txt");
            long     size  = file.Length();
            long     mTime = file.LastModified() - 5000L;

            NUnit.Framework.Assert.IsTrue(file.SetLastModified(mTime));
            DirCache      cache = DirCache.Lock(db.GetIndexFile(), db.FileSystem);
            DirCacheEntry entry = cache.GetEntry("Test.txt");

            NUnit.Framework.Assert.IsNotNull(entry);
            entry.SetLength(0);
            entry.LastModified = 0;
            cache.Write();
            NUnit.Framework.Assert.IsTrue(cache.Commit());
            cache = DirCache.Read(db.GetIndexFile(), db.FileSystem);
            entry = cache.GetEntry("Test.txt");
            NUnit.Framework.Assert.IsNotNull(entry);
            NUnit.Framework.Assert.AreEqual(0, entry.Length);
            NUnit.Framework.Assert.AreEqual(0, entry.LastModified);
            db.GetIndexFile().SetLastModified(db.GetIndexFile().LastModified() - 5000);
            NUnit.Framework.Assert.IsNotNull(git.Checkout().SetName("test").Call());
            cache = DirCache.Read(db.GetIndexFile(), db.FileSystem);
            entry = cache.GetEntry("Test.txt");
            NUnit.Framework.Assert.IsNotNull(entry);
            NUnit.Framework.Assert.AreEqual(size, entry.Length);
            NUnit.Framework.Assert.AreEqual(mTime, entry.LastModified);
        }
Ejemplo n.º 9
0
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException"></exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException"></exception>
        /// <exception cref="NGit.Api.Errors.InvalidRefNameException"></exception>
        public virtual Ref CreateBranch(Git actGit, string name, bool force, string startPoint
			, CreateBranchCommand.SetupUpstreamMode? mode)
        {
            CreateBranchCommand cmd = actGit.BranchCreate();
            cmd.SetName(name);
            cmd.SetForce(force);
            cmd.SetStartPoint(startPoint);
            cmd.SetUpstreamMode(mode != null ? mode.Value : CreateBranchCommand.SetupUpstreamMode.NOT_SET);
            return cmd.Call();
        }
Ejemplo n.º 10
0
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException"></exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException"></exception>
        /// <exception cref="NGit.Api.Errors.InvalidRefNameException"></exception>
        public virtual Ref CreateBranch(Git actGit, string name, bool force, string startPoint
                                        , CreateBranchCommand.SetupUpstreamMode?mode)
        {
            CreateBranchCommand cmd = actGit.BranchCreate();

            cmd.SetName(name);
            cmd.SetForce(force);
            cmd.SetStartPoint(startPoint);
            cmd.SetUpstreamMode(mode != null ? mode.Value : CreateBranchCommand.SetupUpstreamMode.NOT_SET);
            return(cmd.Call());
        }
Ejemplo n.º 11
0
        public virtual void TestCloneRepositoryWithMultipleHeadBranches()
        {
            git.Checkout().SetName(Constants.MASTER).Call();
            git.BranchCreate().SetName("a").Call();
            FilePath directory = CreateTempDirectory("testCloneRepositoryWithMultipleHeadBranches"
                                                     );
            CloneCommand clone = Git.CloneRepository();

            clone.SetDirectory(directory);
            clone.SetURI("file://" + git.GetRepository().WorkTree.GetPath());
            Git git2 = clone.Call();

            AddRepoToClose(git2.GetRepository());
            NUnit.Framework.Assert.IsNotNull(git2);
            NUnit.Framework.Assert.AreEqual(Constants.MASTER, git2.GetRepository().GetBranch(
                                                ));
        }
Ejemplo n.º 12
0
		public override void SetUp()
		{
			base.SetUp();
			git = new Git(db);
			// commit something
			WriteTrashFile("Test.txt", "Hello world");
			git.Add().AddFilepattern("Test.txt").Call();
			initialCommit = git.Commit().SetMessage("Initial commit").Call();
			// create a master branch and switch to it
			git.BranchCreate().SetName("test").Call();
			RefUpdate rup = db.UpdateRef(Constants.HEAD);
			rup.Link("refs/heads/test");
			// commit something on the test branch
			WriteTrashFile("Test.txt", "Some change");
			git.Add().AddFilepattern("Test.txt").Call();
			secondCommit = git.Commit().SetMessage("Second commit").Call();
		}
Ejemplo n.º 13
0
        public override void SetUp()
        {
            base.SetUp();
            git = new Git(db);
            // commit something
            WriteTrashFile("Test.txt", "Hello world");
            git.Add().AddFilepattern("Test.txt").Call();
            initialCommit = git.Commit().SetMessage("Initial commit").Call();
            // create a master branch and switch to it
            git.BranchCreate().SetName("test").Call();
            RefUpdate rup = db.UpdateRef(Constants.HEAD);

            rup.Link("refs/heads/test");
            // commit something on the test branch
            WriteTrashFile("Test.txt", "Some change");
            git.Add().AddFilepattern("Test.txt").Call();
            secondCommit = git.Commit().SetMessage("Second commit").Call();
        }
Ejemplo n.º 14
0
		/// <exception cref="System.Exception"></exception>
		public override void SetUp()
		{
			base.SetUp();
			tr = new TestRepository<Repository>(db);
			git = new Git(db);
			// commit something
			WriteTrashFile("Test.txt", "Hello world");
			git.Add().AddFilepattern("Test.txt").Call();
			git.Commit().SetMessage("Initial commit").Call();
			// create a master branch and switch to it
			git.BranchCreate().SetName("test").Call();
			RefUpdate rup = db.UpdateRef(Constants.HEAD);
			rup.Link("refs/heads/test");
			// commit something on the test branch
			WriteTrashFile("Test.txt", "Some change");
			git.Add().AddFilepattern("Test.txt").Call();
			git.Commit().SetMessage("Second commit").Call();
			RevBlob blob = tr.Blob("blob-not-in-master-branch");
			git.Tag().SetName("tag-for-blob").SetObjectId(blob).Call();
		}
Ejemplo n.º 15
0
        /// <exception cref="System.Exception"></exception>
        public override void SetUp()
        {
            base.SetUp();
            tr  = new TestRepository <Repository>(db);
            git = new Git(db);
            // commit something
            WriteTrashFile("Test.txt", "Hello world");
            git.Add().AddFilepattern("Test.txt").Call();
            git.Commit().SetMessage("Initial commit").Call();
            // create a master branch and switch to it
            git.BranchCreate().SetName("test").Call();
            RefUpdate rup = db.UpdateRef(Constants.HEAD);

            rup.Link("refs/heads/test");
            // commit something on the test branch
            WriteTrashFile("Test.txt", "Some change");
            git.Add().AddFilepattern("Test.txt").Call();
            git.Commit().SetMessage("Second commit").Call();
            RevBlob blob = tr.Blob("blob-not-in-master-branch");

            git.Tag().SetName("tag-for-blob").SetObjectId(blob).Call();
        }
        public virtual void TestPullLocalConflict()
        {
            target.BranchCreate().SetName("basedOnMaster").SetStartPoint("refs/heads/master")
            .SetUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK).Call();
            StoredConfig config = target.GetRepository().GetConfig();

            config.SetString("branch", "basedOnMaster", "remote", ".");
            config.SetString("branch", "basedOnMaster", "merge", "refs/heads/master");
            config.SetBoolean("branch", "basedOnMaster", "rebase", true);
            config.Save();
            target.GetRepository().UpdateRef(Constants.HEAD).Link("refs/heads/basedOnMaster");
            PullResult res = target.Pull().Call();

            // nothing to update since we don't have different data yet
            NUnit.Framework.Assert.IsNull(res.GetFetchResult());
            NUnit.Framework.Assert.AreEqual(RebaseResult.Status.UP_TO_DATE, res.GetRebaseResult
                                                ().GetStatus());
            AssertFileContentsEqual(targetFile, "Hello world");
            // change the file in master
            target.GetRepository().UpdateRef(Constants.HEAD).Link("refs/heads/master");
            WriteToFile(targetFile, "Master change");
            target.Add().AddFilepattern("SomeFile.txt").Call();
            target.Commit().SetMessage("Source change in master").Call();
            // change the file in slave
            target.GetRepository().UpdateRef(Constants.HEAD).Link("refs/heads/basedOnMaster");
            WriteToFile(targetFile, "Slave change");
            target.Add().AddFilepattern("SomeFile.txt").Call();
            target.Commit().SetMessage("Source change in based on master").Call();
            res = target.Pull().Call();
            NUnit.Framework.Assert.IsNull(res.GetFetchResult());
            NUnit.Framework.Assert.AreEqual(RebaseResult.Status.STOPPED, res.GetRebaseResult(
                                                ).GetStatus());
            string result = "<<<<<<< Upstream, based on branch 'master' of local repository\n"
                            + "Master change\n=======\nSlave change\n>>>>>>> 4049c9e Source change in based on master\n";

            AssertFileContentsEqual(targetFile, result);
            NUnit.Framework.Assert.AreEqual(RepositoryState.REBASING_INTERACTIVE, target.GetRepository
                                                ().GetRepositoryState());
        }
Ejemplo n.º 17
0
		/// <summary>
		/// Commit a file with the specified contents on the specified branch,
		/// creating the branch if it didn't exist before.
		/// </summary>
		/// <remarks>
		/// Commit a file with the specified contents on the specified branch,
		/// creating the branch if it didn't exist before.
		/// <p>
		/// It switches back to the original branch after the commit if there was
		/// one.
		/// </remarks>
		/// <param name="filename"></param>
		/// <param name="contents"></param>
		/// <param name="branch"></param>
		/// <returns>the created commit</returns>
		protected internal virtual RevCommit CommitFile(string filename, string contents, 
			string branch)
		{
			try
			{
				Git git = new Git(db);
				string originalBranch = git.GetRepository().GetFullBranch();
				if (git.GetRepository().GetRef(branch) == null)
				{
					git.BranchCreate().SetName(branch).Call();
				}
				git.Checkout().SetName(branch).Call();
				WriteTrashFile(filename, contents);
				git.Add().AddFilepattern(filename).Call();
				RevCommit commit = git.Commit().SetMessage(branch + ": " + filename).Call();
				if (originalBranch != null)
				{
					git.Checkout().SetName(originalBranch).Call();
				}
				return commit;
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
			catch (GitAPIException e)
			{
				throw new RuntimeException(e);
			}
		}
Ejemplo n.º 18
0
		public static FileRepository Clone (string targetLocalPath, string url, IProgressMonitor monitor)
		{
			FileRepository repo = Init (targetLocalPath, url, monitor);
			
			// Fetch
			
			string remoteName = "origin";
			string branch = Constants.R_HEADS + "master";
			Transport tn = Transport.Open (repo, remoteName);
			FetchResult r;

			try {
				r = tn.Fetch(new GitMonitor (monitor), null);
			}
			finally {
				tn.Close ();
			}
			
			// Create the master branch
			
			// branch is like 'Constants.R_HEADS + branchName', we need only
			// the 'branchName' part
			String branchName = branch.Substring (Constants.R_HEADS.Length);
			NGit.Api.Git git = new NGit.Api.Git (repo);
			git.BranchCreate ().SetName (branchName).SetUpstreamMode (CreateBranchCommand.SetupUpstreamMode.TRACK).SetStartPoint ("origin/master").Call ();
			
			// Checkout

			DirCache dc = repo.LockDirCache ();
			try {
				RevWalk rw = new RevWalk (repo);
				ObjectId remCommitId = repo.Resolve (remoteName + "/" + branchName);
				RevCommit remCommit = rw.ParseCommit (remCommitId);
				DirCacheCheckout co = new DirCacheCheckout (repo, null, dc, remCommit.Tree);
				co.Checkout ();
			} catch {
				dc.Unlock ();
				throw;
			}
			
			return repo;
		}
Ejemplo n.º 19
0
 public virtual void TestResetHard()
 {
     Git git = new Git(db);
     WriteTrashFile("f", "f()");
     WriteTrashFile("D/g", "g()");
     git.Add().AddFilepattern(".").Call();
     git.Commit().SetMessage("inital").Call();
     AssertIndex(Mkmap("f", "f()", "D/g", "g()"));
     git.BranchCreate().SetName("topic").Call();
     WriteTrashFile("f", "f()\nmaster");
     WriteTrashFile("D/g", "g()\ng2()");
     WriteTrashFile("E/h", "h()");
     git.Add().AddFilepattern(".").Call();
     RevCommit master = git.Commit().SetMessage("master-1").Call();
     AssertIndex(Mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
     CheckoutBranch("refs/heads/topic");
     AssertIndex(Mkmap("f", "f()", "D/g", "g()"));
     WriteTrashFile("f", "f()\nside");
     NUnit.Framework.Assert.IsTrue(new FilePath(db.WorkTree, "D/g").Delete());
     WriteTrashFile("G/i", "i()");
     git.Add().AddFilepattern(".").Call();
     git.Add().AddFilepattern(".").SetUpdate(true).Call();
     RevCommit topic = git.Commit().SetMessage("topic-1").Call();
     AssertIndex(Mkmap("f", "f()\nside", "G/i", "i()"));
     WriteTrashFile("untracked", "untracked");
     ResetHard(master);
     AssertIndex(Mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
     ResetHard(topic);
     AssertIndex(Mkmap("f", "f()\nside", "G/i", "i()"));
     AssertWorkDir(Mkmap("f", "f()\nside", "G/i", "i()", "untracked", "untracked"));
     NUnit.Framework.Assert.AreEqual(MergeStatus.CONFLICTING, git.Merge().Include(master
         ).Call().GetMergeStatus());
     NUnit.Framework.Assert.AreEqual("[D/g, mode:100644, stage:1][D/g, mode:100644, stage:3][E/h, mode:100644][G/i, mode:100644][f, mode:100644, stage:1][f, mode:100644, stage:2][f, mode:100644, stage:3]"
         , IndexState(0));
     ResetHard(master);
     AssertIndex(Mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
     AssertWorkDir(Mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()", "untracked"
         , "untracked"));
 }
Ejemplo n.º 20
0
        /// <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;
                }
            }
        }
Ejemplo n.º 21
0
		public virtual void TestPushRefUpdate()
		{
			Git git = new Git(db);
			Git git2 = new Git(CreateBareRepository());
			StoredConfig config = git.GetRepository().GetConfig();
			RemoteConfig remoteConfig = new RemoteConfig(config, "test");
			URIish uri = new URIish(git2.GetRepository().Directory.ToURI().ToURL());
			remoteConfig.AddURI(uri);
			remoteConfig.AddPushRefSpec(new RefSpec("+refs/heads/*:refs/heads/*"));
			remoteConfig.Update(config);
			config.Save();
			WriteTrashFile("f", "content of f");
			git.Add().AddFilepattern("f").Call();
			RevCommit commit = git.Commit().SetMessage("adding f").Call();
			NUnit.Framework.Assert.AreEqual(null, git2.GetRepository().Resolve("refs/heads/master"
				));
			git.Push().SetRemote("test").Call();
			NUnit.Framework.Assert.AreEqual(commit.Id, git2.GetRepository().Resolve("refs/heads/master"
				));
			git.BranchCreate().SetName("refs/heads/test").Call();
			git.Checkout().SetName("refs/heads/test").Call();
			for (int i = 0; i < 6; i++)
			{
				WriteTrashFile("f" + i, "content of f" + i);
				git.Add().AddFilepattern("f" + i).Call();
				commit = git.Commit().SetMessage("adding f" + i).Call();
				git.Push().SetRemote("test").Call();
				git2.GetRepository().GetAllRefs();
				NUnit.Framework.Assert.AreEqual(commit.Id, git2.GetRepository().Resolve("refs/heads/test"
					), "failed to update on attempt " + i);
			}
		}