using System; 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 { /// /// The collection of submodules in a /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SubmoduleCollection : IEnumerable { internal readonly Repository repo; /// /// Needed for mocking purposes. /// protected SubmoduleCollection() { } /// /// Initializes a new instance of the class. /// /// The repo. internal SubmoduleCollection(Repository repo) { this.repo = repo; } /// /// Gets the with the specified name. /// public virtual Submodule this[string name] { get { Ensure.ArgumentNotNullOrEmptyString(name, "name"); return Lookup(name, handle => new Submodule(repo, name, Proxy.git_submodule_path(handle), Proxy.git_submodule_url(handle))); } } /// /// Returns an enumerator that iterates through the collection. /// /// An object that can be used to iterate through the collection. public virtual IEnumerator GetEnumerator() { return Proxy.git_submodule_foreach(repo.Handle, (h, n) => LaxUtf8Marshaler.FromNative(n)) .Select(n => this[n]) .GetEnumerator(); } /// /// Returns an enumerator that iterates through the collection. /// /// An object that can be used to iterate through the collection. IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal bool TryStage(string relativePath, bool writeIndex) { return Lookup(relativePath, handle => { if (handle == null) return false; Proxy.git_submodule_add_to_index(handle, writeIndex); return true; }); } internal T Lookup(string name, Func selector, bool throwIfNotFound = false) { using (var handle = Proxy.git_submodule_lookup(repo.Handle, name)) { if (handle != null) { Proxy.git_submodule_reload(handle); return selector(handle); } if (throwIfNotFound) { throw new LibGit2SharpException(string.Format( CultureInfo.InvariantCulture, "Submodule lookup failed for '{0}'.", name)); } return default(T); } } private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "Count = {0}", this.Count()); } } } }