using System; using System.Runtime.InteropServices; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// /// A GitObject /// public class GitObject : IEquatable { internal static GitObjectTypeMap TypeToTypeMap = new GitObjectTypeMap { {typeof (Commit), GitObjectType.Commit}, {typeof (Tree), GitObjectType.Tree}, {typeof (Blob), GitObjectType.Blob}, {typeof (TagAnnotation), GitObjectType.Tag}, {typeof (GitObject), GitObjectType.Any}, }; private static readonly LambdaEqualityHelper equalityHelper = new LambdaEqualityHelper(new Func[] {x => x.Id}); /// /// Initializes a new instance of the class. /// /// The it should be identified by. protected GitObject(ObjectId id) { Id = id; } /// /// Gets the id of this object /// public ObjectId Id { get; private set; } /// /// Gets the 40 character sha1 of this object. /// public string Sha { get { return Id.Sha; } } internal static GitObject CreateFromPtr(IntPtr obj, ObjectId id, Repository repo) { try { var type = NativeMethods.git_object_type(obj); switch (type) { case GitObjectType.Commit: return Commit.BuildFromPtr(obj, id, repo); case GitObjectType.Tree: return Tree.BuildFromPtr(obj, id, repo); case GitObjectType.Tag: return TagAnnotation.BuildFromPtr(obj, id); case GitObjectType.Blob: return Blob.BuildFromPtr(obj, id, repo); default: throw new InvalidOperationException(string.Format("Unexpected type '{0}' for object '{1}'.", type, id)); } } finally { NativeMethods.git_object_close(obj); } } internal static ObjectId ObjectIdOf(IntPtr obj) { var ptr = NativeMethods.git_object_id(obj); return new ObjectId((GitOid)Marshal.PtrToStructure(ptr, typeof(GitOid))); } /// /// Determines whether the specified is equal to the current . /// /// The to compare with the current . /// True if the specified is equal to the current ; otherwise, false. public override bool Equals(object obj) { return Equals(obj as GitObject); } /// /// Determines whether the specified is equal to the current . /// /// The to compare with the current . /// True if the specified is equal to the current ; otherwise, false. public bool Equals(GitObject other) { return equalityHelper.Equals(this, other); } /// /// Returns the hash code for this instance. /// /// A 32-bit signed integer hash code. public override int GetHashCode() { return equalityHelper.GetHashCode(this); } /// /// Tests if two are equal. /// /// First to compare. /// Second to compare. /// True if the two objects are equal; false otherwise. public static bool operator ==(GitObject left, GitObject right) { return Equals(left, right); } /// /// Tests if two are different. /// /// First to compare. /// Second to compare. /// True if the two objects are different; false otherwise. public static bool operator !=(GitObject left, GitObject right) { return !Equals(left, right); } } }