libgit2 / libgit2/libgit2sharp

LibGit2SharpException: can only merge a single branch

オープン
#1,800 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
C#
スター
3.5k
フォーク
925
PR マージ指標
30日以内にマージされた PR はありません

説明

Reproduction steps

Simply use this code:

using LibGit2Sharp;
using LibGit2Sharp.Handlers;
using System;
using System.IO;

namespace WebApi1.Git
{
    public class GitRepository
    {
        private readonly string username;
        private readonly string password;
        private readonly string repositoryUrl;
        private readonly string name;
        private readonly string email;
        private string path;

        public GitRepository(string username, string password, string repositoryUrl, string path, string name, string email)
        {
            this.username = username;
            this.password = password;
            this.repositoryUrl = repositoryUrl;
            this.name = name;
            this.email = email;
            this.path = path;
        }

        public bool IsCloned => Directory.Exists(this.path);

        public bool IsChanged => !string.IsNullOrEmpty(this.Diff());

        public string Diff()
        {
            if (!this.IsCloned)
            {
                throw new InvalidOperationException("Respository not cloned.");
            }

            var result = string.Empty;
            using (var repo = new Repository(this.path))
            {
                foreach (var c in repo.Diff.Compare<TreeChanges>())
                {
                    result += c;
                }
            }

            return result;
        }

        public void Clone()
        {
            if (this.IsCloned)
            {
                throw new InvalidOperationException("Repository already cloned.");
            }

            var co = new CloneOptions
            {
                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = this.username, Password = this.password },
                RecurseSubmodules = true,
            };
            this.path = Repository.Clone(this.repositoryUrl, this.path, co);
        }

        public void Push()
        {
            if (!this.IsCloned)
            {
                throw new InvalidOperationException("Respository not cloned.");
            }

            using (var repo = new Repository(this.path))
            {
                var remote = repo.Network.Remotes["origin"];
                var options = new PushOptions
                {
                    CredentialsProvider = (_url, _user, _cred) =>
                        new UsernamePasswordCredentials { Username = this.username, Password = this.password }
                };
                repo.Network.Push(remote, @"refs/heads/master", options);
            }
        }

        public void Add()
        {
            if (!this.IsCloned)
            {
                throw new InvalidOperationException("Respository not cloned.");
            }

            using (var repo = new Repository(this.path))
            {
                Commands.Stage(repo, $"{this.path}\\*");
            }
        }

        public void Pull()
        {
            if (!this.IsCloned)
            {
                throw new InvalidOperationException("Respository not cloned.");
            }

            using (var repo = new Repository(this.path))
            {
                // Credential information to fetch
                var options = new PullOptions
                {
                    FetchOptions = new FetchOptions
                    {
                        CredentialsProvider = new CredentialsHandler(
                    (url, usernameFromUrl, types) =>
                        new UsernamePasswordCredentials()
                        {
                            Username = this.username,
                            Password = this.password,
                        })
                    },
                    MergeOptions = new MergeOptions
                    {
                        FastForwardStrategy = FastForwardStrategy.FastForwardOnly,
                    },
                };

                // User information to create a merge commit
                var signature = new Signature(
                    new Identity(this.name, this.email), DateTimeOffset.UtcNow);

                // Pull
                Commands.Pull(repo, signature, options);
            }
        }

        public void Commit()
        {
            if (this.IsCloned)
            {
                throw new InvalidOperationException("Respository not cloned.");
            }

            using (var repo = new Repository(this.path))
            {
                // Create the committer's signature and commit
                var author = new Signature(this.name, this.email, DateTime.UtcNow);
                var committer = author;

                // Commit to the repository
                _ = repo.Commit("Updated files.", author, committer);
            }
        }
    }
}

And use this in place of api's in System.IO.File:

using System;
using System.IO;
using System.Text;
using WebApi1.Git;

namespace WebApi1.File
{
    /// <summary>
    /// A clone of System.IO.File that actually allows using symlinks.
    ///
    /// Use this in place of System.IO.File if you want to support symlinks
    /// without overwriting the actual symlink data with the actual file content.
    ///
    /// While the normal .net System.IO.File actually gets the real content from the symlinks,
    /// when saving however the symlink itself gets overwritten which is bad design.
    /// </summary>
    public static class File
    {
        private static readonly GitRepository repo = new GitRepository(
            "[username]",
            "[access token]",
            "[repository with only a single branch.]",
            $"[path inside the current directory of the process that git would normally clone into]",
            "[username again]",
            "[github's noreply email that it gives to you.]");

        /// <summary>
        /// Deletes the actual file and the symlink file.
        /// </summary>
        public static void Delete(string path)
        {
            if (Exists(path))
            {
                var contentText = System.IO.File.ReadAllText(path);
                if (contentText.Contains("symlink: ", StringComparison.Ordinal))
                {
                    contentText = contentText.Substring("symlink: ".Length);
                    if (System.IO.File.Exists(contentText))
                    {
                        System.IO.File.Delete(contentText);
                        System.IO.File.Delete(path);
                    }
                    if (contentText.StartsWith("content", StringComparison.Ordinal))
                    {
                        repo.Add();
                        repo.Commit();
                        repo.Push();
                    }
                }
                else
                {
                    System.IO.File.Delete(path);
                }
            }
        }

        /// <summary>
        /// Checks if the file pointed by the symlink actually exists.
        /// <see langword="false"/> if the symlink file does not exists, or if
        /// the path does not point to a symlink and does not exist, <see langword="true"/> otherwise.
        /// </summary>
        public static bool Exists(string path)
        {
            var result = false;
            if (System.IO.File.Exists(path))
            {
                var contentText = System.IO.File.ReadAllText(path);
                if (contentText.Contains("symlink: ", StringComparison.Ordinal))
                {
                    contentText = contentText.Substring("symlink: ".Length);
                    if (contentText.StartsWith("content", StringComparison.Ordinal) && !Directory.Exists("content"))
                    {
                        repo.Clone();
                    }
                    else if (contentText.StartsWith("content", StringComparison.Ordinal))
                    {
                        if (repo.IsChanged)
                        {
                            repo.Add();
                            repo.Commit();
                            repo.Push();
                        }

                        repo.Pull();
                    }

                    result = System.IO.File.Exists(contentText);
                }
                else
                {
                    result = true;
                }
            }

            return result;
        }

        /// <summary>
        /// Reads all of the bytes inside the symlinked file,
        /// if the file is not symlinked then it returns the bytes
        /// from the original path.
        /// </summary>
        public static byte[] ReadAllBytes(string path)
        {
            var contentText = System.IO.File.ReadAllText(path);
            if (contentText.Contains("symlink: ", StringComparison.Ordinal))
            {
                contentText = contentText.Substring("symlink: ".Length);
                return System.IO.File.ReadAllBytes(contentText);
            }
            else
            {
                return System.IO.File.ReadAllBytes(path);
            }
        }

        /// <summary>
        /// Reads all of the text inside the symlinked file,
        /// if the file is not symlinked then it returns the content
        /// from the original path.
        /// </summary>
        public static string ReadAllText(string path)
        {
            if (Exists(path) || !Exists(path))
            {
                var contentText = System.IO.File.ReadAllText(path);
                if (contentText.Contains("symlink: ", StringComparison.Ordinal))
                {
                    contentText = contentText.Substring("symlink: ".Length);
                    return System.IO.File.ReadAllText(contentText);
                }
                else
                {
                    return System.IO.File.ReadAllText(path);
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// Reads all of the text inside the symlinked file,
        /// if the file is not symlinked then it returns the content
        /// from the original path with the specified encoding.
        /// </summary>
        public static string ReadAllText(string path, Encoding encoding)
        {
            if (Exists(path) || !Exists(path))
            {
                var contentText = System.IO.File.ReadAllText(path);
                if (contentText.Contains("symlink: ", StringComparison.Ordinal))
                {
                    contentText = contentText.Substring("symlink: ".Length);
                    return System.IO.File.ReadAllText(contentText, encoding);
                }
                else
                {
                    return System.IO.File.ReadAllText(path, encoding);
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// Writes the contents to the symlinked file,
        /// if the file is not symlinked then it is written to
        /// the file from the original path.
        /// </summary>
        public static void WriteAllText(string path, string contents)
        {
            if (Exists(path))
            {
                var contentText = System.IO.File.ReadAllText(path);
                if (contentText.Contains("symlink: ", StringComparison.Ordinal))
                {
                    contentText = contentText.Substring("symlink: ".Length);
                    var oldContents = System.IO.File.ReadAllText(contentText);
                    System.IO.File.WriteAllText(contentText, contents);

                    // to avoid issues later with making empty commits.
                    if (contentText.StartsWith("content", StringComparison.Ordinal) && !oldContents.Equals(contents, StringComparison.Ordinal))
                    {
                        repo.Add();
                        repo.Commit();
                        repo.Push();
                    }
                }
                else
                {
                    System.IO.File.WriteAllText(path, contents);
                }
            }
            else
            {
                System.IO.File.WriteAllText(path, contents);
            }
        }
    }
}

Now try to have it open up a file which is a hacked together fake symlink to the real file in a separate git repository that in turn is on github.
You should be able to notice this exception even if it is already up to date.

Expected behavior

For the repository to be pulled to latest changes (like how we can git pull --ff-only in normal git)

Actual behavior
LibGit2SharpException: can only merge a single branch   at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
   at LibGit2Sharp.Repository.Merge(AnnotatedCommitHandle[] annotatedCommits, Signature merger, MergeOptions options)
   at LibGit2Sharp.Repository.MergeFetchedRefs(Signature merger, MergeOptions options)
   at WebApi1.Git.GitRepository.Pull()
   at WebApi1.File.File.Exists(String path)
   at WebApi1.File.File.ReadAllText(String path)
   at WebApi1.Patreon.Controllers.PatreonPledgesController.<GetMainPage>b__10_0()
   at WebApi1.Tasks.TaskHelpers.HelperAction[TResult](Func`1 function)
Version of LibGit2Sharp (release number or SHA1)

Latest on NuGet.org.

Operating system(s) tested; .NET runtime tested

Windows 10 x64 Latest fast ring insider preview; .NET Core 3.1 running ASP.NET.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

提供された GitRepository.Pull メソッドとその Commands.Pull(repo, signature, options) 呼び出しから始め、次に PullOptions と MergeOptions が、説明されている単一ブランチのリポジトリをどのように扱うかを調べます。提供されたコードで LibGit2SharpException を再現し、そのリポジトリで期待される動作を特定します。失敗が解決されるか、その使用要件が明確に確立されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
csharp, git
領域
tooling
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
18/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。