public virtual void RepositoryWithDifferentRevCheckedOutSubmodule() { ObjectId id = ObjectId.FromString("abcd1234abcd1234abcd1234abcd1234abcd1234"); string path = "sub"; DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); editor.Add(new _PathEdit_317(id, path)); editor.Commit(); string url = "git://server/repo.git"; StoredConfig config = ((FileBasedConfig)db.GetConfig()); config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants. CONFIG_KEY_URL, url); config.Save(); FileBasedConfig modulesConfig = new FileBasedConfig(new FilePath(db.WorkTree, Constants .DOT_GIT_MODULES), db.FileSystem); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_PATH, path); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_URL, url); modulesConfig.Save(); Repository subRepo = Git.Init().SetBare(false).SetDirectory(new FilePath(db.WorkTree , path)).Call().GetRepository(); NUnit.Framework.Assert.IsNotNull(subRepo); RefUpdate update = subRepo.UpdateRef(Constants.HEAD, true); update.SetNewObjectId(ObjectId.FromString("aaaa0000aaaa0000aaaa0000aaaa0000aaaa0000" )); update.ForceUpdate(); SubmoduleStatusCommand command = new SubmoduleStatusCommand(db); IDictionary <string, SubmoduleStatus> statuses = command.Call(); NUnit.Framework.Assert.IsNotNull(statuses); NUnit.Framework.Assert.AreEqual(1, statuses.Count); KeyValuePair <string, SubmoduleStatus> module = statuses.EntrySet().Iterator().Next (); NUnit.Framework.Assert.IsNotNull(module); NUnit.Framework.Assert.AreEqual(path, module.Key); SubmoduleStatus status = module.Value; NUnit.Framework.Assert.IsNotNull(status); NUnit.Framework.Assert.AreEqual(path, status.GetPath()); NUnit.Framework.Assert.AreEqual(id, status.GetIndexId()); NUnit.Framework.Assert.AreEqual(update.GetNewObjectId(), status.GetHeadId()); NUnit.Framework.Assert.AreEqual(SubmoduleStatusType.REV_CHECKED_OUT, status.GetType ()); }
public virtual void RenameBranchExistingSection() { string branch = "b1"; StoredConfig config = git.GetRepository().GetConfig(); config.SetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, ConfigConstants .CONFIG_KEY_REBASE, true); config.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, "a", "a" ); config.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, "a", "b"); config.Save(); NUnit.Framework.Assert.IsNotNull(git.BranchRename().SetNewName(branch).Call()); config = git.GetRepository().GetConfig(); CollectionAssert.AreEquivalent(new string[] { "b", "a" }, config.GetStringList(ConfigConstants .CONFIG_BRANCH_SECTION, branch, "a")); }
public virtual void RenameBranchNoConfigValues() { StoredConfig config = git.GetRepository().GetConfig(); config.UnsetSection(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER); config.Save(); string branch = "b1"; NUnit.Framework.Assert.IsTrue(config.GetNames(ConfigConstants.CONFIG_BRANCH_SECTION , Constants.MASTER).IsEmpty()); NUnit.Framework.Assert.IsNotNull(git.BranchRename().SetNewName(branch).Call()); config = git.GetRepository().GetConfig(); NUnit.Framework.Assert.IsTrue(config.GetNames(ConfigConstants.CONFIG_BRANCH_SECTION , Constants.MASTER).IsEmpty()); NUnit.Framework.Assert.IsTrue(config.GetNames(ConfigConstants.CONFIG_BRANCH_SECTION , branch).IsEmpty()); }
public virtual void RenameBranchSingleConfigValue() { StoredConfig config = git.GetRepository().GetConfig(); config.SetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, ConfigConstants .CONFIG_KEY_REBASE, true); config.Save(); string branch = "b1"; NUnit.Framework.Assert.IsTrue(config.GetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION , Constants.MASTER, ConfigConstants.CONFIG_KEY_REBASE, true)); NUnit.Framework.Assert.IsFalse(config.GetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION , branch, ConfigConstants.CONFIG_KEY_REBASE, false)); NUnit.Framework.Assert.IsNotNull(git.BranchRename().SetNewName(branch).Call()); config = git.GetRepository().GetConfig(); NUnit.Framework.Assert.IsFalse(config.GetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION , Constants.MASTER, ConfigConstants.CONFIG_KEY_REBASE, false)); NUnit.Framework.Assert.IsTrue(config.GetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION , branch, ConfigConstants.CONFIG_KEY_REBASE, false)); }
public virtual void RepositoryWithNoSubmoduleRepository() { ObjectId id = ObjectId.FromString("abcd1234abcd1234abcd1234abcd1234abcd1234"); string path = "sub"; DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); editor.Add(new _PathEdit_216(id, path)); editor.Commit(); string url = "git://server/repo.git"; StoredConfig config = ((FileBasedConfig)db.GetConfig()); config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants. CONFIG_KEY_URL, url); config.Save(); FileBasedConfig modulesConfig = new FileBasedConfig(new FilePath(db.WorkTree, Constants .DOT_GIT_MODULES), db.FileSystem); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_PATH, path); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_URL, url); modulesConfig.Save(); SubmoduleStatusCommand command = new SubmoduleStatusCommand(db); IDictionary <string, SubmoduleStatus> statuses = command.Call(); NUnit.Framework.Assert.IsNotNull(statuses); NUnit.Framework.Assert.AreEqual(1, statuses.Count); KeyValuePair <string, SubmoduleStatus> module = statuses.EntrySet().Iterator().Next (); NUnit.Framework.Assert.IsNotNull(module); NUnit.Framework.Assert.AreEqual(path, module.Key); SubmoduleStatus status = module.Value; NUnit.Framework.Assert.IsNotNull(status); NUnit.Framework.Assert.AreEqual(path, status.GetPath()); NUnit.Framework.Assert.AreEqual(id, status.GetIndexId()); NUnit.Framework.Assert.AreEqual(SubmoduleStatusType.UNINITIALIZED, status.GetType ()); }
public virtual void TestTrackingUpdate() { Repository db2 = CreateBareRepository(); string remote = "origin"; string branch = "refs/heads/master"; string trackingBranch = "refs/remotes/" + remote + "/master"; Git git = new Git(db); RevCommit commit1 = git.Commit().SetMessage("Initial commit").Call(); RefUpdate branchRefUpdate = db.UpdateRef(branch); branchRefUpdate.SetNewObjectId(commit1.Id); branchRefUpdate.Update(); RefUpdate trackingBranchRefUpdate = db.UpdateRef(trackingBranch); trackingBranchRefUpdate.SetNewObjectId(commit1.Id); trackingBranchRefUpdate.Update(); StoredConfig config = ((FileBasedConfig)db.GetConfig()); RemoteConfig remoteConfig = new RemoteConfig(config, remote); URIish uri = new URIish(db2.Directory.ToURI().ToURL()); remoteConfig.AddURI(uri); remoteConfig.AddFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/" + remote + "/*")); remoteConfig.Update(config); config.Save(); RevCommit commit2 = git.Commit().SetMessage("Commit to push").Call(); RefSpec spec = new RefSpec(branch + ":" + branch); Iterable <PushResult> resultIterable = git.Push().SetRemote(remote).SetRefSpecs(spec ).Call(); PushResult result = resultIterable.Iterator().Next(); TrackingRefUpdate trackingRefUpdate = result.GetTrackingRefUpdate(trackingBranch); NUnit.Framework.Assert.IsNotNull(trackingRefUpdate); NUnit.Framework.Assert.AreEqual(trackingBranch, trackingRefUpdate.GetLocalName()); NUnit.Framework.Assert.AreEqual(branch, trackingRefUpdate.GetRemoteName()); NUnit.Framework.Assert.AreEqual(commit2.Id, trackingRefUpdate.GetNewObjectId()); NUnit.Framework.Assert.AreEqual(commit2.Id, db.Resolve(trackingBranch)); NUnit.Framework.Assert.AreEqual(commit2.Id, db2.Resolve(branch)); }
public virtual void RepositoryWithSubmodule() { WriteTrashFile("file.txt", "content"); Git git = Git.Wrap(db); git.Add().AddFilepattern("file.txt").Call(); RevCommit commit = git.Commit().SetMessage("create file").Call(); string path = "sub"; DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); editor.Add(new _PathEdit_94(commit, path)); editor.Commit(); StoredConfig config = ((FileBasedConfig)db.GetConfig()); config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants. CONFIG_KEY_URL, db.Directory.ToURI().ToString()); config.Save(); FileBasedConfig modulesConfig = new FileBasedConfig(new FilePath(db.WorkTree, Constants .DOT_GIT_MODULES), db.FileSystem); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_PATH, path); modulesConfig.Save(); SubmoduleUpdateCommand command = new SubmoduleUpdateCommand(db); ICollection <string> updated = command.Call(); NUnit.Framework.Assert.IsNotNull(updated); NUnit.Framework.Assert.AreEqual(1, updated.Count); NUnit.Framework.Assert.AreEqual(path, updated.Iterator().Next()); SubmoduleWalk generator = SubmoduleWalk.ForIndex(db); NUnit.Framework.Assert.IsTrue(generator.Next()); Repository subRepo = generator.GetRepository(); AddRepoToClose(subRepo); NUnit.Framework.Assert.IsNotNull(subRepo); NUnit.Framework.Assert.AreEqual(commit, subRepo.Resolve(Constants.HEAD)); }
public virtual void TestPushWithRefSpecFromConfig() { 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("HEAD:refs/heads/newbranch")); 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/newbranch" )); }
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()); }
/// <exception cref="System.Exception"></exception> private Git SetUpRepoWithRemote() { Repository remoteRepository = CreateWorkRepository(); Git remoteGit = new Git(remoteRepository); // commit something WriteTrashFile("Test.txt", "Hello world"); remoteGit.Add().AddFilepattern("Test.txt").Call(); initialCommit = remoteGit.Commit().SetMessage("Initial commit").Call(); WriteTrashFile("Test.txt", "Some change"); remoteGit.Add().AddFilepattern("Test.txt").Call(); secondCommit = remoteGit.Commit().SetMessage("Second commit").Call(); // create a master branch RefUpdate rup = remoteRepository.UpdateRef("refs/heads/master"); rup.SetNewObjectId(initialCommit.Id); rup.ForceUpdate(); Repository localRepository = CreateWorkRepository(); Git localGit = new Git(localRepository); StoredConfig config = localRepository.GetConfig(); RemoteConfig rc = new RemoteConfig(config, "origin"); rc.AddURI(new URIish(remoteRepository.Directory.GetPath())); rc.AddFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); rc.Update(config); config.Save(); FetchResult res = localGit.Fetch().SetRemote("origin").Call(); NUnit.Framework.Assert.IsFalse(res.GetTrackingRefUpdates().IsEmpty()); rup = localRepository.UpdateRef("refs/heads/master"); rup.SetNewObjectId(initialCommit.Id); rup.ForceUpdate(); rup = localRepository.UpdateRef(Constants.HEAD); rup.Link("refs/heads/master"); rup.SetNewObjectId(initialCommit.Id); rup.Update(); return(localGit); }
public virtual void TestCheckoutRemoteTrackingWithoutLocalBranch() { // create second repository Repository db2 = CreateWorkRepository(); Git git2 = new Git(db2); // setup the second repository to fetch from the first repository StoredConfig config = db2.GetConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db.Directory.ToURI().ToURL()); remoteConfig.AddURI(uri); remoteConfig.Update(config); config.Save(); // fetch from first repository RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/origin/*"); git2.Fetch().SetRemote("origin").SetRefSpecs(spec).Call(); // checkout remote tracking branch in second repository // (no local branches exist yet in second repository) git2.Checkout().SetName("remotes/origin/test").Call(); NUnit.Framework.Assert.AreEqual("[Test.txt, mode:100644, content:Some change]", IndexState (db2, CONTENT)); }
public virtual void TestFetch() { // create other repository Repository db2 = CreateWorkRepository(); Git git2 = new Git(db2); // setup the first repository to fetch from the second repository StoredConfig config = ((FileBasedConfig)db.GetConfig()); RemoteConfig remoteConfig = new RemoteConfig(config, "test"); URIish uri = new URIish(db2.Directory.ToURI().ToURL()); remoteConfig.AddURI(uri); remoteConfig.Update(config); config.Save(); // create some refs via commits and tag RevCommit commit = git2.Commit().SetMessage("initial commit").Call(); RevTag tag = git2.Tag().SetName("tag").Call(); Git git1 = new Git(db); RefSpec spec = new RefSpec("refs/heads/master:refs/heads/x"); git1.Fetch().SetRemote("test").SetRefSpecs(spec).Call(); NUnit.Framework.Assert.AreEqual(commit.Id, db.Resolve(commit.Id.GetName() + "^{commit}" )); NUnit.Framework.Assert.AreEqual(tag.Id, db.Resolve(tag.Id.GetName())); }
/// <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(); } }
/// <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.Api.Errors.RefNotFoundException"> /// if the old branch can not be found (branch with provided old /// name does not exist or old name resolves to a tag) /// </exception> /// <exception cref="NGit.Api.Errors.InvalidRefNameException"> /// if the provided new name is <code>null</code> or otherwise /// invalid /// </exception> /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException">if a branch with the new name already exists /// </exception> /// <exception cref="NGit.Api.Errors.DetachedHeadException"> /// if rename is tried without specifying the old name and HEAD /// is detached /// </exception> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override Ref Call() { CheckCallable(); if (newName == null) { throw new InvalidRefNameException(MessageFormat.Format(JGitText.Get().branchNameInvalid , "<null>")); } try { string fullOldName; string fullNewName; if (repo.GetRef(newName) != null) { throw new RefAlreadyExistsException(MessageFormat.Format(JGitText.Get().refAlreadyExists1 , newName)); } if (oldName != null) { Ref @ref = repo.GetRef(oldName); if (@ref == null) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved , oldName)); } if (@ref.GetName().StartsWith(Constants.R_TAGS)) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().renameBranchFailedBecauseTag , oldName)); } fullOldName = @ref.GetName(); } else { fullOldName = repo.GetFullBranch(); if (ObjectId.IsId(fullOldName)) { throw new DetachedHeadException(); } } if (fullOldName.StartsWith(Constants.R_REMOTES)) { fullNewName = Constants.R_REMOTES + newName; } else { fullNewName = Constants.R_HEADS + newName; } if (!Repository.IsValidRefName(fullNewName)) { throw new InvalidRefNameException(MessageFormat.Format(JGitText.Get().branchNameInvalid , fullNewName)); } RefRename rename = repo.RenameRef(fullOldName, fullNewName); RefUpdate.Result renameResult = rename.Rename(); SetCallable(false); if (RefUpdate.Result.RENAMED != renameResult) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().renameBranchUnexpectedResult , renameResult.ToString())); } if (fullNewName.StartsWith(Constants.R_HEADS)) { string shortOldName = Sharpen.Runtime.Substring(fullOldName, Constants.R_HEADS.Length ); StoredConfig repoConfig = repo.GetConfig(); // Copy all configuration values over to the new branch foreach (string name in repoConfig.GetNames(ConfigConstants.CONFIG_BRANCH_SECTION , shortOldName)) { string[] values = repoConfig.GetStringList(ConfigConstants.CONFIG_BRANCH_SECTION, shortOldName, name); if (values.Length == 0) { continue; } // Keep any existing values already configured for the // new branch name string[] existing = repoConfig.GetStringList(ConfigConstants.CONFIG_BRANCH_SECTION , newName, name); if (existing.Length > 0) { string[] newValues = new string[values.Length + existing.Length]; System.Array.Copy(existing, 0, newValues, 0, existing.Length); System.Array.Copy(values, 0, newValues, existing.Length, values.Length); values = newValues; } repoConfig.SetStringList(ConfigConstants.CONFIG_BRANCH_SECTION, newName, name, Arrays .AsList(values)); } repoConfig.UnsetSection(ConfigConstants.CONFIG_BRANCH_SECTION, shortOldName); repoConfig.Save(); } Ref resultRef = repo.GetRef(newName); if (resultRef == null) { throw new JGitInternalException(JGitText.Get().renameBranchFailedUnknownReason); } return(resultRef); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } }
/// <exception cref="NGit.Api.Errors.RefNotFoundException"> /// if the old branch can not be found (branch with provided old /// name does not exist or old name resolves to a tag) /// </exception> /// <exception cref="NGit.Api.Errors.InvalidRefNameException"> /// if the provided new name is <code>null</code> or otherwise /// invalid /// </exception> /// <exception cref="NGit.Api.Errors.RefAlreadyExistsException">if a branch with the new name already exists /// </exception> /// <exception cref="NGit.Api.Errors.DetachedHeadException"> /// if rename is tried without specifying the old name and HEAD /// is detached /// </exception> public override Ref Call() { CheckCallable(); if (newName == null) { throw new InvalidRefNameException(MessageFormat.Format(JGitText.Get().branchNameInvalid , "<null>")); } try { string fullOldName; string fullNewName; if (repo.GetRef(newName) != null) { throw new RefAlreadyExistsException(MessageFormat.Format(JGitText.Get().refAlreadExists , newName)); } if (oldName != null) { Ref @ref = repo.GetRef(oldName); if (@ref == null) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().refNotResolved , oldName)); } if (@ref.GetName().StartsWith(Constants.R_TAGS)) { throw new RefNotFoundException(MessageFormat.Format(JGitText.Get().renameBranchFailedBecauseTag , oldName)); } fullOldName = @ref.GetName(); } else { fullOldName = repo.GetFullBranch(); if (ObjectId.IsId(fullOldName)) { throw new DetachedHeadException(); } } if (fullOldName.StartsWith(Constants.R_REMOTES)) { fullNewName = Constants.R_REMOTES + newName; } else { fullNewName = Constants.R_HEADS + newName; } if (!Repository.IsValidRefName(fullNewName)) { throw new InvalidRefNameException(MessageFormat.Format(JGitText.Get().branchNameInvalid , fullNewName)); } RefRename rename = repo.RenameRef(fullOldName, fullNewName); RefUpdate.Result renameResult = rename.Rename(); SetCallable(false); bool ok = RefUpdate.Result.RENAMED == renameResult; if (ok) { if (fullNewName.StartsWith(Constants.R_HEADS)) { // move the upstream configuration over to the new branch string shortOldName = Sharpen.Runtime.Substring(fullOldName, Constants.R_HEADS.Length ); StoredConfig repoConfig = repo.GetConfig(); string oldRemote = repoConfig.GetString(ConfigConstants.CONFIG_BRANCH_SECTION, shortOldName , ConfigConstants.CONFIG_KEY_REMOTE); if (oldRemote != null) { repoConfig.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, newName, ConfigConstants .CONFIG_KEY_REMOTE, oldRemote); } string oldMerge = repoConfig.GetString(ConfigConstants.CONFIG_BRANCH_SECTION, shortOldName , ConfigConstants.CONFIG_KEY_MERGE); if (oldMerge != null) { repoConfig.SetString(ConfigConstants.CONFIG_BRANCH_SECTION, newName, ConfigConstants .CONFIG_KEY_MERGE, oldMerge); } repoConfig.UnsetSection(ConfigConstants.CONFIG_BRANCH_SECTION, shortOldName); repoConfig.Save(); } } else { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().renameBranchUnexpectedResult , renameResult.ToString())); } Ref resultRef = repo.GetRef(newName); if (resultRef == null) { throw new JGitInternalException(JGitText.Get().renameBranchFailedUnknownReason); } return(resultRef); } catch (IOException ioe) { throw new JGitInternalException(ioe.Message, ioe); } }
/// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override IDictionary <string, string> Call() { CheckCallable(); try { SubmoduleWalk generator = SubmoduleWalk.ForIndex(repo); if (!paths.IsEmpty()) { generator.SetFilter(PathFilterGroup.CreateFromStrings(paths)); } IDictionary <string, string> synced = new Dictionary <string, string>(); StoredConfig config = repo.GetConfig(); while (generator.Next()) { string remoteUrl = generator.GetRemoteUrl(); if (remoteUrl == null) { continue; } string path = generator.GetPath(); config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants. CONFIG_KEY_URL, remoteUrl); synced.Put(path, remoteUrl); Repository subRepo = generator.GetRepository(); if (subRepo == null) { continue; } StoredConfig subConfig; string branch; try { subConfig = subRepo.GetConfig(); // Get name of remote associated with current branch and // fall back to default remote name as last resort branch = GetHeadBranch(subRepo); string remote = null; if (branch != null) { remote = subConfig.GetString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants .CONFIG_KEY_REMOTE); } if (remote == null) { remote = Constants.DEFAULT_REMOTE_NAME; } subConfig.SetString(ConfigConstants.CONFIG_REMOTE_SECTION, remote, ConfigConstants .CONFIG_KEY_URL, remoteUrl); subConfig.Save(); } finally { subRepo.Close(); } } if (!synced.IsEmpty()) { config.Save(); } return(synced); } catch (IOException e) { throw new JGitInternalException(e.Message, e); } catch (ConfigInvalidException e) { throw new JGitInternalException(e.Message, e); } }
/// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public override Repository Call() { CheckCallable(); if (path == null || path.Length == 0) { throw new ArgumentException(JGitText.Get().pathNotConfigured); } if (uri == null || uri.Length == 0) { throw new ArgumentException(JGitText.Get().uriNotConfigured); } try { if (SubmoduleExists()) { throw new JGitInternalException(MessageFormat.Format(JGitText.Get().submoduleExists , path)); } } catch (IOException e) { throw new JGitInternalException(e.Message, e); } string resolvedUri; try { resolvedUri = SubmoduleWalk.GetSubmoduleRemoteUrl(repo, uri); } catch (IOException e) { throw new JGitInternalException(e.Message, e); } // Clone submodule repository FilePath moduleDirectory = SubmoduleWalk.GetSubmoduleDirectory(repo, path); CloneCommand clone = Git.CloneRepository(); Configure(clone); clone.SetDirectory(moduleDirectory); clone.SetURI(resolvedUri); if (monitor != null) { clone.SetProgressMonitor(monitor); } Repository subRepo = clone.Call().GetRepository(); // Save submodule URL to parent repository's config StoredConfig config = repo.GetConfig(); config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants. CONFIG_KEY_URL, resolvedUri); try { config.Save(); } catch (IOException e) { throw new JGitInternalException(e.Message, e); } // Save path and URL to parent repository's .gitmodules file FileBasedConfig modulesConfig = new FileBasedConfig(new FilePath(repo.WorkTree, Constants .DOT_GIT_MODULES), repo.FileSystem); try { modulesConfig.Load(); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_PATH, path); modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants .CONFIG_KEY_URL, uri); modulesConfig.Save(); } catch (IOException e) { throw new JGitInternalException(e.Message, e); } catch (ConfigInvalidException e) { throw new JGitInternalException(e.Message, e); } AddCommand add = new AddCommand(repo); // Add .gitmodules file to parent repository's index add.AddFilepattern(Constants.DOT_GIT_MODULES); // Add submodule directory to parent repository's index add.AddFilepattern(path); try { add.Call(); } catch (NoFilepatternException e) { throw new JGitInternalException(e.Message, e); } return(subRepo); }