• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# LibGit2Sharp.Repository类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中LibGit2Sharp.Repository的典型用法代码示例。如果您正苦于以下问题:C# Repository类的具体用法?C# Repository怎么用?C# Repository使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Repository类属于LibGit2Sharp命名空间,在下文中一共展示了Repository类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Execute

        public override IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
        {
            var repositoryLocation = Repository.Discover(context.InputFolder);
            if (repositoryLocation == null)
                throw new ArgumentException("No git repository found");

            using (Repository repository = new Repository(repositoryLocation))
            {

                var data = GetCommitInformation(repository);
                var lookup = data.ToLookup(x => x.Path.ToLower());
                return inputs.Select(x =>
                {
                    string relativePath = GetRelativePath(Path.GetDirectoryName(Path.GetDirectoryName(repositoryLocation.ToLower())), x.Source.ToLower()); // yes we need to do it twice
                    if (!lookup.Contains(relativePath))
                        return x;

                    var commitsOfFile = lookup[relativePath]
                        .GroupBy(y => y.Author)
                        .ToDictionary(y => y.Key,
                                    y => y.OrderByDescending(z => z.AuthorDateTime).First())
                        .Select(y => y.Value)
                        .ToArray();

                    return x.Clone(new[]
                    {
                        new KeyValuePair<string, object>(_metadataName, commitsOfFile)
                    });
                }).ToArray(); // Don't do it lazy or Commit is disposed.
            }
        }
开发者ID:st1pps,项目名称:Wyam,代码行数:31,代码来源:GitContributor.cs


示例2: RepositoryWriter

 RepositoryWriter( Repository r, string userName = null, string userEmail = null )
 {
     if( (userEmail == null) != (userName== null ) ) throw new ArgumentException();
     _repo = r;
     _userEmail = userEmail;
     _userName = userName;
 }
开发者ID:SimpleGitVersion,项目名称:SGV-Net,代码行数:7,代码来源:RepositoryWriter.cs


示例3: ContentChanges

 internal ContentChanges(Repository repo, Blob oldBlob, Blob newBlob, GitDiffOptions options)
 {
     Proxy.git_diff_blobs(repo.Handle,
                          oldBlob != null ? oldBlob.Id : null,
                          newBlob != null ? newBlob.Id : null,
                          options, FileCallback, HunkCallback, LineCallback);
 }
开发者ID:kckrinke,项目名称:libgit2sharp,代码行数:7,代码来源:ContentChanges.cs


示例4: PersistentInfo

 public PersistentInfo( Repository r )
     : this()
 {
     if( r == null ) RepositoryError = "No repository.";
     else
     {
         var branch = r.Head;
         if( branch.Tip == null ) RepositoryError = "Unitialized repository.";
         else
         {
             CommitSha = branch.Tip.Sha;
             var repositoryStatus = r.Index.RetrieveStatus();
             IsDirty =  repositoryStatus.Added.Any()
                         || repositoryStatus.Missing.Any()
                         || repositoryStatus.Modified.Any()
                         || repositoryStatus.Removed.Any()
                         || repositoryStatus.Staged.Any();
             ReleasedTag = FindReleasedVersion( r, branch.Tip );
             if( ReleasedTag.IsValid )
             {
                 BranchName = ReleasedTag.BranchName;
             }
             else
             {
                 BranchName = branch.Name;
             }
         }
     }
 }
开发者ID:ismailfatih,项目名称:CK-Stamp,代码行数:29,代码来源:PersistentInfo.cs


示例5: HashWithLibGit2Sharp

 private static string HashWithLibGit2Sharp(Stream file)
 {
     var repository = new Repository(Environment.CurrentDirectory);
     var temp = new FileStream(Path.GetTempFileName(),FileMode.Open);
     file.CopyTo(temp);
     return repository.ObjectDatabase.CreateBlob(temp.Name).Sha.ToString();
 }
开发者ID:EdwinTai,项目名称:git-tfs,代码行数:7,代码来源:HashAndInsertObject.cs


示例6: ObjectDatabase

        internal ObjectDatabase(Repository repo)
        {
            this.repo = repo;
            handle = Proxy.git_repository_odb(repo.Handle);

            repo.RegisterForCleanup(handle);
        }
开发者ID:kckrinke,项目名称:libgit2sharp,代码行数:7,代码来源:ObjectDatabase.cs


示例7: Main

        static void Main(string[] args)
        {
            string ruta = @"C:\Users\developer\Documents\GitHub\libgit2sharp";
            var repo = new Repository(ruta);

            //Listar(repo);
            int numCommits = 0;
            int programadores = 8;
            int años = 2014 - 2010; //desde 2010
            Console.WriteLine("Numero de commits por branch:");

            foreach (var rama in repo.Branches)
            {
                    Console.WriteLine("Rama: " + rama.Name + " tiene " + rama.Commits.Count() + " commits");
                    numCommits += rama.Commits.Count();

            }

            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("\r\nRamas listadas " + repo.Branches.Count());
            Console.WriteLine("Total commits: " + numCommits);
            float lineas = ((numCommits/programadores)/(años*365));

            Console.WriteLine("Lineas media por dia: " + lineas);
            //ObtenerComits(repo);
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.Write("\r\nFin");
            Console.Read();
        }
开发者ID:arkadoel,项目名称:CodigoGitCSharp,代码行数:29,代码来源:Program.cs


示例8: GetConfig

        /// <summary>
        /// Get the git configuration
        /// </summary>
        /// <returns>A Config object.</returns>
        public Config GetConfig()
        {
            //Run at startup, this will create the global repository, only needs to be run once.
            Repository.Init(GlobalGitRepositoryLocation, true);

            //Run at startup, this will create the instance specific clone on the local machine, should be run on every service start.
            //Don't need to do this more than once the first time
            if (!Repository.IsValid(LocalGitRepositoryLocation)) { Repository.Clone(GlobalGitRepositoryLocation, LocalGitRepositoryLocation, new CloneOptions { IsBare = true }); }

            //In application code attempt to use the git repository
            using (var repository = new Repository(LocalGitRepositoryLocation))
            {
                try { repository.Network.Fetch(repository.Network.Remotes[ConfigurationRemote]); } catch { }

                var refOriginMaster = repository.Refs[ConfigurationRemoteRef];
                if (refOriginMaster == null) { return new Config(); }

                var sha = refOriginMaster.TargetIdentifier;

                var configFile = repository.Lookup<Commit>(sha)[GitConfigurationFile];
                if (configFile == null || !(configFile.Target is Blob)) { return new Config(); }

                using (var fileStream = ((Blob)configFile.Target).GetContentStream())
                using (var reader = new StreamReader(fileStream, Encoding.UTF8))
                {
                    var result = reader.ReadToEnd();
                    try { return new JavaScriptSerializer().Deserialize<Config>(result); }
                    catch { return new Config(); }
                }
            }
        }
开发者ID:wparad,项目名称:Microservice,代码行数:35,代码来源:ConfigurationManager.cs


示例9: AddUpdateFile

 public static void AddUpdateFile(string FileName, string RepoPath)
 {
     using (var repo = new Repository(RepoPath))
     {
         repo.Index.Stage(FileName);
     }
 }
开发者ID:jamessantiago,项目名称:jamescms,代码行数:7,代码来源:GitHelper.cs


示例10: btnCommit_Click

        private void btnCommit_Click(object sender, RibbonControlEventArgs e)
        {
            //Get Active  Project
            var pj = Globals.ThisAddIn.Application.ActiveProject;

            //Get Project Filename.
            var projectFile = pj.FullName;

            //Get Directory from File Name
            var directory = Path.GetDirectoryName(projectFile);

            //Create a new Git Repository
            Repository.Init(directory);

            //Open the git repository in a using context so its automatically disposed of.
            using (var repo = new Repository(directory))
            {
                // Stage the file
                repo.Index.Stage(projectFile);

                // Create the committer's signature and commit
                var author = new Signature("Richard", "@ARM", DateTime.Now);
                var committer = author;

                // Commit to the repository
                var commit = repo.Commit("Initial commit", author, committer);
            }
        }
开发者ID:rcookerly,项目名称:ProjectVersionControl,代码行数:28,代码来源:GitRibbon.cs


示例11: TestLibGit2_CreateLocalBranches

 public void TestLibGit2_CreateLocalBranches()
 {
     using (var myRepository = new Repository(@"C:\dev1\Gsx.Monitor.Project"))
     {
         Trace.WriteLine(string.Join("\n", from b in myRepository.Branches select $"{b.FriendlyName}({b.IsRemote})"));
     }
 }
开发者ID:Bhaal22,项目名称:Msbuild.GitCloneTask,代码行数:7,代码来源:VersionResolverTests.cs


示例12: RepositoryBase

 protected RepositoryBase(string path, string repoName, string userName, string password)
 {
     Repository = new Repository(path);
     RepositoryName = repoName;
     UserName = userName;
     Password = password;
 }
开发者ID:TyOverby,项目名称:roslyn,代码行数:7,代码来源:RepositoryBase.cs


示例13: BuildFileHistory

        /// <summary>
        /// Builds the file history from a repository path, file path and the reference to object SysVersionControlTmpItem
        /// </summary>
        /// <param name="repoPath">Repository main path</param>
        /// <param name="filePath">File to be pulling the commits</param>
        /// <param name="tmpItem">Ref to the SysVersionControlTmpItem object to be inserting to</param>
        /// <returns>A SysVersionControlTmpItem filled with the commits</returns>
        public static SysVersionControlTmpItem BuildFileHistory(string repoPath, string filePath, ref SysVersionControlTmpItem tmpItem)
        {
            FileInfo fileInfo = new FileInfo(filePath);

            using (var repo = new Repository(repoPath))
            {
                var indexPath = fileInfo.FullName.Replace(repo.Info.WorkingDirectory, string.Empty);
                var commits = repo.Head.Commits.Where(c => c.Parents.Count() == 1 && c.Tree[indexPath] != null && (c.Parents.FirstOrDefault().Tree[indexPath] == null || c.Tree[indexPath].Target.Id != c.Parents.FirstOrDefault().Tree[indexPath].Target.Id));

                foreach (Commit commit in commits)
                {
                    tmpItem.User = commit.Author.ToString();
                    tmpItem.GTXShaShort = commit.Sha.Substring(0, 7);
                    tmpItem.GTXSha = commit.Sha;
                    tmpItem.Comment = commit.Message;
                    tmpItem.ShortComment = commit.MessageShort;
                    tmpItem.VCSDate = commit.Committer.When.Date;
                    tmpItem.VCSTime = (int)commit.Committer.When.DateTime.TimeOfDay.TotalSeconds;
                    tmpItem.Filename_ = FileGetVersion(repoPath, fileInfo.FullName, commit.Sha, Path.Combine(Path.GetTempPath(), string.Format("{0}_{1}", commit.Sha.Substring(0, 7), fileInfo.Name)));
                    tmpItem.InternalFilename = fileInfo.FullName;
                    tmpItem.ItemPath = indexPath;
                    tmpItem.GTXFileRepoStatus = GetFileStatus(repoPath, fileInfo.FullName);
                    tmpItem.insert();
                }
            }

            return tmpItem;
        }
开发者ID:shoaibcop,项目名称:gitax,代码行数:35,代码来源:GTXRepo.cs


示例14: ChangeBranch

        public void ChangeBranch(RepositoryItem repository, string BranchName)
        {
            var repo = new LibGit2Sharp.Repository(repository.Path);

            var branches = repo.Branches.Where(b => b.Name == BranchName).ToList();
            if (branches.Any())
            {
                var localBranch = branches.FirstOrDefault(x => !x.IsRemote);
                if (localBranch != null)
                {
                    repo.Checkout(localBranch, new CheckoutOptions(), new Signature(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.Now));
                }
                else
                {
                    throw new Exception("You must checkout manually the first time");

                    //COMMENTED THIS OUT AS IT CREATES DUPLICATE REMOTE BRANCHES, For instance R15_Release will duplicate as origin/R15_Release.
                    //Current work around is to get them to check out the branch manually the first time around.

                    //var remoteBranch = branches.FirstOrDefault(x => x.IsRemote);
                    //if (remoteBranch != null)
                    //{
                    //    var newLocalBranch = repo.CreateBranch(BranchName, remoteBranch.Tip);
                    //    newLocalBranch = repo.Branches.Update(newLocalBranch,
                    //        b =>
                    //        {
                    //            b.TrackedBranch = remoteBranch.CanonicalName;
                    //        });
                    //    repo.Checkout(newLocalBranch, new CheckoutOptions(), new Signature(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.Now));
                    //}
                }
            }
        }
开发者ID:BradleySewell,项目名称:GitList,代码行数:33,代码来源:GitManager.cs


示例15: NormalizeGitDirectory

        public static void NormalizeGitDirectory(string gitDirectory, Arguments arguments, string branch = null)
        {
            using (var repo = new Repository(gitDirectory))
            {
                var remote = EnsureOnlyOneRemoteIsDefined(repo);

                AddMissingRefSpecs(repo, remote);

                Logger.WriteInfo(string.Format("Fetching from remote '{0}' using the following refspecs: {1}.",
                    remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))));

                var fetchOptions = BuildFetchOptions(arguments.Username, arguments.Password);
                repo.Network.Fetch(remote, fetchOptions);

                CreateMissingLocalBranchesFromRemoteTrackingOnes(repo, remote.Name);

                if (!repo.Info.IsHeadDetached)
                {
                    Logger.WriteInfo(string.Format("HEAD points at branch '{0}'.", repo.Refs.Head.TargetIdentifier));
                    return;
                }

                Logger.WriteInfo(string.Format("HEAD is detached and points at commit '{0}'.", repo.Refs.Head.TargetIdentifier));

                if (branch != null)
                {
                    Logger.WriteInfo(string.Format("Checking out local branch 'refs/heads/{0}'.", branch));
                    repo.Checkout("refs/heads/" + branch);
                }
                else
                {
                    CreateFakeBranchPointingAtThePullRequestTip(repo);
                }
            }
        }
开发者ID:potherca-contrib,项目名称:GitVersion,代码行数:35,代码来源:GitHelper.cs


示例16: CreateEmptyRepo

 public void CreateEmptyRepo()
 {
     _repoPath = Environment.CurrentDirectory + "\\myRepo";
     var directory = Directory.CreateDirectory(_repoPath);
     LibGit2Sharp.Repository.Init(_repoPath);
     _repo = new LibGit2Sharp.Repository(_repoPath);
 }
开发者ID:fridamat,项目名称:GitComparer,代码行数:7,代码来源:ComparerIntegrationTests.cs


示例17: BranchInfoActor

        public BranchInfoActor()
        {
            Receive<GetBranchInfo>(message =>
            {
                Logger.WriteLine($"Starting Branch info {message.DirPath} -> {message.BranchName}");
                using (var repository = new Repository(message.RepositoryPath))
                {
                    var branch = repository.Branches[message.BranchName];
                    var branchLastCommit = branch.Tip;
                    var branchInfo = new BranchInfo
                    {
                        Name = branch.Name,
                        CommitterDate = branchLastCommit.Committer.When,
                        CommitterName = branchLastCommit.Committer.Name,
                        CommitterEmail = branchLastCommit.Committer.Email,
                        Message = branchLastCommit.Message,
                        Sha = branchLastCommit.Sha,
                    };

                    var repoAndBranchInfo = new RepoAndBranchInfo(message.DirPath, branchInfo);

                    Context.ActorSelection(ActorSelectionRouting.BranchInfoAggregationActorPath)
                        .Tell(new RepositoryAndBranchInfo(repoAndBranchInfo));

                }
            });
        }
开发者ID:CBurbidge,项目名称:ShamefulOldGit,代码行数:27,代码来源:BranchInfoActor.cs


示例18: Stalker

        //readonly Tree masterTree;
        //readonly Tree currentTree;
        public Stalker(String localRepo, String sourceFileName, String ignoreFileName, String localStalkBranch = null, String targetTag = null, String localMaster = "master")
        {
            repo = new Repository (localRepo);

            master = repo.Branches.Single (branch => branch.FriendlyName == localMaster);

            if (targetTag != null) {
                tag = repo.Tags.Single (t => t.FriendlyName == targetTag);
            }

            //			if (localStalkBranch != null)
                head = repo.Branches.Single (branch => branch.FriendlyName == localStalkBranch);
            //			else
            //				head = repo.Head;

            //			if (head != repo.Branches.Single (b => b.IsCurrentRepositoryHead)) {
            //                repo.Checkout(head);
            //			}
            //            head = repo.Branches.Single(b => b.IsCurrentRepositoryHead);
            //var filter = new CommitFilter { Since = repo.Branches["master"], Until = repo.Branches["development"] };
            //masterTree = repo.Lookup<Tree>(master.Tip.Sha);
            //currentTree = repo.Lookup<Tree>(head.Tip.Sha);
            try {
                sources = File.ReadAllLines (Path.Combine (localRepo, sourceFileName));
            } catch {
            } finally {
            }
            try {
                ignore = File.ReadAllLines (Path.Combine (localRepo, ignoreFileName));
            } catch {
            } finally {
            }
        }
开发者ID:sushihangover,项目名称:ForkStalker,代码行数:35,代码来源:Stalker.cs


示例19: FetchAllFiles

        public Task<List<ISourceItem>> FetchAllFiles(BuildConfig config)
        {

            string gitFolder = config.BuildFolder + "\\git";

            //// temporary hack...
            //// git-pull does not work
            //if (Directory.Exists(gitFolder)) {
            //    Directory.Delete(gitFolder, true);
            //}

            if (!Directory.Exists(gitFolder))
            {
                Directory.CreateDirectory(gitFolder);


                Console.WriteLine("Cloning repository " + config.SourceUrl);

                CloneOptions clone = new CloneOptions();
                clone.CredentialsProvider = CredentialsHandler;
                var rep = Repository.Clone(config.SourceUrl, gitFolder, clone);

                Console.WriteLine("Repository clone successful");
            }
            else {
                Console.WriteLine("Fetching remote Repository");
                var rep = new Repository(gitFolder);
                FetchOptions options = new FetchOptions();
                options.CredentialsProvider = CredentialsHandler;
                Remote remote = rep.Network.Remotes["origin"];

                //Commands.Fetch(rep,remote.Name,)

                //rep.Fetch(remote.Name, options);
                var master = rep.Branches["master"];
                Commands.Pull(rep, new Signature("IISCI", "[email protected]", DateTime.Now),  new PullOptions()
                {
                    FetchOptions = options,
                    MergeOptions = new MergeOptions() { 
                        MergeFileFavor = MergeFileFavor.Theirs,
                        CommitOnSuccess = true                        
                    }
                });
                Console.WriteLine("Fetch successful");
            }

            List<ISourceItem> files = new List<ISourceItem>();

            EnumerateFiles( new DirectoryInfo(gitFolder), files, "" );


            Parallel.ForEach(files, file =>
            {
                var md5 = System.Security.Cryptography.MD5.Create();
                ((GitSourceItem)file).Version = Convert.ToBase64String(md5.ComputeHash(File.ReadAllBytes(file.Url)));
            });


            return Task.FromResult(files);
        }
开发者ID:neurospeech,项目名称:iis-ci,代码行数:60,代码来源:GitSourceController.cs


示例20: Get

        // GET api/values
        public HttpResponseMessage Get(string path)
        {
            using (var repo = new Repository(path))
            {
                var files = repo
                    .RetrieveStatus(new StatusOptions() { IncludeUnaltered = true })
                    .Where(s => s.State != FileStatus.Ignored && s.State != FileStatus.NewInWorkdir)
                    .Select(s => s.FilePath)
                    .ToList();
                var diffs =
                    files.Select(f => new { path = f, history = repo.Commits.QueryBy(f).Select(x => x.Commit).ToList() })
                        .ToList();

                var patches =
                    diffs.Select(
                        d =>
                            new
                            {
                                d.path,
                                history =
                                    d.history.Where(p => p.Parents.Any())
                                        .SelectMany(
                                            c =>
                                                repo.Diff.Compare<Patch>(c.Parents.First().Tree,c.Tree)
                                                    .Where(p => p.Path == d.path)
                                                    .Select(p => new { p.LinesAdded, p.LinesDeleted, c.Author.When })
                                                    .ToArray())
                                        .ToArray()
                            }).ToArray();
                return Request.CreateResponse(HttpStatusCode.OK, patches);
            }
        }
开发者ID:linkerro,项目名称:CodeChurn,代码行数:33,代码来源:GitController.cs



注:本文中的LibGit2Sharp.Repository类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# TestHelpers.TemporaryCloneOfTestRepo类代码示例发布时间:2022-05-26
下一篇:
C# LibGit2Sharp.Commit类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap