using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// /// A container which references a list of other s and s. /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Tree : GitObject, IEnumerable { private readonly FilePath path; private readonly ILazy lazyCount; /// /// Needed for mocking purposes. /// protected Tree() { } internal Tree(Repository repo, ObjectId id, FilePath path) : base(repo, id) { this.path = path ?? ""; lazyCount = GitObjectLazyGroup.Singleton(repo, id, Proxy.git_tree_entrycount); } /// /// Gets the number of immediately under this . /// public virtual int Count { get { return lazyCount.Value; } } /// /// Gets the pointed at by the in this instance. /// /// The relative path to the from this instance. /// null if nothing has been found, the otherwise. public virtual TreeEntry this[string relativePath] { get { return RetrieveFromPath(relativePath); } } private TreeEntry RetrieveFromPath(FilePath relativePath) { if (relativePath.IsNullOrEmpty()) { return null; } using (TreeEntrySafeHandle_Owned treeEntryPtr = Proxy.git_tree_entry_bypath(repo.Handle, Id, relativePath)) { if (treeEntryPtr == null) { return null; } string posixPath = relativePath.Posix; string filename = posixPath.Split('/').Last(); string parentPath = posixPath.Substring(0, posixPath.Length - filename.Length); return new TreeEntry(treeEntryPtr, Id, repo, path.Combine(parentPath)); } } internal string Path { get { return path.Native; } } #region IEnumerable Members /// /// Returns an enumerator that iterates through the collection. /// /// An object that can be used to iterate through the collection. public virtual IEnumerator GetEnumerator() { using (var obj = new ObjectSafeWrapper(Id, repo.Handle)) { for (uint i = 0; i < Count; i++) { TreeEntrySafeHandle handle = Proxy.git_tree_entry_byindex(obj.ObjectPtr, i); yield return new TreeEntry(handle, Id, repo, path); } } } /// /// Returns an enumerator that iterates through the collection. /// /// An object that can be used to iterate through the collection. IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "{0}, Count = {1}", Id.ToString(7), Count); } } } }