/// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
 public override IDictionary <string, SubmoduleStatus> Call()
 {
     CheckCallable();
     try
     {
         SubmoduleWalk generator = SubmoduleWalk.ForIndex(repo);
         if (!paths.IsEmpty())
         {
             generator.SetFilter(PathFilterGroup.CreateFromStrings(paths));
         }
         IDictionary <string, SubmoduleStatus> statuses = new Dictionary <string, SubmoduleStatus
                                                                          >();
         while (generator.Next())
         {
             SubmoduleStatus status = GetStatus(generator);
             statuses.Put(status.GetPath(), status);
         }
         return(statuses);
     }
     catch (IOException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
     catch (ConfigInvalidException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
 }
Exemple #2
0
 /// <summary>
 /// Executes the
 /// <code>Log</code>
 /// command with all the options and parameters
 /// collected by the setter methods (e.g.
 /// <see cref="Add(NGit.AnyObjectId)">Add(NGit.AnyObjectId)</see>
 /// ,
 /// <see cref="Not(NGit.AnyObjectId)">Not(NGit.AnyObjectId)</see>
 /// , ..) of this class. Each instance of this class
 /// should only be used for one invocation of the command. Don't call this
 /// method twice on an instance.
 /// </summary>
 /// <returns>an iteration over RevCommits</returns>
 /// <exception cref="NGit.Api.Errors.NoHeadException"></exception>
 /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception>
 public override Iterable <RevCommit> Call()
 {
     CheckCallable();
     if (pathFilters.Count > 0)
     {
         walk.SetTreeFilter(PathFilterGroup.Create(pathFilters));
     }
     if (!startSpecified)
     {
         try
         {
             ObjectId headId = repo.Resolve(Constants.HEAD);
             if (headId == null)
             {
                 throw new NoHeadException(JGitText.Get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified
                                           );
             }
             Add(headId);
         }
         catch (IOException e)
         {
             // all exceptions thrown by add() shouldn't occur and represent
             // severe low-level exception which are therefore wrapped
             throw new JGitInternalException(JGitText.Get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD
                                             , e);
         }
     }
     SetCallable(false);
     return(walk);
 }
        public GitFileStatus GetFileStatusNoCache(string fileName)
        {
            //Debug.WriteLine(string.Format("===+ GetFileStatusNoCache {0}", fileName));

            var fileNameRel = GetRelativeFileNameForGit(fileName);

            IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, new FileTreeIterator(repository));

            indexDiff.SetFilter(PathFilterGroup.CreateFromStrings(fileNameRel));
            indexDiff.Diff();

            if (indexDiff.GetModified().Count > 0)
            {
                return(GitFileStatus.Modified);
            }

            if (indexDiff.GetConflicting().Count > 0)
            {
                return(GitFileStatus.Conflict);
            }

            if (indexDiff.GetUntracked().Count > 0 || indexDiff.GetUntrackedFolders().Count > 0)
            {
                if (File.Exists(fileName))
                {
                    return(GitFileStatus.New);
                }

                return(GitFileStatus.NotControlled);
            }

            if (indexDiff.GetAdded().Count > 0)
            {
                return(GitFileStatus.Added);
            }

            if (!File.Exists(fileName))
            {
                if (indexDiff.GetMissing().Count > 0)
                {
                    return(GitFileStatus.Removed);
                }

                return(GitFileStatus.Deleted);
            }

            if (indexDiff.GetChanged().Count > 0)
            {
                return(GitFileStatus.Staged);
            }

            if (indexDiff.GetIgnoredNotInIndex().Count > 0)
            {
                return(GitFileStatus.Ignored);
            }

            return(GitFileStatus.Tracked);
        }
 /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
 public override ICollection <string> Call()
 {
     CheckCallable();
     try
     {
         SubmoduleWalk generator = SubmoduleWalk.ForIndex(repo);
         if (!paths.IsEmpty())
         {
             generator.SetFilter(PathFilterGroup.CreateFromStrings(paths));
         }
         StoredConfig   config      = repo.GetConfig();
         IList <string> initialized = new AList <string>();
         while (generator.Next())
         {
             // Ignore entry if URL is already present in config file
             if (generator.GetConfigUrl() != null)
             {
                 continue;
             }
             string path = generator.GetPath();
             // Copy 'url' and 'update' fields from .gitmodules to config
             // file
             string url    = generator.GetRemoteUrl();
             string update = generator.GetModulesUpdate();
             if (url != null)
             {
                 config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.
                                  CONFIG_KEY_URL, url);
             }
             if (update != null)
             {
                 config.SetString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.
                                  CONFIG_KEY_UPDATE, update);
             }
             if (url != null || update != null)
             {
                 initialized.AddItem(path);
             }
         }
         // Save repository config if any values were updated
         if (!initialized.IsEmpty())
         {
             config.Save();
         }
         return(initialized);
     }
     catch (IOException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
     catch (ConfigInvalidException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
 }
Exemple #5
0
        /**
         * Open a tree walk and filter to exactly one path.
         * <para />
         * The returned tree walk is already positioned on the requested path, so
         * the caller should not need to invoke {@link #next()} unless they are
         * looking for a possible directory/file name conflict.
         *
         * @param db
         *            repository to Read tree object data from.
         * @param path
         *            single path to advance the tree walk instance into.
         * @param trees
         *            one or more trees to walk through, all with the same root.
         * @return a new tree walk configured for exactly this one path; null if no
         *         path was found in any of the trees.
         * @throws IOException
         *             reading a pack file or loose object failed.
         * @throws CorruptObjectException
         *             an tree object could not be Read as its data stream did not
         *             appear to be a tree, or could not be inflated.
         * @throws IncorrectObjectTypeException
         *             an object we expected to be a tree was not a tree.
         * @throws MissingObjectException
         *             a tree object was not found.
         */

        public static TreeWalk ForPath(Repository db, string path, params AnyObjectId[] trees)
        {
            var r = new TreeWalk(db);

            r.Recursive = r.getFilter().shouldBeRecursive();

            r.setFilter(PathFilterGroup.createFromStrings(new HashSet <string> {
                path
            }));
            r.reset(trees);
            return(r.next() ? r : null);
        }
Exemple #6
0
        public void testPathFilterGroup_DoesNotSkipTail()
        {
            DirCache dc = DirCache.read(db);

            var mode = FileMode.RegularFile;

            string[] paths = { "a.", "a/b", "a/c", "a/d", "a0b" };
            var      ents  = new DirCacheEntry[paths.Length];

            for (int i = 0; i < paths.Length; i++)
            {
                ents[i] = new DirCacheEntry(paths[i]);
                ents[i].setFileMode(mode);
            }

            DirCacheBuilder builder = dc.builder();

            for (int i = 0; i < ents.Length; i++)
            {
                builder.add(ents[i]);
            }
            builder.finish();

            const int       expIdx = 2;
            DirCacheBuilder b      = dc.builder();
            var             tw     = new GitSharp.Core.TreeWalk.TreeWalk(db);

            tw.reset();
            tw.addTree(new DirCacheBuildIterator(b));
            tw.Recursive = true;
            tw.setFilter(PathFilterGroup.createFromStrings(new[] { paths[expIdx] }));

            Assert.IsTrue(tw.next(), "found " + paths[expIdx]);
            var c = tw.getTree <DirCacheIterator>(0, typeof(DirCacheIterator));

            Assert.IsNotNull(c);
            Assert.AreEqual(expIdx, c.Pointer);
            Assert.AreSame(ents[expIdx], c.getDirCacheEntry());
            Assert.AreEqual(paths[expIdx], tw.getPathString());
            Assert.AreEqual(mode.Bits, tw.getRawMode(0));
            Assert.AreSame(mode, tw.getFileMode(0));
            b.add(c.getDirCacheEntry());

            Assert.IsFalse(tw.next(), "no more entries");

            b.finish();
            Assert.AreEqual(ents.Length, dc.getEntryCount());
            for (int i = 0; i < ents.Length; i++)
            {
                Assert.AreSame(ents[i], dc.getEntry(i));
            }
        }
Exemple #7
0
        private void ResetIndexForPaths(RevCommit commit)
        {
            DirCache       dc = null;
            DirCacheEditor edit;

            try
            {
                dc   = repo.LockDirCache();
                edit = dc.Editor();
                TreeWalk tw = new TreeWalk(repo);
                tw.AddTree(new DirCacheIterator(dc));
                tw.AddTree(commit.Tree);
                tw.Filter    = PathFilterGroup.CreateFromStrings(filepaths);
                tw.Recursive = true;
                while (tw.Next())
                {
                    string path = tw.PathString;
                    // DirCacheIterator dci = tw.getTree(0, DirCacheIterator.class);
                    CanonicalTreeParser tree = tw.GetTree <CanonicalTreeParser>(1);
                    if (tree == null)
                    {
                        // file is not in the commit, remove from index
                        edit.Add(new DirCacheEditor.DeletePath(path));
                    }
                    else
                    {
                        // revert index to commit
                        // it seams that there is concurrent access to tree
                        // variable, therefore we need to keep references to
                        // entryFileMode and entryObjectId in local
                        // variables
                        FileMode entryFileMode = tree.EntryFileMode;
                        ObjectId entryObjectId = tree.EntryObjectId;
                        edit.Add(new _PathEdit_305(entryFileMode, entryObjectId, path));
                    }
                }
                edit.Commit();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            finally
            {
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
        }
Exemple #8
0
        /// <summary>Update any smudged entries with information from the working tree.</summary>
        /// <remarks>Update any smudged entries with information from the working tree.</remarks>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        private void UpdateSmudgedEntries()
        {
            TreeWalk       walk  = new TreeWalk(repository);
            IList <string> paths = new AList <string>(128);

            try
            {
                for (int i = 0; i < entryCnt; i++)
                {
                    if (sortedEntries[i].IsSmudged)
                    {
                        paths.AddItem(sortedEntries[i].PathString);
                    }
                }
                if (paths.IsEmpty())
                {
                    return;
                }
                walk.Filter = PathFilterGroup.CreateFromStrings(paths);
                DirCacheIterator iIter = new DirCacheIterator(this);
                FileTreeIterator fIter = new FileTreeIterator(repository);
                walk.AddTree(iIter);
                walk.AddTree(fIter);
                walk.Recursive = true;
                while (walk.Next())
                {
                    iIter = walk.GetTree <DirCacheIterator>(0);
                    if (iIter == null)
                    {
                        continue;
                    }
                    fIter = walk.GetTree <FileTreeIterator>(1);
                    if (fIter == null)
                    {
                        continue;
                    }
                    DirCacheEntry entry = iIter.GetDirCacheEntry();
                    if (entry.IsSmudged && iIter.IdEqual(fIter))
                    {
                        entry.SetLength(fIter.GetEntryLength());
                        entry.LastModified = fIter.GetEntryLastModified();
                    }
                }
            }
            finally
            {
                walk.Release();
            }
        }
        /// <summary>Checkout paths into index and working directory</summary>
        /// <returns>this instance</returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException
        ///     </exception>
        protected internal virtual NGit.Api.CheckoutCommand CheckoutPaths()
        {
            RevWalk  revWalk = new RevWalk(repo);
            DirCache dc      = repo.LockDirCache();

            try
            {
                DirCacheEditor editor    = dc.Editor();
                TreeWalk       startWalk = new TreeWalk(revWalk.GetObjectReader());
                startWalk.Recursive = true;
                if (!checkoutAllPaths)
                {
                    startWalk.Filter = PathFilterGroup.CreateFromStrings(paths);
                }
                bool checkoutIndex = startCommit == null && startPoint == null;
                if (!checkoutIndex)
                {
                    startWalk.AddTree(revWalk.ParseCommit(GetStartPoint()).Tree);
                }
                else
                {
                    startWalk.AddTree(new DirCacheIterator(dc));
                }
                FilePath     workTree = repo.WorkTree;
                ObjectReader r        = repo.ObjectDatabase.NewReader();
                try
                {
                    while (startWalk.Next())
                    {
                        ObjectId blobId = startWalk.GetObjectId(0);
                        FileMode mode   = startWalk.GetFileMode(0);
                        editor.Add(new _PathEdit_349(this, checkoutIndex, blobId, mode, workTree, r, startWalk
                                                     .PathString));
                    }
                    editor.Commit();
                }
                finally
                {
                    startWalk.Release();
                    r.Release();
                }
            }
            finally
            {
                dc.Unlock();
                revWalk.Release();
            }
            return(this);
        }
Exemple #10
0
        /// <summary>
        /// Executes the
        /// <code>Rm</code>
        /// command. Each instance of this class should only
        /// be used for one invocation of the command. Don't call this method twice
        /// on an instance.
        /// </summary>
        /// <returns>the DirCache after Rm</returns>
        /// <exception cref="NGit.Api.Errors.NoFilepatternException"></exception>
        public override DirCache Call()
        {
            if (filepatterns.IsEmpty())
            {
                throw new NoFilepatternException(JGitText.Get().atLeastOnePatternIsRequired);
            }
            CheckCallable();
            DirCache dc = null;

            try
            {
                dc = repo.LockDirCache();
                DirCacheBuilder builder = dc.Builder();
                TreeWalk        tw      = new TreeWalk(repo);
                tw.Reset();
                // drop the first empty tree, which we do not need here
                tw.Recursive = true;
                tw.Filter    = PathFilterGroup.CreateFromStrings(filepatterns);
                tw.AddTree(new DirCacheBuildIterator(builder));
                while (tw.Next())
                {
                    FilePath path = new FilePath(repo.WorkTree, tw.PathString);
                    FileMode mode = tw.GetFileMode(0);
                    if (mode.GetObjectType() == Constants.OBJ_BLOB)
                    {
                        // Deleting a blob is simply a matter of removing
                        // the file or symlink named by the tree entry.
                        Delete(path);
                    }
                }
                builder.Commit();
                SetCallable(false);
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfRmCommand
                                                , e);
            }
            finally
            {
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
            return(dc);
        }
Exemple #11
0
        public virtual void TestPathFilterGroup_DoesNotSkipTail()
        {
            DirCache dc   = db.ReadDirCache();
            FileMode mode = FileMode.REGULAR_FILE;

            string[]        paths = new string[] { "a.", "a/b", "a/c", "a/d", "a0b" };
            DirCacheEntry[] ents  = new DirCacheEntry[paths.Length];
            for (int i = 0; i < paths.Length; i++)
            {
                ents[i]          = new DirCacheEntry(paths[i]);
                ents[i].FileMode = mode;
            }
            {
                DirCacheBuilder b = dc.Builder();
                for (int i_1 = 0; i_1 < ents.Length; i_1++)
                {
                    b.Add(ents[i_1]);
                }
                b.Finish();
            }
            int             expIdx = 2;
            DirCacheBuilder b_1    = dc.Builder();
            TreeWalk        tw     = new TreeWalk(db);

            tw.AddTree(new DirCacheBuildIterator(b_1));
            tw.Recursive = true;
            tw.Filter    = PathFilterGroup.CreateFromStrings(Collections.Singleton(paths[expIdx]
                                                                                   ));
            NUnit.Framework.Assert.IsTrue(tw.Next(), "found " + paths[expIdx]);
            DirCacheIterator c = tw.GetTree <DirCacheIterator>(0);

            NUnit.Framework.Assert.IsNotNull(c);
            NUnit.Framework.Assert.AreEqual(expIdx, c.ptr);
            NUnit.Framework.Assert.AreSame(ents[expIdx], c.GetDirCacheEntry());
            NUnit.Framework.Assert.AreEqual(paths[expIdx], tw.PathString);
            NUnit.Framework.Assert.AreEqual(mode.GetBits(), tw.GetRawMode(0));
            NUnit.Framework.Assert.AreSame(mode, tw.GetFileMode(0));
            b_1.Add(c.GetDirCacheEntry());
            NUnit.Framework.Assert.IsFalse(tw.Next(), "no more entries");
            b_1.Finish();
            NUnit.Framework.Assert.AreEqual(ents.Length, dc.GetEntryCount());
            for (int i_2 = 0; i_2 < ents.Length; i_2++)
            {
                NUnit.Framework.Assert.AreSame(ents[i_2], dc.GetEntry(i_2));
            }
        }
Exemple #12
0
        /// <summary>Checkout paths into index and working directory</summary>
        /// <returns>this instance</returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException
        ///     </exception>
        protected internal virtual NGit.Api.CheckoutCommand CheckoutPaths()
        {
            RevWalk  revWalk = new RevWalk(repo);
            DirCache dc      = repo.LockDirCache();

            try
            {
                TreeWalk treeWalk = new TreeWalk(revWalk.GetObjectReader());
                treeWalk.Recursive = true;
                treeWalk.AddTree(new DirCacheIterator(dc));
                treeWalk.Filter = PathFilterGroup.CreateFromStrings(paths);
                IList <string> files = new List <string>();
                while (treeWalk.Next())
                {
                    files.AddItem(treeWalk.PathString);
                }
                if (startCommit != null || startPoint != null)
                {
                    DirCacheEditor editor    = dc.Editor();
                    TreeWalk       startWalk = new TreeWalk(revWalk.GetObjectReader());
                    startWalk.Recursive = true;
                    startWalk.Filter    = treeWalk.Filter;
                    startWalk.AddTree(revWalk.ParseCommit(GetStartPoint()).Tree);
                    while (startWalk.Next())
                    {
                        ObjectId blobId = startWalk.GetObjectId(0);
                        editor.Add(new _PathEdit_258(blobId, startWalk.PathString));
                    }
                    editor.Commit();
                }
                FilePath workTree = repo.WorkTree;
                foreach (string file in files)
                {
                    DirCacheCheckout.CheckoutEntry(repo, new FilePath(workTree, file), dc.GetEntry(file
                                                                                                   ));
                }
            }
            finally
            {
                dc.Unlock();
                revWalk.Release();
            }
            return(this);
        }
Exemple #13
0
        private void ResetIndexForPaths(RevCommit commit)
        {
            DirCache       dc = null;
            DirCacheEditor edit;

            try
            {
                dc   = repo.LockDirCache();
                edit = dc.Editor();
                TreeWalk tw = new TreeWalk(repo);
                tw.AddTree(new DirCacheIterator(dc));
                tw.AddTree(commit.Tree);
                tw.Filter = PathFilterGroup.CreateFromStrings(filepaths);
                while (tw.Next())
                {
                    string path = tw.PathString;
                    // DirCacheIterator dci = tw.getTree(0, DirCacheIterator.class);
                    CanonicalTreeParser tree = tw.GetTree <CanonicalTreeParser>(1);
                    if (tree == null)
                    {
                        // file is not in the commit, remove from index
                        edit.Add(new DirCacheEditor.DeletePath(path));
                    }
                    else
                    {
                        // revert index to commit
                        edit.Add(new _PathEdit_281(tree, path));
                    }
                }
                edit.Commit();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            finally
            {
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
        }
        public void testTwoLevelSubtree_FilterPath()
        {
            DirCache dc = DirCache.read(db);

            FileMode mode = FileMode.RegularFile;

            string[] paths = { "a.", "a/b", "a/c/e", "a/c/f", "a/d", "a0b" };
            var      ents  = new DirCacheEntry[paths.Length];

            for (int i = 0; i < paths.Length; i++)
            {
                ents[i] = new DirCacheEntry(paths[i]);
                ents[i].setFileMode(mode);
            }

            DirCacheBuilder b = dc.builder();

            for (int i = 0; i < ents.Length; i++)
            {
                b.add(ents[i]);
            }
            b.finish();

            var tw = new TreeWalk(db);

            for (int victimIdx = 0; victimIdx < paths.Length; victimIdx++)
            {
                tw.reset();
                tw.addTree(new DirCacheIterator(dc));
                tw.setFilter(PathFilterGroup.createFromStrings(new[] { paths[victimIdx] }));
                tw.Recursive = tw.getFilter().shouldBeRecursive();
                Assert.IsTrue(tw.next());
                var c = tw.getTree <DirCacheIterator>(0, typeof(DirCacheIterator));
                Assert.IsNotNull(c);
                Assert.AreEqual(victimIdx, c.Pointer);
                Assert.AreSame(ents[victimIdx], c.getDirCacheEntry());
                Assert.AreEqual(paths[victimIdx], tw.getPathString());
                Assert.AreEqual(mode.Bits, tw.getRawMode(0));
                Assert.AreSame(mode, tw.getFileMode(0));
                Assert.IsFalse(tw.next());
            }
        }
Exemple #15
0
        /**
         * Lookup an entry stored in a tree, failing if not present.
         *
         * @param tree
         *            the tree to search.
         * @param path
         *            the path to find the entry of.
         * @return the parsed object entry at this path, never null.
         * @throws AssertionFailedError
         *             if the path does not exist in the given tree.
         * @throws Exception
         */
        public RevObject get(RevTree tree, String path)
        {
            TreeWalk tw = new TreeWalk(db);

            tw.setFilter(PathFilterGroup.createFromStrings(new[] { path }));
            tw.reset(tree);
            while (tw.next())
            {
                if (tw.isSubtree() && !path.Equals(tw.getPathString()))
                {
                    tw.enterSubtree();
                    continue;
                }
                ObjectId entid   = tw.getObjectId(0);
                FileMode entmode = tw.getFileMode(0);
                return(pool.lookupAny(entid, (int)entmode.ObjectType));
            }
            Assert.Fail("Can't find " + path + " in tree " + tree.Name);
            return(null); // never reached.
        }
        public override NGit.Api.Status Call()
        {
            if (iter == null)
            {
                iter = new FileTreeIterator(repo);
            }

            diff = new IndexDiff(repo, Constants.HEAD, iter);
            if (Files != null)
            {
                var filters = Files.Where(f => f != ".").ToArray();
                if (filters.Length > 0)
                {
                    diff.SetFilter(PathFilterGroup.CreateFromStrings(filters));
                }
            }

            diff.Diff();
            return(new NGit.Api.Status(diff));
        }
Exemple #17
0
        private void ResetIndexForPaths(RevCommit commit)
        {
            DirCache dc = null;

            try
            {
                dc = repo.LockDirCache();
                DirCacheBuilder builder = dc.Builder();
                TreeWalk        tw      = new TreeWalk(repo);
                tw.AddTree(new DirCacheBuildIterator(builder));
                tw.AddTree(commit.Tree);
                tw.Filter    = PathFilterGroup.CreateFromStrings(filepaths);
                tw.Recursive = true;
                while (tw.Next())
                {
                    CanonicalTreeParser tree = tw.GetTree <CanonicalTreeParser>(1);
                    // only keep file in index if it's in the commit
                    if (tree != null)
                    {
                        // revert index to commit
                        DirCacheEntry entry = new DirCacheEntry(tw.RawPath);
                        entry.FileMode = tree.EntryFileMode;
                        entry.SetObjectId(tree.EntryObjectId);
                        builder.Add(entry);
                    }
                }
                builder.Commit();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            finally
            {
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
        }
Exemple #18
0
        public virtual void TestTwoLevelSubtree_FilterPath()
        {
            DirCache dc   = DirCache.NewInCore();
            FileMode mode = FileMode.REGULAR_FILE;

            string[]        paths = new string[] { "a.", "a/b", "a/c/e", "a/c/f", "a/d", "a0b" };
            DirCacheEntry[] ents  = new DirCacheEntry[paths.Length];
            for (int i = 0; i < paths.Length; i++)
            {
                ents[i]          = new DirCacheEntry(paths[i]);
                ents[i].FileMode = mode;
            }
            DirCacheBuilder b = dc.Builder();

            for (int i_1 = 0; i_1 < ents.Length; i_1++)
            {
                b.Add(ents[i_1]);
            }
            b.Finish();
            TreeWalk tw = new TreeWalk(db);

            for (int victimIdx = 0; victimIdx < paths.Length; victimIdx++)
            {
                tw.Reset();
                tw.AddTree(new DirCacheIterator(dc));
                tw.Filter = PathFilterGroup.CreateFromStrings(Collections.Singleton(paths[victimIdx
                                                                                    ]));
                tw.Recursive = tw.Filter.ShouldBeRecursive();
                NUnit.Framework.Assert.IsTrue(tw.Next());
                DirCacheIterator c = tw.GetTree <DirCacheIterator>(0);
                NUnit.Framework.Assert.IsNotNull(c);
                NUnit.Framework.Assert.AreEqual(victimIdx, c.ptr);
                NUnit.Framework.Assert.AreSame(ents[victimIdx], c.GetDirCacheEntry());
                NUnit.Framework.Assert.AreEqual(paths[victimIdx], tw.PathString);
                NUnit.Framework.Assert.AreEqual(mode.GetBits(), tw.GetRawMode(0));
                NUnit.Framework.Assert.AreSame(mode, tw.GetFileMode(0));
                NUnit.Framework.Assert.IsFalse(tw.Next());
            }
        }
Exemple #19
0
        public string ReadCommit(string commitId, string fileName)
        {
            var repo = m_git.GetRepository();
            var id   = ObjectId.FromString(commitId);

            RevCommit commit = null;

            try
            {
                commit = ParseCommit(repo, id);
                if (commit == null)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                return(null);
            }
            //var commits = m_git.Log().AddRange(id, id).Call();
            //var commit = commits.SingleOrDefault();
            //if (commit == null)
            //    return null;

            TreeWalk walk = new TreeWalk(repo);

            //RevWalk r = new RevWalk(m_git.GetRepository());
            //var tree = r.ParseTree(commit.Tree.Id);
            //r.LookupTree(
            //walk.AddTree(new FileTreeIterator(repo));

            //var tree = ParseTree(repo, commit.Tree.Id);
            walk.AddTree(commit.Tree);
            var filter = GetGitFriendlyName(fileName);

            walk.Filter = PathFilterGroup.CreateFromStrings(new string[] { filter });
            //walk.EnterSubtree();
            while (walk.Next())
            {
                var path = walk.PathString;
                if (walk.IsSubtree)
                {
                    walk.EnterSubtree();
                    continue;
                }
                if (path == filter)
                {
                    var          cur = walk.GetObjectId(0);
                    ObjectLoader ol  = repo.Open(cur);

                    //    //Console.WriteLine(string.Format("Path: {0}{1}", walk.PathString, walk.IsSubtree ? "/" : ""));
                    //    //var loader = reader.Open(commit.Tree.Id);
                    var text = "";
                    using (var stream = ol.OpenStream())
                        using (var sr = new System.IO.StreamReader(stream))
                        {
                            text = sr.ReadToEnd();
                        }
                    return(text);
                }
            }
            //walk.Reset();
            //reader.Open();
            return("");
        }
Exemple #20
0
        /// <summary>
        /// Executes the
        /// <code>Add</code>
        /// command. Each instance of this class should only
        /// be used for one invocation of the command. Don't call this method twice
        /// on an instance.
        /// </summary>
        /// <returns>the DirCache after Add</returns>
        /// <exception cref="NGit.Api.Errors.GitAPIException"></exception>
        /// <exception cref="NGit.Api.Errors.NoFilepatternException"></exception>
        public override DirCache Call()
        {
            if (filepatterns.IsEmpty())
            {
                throw new NoFilepatternException(JGitText.Get().atLeastOnePatternIsRequired);
            }
            CheckCallable();
            DirCache dc     = null;
            bool     addAll = false;

            if (filepatterns.Contains("."))
            {
                addAll = true;
            }
            ObjectInserter inserter = repo.NewObjectInserter();

            try
            {
                dc = repo.LockDirCache();
                DirCacheIterator c;
                DirCacheBuilder  builder = dc.Builder();
                TreeWalk         tw      = new TreeWalk(repo);
                tw.AddTree(new DirCacheBuildIterator(builder));
                if (workingTreeIterator == null)
                {
                    workingTreeIterator = new FileTreeIterator(repo);
                }
                tw.AddTree(workingTreeIterator);
                tw.Recursive = true;
                if (!addAll)
                {
                    tw.Filter = PathFilterGroup.CreateFromStrings(filepatterns);
                }
                string lastAddedFile = null;
                while (tw.Next())
                {
                    string path           = tw.PathString;
                    WorkingTreeIterator f = tw.GetTree <WorkingTreeIterator>(1);
                    if (tw.GetTree <DirCacheIterator>(0) == null && f != null && f.IsEntryIgnored())
                    {
                    }
                    else
                    {
                        // file is not in index but is ignored, do nothing
                        // In case of an existing merge conflict the
                        // DirCacheBuildIterator iterates over all stages of
                        // this path, we however want to add only one
                        // new DirCacheEntry per path.
                        if (!(path.Equals(lastAddedFile)))
                        {
                            if (!(update && tw.GetTree <DirCacheIterator>(0) == null))
                            {
                                c = tw.GetTree <DirCacheIterator>(0);
                                if (f != null)
                                {
                                    // the file exists
                                    long          sz    = f.GetEntryLength();
                                    DirCacheEntry entry = new DirCacheEntry(path);
                                    if (c == null || c.GetDirCacheEntry() == null || !c.GetDirCacheEntry().IsAssumeValid)
                                    {
                                        FileMode mode = f.GetIndexFileMode(c);
                                        entry.FileMode = mode;
                                        if (FileMode.GITLINK != mode)
                                        {
                                            entry.SetLength(sz);
                                            entry.LastModified = f.GetEntryLastModified();
                                            long        contentSize = f.GetEntryContentLength();
                                            InputStream @in         = f.OpenEntryStream();
                                            try
                                            {
                                                entry.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, contentSize, @in));
                                            }
                                            finally
                                            {
                                                @in.Close();
                                            }
                                        }
                                        else
                                        {
                                            entry.SetObjectId(f.EntryObjectId);
                                        }
                                        builder.Add(entry);
                                        lastAddedFile = path;
                                    }
                                    else
                                    {
                                        builder.Add(c.GetDirCacheEntry());
                                    }
                                }
                                else
                                {
                                    if (c != null && (!update || FileMode.GITLINK == c.EntryFileMode))
                                    {
                                        builder.Add(c.GetDirCacheEntry());
                                    }
                                }
                            }
                        }
                    }
                }
                inserter.Flush();
                builder.Commit();
                SetCallable(false);
            }
            catch (IOException e)
            {
                throw new JGitInternalException(JGitText.Get().exceptionCaughtDuringExecutionOfAddCommand
                                                , e);
            }
            finally
            {
                inserter.Release();
                if (dc != null)
                {
                    dc.Unlock();
                }
            }
            return(dc);
        }
 protected internal virtual void Filter(string path)
 {
     rw.SetTreeFilter(AndTreeFilter.Create(PathFilterGroup.CreateFromStrings(Sharpen.Collections
                                                                             .Singleton(path)), TreeFilter.ANY_DIFF));
 }
 /// <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);
     }
 }
Exemple #23
0
 /// <summary>Execute the SubmoduleUpdateCommand command.</summary>
 /// <remarks>Execute the SubmoduleUpdateCommand command.</remarks>
 /// <returns>a collection of updated submodule paths</returns>
 /// <exception cref="NGit.Api.Errors.ConcurrentRefUpdateException">NGit.Api.Errors.ConcurrentRefUpdateException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.CheckoutConflictException">NGit.Api.Errors.CheckoutConflictException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.InvalidMergeHeadsException">NGit.Api.Errors.InvalidMergeHeadsException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.InvalidConfigurationException">NGit.Api.Errors.InvalidConfigurationException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.NoHeadException">NGit.Api.Errors.NoHeadException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.NoMessageException">NGit.Api.Errors.NoMessageException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.RefNotFoundException">NGit.Api.Errors.RefNotFoundException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.WrongRepositoryStateException">NGit.Api.Errors.WrongRepositoryStateException
 ///     </exception>
 /// <exception cref="NGit.Api.Errors.GitAPIException">NGit.Api.Errors.GitAPIException
 ///     </exception>
 public override ICollection <string> Call()
 {
     CheckCallable();
     try
     {
         SubmoduleWalk generator = SubmoduleWalk.ForIndex(repo);
         if (!paths.IsEmpty())
         {
             generator.SetFilter(PathFilterGroup.CreateFromStrings(paths));
         }
         IList <string> updated = new AList <string>();
         while (generator.Next())
         {
             // Skip submodules not registered in .gitmodules file
             if (generator.GetModulesPath() == null)
             {
                 continue;
             }
             // Skip submodules not registered in parent repository's config
             string url = generator.GetConfigUrl();
             if (url == null)
             {
                 continue;
             }
             Repository submoduleRepo = generator.GetRepository();
             // Clone repository is not present
             if (submoduleRepo == null)
             {
                 CloneCommand clone = Git.CloneRepository();
                 Configure(clone);
                 clone.SetURI(url);
                 clone.SetDirectory(generator.GetDirectory());
                 if (monitor != null)
                 {
                     clone.SetProgressMonitor(monitor);
                 }
                 submoduleRepo = clone.Call().GetRepository();
             }
             try
             {
                 RevWalk   walk   = new RevWalk(submoduleRepo);
                 RevCommit commit = walk.ParseCommit(generator.GetObjectId());
                 string    update = generator.GetConfigUpdate();
                 if (ConfigConstants.CONFIG_KEY_MERGE.Equals(update))
                 {
                     MergeCommand merge = new MergeCommand(submoduleRepo);
                     merge.Include(commit);
                     merge.Call();
                 }
                 else
                 {
                     if (ConfigConstants.CONFIG_KEY_REBASE.Equals(update))
                     {
                         RebaseCommand rebase = new RebaseCommand(submoduleRepo);
                         rebase.SetUpstream(commit);
                         rebase.Call();
                     }
                     else
                     {
                         // Checkout commit referenced in parent repository's
                         // index as a detached HEAD
                         DirCacheCheckout co = new DirCacheCheckout(submoduleRepo, submoduleRepo.LockDirCache
                                                                        (), commit.Tree);
                         co.SetFailOnConflict(true);
                         co.Checkout();
                         RefUpdate refUpdate = submoduleRepo.UpdateRef(Constants.HEAD, true);
                         refUpdate.SetNewObjectId(commit);
                         refUpdate.ForceUpdate();
                     }
                 }
             }
             finally
             {
                 submoduleRepo.Close();
             }
             updated.AddItem(generator.GetPath());
         }
         return(updated);
     }
     catch (IOException e)
     {
         throw new JGitInternalException(e.Message, e);
     }
     catch (ConfigInvalidException e)
     {
         throw new InvalidConfigurationException(e.Message, e);
     }
 }
 protected void filter(string path)
 {
     rw.setTreeFilter(AndTreeFilter.create(
                          PathFilterGroup.createFromStrings(new[] { path }), TreeFilter.ANY_DIFF));
 }