libgit2 / libgit2/libgit2sharp

LibGit2SharpException: can only merge a single branch

Aberta
#1,800 1 comentário 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Linguagem predominante
C#
Estrelas
3.5k
Forks
925
Métricas de merge de PRs
Nenhum PR com merge em 30d

Descrição

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.

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece pelo método GitRepository.Pull fornecido e sua chamada a Commands.Pull(repo, signature, options), depois inspecione como PullOptions e MergeOptions lidam com o repositório de branch único descrito. Reproduza a LibGit2SharpException com o código fornecido e determine o comportamento esperado para esse repositório; o trabalho estará concluído quando a falha for resolvida ou seu requisito de uso for claramente estabelecido.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
csharp, git
Domínio
tooling
Tipo de issue
Bug
Dificuldade
4/5
Tempo estimado
3-5 dias
Status de atividade
Estagnada
Clareza
Precisa de esclarecimento
Facilidade para iniciantes
18/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.