<commit_before>using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Threading;
using LibGit2Sharp.Core.Handles;

// ReSharper disable InconsistentNaming
namespace LibGit2Sharp.Core
{
    internal static class NativeMethods
    {
        public const uint GIT_PATH_MAX = 4096;
        private const string libgit2 = NativeDllName.Name;
        // This is here to keep the pointer alive
        #pragma warning disable 0414
        private static readonly LibraryLifetimeObject lifetimeObject;
        #pragma warning restore 0414
        private static int handlesCount;

        /// <summary>
        /// Internal hack to ensure that the call to git_threads_shutdown is called after all handle finalizers
        /// have run to completion ensuring that no dangling git-related finalizer runs after git_threads_shutdown.
        /// There should never be more than one instance of this object per AppDomain.
        /// </summary>
        private sealed class LibraryLifetimeObject : CriticalFinalizerObject
        {
            // Ensure mono can JIT the .cctor and adjust the PATH before trying to load the native library.
            // See https://github.com/libgit2/libgit2sharp/pull/190
            [MethodImpl(MethodImplOptions.NoInlining)]
            public LibraryLifetimeObject()
            {
                int res = git_libgit2_init();
                Ensure.Int32Result(res);
                if (res == 1)
                {
                    // Ignore the error that this propagates. Call it in case openssl is being used.
                    git_openssl_set_locking();
                }
                AddHandle();
            }

            ~LibraryLifetimeObject()
            {
                RemoveHandle();
            }
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal static void AddHandle()
        {
            Interlocked.Increment(ref handlesCount);
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal static void RemoveHandle()
        {
            int count = Interlocked.Decrement(ref handlesCount);
            if (count == 0)
            {
                git_libgit2_shutdown();
            }
        }

        static NativeMethods()
        {
            if (Platform.OperatingSystem == OperatingSystemType.Windows)
            {
                string nativeLibraryPath = GlobalSettings.GetAndLockNativeLibraryPath();

                var pathStringToAdd = GetPathStringToAdd(nativeLibraryPath);

                const string pathEnvVariable = "PATH";
                Environment.SetEnvironmentVariable(pathEnvVariable,
                    String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", pathStringToAdd, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
            }

            // See LibraryLifetimeObject description.
            lifetimeObject = new LibraryLifetimeObject();
        }

        private static string GetPathStringToAdd(string nativeLibraryPath)
        {
            const string nativeBinariesFolderSlash = "NativeBinaries\\";
            var subFolders = Platform.ProcessorArchitecture == Architecture.x86
                ? new[] { "x86" }
                : new[] { "amd64", "x64" };
            var pathsToAdd = subFolders.Select(f => Path.Combine(nativeLibraryPath, f))
                .Concat(subFolders.Select(f => Path.Combine(nativeLibraryPath, nativeBinariesFolderSlash + f)));
            var pathStringToAdd = string.Join(Path.PathSeparator.ToString(), pathsToAdd.ToArray());
            return pathStringToAdd;
        }

        [DllImport(libgit2)]
        internal static extern unsafe GitError* giterr_last();

        [DllImport(libgit2)]
        internal static extern void giterr_set_str(
            GitErrorCategory error_class,
            [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string errorString);

        [DllImport(libgit2)]<commit_msg>Update path with location of native binaries.<commit_after>using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Threading;
using LibGit2Sharp.Core.Handles;

// ReSharper disable InconsistentNaming
namespace LibGit2Sharp.Core
{
    internal static class NativeMethods
    {
        public const uint GIT_PATH_MAX = 4096;
        private const string libgit2 = NativeDllName.Name;
        // This is here to keep the pointer alive
        #pragma warning disable 0414
        private static readonly LibraryLifetimeObject lifetimeObject;
        #pragma warning restore 0414
        private static int handlesCount;

        /// <summary>
        /// Internal hack to ensure that the call to git_threads_shutdown is called after all handle finalizers
        /// have run to completion ensuring that no dangling git-related finalizer runs after git_threads_shutdown.
        /// There should never be more than one instance of this object per AppDomain.
        /// </summary>
        private sealed class LibraryLifetimeObject : CriticalFinalizerObject
        {
            // Ensure mono can JIT the .cctor and adjust the PATH before trying to load the native library.
            // See https://github.com/libgit2/libgit2sharp/pull/190
            [MethodImpl(MethodImplOptions.NoInlining)]
            public LibraryLifetimeObject()
            {
                int res = git_libgit2_init();
                Ensure.Int32Result(res);
                if (res == 1)
                {
                    // Ignore the error that this propagates. Call it in case openssl is being used.
                    git_openssl_set_locking();
                }
                AddHandle();
            }

            ~LibraryLifetimeObject()
            {
                RemoveHandle();
            }
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal static void AddHandle()
        {
            Interlocked.Increment(ref handlesCount);
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal static void RemoveHandle()
        {
            int count = Interlocked.Decrement(ref handlesCount);
            if (count == 0)
            {
                git_libgit2_shutdown();
            }
        }

        static NativeMethods()
        {
            if (Platform.OperatingSystem == OperatingSystemType.Windows)
            {
                string nativeLibraryPath = GlobalSettings.GetAndLockNativeLibraryPath();

                string path = Path.Combine(nativeLibraryPath, Platform.ProcessorArchitecture);

                const string pathEnvVariable = "PATH";
                Environment.SetEnvironmentVariable(pathEnvVariable,
                    String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
            }

            // See LibraryLifetimeObject description.
            lifetimeObject = new LibraryLifetimeObject();
        }

        [DllImport(libgit2)]
        internal static extern unsafe GitError* giterr_last();

        [DllImport(libgit2)]
        internal static extern void giterr_set_str(
            GitErrorCategory error_class,
            [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string errorString);

        [DllImport(libgit2)]
{'fraction_non_alphanumeric': 0.07353881570533316, 'fraction_numerical': 0.00946412584729505, 'mean_word_length': 2.1970564186426818, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5505576', 'n_tokens_mistral': 1993, 'n_tokens_neox': 1885, 'n_words': 497}