Example #1
0
        /// <exception cref="Sharpen.URISyntaxException"></exception>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        /// <exception cref="NGit.Api.Errors.InvalidRemoteException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private FetchResult Fetch(Repository repo, URIish u)
        {
            // create the remote config and save it
            RemoteConfig config = new RemoteConfig(repo.GetConfig(), remote);

            config.AddURI(u);
            string  dst     = Constants.R_REMOTES + config.Name;
            RefSpec refSpec = new RefSpec();

            refSpec = refSpec.SetForceUpdate(true);
            refSpec = refSpec.SetSourceDestination(Constants.R_HEADS + "*", dst + "/*");
            //$NON-NLS-1$ //$NON-NLS-2$
            config.AddFetchRefSpec(refSpec);
            config.Update(repo.GetConfig());
            repo.GetConfig().SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants
                                       .CONFIG_KEY_REMOTE, remote);
            repo.GetConfig().SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants
                                       .CONFIG_KEY_MERGE, branch);
            repo.GetConfig().Save();
            // run the fetch command
            FetchCommand command = new FetchCommand(repo);

            command.SetRemote(remote);
            command.SetProgressMonitor(monitor);
            command.SetTagOpt(TagOpt.FETCH_TAGS);
            if (credentialsProvider != null)
            {
                command.SetCredentialsProvider(credentialsProvider);
            }
            return(command.Call());
        }
Example #2
0
        /// <exception cref="Sharpen.URISyntaxException"></exception>
        /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
        /// <exception cref="NGit.Api.Errors.InvalidRemoteException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private FetchResult Fetch(Repository repo, URIish u)
        {
            // create the remote config and save it
            RemoteConfig config = new RemoteConfig(repo.GetConfig(), remote);

            config.AddURI(u);
            string  dst     = bare ? Constants.R_HEADS : Constants.R_REMOTES + config.Name;
            RefSpec refSpec = new RefSpec();

            refSpec = refSpec.SetForceUpdate(true);
            refSpec = refSpec.SetSourceDestination(Constants.R_HEADS + "*", dst + "/*");
            //$NON-NLS-1$ //$NON-NLS-2$
            config.AddFetchRefSpec(refSpec);
            config.Update(repo.GetConfig());
            repo.GetConfig().Save();
            // run the fetch command
            FetchCommand command = new FetchCommand(repo);

            command.SetRemote(remote);
            command.SetProgressMonitor(monitor);
            command.SetTagOpt(TagOpt.FETCH_TAGS);
            command.SetTimeout(timeout);
            if (credentialsProvider != null)
            {
                command.SetCredentialsProvider(credentialsProvider);
            }
            IList <RefSpec> specs = CalculateRefSpecs(dst);

            command.SetRefSpecs(specs);
            return(command.Call());
        }
Example #3
0
        /// <exception cref="System.IO.IOException"></exception>
        private void AddMergeConfig(Repository repo, Ref head)
        {
            string branchName = Repository.ShortenRefName(head.GetName());

            repo.GetConfig().SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants
                                       .CONFIG_KEY_REMOTE, remote);
            repo.GetConfig().SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants
                                       .CONFIG_KEY_MERGE, head.GetName());
            repo.GetConfig().Save();
        }
Example #4
0
 /// <summary>Reset generator and start new submodule walk</summary>
 /// <returns>this generator</returns>
 public virtual NGit.Submodule.SubmoduleWalk Reset()
 {
     repoConfig    = repository.GetConfig();
     modulesConfig = null;
     walk.Reset();
     return(this);
 }
Example #5
0
 /// <summary>Create submodule generator</summary>
 /// <param name="repository"></param>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public SubmoduleWalk(Repository repository)
 {
     this.repository = repository;
     repoConfig      = repository.GetConfig();
     walk            = new TreeWalk(repository);
     walk.Recursive  = true;
 }
Example #6
0
 public virtual void TestCheckoutRemoteTrackingWithoutLocalBranch()
 {
     try
     {
         // 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));
     }
     catch (Exception e)
     {
         NUnit.Framework.Assert.Fail(e.Message);
     }
 }
Example #7
0
        public async Task Clone()
        {
            if (Repository != null)
            {
                throw new InvalidOperationException();
            }
            var url = "https://github.com/" + Settings.Owner + "/" + Settings.Repository + ".git";
            var git = Git.Init().SetDirectory(Location).Call();

            Repository = git.GetRepository();

            var config       = Repository.GetConfig();
            var remoteConfig = new RemoteConfig(config, "origin");

            remoteConfig.AddURI(new URIish(url));
            remoteConfig.AddFetchRefSpec(new RefSpec(
                                             "+refs/heads/" + Settings.Branch +
                                             ":refs/remotes/origin/" + Settings.Branch));
            remoteConfig.Update(config);
            config.Save();

            await Fetch();

            await Task.Run(() => {
                git.BranchCreate().SetName(Settings.Branch).SetStartPoint("origin/" + Settings.Branch)
                .SetUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).Call();
                git.Checkout().SetName(Settings.Branch).Call();
            });
        }
Example #8
0
 /// <summary>Create submodule generator</summary>
 /// <param name="repository"></param>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public SubmoduleWalk(Repository repository)
 {
     this.repository = repository;
     repoConfig = repository.GetConfig();
     walk = new TreeWalk(repository);
     walk.Recursive = true;
 }
		/// <summary>
		/// Compute the tracking status for the <code>branchName</code> in
		/// <code>repository</code>.
		/// </summary>
		/// <remarks>
		/// Compute the tracking status for the <code>branchName</code> in
		/// <code>repository</code>.
		/// </remarks>
		/// <param name="repository">the git repository to compute the status from</param>
		/// <param name="branchName">the local branch</param>
		/// <returns>the tracking status, or null if it is not known</returns>
		/// <exception cref="System.IO.IOException">System.IO.IOException</exception>
		public static NGit.BranchTrackingStatus Of(Repository repository, string branchName
			)
		{
			BranchConfig branchConfig = new BranchConfig(repository.GetConfig(), branchName);
			string trackingBranch = branchConfig.GetTrackingBranch();
			if (trackingBranch == null)
			{
				return null;
			}
			Ref tracking = repository.GetRef(trackingBranch);
			if (tracking == null)
			{
				return null;
			}
			Ref local = repository.GetRef(branchName);
			if (local == null)
			{
				return null;
			}
			RevWalk walk = new RevWalk(repository);
			RevCommit localCommit = walk.ParseCommit(local.GetObjectId());
			RevCommit trackingCommit = walk.ParseCommit(tracking.GetObjectId());
			walk.SetRevFilter(RevFilter.MERGE_BASE);
			walk.MarkStart(localCommit);
			walk.MarkStart(trackingCommit);
			RevCommit mergeBase = walk.Next();
			walk.Reset();
			walk.SetRevFilter(RevFilter.ALL);
			int aheadCount = RevWalkUtils.Count(walk, localCommit, mergeBase);
			int behindCount = RevWalkUtils.Count(walk, trackingCommit, mergeBase);
			return new NGit.BranchTrackingStatus(trackingBranch, aheadCount, behindCount);
		}
Example #10
0
		/// <summary>Creates new PersonIdent from config info in repository, with current time.
		/// 	</summary>
		/// <remarks>
		/// Creates new PersonIdent from config info in repository, with current time.
		/// This new PersonIdent gets the info from the default committer as available
		/// from the configuration.
		/// </remarks>
		/// <param name="repo"></param>
		public PersonIdent(Repository repo)
		{
			UserConfig config = repo.GetConfig().Get(UserConfig.KEY);
			name = config.GetCommitterName();
			emailAddress = config.GetCommitterEmail();
			when = SystemReader.GetInstance().GetCurrentTime();
			tzOffset = SystemReader.GetInstance().GetTimezone(when);
		}
        /// <summary>Create a new rename detector for the given repository</summary>
        /// <param name="repo">the repository to use for rename detection</param>
        public RenameDetector(Repository repo)
        {
            this.repo = repo;
            DiffConfig cfg = repo.GetConfig().Get(DiffConfig.KEY);

            renameLimit = cfg.GetRenameLimit();
            Reset();
        }
Example #12
0
 private bool IsEnabledFor(Repository db)
 {
     if (IsOverridable())
     {
         return(db.GetConfig().Get(configKey).enabled);
     }
     return(IsEnabled());
 }
Example #13
0
        private IGitTfsRemote FindOrInitTfsRemoteOfChangeset(int parentChangesetId, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch)
        {
            omittedParentBranch = null;
            IGitTfsRemote tfsRemote;
            IChangeset    parentChangeset = Tfs.GetChangeset(parentChangesetId);
            //I think you want something that uses GetPathInGitRepo and ShouldSkip. See TfsChangeset.Apply.
            //Don't know if there is a way to extract remote tfs repository path from changeset datas! Should be better!!!
            var remote = Repository.ReadAllTfsRemotes().FirstOrDefault(r => parentChangeset.Changes.Any(c => r.GetPathInGitRepo(c.Item.ServerItem) != null));

            if (remote != null)
            {
                tfsRemote = remote;
            }
            else
            {
                // If the changeset has created multiple folders, the expected branch folder will not always be the first
                // so we scan all the changes of type folder to try to detect the first one which is a branch.
                // In most cases it will change nothing: the first folder is the good one
                IBranchObject tfsBranch   = null;
                string        tfsPath     = null;
                var           allBranches = Tfs.GetBranches(true);
                foreach (var change in parentChangeset.Changes)
                {
                    tfsPath = change.Item.ServerItem;
                    tfsPath = tfsPath.EndsWith("/") ? tfsPath : tfsPath + "/";

                    tfsBranch = allBranches.SingleOrDefault(b => tfsPath.StartsWith(b.Path.EndsWith("/") ? b.Path : b.Path + "/"));
                    if (tfsBranch != null)
                    {
                        // we found a branch, we stop here
                        break;
                    }
                }

                if (mergeChangeset && tfsBranch != null &&
                    string.Equals(Repository.GetConfig(GitTfsConstants.IgnoreNotInitBranches), true.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    Trace.TraceInformation("warning: skip not initialized branch for path " + tfsBranch.Path);
                    tfsRemote           = null;
                    omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
                }
                else if (tfsBranch == null)
                {
                    Trace.TraceInformation("error: branch not found. Verify that all the folders have been converted to branches (or something else :().\n\tpath {0}", tfsPath);
                    tfsRemote           = null;
                    omittedParentBranch = ";C" + parentChangesetId;
                }
                else
                {
                    tfsRemote = InitTfsRemoteOfChangeset(tfsBranch, parentChangeset.ChangesetId, renameResult);
                    if (tfsRemote == null)
                    {
                        omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
                    }
                }
            }
            return(tfsRemote);
        }
Example #14
0
        /// <summary>Creates new PersonIdent from config info in repository, with current time.
        ///     </summary>
        /// <remarks>
        /// Creates new PersonIdent from config info in repository, with current time.
        /// This new PersonIdent gets the info from the default committer as available
        /// from the configuration.
        /// </remarks>
        /// <param name="repo"></param>
        public PersonIdent(Repository repo)
        {
            UserConfig config = repo.GetConfig().Get(UserConfig.KEY);

            name         = config.GetCommitterName();
            emailAddress = config.GetCommitterEmail();
            when         = SystemReader.GetInstance().GetCurrentTime();
            tzOffset     = SystemReader.GetInstance().GetTimezone(when);
        }
Example #15
0
        /// <exception cref="System.IO.IOException"></exception>
        private void AddMergeConfig(Repository clonedRepo, Ref head)
        {
            string branchName = Repository.ShortenRefName(head.GetName());

            clonedRepo.GetConfig().SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName
                                             , ConfigConstants.CONFIG_KEY_REMOTE, remote);
            clonedRepo.GetConfig().SetString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName
                                             , ConfigConstants.CONFIG_KEY_MERGE, head.GetName());
            string autosetupRebase = clonedRepo.GetConfig().GetString(ConfigConstants.CONFIG_BRANCH_SECTION
                                                                      , null, ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);

            if (ConfigConstants.CONFIG_KEY_ALWAYS.Equals(autosetupRebase) || ConfigConstants.
                CONFIG_KEY_REMOTE.Equals(autosetupRebase))
            {
                clonedRepo.GetConfig().SetBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName
                                                  , ConfigConstants.CONFIG_KEY_REBASE, true);
            }
            clonedRepo.GetConfig().Save();
        }
Example #16
0
        public virtual void RepositoryWithSubmodule()
        {
            WriteTrashFile("file.txt", "content");
            Git git = Git.Wrap(db);

            git.Add().AddFilepattern("file.txt").Call();
            git.Commit().SetMessage("create file").Call();
            ObjectId       id     = ObjectId.FromString("abcd1234abcd1234abcd1234abcd1234abcd1234");
            string         path   = "sub";
            DirCache       cache  = db.LockDirCache();
            DirCacheEditor editor = cache.Editor();

            editor.Add(new _PathEdit_96(id, path));
            editor.Commit();
            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);
            string url = "git://server/repo.git";

            modulesConfig.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants
                                    .CONFIG_KEY_URL, url);
            modulesConfig.Save();
            Repository subRepo = Git.CloneRepository().SetURI(db.Directory.ToURI().ToString()
                                                              ).SetDirectory(new FilePath(db.WorkTree, path)).Call().GetRepository();

            AddRepoToClose(subRepo);
            NUnit.Framework.Assert.IsNotNull(subRepo);
            SubmoduleWalk generator = SubmoduleWalk.ForIndex(db);

            NUnit.Framework.Assert.IsTrue(generator.Next());
            NUnit.Framework.Assert.IsNull(generator.GetConfigUrl());
            NUnit.Framework.Assert.AreEqual(url, generator.GetModulesUrl());
            SubmoduleSyncCommand         command = new SubmoduleSyncCommand(db);
            IDictionary <string, string> synced  = command.Call();

            NUnit.Framework.Assert.IsNotNull(synced);
            NUnit.Framework.Assert.AreEqual(1, synced.Count);
            KeyValuePair <string, string> module = synced.EntrySet().Iterator().Next();

            NUnit.Framework.Assert.AreEqual(path, module.Key);
            NUnit.Framework.Assert.AreEqual(url, module.Value);
            generator = SubmoduleWalk.ForIndex(db);
            NUnit.Framework.Assert.IsTrue(generator.Next());
            NUnit.Framework.Assert.AreEqual(url, generator.GetConfigUrl());
            Repository subModRepository = generator.GetRepository();

            AddRepoToClose(subModRepository);
            StoredConfig submoduleConfig = subModRepository.GetConfig();

            NUnit.Framework.Assert.AreEqual(url, submoduleConfig.GetString(ConfigConstants.CONFIG_REMOTE_SECTION
                                                                           , Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL));
        }
Example #17
0
 /// <param name="local"></param>
 /// <param name="inCore"></param>
 protected internal ResolveMerger(Repository local, bool inCore) : base(local)
 {
     DiffAlgorithm.SupportedAlgorithm diffAlg = local.GetConfig().GetEnum(ConfigConstants
                                                                          .CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm
                                                                          .HISTOGRAM);
     mergeAlgorithm = new MergeAlgorithm(DiffAlgorithm.GetAlgorithm(diffAlg));
     commitNames    = new string[] { "BASE", "OURS", "THEIRS" };
     this.inCore    = inCore;
     if (inCore)
     {
         dircache = DirCache.NewInCore();
     }
 }
Example #18
0
        private bool IsGitIgnoreSupportEnabled()
        {
            var isGitIgnoreSupportDisabled = true;

            var  value = Repository.GetConfig <string>(GitTfsConstants.DisableGitignoreSupport, null);
            bool disableGitignoreSupport;

            if (value != null && bool.TryParse(value, out disableGitignoreSupport))
            {
                isGitIgnoreSupportDisabled = disableGitignoreSupport;
            }

            return(!isGitIgnoreSupportDisabled);
        }
Example #19
0
        /// <summary>
        /// Updates the file in the working tree with content and mode from an entry
        /// in the index.
        /// </summary>
        /// <remarks>
        /// Updates the file in the working tree with content and mode from an entry
        /// in the index. The new content is first written to a new temporary file in
        /// the same directory as the real file. Then that new file is renamed to the
        /// final filename.
        /// TODO: this method works directly on File IO, we may need another
        /// abstraction (like WorkingTreeIterator). This way we could tell e.g.
        /// Eclipse that Files in the workspace got changed
        /// </remarks>
        /// <param name="repo"></param>
        /// <param name="f">
        /// the file to be modified. The parent directory for this file
        /// has to exist already
        /// </param>
        /// <param name="entry">the entry containing new mode and content</param>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public static void CheckoutEntry(Repository repo, FilePath f, DirCacheEntry entry
                                         )
        {
            ObjectLoader     ol        = repo.Open(entry.GetObjectId());
            FilePath         parentDir = f.GetParentFile();
            FilePath         tmpFile   = FilePath.CreateTempFile("._" + f.GetName(), null, parentDir);
            FileOutputStream channel   = new FileOutputStream(tmpFile);

            try
            {
                ol.CopyTo(channel);
            }
            finally
            {
                channel.Close();
            }
            FS fs = repo.FileSystem;
            WorkingTreeOptions opt = repo.GetConfig().Get(WorkingTreeOptions.KEY);

            if (opt.IsFileMode() && fs.SupportsExecute())
            {
                if (FileMode.EXECUTABLE_FILE.Equals(entry.RawMode))
                {
                    if (!fs.CanExecute(tmpFile))
                    {
                        fs.SetExecute(tmpFile, true);
                    }
                }
                else
                {
                    if (fs.CanExecute(tmpFile))
                    {
                        fs.SetExecute(tmpFile, false);
                    }
                }
            }
            if (!tmpFile.RenameTo(f))
            {
                // tried to rename which failed. Let' delete the target file and try
                // again
                FileUtils.Delete(f);
                if (!tmpFile.RenameTo(f))
                {
                    throw new IOException(MessageFormat.Format(JGitText.Get().couldNotWriteFile, tmpFile
                                                               .GetPath(), f.GetPath()));
                }
            }
            entry.LastModified = f.LastModified();
            entry.SetLength((int)ol.GetSize());
        }
        private bool Config_filemode()
        {
            // temporary til we can actually set parameters. We need to be able
            // to change this for testing.
            if (filemode != null)
            {
                return(filemode);
            }
            Config config = db.GetConfig();

            filemode = Sharpen.Extensions.ValueOf(config.GetBoolean("core", null, "filemode",
                                                                    true));
            return(filemode);
        }
Example #21
0
        /// <summary>Set the repository the formatter can load object contents from.</summary>
        /// <remarks>
        /// Set the repository the formatter can load object contents from.
        /// Once a repository has been set, the formatter must be released to ensure
        /// the internal ObjectReader is able to release its resources.
        /// </remarks>
        /// <param name="repository">source repository holding referenced objects.</param>
        public virtual void SetRepository(Repository repository)
        {
            if (reader != null)
            {
                reader.Release();
            }
            db     = repository;
            reader = db.NewObjectReader();
            ContentSource cs = ContentSource.Create(reader);

            source = new ContentSource.Pair(cs, cs);
            DiffConfig dc = db.GetConfig().Get(DiffConfig.KEY);

            if (dc.IsNoPrefix())
            {
                SetOldPrefix(string.Empty);
                SetNewPrefix(string.Empty);
            }
            SetDetectRenames(dc.IsRenameDetectionEnabled());
            diffAlgorithm = DiffAlgorithm.GetAlgorithm(db.GetConfig().GetEnum(ConfigConstants
                                                                              .CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm
                                                                              .HISTOGRAM));
        }
Example #22
0
        public virtual void AddSubmoduleWithRelativeUri()
        {
            Git git = new Git(db);

            WriteTrashFile("file.txt", "content");
            git.Add().AddFilepattern("file.txt").Call();
            RevCommit           commit  = git.Commit().SetMessage("create file").Call();
            SubmoduleAddCommand command = new SubmoduleAddCommand(db);
            string path = "sub";
            string uri  = "./.git";

            command.SetPath(path);
            command.SetURI(uri);
            Repository repo = command.Call();

            NUnit.Framework.Assert.IsNotNull(repo);
            AddRepoToClose(repo);
            SubmoduleWalk generator = SubmoduleWalk.ForIndex(db);

            NUnit.Framework.Assert.IsTrue(generator.Next());
            NUnit.Framework.Assert.AreEqual(path, generator.GetPath());
            NUnit.Framework.Assert.AreEqual(commit, generator.GetObjectId());
            NUnit.Framework.Assert.AreEqual(uri, generator.GetModulesUrl());
            NUnit.Framework.Assert.AreEqual(path, generator.GetModulesPath());
            string fullUri = db.Directory.GetAbsolutePath();

            if (FilePath.separatorChar == '\\')
            {
                fullUri = fullUri.Replace('\\', '/');
            }
            NUnit.Framework.Assert.AreEqual(fullUri, generator.GetConfigUrl());
            Repository subModRepo = generator.GetRepository();

            AddRepoToClose(subModRepo);
            NUnit.Framework.Assert.IsNotNull(subModRepo);
            NUnit.Framework.Assert.AreEqual(fullUri, subModRepo.GetConfig().GetString(ConfigConstants
                                                                                      .CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL
                                                                                      ));
            NUnit.Framework.Assert.AreEqual(commit, repo.Resolve(Constants.HEAD));
            Status status = Git.Wrap(db).Status().Call();

            NUnit.Framework.Assert.IsTrue(status.GetAdded().Contains(Constants.DOT_GIT_MODULES
                                                                     ));
            NUnit.Framework.Assert.IsTrue(status.GetAdded().Contains(path));
        }
Example #23
0
        private IGitTfsRemote FindOrInitTfsRemoteOfChangeset(int parentChangesetId, bool mergeChangeset, out string omittedParentBranch)
        {
            omittedParentBranch = null;
            IGitTfsRemote tfsRemote;
            IChangeset    parentChangeset = Tfs.GetChangeset(parentChangesetId);
            //I think you want something that uses GetPathInGitRepo and ShouldSkip. See TfsChangeset.Apply.
            //Don't know if there is a way to extract remote tfs repository path from changeset datas! Should be better!!!
            var remote = Repository.ReadAllTfsRemotes().FirstOrDefault(r => parentChangeset.Changes.Any(c => r.GetPathInGitRepo(c.Item.ServerItem) != null));

            if (remote != null)
            {
                tfsRemote = remote;
            }
            else
            {
                var tfsPath = parentChangeset.Changes.First().Item.ServerItem;
                tfsPath = tfsPath.EndsWith("/") ? tfsPath : tfsPath + "/";
                var tfsBranch = Tfs.GetBranches(true).SingleOrDefault(b => tfsPath.StartsWith(b.Path.EndsWith("/") ? b.Path : b.Path + "/"));

                if (mergeChangeset && tfsBranch != null && Repository.GetConfig(GitTfsConstants.IgnoreNotInitBranches) == true.ToString())
                {
                    stdout.WriteLine("warning: skip not initialized branch for path " + tfsBranch.Path);
                    tfsRemote           = null;
                    omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
                }
                else if (tfsBranch == null)
                {
                    stdout.WriteLine("error: branch  not found. Verify that all the folders have been converted to branches (or something else :().\n\tpath {0}", tfsPath);
                    tfsRemote           = null;
                    omittedParentBranch = ";C" + parentChangesetId;
                }
                else
                {
                    tfsRemote = InitTfsRemoteOfChangeset(tfsBranch, parentChangeset.ChangesetId);
                    if (tfsRemote == null)
                    {
                        omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
                    }
                }
            }
            return(tfsRemote);
        }
Example #24
0
        private bool ProcessMergeChangeset(ITfsChangeset changeset, bool stopOnFailMergeCommit, ref string parentCommit)
        {
            if (!Tfs.CanGetBranchInformation)
            {
                stdout.WriteLine("info: this changeset " + changeset.Summary.ChangesetId +
                                 " is a merge changeset. But was not treated as is because this version of TFS can't manage branches...");
            }
            else if (Repository.GetConfig(GitTfsConstants.IgnoreBranches) != true.ToString())
            {
                var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this);
                var shaParent         = Repository.FindCommitHashByChangesetId(parentChangesetId);
                if (shaParent == null)
                {
                    string omittedParentBranch;
                    shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit, out omittedParentBranch);
                    changeset.OmittedParentBranch = omittedParentBranch;
                }
                if (shaParent != null)
                {
                    parentCommit = shaParent;
                }
                else
                {
                    if (stopOnFailMergeCommit)
                    {
                        return(false);
                    }

                    stdout.WriteLine("warning: this changeset " + changeset.Summary.ChangesetId +
                                     " is a merge changeset. But git-tfs failed to find and fetch the parent changeset "
                                     + parentChangesetId + ". Parent changeset will be ignored...");
                }
            }
            else
            {
                stdout.WriteLine("info: this changeset " + changeset.Summary.ChangesetId +
                                 " is a merge changeset. But was not treated as is because of your git setting...");
                changeset.OmittedParentBranch = ";C" + changeset.Summary.ChangesetId;
            }
            return(true);
        }
        /// <summary>
        /// Compute the tracking status for the <code>branchName</code> in
        /// <code>repository</code>.
        /// </summary>
        /// <remarks>
        /// Compute the tracking status for the <code>branchName</code> in
        /// <code>repository</code>.
        /// </remarks>
        /// <param name="repository">the git repository to compute the status from</param>
        /// <param name="branchName">the local branch</param>
        /// <returns>the tracking status, or null if it is not known</returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public static NGit.BranchTrackingStatus Of(Repository repository, string branchName
                                                   )
        {
            BranchConfig branchConfig         = new BranchConfig(repository.GetConfig(), branchName);
            string       remoteTrackingBranch = branchConfig.GetRemoteTrackingBranch();

            if (remoteTrackingBranch == null)
            {
                return(null);
            }
            Ref tracking = repository.GetRef(remoteTrackingBranch);

            if (tracking == null)
            {
                return(null);
            }
            Ref local = repository.GetRef(branchName);

            if (local == null)
            {
                return(null);
            }
            RevWalk   walk           = new RevWalk(repository);
            RevCommit localCommit    = walk.ParseCommit(local.GetObjectId());
            RevCommit trackingCommit = walk.ParseCommit(tracking.GetObjectId());

            walk.SetRevFilter(RevFilter.MERGE_BASE);
            walk.MarkStart(localCommit);
            walk.MarkStart(trackingCommit);
            RevCommit mergeBase = walk.Next();

            walk.Reset();
            walk.SetRevFilter(RevFilter.ALL);
            int aheadCount  = RevWalkUtils.Count(walk, localCommit, mergeBase);
            int behindCount = RevWalkUtils.Count(walk, trackingCommit, mergeBase);

            return(new NGit.BranchTrackingStatus(remoteTrackingBranch, aheadCount, behindCount
                                                 ));
        }
Example #26
0
        /// <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);
        }
Example #27
0
 /// <exception cref="System.NotSupportedException"></exception>
 protected internal TransportHttp(Repository local, URIish uri) : base(local, uri)
 {
     try
     {
         string uriString = uri.ToString();
         if (!uriString.EndsWith("/"))
         {
             //$NON-NLS-1$
             uriString += "/";
         }
         //$NON-NLS-1$
         baseUrl    = new Uri(uriString);
         objectsUrl = new Uri(baseUrl, "objects/");
     }
     catch (UriFormatException e)
     {
         //$NON-NLS-1$
         throw new NotSupportedException(MessageFormat.Format(JGitText.Get().invalidURL, uri
                                                              ), e);
     }
     http          = local.GetConfig().Get(HTTP_KEY);
     proxySelector = ProxySelector.GetDefault();
 }
Example #28
0
        public bool IsIgnoringBranches()
        {
            var  value = Repository.GetConfig <string>(GitTfsConstants.IgnoreBranches, null);
            bool isIgnoringBranches;

            if (value != null && bool.TryParse(value, out isIgnoringBranches))
            {
                return(isIgnoringBranches);
            }

            stdout.WriteLine("warning: no value found for branch management setting '" + GitTfsConstants.IgnoreBranches +
                             "'...");
            var isIgnoringBranchesDetected = Repository.ReadAllTfsRemotes().Count() < 2;

            stdout.WriteLine("=> Branch support " + (isIgnoringBranchesDetected ? "disabled!" : "enabled!"));
            if (isIgnoringBranchesDetected)
            {
                stdout.WriteLine("   if you want to enable branch support, use the command:" + Environment.NewLine
                                 + "    git config --local " + GitTfsConstants.IgnoreBranches + " false");
            }
            globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, isIgnoringBranchesDetected.ToString());
            return(isIgnoringBranchesDetected);
        }
Example #29
0
            /// <exception cref="System.IO.IOException"></exception>
            internal override IgnoreNode Load()
            {
                IgnoreNode r;

                if (entry != null)
                {
                    r = base.Load();
                    if (r == null)
                    {
                        r = new IgnoreNode();
                    }
                }
                else
                {
                    r = new IgnoreNode();
                }
                FS     fs   = repository.FileSystem;
                string path = repository.GetConfig().Get(CoreConfig.KEY).GetExcludesFile();

                if (path != null)
                {
                    FilePath excludesfile;
                    if (path.StartsWith("~/"))
                    {
                        excludesfile = fs.Resolve(fs.UserHome(), Sharpen.Runtime.Substring(path, 2));
                    }
                    else
                    {
                        excludesfile = fs.Resolve(null, path);
                    }
                    LoadRulesFromFile(r, excludesfile);
                }
                FilePath exclude = fs.Resolve(repository.Directory, "info/exclude");

                LoadRulesFromFile(r, exclude);
                return(r.GetRules().IsEmpty() ? null : r);
            }
Example #30
0
 /// <summary>Create a new transport instance.</summary>
 /// <remarks>Create a new transport instance.</remarks>
 /// <param name="local">
 /// the repository this instance will fetch into, or push out of.
 /// This must be the repository passed to
 /// <see cref="Open(NGit.Repository, URIish)">Open(NGit.Repository, URIish)</see>
 /// .
 /// </param>
 /// <param name="uri">
 /// the URI used to access the remote repository. This must be the
 /// URI passed to
 /// <see cref="Open(NGit.Repository, URIish)">Open(NGit.Repository, URIish)</see>
 /// .
 /// </param>
 protected internal Transport(Repository local, URIish uri)
 {
     TransferConfig tc = local.GetConfig().Get(TransferConfig.KEY);
     this.local = local;
     this.uri = uri;
     this.checkFetchedObjects = tc.IsFsckObjects();
     this.credentialsProvider = CredentialsProvider.GetDefault();
 }
Example #31
0
 private bool IsLogAllRefUpdates()
 {
     return(parent.GetConfig().Get(CoreConfig.KEY).IsLogAllRefUpdates());
 }
Example #32
0
        /// <summary>
        /// Run the diff operation. Until this is called, all lists will be empty
        /// </summary>
        /// <returns>true if anything is different between index, tree, and workdir</returns>
        private void UpdateDirectory(IEnumerable <string> paths, bool recursive)
        {
            RevWalk  rw     = new RevWalk(Repository);
            ObjectId id     = Repository.Resolve(Constants.HEAD);
            var      commit = id != null?rw.ParseCommit(id) : null;

            TreeWalk treeWalk = new TreeWalk(Repository);

            treeWalk.Reset();
            treeWalk.Recursive = false;

            if (commit != null)
            {
                treeWalk.AddTree(commit.Tree);
            }
            else
            {
                treeWalk.AddTree(new EmptyTreeIterator());
            }

            DirCache dc = Repository.ReadDirCache();

            treeWalk.AddTree(new DirCacheIterator(dc));

            FileTreeIterator workTree = new FileTreeIterator(Repository.WorkTree, Repository.FileSystem, WorkingTreeOptions.KEY.Parse(Repository.GetConfig()));

            treeWalk.AddTree(workTree);

            List <TreeFilter> filters = new List <TreeFilter> ();

            filters.Add(new SkipWorkTreeFilter(1));

            var pathFilters = paths.Where(p => p != ".").Select(p => PathFilter.Create(p)).ToArray();

            if (pathFilters.Length > 1)
            {
                filters.Add(OrTreeFilter.Create(pathFilters));                   // Use an OR to join all path filters
            }
            else if (pathFilters.Length == 1)
            {
                filters.Add(pathFilters[0]);
            }

            if (filters.Count > 1)
            {
                treeWalk.Filter = AndTreeFilter.Create(filters);
            }
            else
            {
                treeWalk.Filter = filters[0];
            }

            while (treeWalk.Next())
            {
                AbstractTreeIterator treeIterator        = treeWalk.GetTree <AbstractTreeIterator>(0);
                DirCacheIterator     dirCacheIterator    = treeWalk.GetTree <DirCacheIterator>(1);
                WorkingTreeIterator  workingTreeIterator = treeWalk.GetTree <WorkingTreeIterator>(2);
                NGit.FileMode        fileModeTree        = treeWalk.GetFileMode(0);

                if (treeWalk.IsSubtree)
                {
                    treeWalk.EnterSubtree();
                    continue;
                }

                int stage = dirCacheIterator != null?dirCacheIterator.GetDirCacheEntry().Stage : 0;

                if (stage > 1)
                {
                    continue;
                }
                else if (stage == 1)
                {
                    MergeConflict.Add(dirCacheIterator.EntryPathString);
                    changesExist = true;
                    continue;
                }

                if (treeIterator != null)
                {
                    if (dirCacheIterator != null)
                    {
                        if (!treeIterator.EntryObjectId.Equals(dirCacheIterator.EntryObjectId))
                        {
                            // in repo, in index, content diff => changed
                            Modified.Add(dirCacheIterator.EntryPathString);
                            changesExist = true;
                        }
                    }
                    else
                    {
                        // in repo, not in index => removed
                        if (!fileModeTree.Equals(NGit.FileMode.TYPE_TREE))
                        {
                            Removed.Add(treeIterator.EntryPathString);
                            changesExist = true;
                        }
                    }
                }
                else
                {
                    if (dirCacheIterator != null)
                    {
                        // not in repo, in index => added
                        Added.Add(dirCacheIterator.EntryPathString);
                        changesExist = true;
                    }
                    else
                    {
                        // not in repo, not in index => untracked
                        if (workingTreeIterator != null && !workingTreeIterator.IsEntryIgnored())
                        {
                            Untracked.Add(workingTreeIterator.EntryPathString);
                            changesExist = true;
                        }
                    }
                }
                if (dirCacheIterator != null)
                {
                    if (workingTreeIterator == null)
                    {
                        // in index, not in workdir => missing
                        Missing.Add(dirCacheIterator.EntryPathString);
                        changesExist = true;
                    }
                    else
                    {
                        // Workaround to file time resolution issues
                        long itime = dirCacheIterator.GetDirCacheEntry().LastModified;
                        long ftime = workingTreeIterator.GetEntryLastModified();
                        if (itime / 1000 != ftime / 1000)
                        {
                            if (!dirCacheIterator.IdEqual(workingTreeIterator))
                            {
                                // in index, in workdir, content differs => modified
                                Modified.Add(dirCacheIterator.EntryPathString);
                                changesExist = true;
                            }
                        }
                    }
                }
            }
        }
Example #33
0
		/// <summary>Creates new PersonIdent from config info in repository, with current time.
		/// 	</summary>
		/// <remarks>
		/// Creates new PersonIdent from config info in repository, with current time.
		/// This new PersonIdent gets the info from the default committer as available
		/// from the configuration.
		/// </remarks>
		/// <param name="repo"></param>
		public PersonIdent(Repository repo) : this(repo.GetConfig().Get(UserConfig.KEY))
		{
		}
Example #34
0
        /// <summary>
        /// Updates the file in the working tree with content and mode from an entry
        /// in the index.
        /// </summary>
        /// <remarks>
        /// Updates the file in the working tree with content and mode from an entry
        /// in the index. The new content is first written to a new temporary file in
        /// the same directory as the real file. Then that new file is renamed to the
        /// final filename.
        /// <p>
        /// TODO: this method works directly on File IO, we may need another
        /// abstraction (like WorkingTreeIterator). This way we could tell e.g.
        /// Eclipse that Files in the workspace got changed
        /// </p>
        /// </remarks>
        /// <param name="repo"></param>
        /// <param name="f">
        /// the file to be modified. The parent directory for this file
        /// has to exist already
        /// </param>
        /// <param name="entry">the entry containing new mode and content</param>
        /// <param name="or">object reader to use for checkout</param>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public static void CheckoutEntry(Repository repo, FilePath f, DirCacheEntry entry
			, ObjectReader or)
        {
            ObjectLoader ol = or.Open(entry.GetObjectId());
            FilePath parentDir = f.GetParentFile();
            FilePath tmpFile = FilePath.CreateTempFile("._" + f.GetName(), null, parentDir);
            WorkingTreeOptions opt = repo.GetConfig().Get(WorkingTreeOptions.KEY);
            FileOutputStream rawChannel = new FileOutputStream(tmpFile);
            OutputStream channel;
            if (opt.GetAutoCRLF() == CoreConfig.AutoCRLF.TRUE)
            {
                channel = new AutoCRLFOutputStream(rawChannel);
            }
            else
            {
                channel = rawChannel;
            }
            try
            {
                ol.CopyTo(channel);
            }
            finally
            {
                channel.Close();
            }
            FS fs = repo.FileSystem;
            if (opt.IsFileMode() && fs.SupportsExecute())
            {
                if (FileMode.EXECUTABLE_FILE.Equals(entry.RawMode))
                {
                    if (!fs.CanExecute(tmpFile))
                    {
                        fs.SetExecute(tmpFile, true);
                    }
                }
                else
                {
                    if (fs.CanExecute(tmpFile))
                    {
                        fs.SetExecute(tmpFile, false);
                    }
                }
            }
            if (!tmpFile.RenameTo(f))
            {
                // tried to rename which failed. Let' delete the target file and try
                // again
                FileUtils.Delete(f);
                if (!tmpFile.RenameTo(f))
                {
                    throw new IOException(MessageFormat.Format(JGitText.Get().couldNotWriteFile, tmpFile
                        .GetPath(), f.GetPath()));
                }
            }
            entry.LastModified = f.LastModified();
            if (opt.GetAutoCRLF() != CoreConfig.AutoCRLF.FALSE)
            {
                entry.SetLength(f.Length());
            }
            else
            {
                // AutoCRLF wants on-disk-size
                entry.SetLength((int)ol.GetSize());
            }
        }
Example #35
0
 /// <summary>Create a configuration honoring the repository's settings.</summary>
 /// <remarks>Create a configuration honoring the repository's settings.</remarks>
 /// <param name="db">
 /// the repository to read settings from. The repository is not
 /// retained by the new configuration, instead its settings are
 /// copied during the constructor.
 /// </param>
 public PackConfig(Repository db)
 {
     // Fields are initialized to defaults.
     FromConfig(db.GetConfig());
 }
Example #36
0
		/// <summary>Create an index pack instance to load a new pack into a repository.</summary>
		/// <remarks>
		/// Create an index pack instance to load a new pack into a repository.
		/// <p>
		/// The received pack data and generated index will be saved to temporary
		/// files within the repository's <code>objects</code> directory. To use the
		/// data contained within them call
		/// <see cref="RenameAndOpenPack()">RenameAndOpenPack()</see>
		/// once the
		/// indexing is complete.
		/// </remarks>
		/// <param name="db">the repository that will receive the new pack.</param>
		/// <param name="is">
		/// stream to read the pack data from. If the stream is buffered
		/// use
		/// <see cref="BUFFER_SIZE">BUFFER_SIZE</see>
		/// as the buffer size for the stream.
		/// </param>
		/// <returns>a new index pack instance.</returns>
		/// <exception cref="System.IO.IOException">a temporary file could not be created.</exception>
		public static NGit.Transport.IndexPack Create(Repository db, InputStream @is)
		{
			string suffix = ".pack";
			FilePath objdir = db.ObjectsDirectory;
			FilePath tmp = FilePath.CreateTempFile("incoming_", suffix, objdir);
			string n = tmp.GetName();
			FilePath @base;
			@base = new FilePath(objdir, Sharpen.Runtime.Substring(n, 0, n.Length - suffix.Length
				));
			NGit.Transport.IndexPack ip = new NGit.Transport.IndexPack(db, @is, @base);
			ip.SetIndexVersion(db.GetConfig().Get(CoreConfig.KEY).GetPackIndexVersion());
			return ip;
		}
Example #37
0
		/// <summary>Create a new iterator to traverse the work tree and its children.</summary>
		/// <remarks>Create a new iterator to traverse the work tree and its children.</remarks>
		/// <param name="repo">the repository whose working tree will be scanned.</param>
		public FileTreeIterator(Repository repo) : this(repo.WorkTree, repo.FileSystem, repo
			.GetConfig().Get(WorkingTreeOptions.KEY))
		{
			InitRootIterator(repo);
		}
Example #38
0
		/// <summary>Create a configuration honoring the repository's settings.</summary>
		/// <remarks>Create a configuration honoring the repository's settings.</remarks>
		/// <param name="db">
		/// the repository to read settings from. The repository is not
		/// retained by the new configuration, instead its settings are
		/// copied during the constructor.
		/// </param>
		public PackConfig(Repository db)
		{
			// Fields are initialized to defaults.
			FromConfig(db.GetConfig());
		}
Example #39
0
 /// <summary>Create a new iterator to traverse the work tree and its children.</summary>
 /// <remarks>Create a new iterator to traverse the work tree and its children.</remarks>
 /// <param name="repo">the repository whose working tree will be scanned.</param>
 public FileTreeIterator(Repository repo) : this(repo.WorkTree, repo.FileSystem, repo
                                                 .GetConfig().Get(WorkingTreeOptions.KEY))
 {
     InitRootIterator(repo);
 }
		/// <param name="local"></param>
		/// <param name="inCore"></param>
		protected internal ResolveMerger(Repository local, bool inCore) : base(local)
		{
			DiffAlgorithm.SupportedAlgorithm diffAlg = local.GetConfig().GetEnum(ConfigConstants
				.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm
				.HISTOGRAM);
			mergeAlgorithm = new MergeAlgorithm(DiffAlgorithm.GetAlgorithm(diffAlg));
			commitNames = new string[] { "BASE", "OURS", "THEIRS" };
			oi = GetObjectInserter();
			this.inCore = inCore;
			if (inCore)
			{
				dircache = DirCache.NewInCore();
			}
		}
Example #41
0
        /// <summary>Open a new transport instance to connect two repositories.</summary>
        /// <remarks>Open a new transport instance to connect two repositories.</remarks>
        /// <param name="local">existing local repository.</param>
        /// <param name="remote">
        /// location of the remote repository - may be URI or remote
        /// configuration name.
        /// </param>
        /// <param name="op">
        /// planned use of the returned Transport; the URI may differ
        /// based on the type of connection desired.
        /// </param>
        /// <returns>
        /// the new transport instance. Never null. In case of multiple URIs
        /// in remote configuration, only the first is chosen.
        /// </returns>
        /// <exception cref="Sharpen.URISyntaxException">
        /// the location is not a remote defined in the configuration
        /// file and is not a well-formed URL.
        /// </exception>
        /// <exception cref="System.NotSupportedException">the protocol specified is not supported.
        /// 	</exception>
        /// <exception cref="NGit.Errors.TransportException">the transport cannot open this URI.
        /// 	</exception>
        public static NGit.Transport.Transport Open(Repository local, string remote, Transport.Operation
			 op)
        {
            RemoteConfig cfg = new RemoteConfig(local.GetConfig(), remote);
            if (DoesNotExist(cfg))
            {
                return Open(local, new URIish(remote), null);
            }
            return Open(local, cfg, op);
        }
Example #42
0
        /// <summary>Open new transport instances to connect two repositories.</summary>
        /// <remarks>Open new transport instances to connect two repositories.</remarks>
        /// <param name="local">existing local repository.</param>
        /// <param name="remote">
        /// location of the remote repository - may be URI or remote
        /// configuration name.
        /// </param>
        /// <param name="op">
        /// planned use of the returned Transport; the URI may differ
        /// based on the type of connection desired.
        /// </param>
        /// <returns>
        /// the list of new transport instances for every URI in remote
        /// configuration.
        /// </returns>
        /// <exception cref="Sharpen.URISyntaxException">
        /// the location is not a remote defined in the configuration
        /// file and is not a well-formed URL.
        /// </exception>
        /// <exception cref="System.NotSupportedException">the protocol specified is not supported.
        /// 	</exception>
        /// <exception cref="NGit.Errors.TransportException">the transport cannot open this URI.
        /// 	</exception>
        public static IList<NGit.Transport.Transport> OpenAll(Repository local, string remote
			, Transport.Operation op)
        {
            RemoteConfig cfg = new RemoteConfig(local.GetConfig(), remote);
            if (DoesNotExist(cfg))
            {
                AList<NGit.Transport.Transport> transports = new AList<NGit.Transport.Transport>(
                    1);
                transports.AddItem(Open(local, new URIish(remote), null));
                return transports;
            }
            return OpenAll(local, cfg, op);
        }
Example #43
0
		/// <summary>Resolve submodule repository URL.</summary>
		/// <remarks>
		/// Resolve submodule repository URL.
		/// <p>
		/// This handles relative URLs that are typically specified in the
		/// '.gitmodules' file by resolving them against the remote URL of the parent
		/// repository.
		/// <p>
		/// Relative URLs will be resolved against the parent repository's working
		/// directory if the parent repository has no configured remote URL.
		/// </remarks>
		/// <param name="parent">parent repository</param>
		/// <param name="url">absolute or relative URL of the submodule repository</param>
		/// <returns>resolved URL</returns>
		/// <exception cref="System.IO.IOException">System.IO.IOException</exception>
		public static string GetSubmoduleRemoteUrl(Repository parent, string url)
		{
			if (!url.StartsWith("./") && !url.StartsWith("../"))
			{
				return url;
			}
			string remoteName = null;
			// Look up remote URL associated wit HEAD ref
			Ref @ref = parent.GetRef(Constants.HEAD);
			if (@ref != null)
			{
				if (@ref.IsSymbolic())
				{
					@ref = @ref.GetLeaf();
				}
				remoteName = parent.GetConfig().GetString(ConfigConstants.CONFIG_BRANCH_SECTION, 
					Repository.ShortenRefName(@ref.GetName()), ConfigConstants.CONFIG_KEY_REMOTE);
			}
			// Fall back to 'origin' if current HEAD ref has no remote URL
			if (remoteName == null)
			{
				remoteName = Constants.DEFAULT_REMOTE_NAME;
			}
			string remoteUrl = parent.GetConfig().GetString(ConfigConstants.CONFIG_REMOTE_SECTION
				, remoteName, ConfigConstants.CONFIG_KEY_URL);
			// Fall back to parent repository's working directory if no remote URL
			if (remoteUrl == null)
			{
				remoteUrl = parent.WorkTree.GetAbsolutePath();
				// Normalize slashes to '/'
				if ('\\' == FilePath.separatorChar)
				{
					remoteUrl = remoteUrl.Replace('\\', '/');
				}
			}
			// Remove trailing '/'
			if (remoteUrl[remoteUrl.Length - 1] == '/')
			{
				remoteUrl = Sharpen.Runtime.Substring(remoteUrl, 0, remoteUrl.Length - 1);
			}
			char separator = '/';
			string submoduleUrl = url;
			while (submoduleUrl.Length > 0)
			{
				if (submoduleUrl.StartsWith("./"))
				{
					submoduleUrl = Sharpen.Runtime.Substring(submoduleUrl, 2);
				}
				else
				{
					if (submoduleUrl.StartsWith("../"))
					{
						int lastSeparator = remoteUrl.LastIndexOf('/');
						if (lastSeparator < 1)
						{
							lastSeparator = remoteUrl.LastIndexOf(':');
							separator = ':';
						}
						if (lastSeparator < 1)
						{
							throw new IOException(MessageFormat.Format(JGitText.Get().submoduleParentRemoteUrlInvalid
								, remoteUrl));
						}
						remoteUrl = Sharpen.Runtime.Substring(remoteUrl, 0, lastSeparator);
						submoduleUrl = Sharpen.Runtime.Substring(submoduleUrl, 3);
					}
					else
					{
						break;
					}
				}
			}
			return remoteUrl + separator + submoduleUrl;
		}