using System;
using System.Globalization;
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
{
GitObjectType 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, repo);
case GitObjectType.Blob:
return Blob.BuildFromPtr(obj, id, repo);
default:
throw new LibGit2Exception(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' for object '{1}'.", type, id));
}
}
finally
{
NativeMethods.git_object_free(obj);
}
}
internal static ObjectId ObjectIdOf(IntPtr obj)
{
IntPtr ptr = NativeMethods.git_object_id(obj);
return new ObjectId(ptr.MarshalAsOid());
}
///
/// 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);
}
}
}