GithubHelp home page GithubHelp logo

libgit2 / libgit2sharp Goto Github PK

View Code? Open in Web Editor NEW
3.1K 3.1K 870.0 160.45 MB

Git + .NET = ❤

Home Page: http://libgit2.github.com

License: MIT License

C# 100.00%
dotnet dotnet-core git libgit2 version-control

libgit2sharp's Introduction

libgit2 - the Git linkable library

Build Status
main branch CI builds CI Build
v1.8 branch CI builds CI Build
v1.7 branch CI builds CI Build
Nightly builds Nightly Build Coverity Scan Status

libgit2 is a portable, pure C implementation of the Git core methods provided as a linkable library with a solid API, allowing to build Git functionality into your application. Language bindings like Rugged (Ruby), LibGit2Sharp (.NET), pygit2 (Python) and NodeGit (Node) allow you to build Git tooling in your favorite language.

libgit2 is used to power Git GUI clients like GitKraken and GitButler and on Git hosting providers like GitHub, GitLab and Azure DevOps. We perform the merge every time you click "merge pull request".

libgit2 is licensed under a very permissive license (GPLv2 with a special Linking Exception). This means that you can link against the library with any kind of software without making that software fall under the GPL. Changes to libgit2 would still be covered under its GPL license. Additionally, the example code has been released to the public domain (see the separate license for more information).

Table of Contents

Using libgit2

Most of these instructions assume that you're writing an application in C and want to use libgit2 directly. If you're not using C, and you're writing in a different language or platform like .NET, Node.js, or Ruby, then there is probably a "language binding" that you can use to take care of the messy tasks of calling into native code.

But if you do want to use libgit2 directly - because you're building an application in C - then you may be able use an existing binary. There are packages for the vcpkg and conan package managers. And libgit2 is available in Homebrew and most Linux distributions.

However, these versions may be outdated and we recommend using the latest version if possible. Thankfully libgit2 is not hard to compile.

Quick Start

Prerequisites for building libgit2:

  1. CMake, and is recommended to be installed into your PATH.
  2. Python is used by our test framework, and should be installed into your PATH.
  3. C compiler: libgit2 is C90 and should compile on most compilers.
    • Windows: Visual Studio is recommended
    • Mac: Xcode is recommended
    • Unix: gcc or clang is recommended.

Build

  1. Create a build directory beneath the libgit2 source directory, and change into it: mkdir build && cd build
  2. Create the cmake build environment: cmake ..
  3. Build libgit2: cmake --build .

Trouble with these steps? Read our troubleshooting guide. More detailed build guidance is available below.

Getting Help

Chat with us

Getting Help

If you have questions about the library, please be sure to check out the API documentation. If you still have questions, reach out to us on Slack or post a question on StackOverflow (with the libgit2 tag).

Reporting Bugs

Please open a GitHub Issue and include as much information as possible. If possible, provide sample code that illustrates the problem you're seeing. If you're seeing a bug only on a specific repository, please provide a link to it if possible.

We ask that you not open a GitHub Issue for help, only for bug reports.

Reporting Security Issues

Please have a look at SECURITY.md.

What It Can Do

libgit2 provides you with the ability to manage Git repositories in the programming language of your choice. It's used in production to power many applications including GitHub.com, Plastic SCM and Azure DevOps.

It does not aim to replace the git tool or its user-facing commands. Some APIs resemble the plumbing commands as those align closely with the concepts of the Git system, but most commands a user would type are out of scope for this library to implement directly.

The library provides:

  • SHA conversions, formatting and shortening
  • abstracted ODB backend system
  • commit, tag, tree and blob parsing, editing, and write-back
  • tree traversal
  • revision walking
  • index file (staging area) manipulation
  • reference management (including packed references)
  • config file management
  • high level repository management
  • thread safety and reentrancy
  • descriptive and detailed error messages
  • ...and more (over 175 different API calls)

As libgit2 is purely a consumer of the Git system, we have to adjust to changes made upstream. This has two major consequences:

  • Some changes may require us to change provided interfaces. While we try to implement functions in a generic way so that no future changes are required, we cannot promise a completely stable API.
  • As we have to keep up with changes in behavior made upstream, we may lag behind in some areas. We usually to document these incompatibilities in our issue tracker with the label "git change".

Optional dependencies

While the library provides git functionality without the need for dependencies, it can make use of a few libraries to add to it:

  • pthreads (non-Windows) to enable threadsafe access as well as multi-threaded pack generation
  • OpenSSL (non-Windows) to talk over HTTPS and provide the SHA-1 functions
  • LibSSH2 to enable the SSH transport
  • iconv (OSX) to handle the HFS+ path encoding peculiarities

Initialization

The library needs to keep track of some global state. Call

git_libgit2_init();

before calling any other libgit2 functions. You can call this function many times. A matching number of calls to

git_libgit2_shutdown();

will free the resources. Note that if you have worker threads, you should call git_libgit2_shutdown after those threads have exited. If you require assistance coordinating this, simply have the worker threads call git_libgit2_init at startup and git_libgit2_shutdown at shutdown.

Threading

See threading for information

Conventions

See conventions for an overview of the external and internal API/coding conventions we use.

Building libgit2 - Using CMake

Building

libgit2 builds cleanly on most platforms without any external dependencies. Under Unix-like systems, like Linux, *BSD and Mac OS X, libgit2 expects pthreads to be available; they should be installed by default on all systems. Under Windows, libgit2 uses the native Windows API for threading.

The libgit2 library is built using CMake (version 2.8 or newer) on all platforms.

On most systems you can build the library using the following commands

$ mkdir build && cd build
$ cmake ..
$ cmake --build .

Alternatively you can point the CMake GUI tool to the CMakeLists.txt file and generate platform specific build project or IDE workspace.

If you're not familiar with CMake, a more detailed explanation may be helpful.

Running Tests

Once built, you can run the tests from the build directory with the command

$ ctest -V

Alternatively you can run the test suite directly using,

$ ./libgit2_tests

Invoking the test suite directly is useful because it allows you to execute individual tests, or groups of tests using the -s flag. For example, to run the index tests:

$ ./libgit2_tests -sindex

To run a single test named index::racy::diff, which corresponds to the test function test_index_racy__diff:

$ ./libgit2_tests -sindex::racy::diff

The test suite will print a . for every passing test, and an F for any failing test. An S indicates that a test was skipped because it is not applicable to your platform or is particularly expensive.

Note: There should be no failing tests when you build an unmodified source tree from a release, or from the main branch. Please contact us or open an issue if you see test failures.

Installation

To install the library you can specify the install prefix by setting:

$ cmake .. -DCMAKE_INSTALL_PREFIX=/install/prefix
$ cmake --build . --target install

Advanced Usage

For more advanced use or questions about CMake please read https://cmake.org/Wiki/CMake_FAQ.

The following CMake variables are declared:

  • CMAKE_INSTALL_BINDIR: Where to install binaries to.
  • CMAKE_INSTALL_LIBDIR: Where to install libraries to.
  • CMAKE_INSTALL_INCLUDEDIR: Where to install headers to.
  • BUILD_SHARED_LIBS: Build libgit2 as a Shared Library (defaults to ON)
  • BUILD_TESTS: Build the unit and integration test suites (defaults to ON)
  • USE_THREADS: Build libgit2 with threading support (defaults to ON)

To list all build options and their current value, you can do the following:

# Create and set up a build directory
$ mkdir build
$ cmake ..
# List all build options and their values
$ cmake -L

Compiler and linker options

CMake lets you specify a few variables to control the behavior of the compiler and linker. These flags are rarely used but can be useful for 64-bit to 32-bit cross-compilation.

  • CMAKE_C_FLAGS: Set your own compiler flags
  • CMAKE_FIND_ROOT_PATH: Override the search path for libraries
  • ZLIB_LIBRARY, OPENSSL_SSL_LIBRARY AND OPENSSL_CRYPTO_LIBRARY: Tell CMake where to find those specific libraries
  • LINK_WITH_STATIC_LIBRARIES: Link only with static versions of system libraries

MacOS X

If you want to build a universal binary for Mac OS X, CMake sets it all up for you if you use -DCMAKE_OSX_ARCHITECTURES="i386;x86_64" when configuring.

Android

Extract toolchain from NDK using, make-standalone-toolchain.sh script. Optionally, crosscompile and install OpenSSL inside of it. Then create CMake toolchain file that configures paths to your crosscompiler (substitute {PATH} with full path to the toolchain):

SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION Android)

SET(CMAKE_C_COMPILER   {PATH}/bin/arm-linux-androideabi-gcc)
SET(CMAKE_CXX_COMPILER {PATH}/bin/arm-linux-androideabi-g++)
SET(CMAKE_FIND_ROOT_PATH {PATH}/sysroot/)

SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

Add -DCMAKE_TOOLCHAIN_FILE={pathToToolchainFile} to cmake command when configuring.

MinGW

If you want to build the library in MinGW environment with SSH support enabled, you may need to pass -DCMAKE_LIBRARY_PATH="${MINGW_PREFIX}/${MINGW_CHOST}/lib/" flag to CMake when configuring. This is because CMake cannot find the Win32 libraries in MinGW folders by default and you might see an error message stating that CMake could not resolve ws2_32 library during configuration.

Another option would be to install msys2-w32api-runtime package before configuring. This package installs the Win32 libraries into /usr/lib folder which is by default recognized as the library path by CMake. Please note though that this package is meant for MSYS subsystem which is different from MinGW.

Language Bindings

Here are the bindings to libgit2 that are currently available:

If you start another language binding to libgit2, please let us know so we can add it to the list.

How Can I Contribute?

We welcome new contributors! We have a number of issues marked as "up for grabs" and "easy fix" that are good places to jump in and get started. There's much more detailed information in our list of outstanding projects.

Please be sure to check the contribution guidelines to understand our workflow, and the libgit2 coding conventions.

License

libgit2 is under GPL2 with linking exception. This means you can link to and use the library from any program, proprietary or open source; paid or gratis. However, if you modify libgit2 itself, you must distribute the source to your modified version of libgit2.

See the COPYING file for the full license text.

libgit2sharp's People

Contributors

aarnott avatar aimeast avatar anaisbetts avatar ben avatar bording avatar carlosmn avatar dahlbyk avatar ethomson avatar fbezdeka avatar jairbubbles avatar jamill avatar jcansdale avatar jpaulduncan avatar martinwoodward avatar mminns avatar niik avatar nulltoken avatar phkelley avatar saaman avatar sharwell avatar shiftkey avatar someoneigna avatar stijn-rutten avatar tclem avatar therzok avatar thomasbarnekow avatar tmat avatar txdv avatar yogu avatar yorah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libgit2sharp's Issues

Error when reading commits for some git repositories

Repro steps:

  1. clone this project (libgit2) locally
  2. Write the following code:
var r = new Repository(@"C:\dev\github\libgit2sharp\.git");
foreach (var c in r.Commits.ToList()) {
    Console.WriteLine(c);
}

It blows up with:

Unhandled Exception: System.ApplicationException: An error was raised by libgit2
. Error code = GIT_EOBJCORRUPTED (-28).
An error occured
   at LibGit2Sharp.Core.Ensure.Success(Int32 result, Boolean allowPositiveResult
)
   at LibGit2Sharp.Repository.Lookup(ObjectId id, GitObjectType type)
   at LibGit2Sharp.RepositoryExtensions.Lookup[T](Repository repository, ObjectI
d id)
   at LibGit2Sharp.CommitCollection.CommitEnumerator.get_Current()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

Tracked branch details

Proposal to add the following to Branch:

  • bool IsTracking { get; }
  • Branch TrackedBranch { get; }
  • int AheadBy { get; }
  • int BehindBy { get; }

Which would satisfy the following:

Branch branch = repo.Branches["test"];
branch.IsTracking.ShouldBeFalse();
branch.TrackedBranch.ShouldBeNull();
branch.AheadBy.ShouldEqual(0);
branch.BehindBy.ShouldEqual(0);

Branch master = repo.Branches["master"];
master.IsTracking.ShouldBeTrue();
master.TrackedBranch.ShouldEqual(repo.Branches["refs/remotes/origin/master"]);
master.AheadBy.ShouldEqual(1);
master.BehindBy.ShouldEqual(2);

(assuming master has one commit origin/master doesn't and origin/master has two commits master doesn't)

Remove pre build events

If we want to allow building on a Mono/Linux platform, the Dos commands in pre/post build events may not play nicely. Maybe should we rather favor a base test class in charge of checking and setting up the test environment.

This base class would be responsible of:

  • Making sure the resource are copied and available to the tests
  • Renaming the "dot_git" folder into ".git" (and replace this piece of code)

time size problem

We have a big freaking problem.
time_t on 32bit linbux is 32bits long and you are using long, I guess, 64bit windows?
I think it is generally 64bit long on windows.
It is possible to determine the environment on runtime and do a workaround, but I first have to know how long it time_t on windows 32bit is.

Question: How to Index.Remove() already deleted files

Hi @ALL,

lets say we have the following workflow:

  1. Adding a file to the repository
  2. Commit
  3. The file will be deleted in the working copy (not with Index.Remove())
  4. How to get the repository in sync with the current working copy?

If you call Index.Remove() on an already deleted file you will get an exception.

I made some changes but my changes will result in some failing tests afterwards... So... How to remove an already deleted file?

[Update]
The above mentioned changes can be seen here

Add .gitattributes definition

This would help ensuring that LF line endings are being committed into the repository without compelling the contributors to change their local configuration.

Listing commits for an empty repository throws a null reference exception

Repro steps:

Create a new git repository:

mkdir folder
cd folder
git init

Create a repository instance and try to list commits.

var repo = new Repository(@"C:\dev\folder\.git");
foreach (var c in repo.Commits) {
    Console.WriteLine(c.Id);
}

Expected:

Empty commit collection

Actual:

Null reference exception

I actually dug a little deeper into why it throws. It seems that this line throws (CommitCollection.StartingAt):

return new CommitCollection(repo) { sortOptions = sortOptions, pushedSha =   reference.ResolveToDirectReference().Target.Sha };

ResolveToDirectReference() returns null since the reference is the head which doesn't point to any commits by default.

mono dllimport compatibility

        [DllImport(libgit2)]
        public static extern int git_reference_listall(git_strarray* array, RepositorySafeHandle repo, GitReferenceType flags);

        [DllImport(libgit2)]
        public static extern int git_tag_list(git_strarray* array, RepositorySafeHandle repo);

        [DllImport(libgit2)]
        public static extern void git_strarray_free(git_strarray* array);

Consider changing "git_starray*" "out git_strarray". This will make libgit2sharp run on mono 2.8+.

No way to get tree object

There is empty Tree class, and no bindings in native methods. Let me implement this feature by myself.

Bug: Index.Unstage()

Hi everyone,

I think you have a bug in your Index.Unstage() implementation.

The Unstage method will call Index.RestorePotentialPreviousVersionOf() which will call AddToIndex().

I think this is not what you want.

Regards.

Clean clone and build has errors.

I cloned libgit2sharp and ran runbuild.cmd and I get the following error:

 C:\dev\github\libgit2sharp\Lib\NUnit\nunit-console.exe /nologo C:\dev\github\
  libgit2sharp\build\LibGit2Sharp.Tests.dll /xml=C:\dev\github\libgit2sharp\bui
  ld\Test-result.xml
  ProcessModel: Default    DomainUsage: Single
  Execution Runtime: Default
  Unhandled Exception:
  System.BadImageFormatException: Could not load file or assembly 'LibGit2Sharp
  .Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its
  dependencies. An attempt was made to load a program with an incorrect format.
  File name: 'LibGit2Sharp.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyTo
  ken=null'

  Server stack trace:
     at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBas
  e, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMar
  k, Boolean throwOnFileNotFound, Boolean forIntrospection)
     at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evide
  nce assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
     at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
     at NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
     at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Bool
  ean autoSuites)
     at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Stri
  ng testName, Boolean autoSuites)
     at NUnit.Core.TestSuiteBuilder.BuildSingleAssembly(TestPackage package)
     at NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
     at NUnit.Core.SimpleTestRunner.Load(TestPackage package)
     at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
     at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
     at NUnit.Core.RemoteTestRunner.Load(TestPackage package)
     at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessa
  ge(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecute
  InContext, Object[]& outArgs)
     at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(I
  Message msg, Int32 methodPtr, Boolean fExecuteInContext)

  Exception rethrown at [0]:
     at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)
     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& ms
  gData, Int32 type)
     at NUnit.Core.TestRunner.Load(TestPackage package)
     at NUnit.Util.TestDomain.Load(TestPackage package)
     at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
     at NUnit.ConsoleRunner.Runner.Main(String[] args)

  WRN: Assembly binding logging is turned OFF.
  To enable assembly bind failure logging, set the registry value [HKLM\Softwar
  e\Microsoft\Fusion!EnableLog] (DWORD) to 1.
  Note: There is some performance penalty associated with assembly bind failure
   logging.
  To turn this feature off, remove the registry value [HKLM\Software\Microsoft\
  Fusion!EnableLog].

C:\dev\github\libgit2sharp\CI-build.msbuild(31,5): error MSB6006: "nunit-console.exe" exited with code -100.

Am I missing anything obvious?

POSIX Path Handling

Currently POSIX path handling is not consistent across various APIs. For example, paths passed into and returned from the index are still in POSIX.

I have two changes in mind that might help with this:

  • A PosixPath class with implicit cast to/from string to make explicit where the path must be in POSIX
  • A PosixMarshaler (likely a subclass of Utf8Marshaler) to let the appropriate NativeMethods use PosixPath

Thoughts?

Support for server side smart HTTP

Hi,

I plan to use libgit2sharp in the backend to serve bare git repositories. The idea is to allow clients to do clone requests from the server using smart http. Is this supported with this library? If so what would the code look like?

Upgrade to Nuget 1.5

As stated by @davidebbo and @davidfowl

Earlier versions of ‘nuget pack’ built the solution, while the newer ones expect it to be built already

If you want to build the package from a project and have it build then you have to use the -build switch. Alternatively, you can use >the new workflow to build a package from a project:

  • Install-Package NuGetPowerTools
  • Enable-PackageBuild ProjectName

That will setup your project to build a package as well as well as a symbols package on build.

Correct usage of the using statement should be documented

Hi,

I have an example listed below. Can you see any problem from it?

    public IEnumerable<string> GetRefs()
    {
        var tempFolder = ".....";

        using (var repository = new LibGit2Sharp.Repository(tempFolder))
        {
            return from r in repository.Refs
                       select r.CanonicalName;
        }
    }

    [TestMethod()]
    public void GetRefsTest()
    {
        var refs = GetRefs();
        foreach (var r in refs)
        {
            Console.WriteLine(r);
        }
    }

The test method GetRefsTest will throw exception: System.ObjectDisposedException: Safe handle has been closed.

Regards,

yysun

Implement reference moving

Bind libgit2's methods

GIT_EXTERN(int) git_reference_rename(git_reference *ref, const char *new_name);

GIT_EXTERN(int) git_reference_rename_f(git_reference *ref, const char *new_name);

Add following method to ReferenceCollection

public Reference Move(string oldName, string newName, bool allowOverwrite = false);

Provide default value for non existent configuration setting

Currently LibGIt2Sharp throws when reading from a non existent configuration setting

Proposal is to make the following tests pass:

Assert.AreEqual("tclem rulz", repo.Config.Get<string>("unittests.ghostsetting", "tclem rulz"));
Assert.AreEqual(true, repo.Config.Get<bool>("unittests.ghostsetting", true));
Assert.AreEqual(42, repo.Config.Get<int>("unittests.ghostsetting"), 42);
Assert.AreEqual(17, repo.Config.Get<long>("unittests.ghostsetting"), 17);

Proper pull, fetch, merge support

Currently there doesn't seem to be a way to do a pull, or even a separate fetch-merge operation. Will be nice, and quite useful, to have this...

Split the Library into Two

I saw on the Wiki page that the design goal of LitGit2Sharp is to provider a high level wrapper to, but not be a 1:1 mapping of the libgit2 C API. I would like to suggest you split the LitGit2Sharp into two libraries. One only contains P-Invoke functions and unsafe helpers. The other one for high level wrappers.

Alternatively, maybe you can make P-Invoke functions and unsafe helpers public, so that we can call them directly.

Thanks,

yysun

Automatically try open path + "/.git"

Is it possible in the constructor of Repository if repo not found on given path, automatically try path + "/.git", and then path + ".git", maybe even parent directories, before throw exception?

thanks,

yysun

Configuration tests assumes global config located in MyDocuments folder

It is not exactly an issue, just small inconvenience in checking test greenness.

I have user's environment variable HOME and my global .gitconfig is located there. libgit2 correctly determines that and Configuration.Set writes values there. On the contrary ConfigurationFixture.CanSetGlobalStringValue test assumes that global settings are located at Environment.SpecialFolder.MyDocuments folder and thus gives false fail (and strange file c:\Users\idanilov\.gitconfig as a result).

Implement tag and reference overwriting

Bind libgit2's methods

GIT_EXTERN(int) git_tag_create_f(
        git_oid *oid,
        git_repository *repo,
        const char *tag_name,
        const git_oid *target,
        git_otype target_type,
        const git_signature *tagger,
        const char *message);

GIT_EXTERN(int) git_reference_create_oid_f(git_reference **ref_out, 
                         git_repository *repo, const char *name, const git_oid *id);

GIT_EXTERN(int) git_reference_create_symbolic_f(git_reference **ref_out, 
                        git_repository *repo, const char *name, const char *target);

Change signature of the Create() methods of TagCollection into

public Tag Create(string name, string target, Signature tagger, 
             string message, bool allowOverwrite = false);

public Tag Create(string name, string target, bool allowOverwrite = false);

Change signature of the Create() methods of RefCollection into

public Reference Create(string name, string target, bool allowOverwrite = false);

public Reference Create(string name, ObjectId target, bool allowOverwrite = false);

How to implement the equivalent of "git status"

I'm trying to figure out how I'd implement the equivalent of git status using libgit2sharp. All of the collections on Index (Modified, Staged, Unstaged) all throw NotImplementedException. When there are files in the index, it seems like they are always in the "NotModified" state.

Am I missing something or is the functionality not there yet?

Repository.Init doesn't create a config file

When calling Repository.Init, it does not create a .git/config file. This seems to throw off some git client. For instance, it causes GitSharp to fail when trying to open the repo.

Looking in more details, it looks like the minimal settings that makes GitSharp happy is:

[core] repositoryformatversion = 0

Should libgit2sharp be creating the config file when creating the repo?

Lazy Load

In the constructor of Repository, commits, branches, refs and tags are all loaded. In my case it makes LibGit2Sharp 4x slower than GitSharp. Please consider apply lazy loading everywhere to load data only needed. e.g.

    public ReferenceCollection Refs
    {
        get 
        {
                if (refs==null) refs = new ReferenceCollection(this); 
                return refs; 
        }
    }

Listed below is the test case.

    [TestMethod()]
    public void RefsTest()
    {
        var tempFolder = ".......";

        Stopwatch w = new Stopwatch();
        w.Start();

        for (int i = 0; i < 5000; i++)
        {
            var repository = new LibGit2Sharp.Repository(tempFolder);

            foreach (var r in repository.Refs)
            {
                var k = r.CanonicalName;
            }
            repository.Dispose();
        }

        w.Stop();
        Console.WriteLine("Time elapsed: {0}", w.Elapsed);
    }

Thanks,

yysun

trying to run the test project

Error 1 The command "xcopy "L:\Data\SeaRisen\Code\C#\C#Lib\libgit2-libgit2sharp-v0.2.0-7\LibGit2Sharp.Tests\Resources*.*" "L:\Data\SeaRisen\Code\C#\C#Lib\libgit2-libgit2sharp-v0.2.0-7\LibGit2Sharp.Tests\bin\Debug\Resources" /E /I /Y /F /H > NUL" exited with code 4. LibGit2Sharp.Tests

There is no LibGit2Sharp.Tests\Resources folder included in the source.

Exception when enumerating remote branches

For a repository with remote branches, enumerating repository.Branches throws:

System.ArgumentException : 'refs/remotes/origin/master' is not a valid Sha-1.
    ObjectId.cs(57,0): at LibGit2Sharp.ObjectId..ctor(String sha)
    Reference.cs(73,0): at LibGit2Sharp.Reference.BuildFromPtr[T](IntPtr ptr, Repository repo)
    ReferenceCollection.cs(163,0): at LibGit2Sharp.ReferenceCollection.Resolve[T](String name)
    BranchCollection.cs(31,0): at LibGit2Sharp.BranchCollection.get_Item(String name)
    BranchCollection.cs(44,0): at LibGit2Sharp.BranchCollection.<GetEnumerator>b__0(String n)
    at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()

I'm working on a patch.

Use File.PathSeperator and Path.Combine instead of hardcoded paths

Hardcoded paths containing the file seperators are considered bad!
The PathSeperator on Windows and Unix differ and since there is already functionality in the .NET framework itself solving this problem -> we should be utilizing that functionality to make it platform independent.

Hardcoded paths containing \ are so yesterday :P
The kewl libs nowadays use Path.Combine.

Repository ctor should be able to handle working folder

One thing I find a bit quirky is that if your repo is in c:\foo, then you have to pass "c:\foo.git" when creating a Repository. Would it make sense to add some smart to the Repository ctor to handle both cases? The .git folder is sort of a git implementation detail that the API consumer should not have to deal with.

The logic would all be in LibGit2Sharp and not affect LibGit2. Could be as simple as saying that if the passed in folder contains a .git folder, then use that instead. And if it's that simple, I'll sign up to do it :)

Getting Started

I've successfully created a Repository:

UriAgility gitUri = UriAgility.Parse("~/App_Data/SCommunity/wikiRepo/.git");
if (!gitUri.FileInfo.Directory.Exists)
Repository.Init(gitUri.FileInfo.DirectoryName);

using (var repo = new Repository(gitUri.PhysicalPath))
{
HttpContext.Current.Response.Write(string.Format("Working directory: {0}
", repo.Info.WorkingDirectory));
HttpContext.Current.Response.Write(string.Format("Repository path: {0}
", repo.Info.Path));

...
What do I put here to Add file to the repository?
What do I do to get the file once it is in?
How do I get the diff between versions?
...
}

Configuration reader can't read symbollically linked file

I'm running Windows 7 x64.

I'm unable to retrieve any configuration settings from the Configuration object when my .gitconfig is a symbolic link (made from mklink). Otherwise it works fine.

Great work so far on the project, nice clean API. Can't wait for pull/push implementation! :)

Cheers,
Thiru

Publish source and PDBs at symbolsource.org

LibGIt2Sharp is published as a NuGet package. In order to ease the consumer debugging experience, sources and pdbs should be published at symbolsource.org.

For further information, refer to

  • @davidebbo's post
  • This thread which gives some hints about the expected symbolsource package structure

Building on top on nulltoken/libgit2sharp@e12b358, running build.nuget.package.cmd should produce the symbolsource package as well.

Unable to load DLL 'git2': The specified module could not be found

This is a cross post from http://stackoverflow.com/questions/6313203/unable-to-load-dll-git2-dll-the-specified-module-could-not-be-found/6315033#6315033

I'm using VS2008 and had to create a new solution since the solution and csharp files are .Net 4.0. As far as I could tell its just default parameters that I had to create overloaded methods to handle them to convert to 3.5.

I've copied the git2.dll into every bin folder and have linked it and set copy if newer, but still get the "Unable to load DLL 'git2'" error for

Repository.cs
Line 27: var res = NativeMethods.git_repository_open(out handle, PosixPathHelper.ToPosix(path));

I'm trying to use the library in a ASP.NET website via a custom-controls library.

Thread safety

Hello,

i´m using the libgit2sharp in a multithreaded win32 application. Two days ago i got some strange application behavior. My App crashed with error Code "0xC0000417" (STATUS_INVALID_CRUNTIME_PARAMETER). And it took me some time to track down the source of this error. It was caused by a threaded access to libgit2sharp.
To solve this error i built my own libgit2 dll (git2.dll) with enabled THREADSAFE flag and used this dll to rebuild the libgit2sharp dll.

Is it the case that the shipped git2.dll is build without the THREADSAFE flag ?

Can't Stage a Full Path

I would like to stage a file with a full path. I have a failing test showing this doesn't work (cbilson/libgit2sharp@d849ca7b93538d85cc4a). I thought maybe using the posix helper on the path would fix it (cbilson/libgit2sharp@aae13a51b75d98a20b5c), but it didn't.

Any ideas? Should I just not try to do this? Thanks!

DateTime of Commit

Hi.

I'm missing a Date/Time Property on the Commit class. There's the git_commit_time in libgit2 but it seems The libgit2sharp binding doesn't make any use of it. Or is there another special way to get the DateTime when a commit was added to the repository?

Greetings
Daniel

Tags are recognized as commits

Hi! I've found a strange issue. Enumerating tag in repository git://github.com/spdr870/gitextensions.git gives 81 nulls and 1 real tag. All other tags are visible in repo.Refs as commits.

Code to list tags:

        const string path = @"x:/git/ge/.git";
        using (var repo = new Repository(path))
        {
            int found = 0;
            foreach (var tag in repo.Tags.Where(t => t != null))
            {
                Console.WriteLine(tag.Name);
                found++;
            }

            Console.WriteLine("Found {0} of {1} tags.",found, repo.Tags.Count());

        }

sample code is available here - [email protected]:gorbach/libgit2sharp.git (branch git-log)

Of git log --all and corner cases

@projectkudu relies on git log --all to page through the commits. A very first draft implementation is available with PR #61.

Notable new usages are covered there:

  • CanEnumerateCommitsFromMixedStartingPoints
  • CanEnumerateCommitsFromATag
  • CanEnumerateAllCommits

I'd like to make this feature available for the next release (v0.5). However in order to be as complete as possible I'd like some feedback about how should the feature react when dealing with the following:

  • A reference which points to an objectId/Sha which doesn't exist in the repository
  • A tag which points to a tree or a blob

@davidfowl, @davidebbo, @tclem, @xpaulbettsx, @henon Should this throw? Should this be detected as a weirdo use case and silently ignored? Can you think of other strange configurations that should be dealt with?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.