using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
///
/// A container which references a list of other s and s.
///
public class Tree : GitObject, IEnumerable
{
private Repository repo;
internal Tree(ObjectId id)
: base(id)
{
}
///
/// Gets the number of immediately under this .
///
public int Count { get; private set; }
///
/// 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 TreeEntry this[string relativePath]
{
get { return RetrieveFromPath(relativePath); }
}
private TreeEntry RetrieveFromPath(FilePath relativePath)
{
if (string.IsNullOrEmpty(relativePath.Posix))
{
return null;
}
using (var obj = new ObjectSafeWrapper(Id, repo))
{
IntPtr objectPtr;
int res = NativeMethods.git_tree_get_subtree(out objectPtr, obj.ObjectPtr, relativePath);
if (res == (int)GitErrorCode.GIT_ENOTFOUND)
{
return null;
}
Ensure.Success(res);
IntPtr e = NativeMethods.git_tree_entry_byname(objectPtr, relativePath.Posix.Split('/').Last());
if (e == IntPtr.Zero)
{
return null;
}
return new TreeEntry(e, Id, repo);
}
}
///
/// Gets the s immediately under this .
///
public IEnumerable Trees
{
get
{
return this
.Where(e => e.Type == GitObjectType.Tree)
.Select(e => e.Target)
.Cast();
}
}
///
/// Gets the s immediately under this .
///
public IEnumerable Files
{
get
{
return this
.Where(e => e.Type == GitObjectType.Blob)
.Select(e => e.Target)
.Cast();
}
}
#region IEnumerable Members
///
/// Returns an enumerator that iterates through the collection.
///
/// An object that can be used to iterate through the collection.
public IEnumerator GetEnumerator()
{
using (var obj = new ObjectSafeWrapper(Id, repo))
{
for (uint i = 0; i < Count; i++)
{
IntPtr e = NativeMethods.git_tree_entry_byindex(obj.ObjectPtr, i);
yield return new TreeEntry(e, Id, repo);
}
}
}
///
/// 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
internal static Tree BuildFromPtr(IntPtr obj, ObjectId id, Repository repo)
{
var tree = new Tree(id) { repo = repo, Count = (int)NativeMethods.git_tree_entrycount(obj) };
return tree;
}
}
}