Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 342 lines (286 sloc) 13.993 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;

namespace LibGit2Sharp
{
    /// <summary>
    /// The Collection of references in a <see cref = "Repository" />
    /// </summary>
    public class ReferenceCollection : IEnumerable<Reference>
    {
        private readonly Repository repo;

        /// <summary>
        /// Needed for mocking purposes.
        /// </summary>
        protected ReferenceCollection()
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref = "ReferenceCollection" /> class.
        /// </summary>
        /// <param name = "repo">The repo.</param>
        internal ReferenceCollection(Repository repo)
        {
            this.repo = repo;
        }

        /// <summary>
        /// Gets the <see cref = "LibGit2Sharp.Reference" /> with the specified name.
        /// </summary>
        /// <param name = "name">The canonical name of the reference to resolve.</param>
        /// <returns>The resolved <see cref = "LibGit2Sharp.Reference" /> if it has been found, null otherwise.</returns>
        public virtual Reference this[string name]
        {
            get { return Resolve<Reference>(name); }
        }

        #region IEnumerable<Reference> Members

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>An <see cref = "IEnumerator{T}" /> object that can be used to iterate through the collection.</returns>
        public virtual IEnumerator<Reference> GetEnumerator()
        {
            return Libgit2UnsafeHelper
                .ListAllReferenceNames(repo.Handle, GitReferenceType.ListAll)
                .Select(n => this[n])
                .GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>An <see cref = "IEnumerator" /> object that can be used to iterate through the collection.</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        private enum RefState
        {
            Exists,
            DoesNotExistButLooksValid,
            DoesNotLookValid,
        }

        private RefState TryResolveReference(out Reference reference, string canonicalName)
        {
            try
            {
                //TODO: Maybe would it be better to rather rely on git_reference_normalize_name()
                //This would be much more straightforward and less subject to fail for the wrong reason.

                reference = repo.Refs[canonicalName];

                if (reference != null)
                {
                    return RefState.Exists;
                }

                return RefState.DoesNotExistButLooksValid;
            }
            catch (LibGit2SharpException)
            {
                reference = null;
                return RefState.DoesNotLookValid;
            }
        }

        /// <summary>
        /// Creates a direct or symbolic reference with the specified name and target
        /// </summary>
        /// <param name = "name">The name of the reference to create.</param>
        /// <param name = "canonicalRefNameOrObjectish">The target which can be either the canonical name of a branch reference or a revparse spec.</param>
        /// <param name = "allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <returns>A new <see cref = "Reference" />.</returns>
        public virtual Reference Add(string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish");

            Reference reference;
            RefState refState = TryResolveReference(out reference, canonicalRefNameOrObjectish);

            var gitObject = repo.Lookup(canonicalRefNameOrObjectish, GitObjectType.Any, LookUpOptions.None);

            if (refState == RefState.Exists || (refState == RefState.DoesNotExistButLooksValid && gitObject == null))
            {
                using (ReferenceSafeHandle handle = CreateSymbolicReference(name, canonicalRefNameOrObjectish, allowOverwrite))
                {
                    return Reference.BuildFromPtr<Reference>(handle, repo);
                }
            }

            return Add(name, gitObject.Id, allowOverwrite);
        }

        /// <summary>
        /// Creates a direct reference with the specified name and target
        /// </summary>
        /// <param name = "name">The name of the reference to create.</param>
        /// <param name = "targetId">Id of the target object.</param>
        /// <param name = "allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <returns>A new <see cref = "Reference" />.</returns>
        public virtual DirectReference Add(string name, ObjectId targetId, bool allowOverwrite = false)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNull(targetId, "targetId");

            using (ReferenceSafeHandle handle = CreateDirectReference(name, targetId, allowOverwrite))
            {
                return (DirectReference)Reference.BuildFromPtr<Reference>(handle, repo);
            }
        }

        /// <summary>
        /// Creates a direct or symbolic reference with the specified name and target
        /// </summary>
        /// <param name = "name">The name of the reference to create.</param>
        /// <param name = "target">The target which can be either a sha or the canonical name of another reference.</param>
        /// <param name = "allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <returns>A new <see cref = "Reference" />.</returns>
[Obsolete("This method will be removed in the next release. Please use Add() instead.")]
        public virtual Reference Create(string name, string target, bool allowOverwrite = false)
        {
            return Add(name, target, allowOverwrite);
        }

        private ReferenceSafeHandle CreateSymbolicReference(string name, string target, bool allowOverwrite)
        {
            ReferenceSafeHandle handle;
            Ensure.Success(NativeMethods.git_reference_create_symbolic(out handle, repo.Handle, name, target, allowOverwrite));
            return handle;
        }

        private ReferenceSafeHandle CreateDirectReference(string name, ObjectId targetId, bool allowOverwrite)
        {
            GitOid oid = targetId.Oid;

            ReferenceSafeHandle handle;
            Ensure.Success(NativeMethods.git_reference_create_oid(out handle, repo.Handle, name, ref oid, allowOverwrite));
            return handle;
        }

        /// <summary>
        /// Delete a reference with the specified name
        /// </summary>
        /// <param name = "name">The name of the reference to delete.</param>
        public virtual void Remove(string name)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");

            using (ReferenceSafeHandle handle = RetrieveReferencePtr(name))
            {
                int res = NativeMethods.git_reference_delete(handle);
                
                //TODO Make git_reference_delete() set the ref pointer to NULL and remove the following line
                handle.SetHandleAsInvalid();
                
                Ensure.Success(res);
            }
        }

        /// <summary>
        /// Delete a reference with the specified name
        /// </summary>
        /// <param name = "name">The name of the reference to delete.</param>
[Obsolete("This method will be removed in the next release. Please use Remove() instead.")]
        public virtual void Delete(string name)
        {
            Remove(name);
        }

        /// <summary>
        /// Rename an existing reference with a new name
        /// </summary>
        /// <param name = "currentName">The canonical name of the reference to rename.</param>
        /// <param name = "newName">The new canonical name.</param>
        /// <param name = "allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <returns></returns>
        public virtual Reference Move(string currentName, string newName, bool allowOverwrite = false)
        {
            Ensure.ArgumentNotNullOrEmptyString(currentName, "currentName");
            Ensure.ArgumentNotNullOrEmptyString(newName, "newName");

            using (ReferenceSafeHandle handle = RetrieveReferencePtr(currentName))
            {
                int res = NativeMethods.git_reference_rename(handle, newName, allowOverwrite);
                Ensure.Success(res);

                return Reference.BuildFromPtr<Reference>(handle, repo);
            }
        }

        internal T Resolve<T>(string name) where T : Reference
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");

            using (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(name, false))
            {
                return referencePtr == null ? null : Reference.BuildFromPtr<T>(referencePtr, repo);
            }
        }

        /// <summary>
        /// Updates the target on a reference.
        /// </summary>
        /// <param name = "name">The name of the reference.</param>
        /// <param name = "target">The target which can be either a sha or the name of another reference.</param>
        public virtual Reference UpdateTarget(string name, string target)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(target, "target");

            if (name == "HEAD")
            {
                return Add("HEAD", target, true);
            }

            using (ReferenceSafeHandle referencePtr = RetrieveReferencePtr(name))
            {
                int res;

                ObjectId id;
                bool isObjectIdentifier = ObjectId.TryParse(target, out id);

                GitReferenceType type = NativeMethods.git_reference_type(referencePtr);
                switch (type)
                {
                    case GitReferenceType.Oid:
                        if (!isObjectIdentifier)
                        {
                            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The reference specified by {0} is an Oid reference, you must provide a sha as the target.", name), "target");
                        }

                        GitOid oid = id.Oid;
                        res = NativeMethods.git_reference_set_oid(referencePtr, ref oid);
                        break;

                    case GitReferenceType.Symbolic:
                        if (isObjectIdentifier)
                        {
                            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The reference specified by {0} is a Symbolic reference, you must provide a reference canonical name as the target.", name), "target");
                        }

                        res = NativeMethods.git_reference_set_target(referencePtr, target);
                        break;

                    default:
                        throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Reference '{0}' has an unexpected type ('{1}').", name, type));
                }

                Ensure.Success(res);

                return Reference.BuildFromPtr<Reference>(referencePtr, repo);
            }
        }

        private ReferenceSafeHandle RetrieveReferencePtr(string referenceName, bool shouldThrowIfNotFound = true)
        {
            ReferenceSafeHandle reference;
            int res = NativeMethods.git_reference_lookup(out reference, repo.Handle, referenceName);

            if (!shouldThrowIfNotFound && res == (int)GitErrorCode.NotFound)
            {
                return null;
            }

            Ensure.Success(res);

            return reference;
        }

        /// <summary>
        /// Returns the list of references of the repository matching the specified <paramref name = "pattern" />.
        /// </summary>
        /// <param name = "pattern">The glob pattern the reference name should match.</param>
        /// <returns>A list of references, ready to be enumerated.</returns>
        public virtual IEnumerable<Reference> FromGlob(string pattern)
        {
            Ensure.ArgumentNotNullOrEmptyString(pattern, "pattern");

            return new GlobedReferenceEnumerable(repo.Handle, pattern).Select(n => this[n]);
        }

        private class GlobedReferenceEnumerable : IEnumerable<string>
        {
            private readonly List<string> list = new List<string>();

            public GlobedReferenceEnumerable(RepositorySafeHandle handle, string pattern)
            {
                Ensure.Success(NativeMethods.git_reference_foreach_glob(handle, pattern, GitReferenceType.ListAll, Callback, IntPtr.Zero));
                list.Sort(StringComparer.Ordinal);
            }

            private int Callback(IntPtr branchName, IntPtr payload)
            {
                string name = Utf8Marshaler.FromNative(branchName);
                list.Add(name);
                return 0;
            }

            public IEnumerator<string> GetEnumerator()
            {
                return list.GetEnumerator();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
        }
    }
}
Something went wrong with that request. Please try again.