Search code examples
c#.netgithub-apioctokit.net

How to get list of files for every commit with octokit and c#


I have one class GitHub with one method which should return list of all commits for specific username and repo on GitHub:

using System;
using Octokit;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace ReadRepo
{
    public class GitHub
    {
        public GitHub()
        {
        }

        public async Task<List<GitHubCommit>> getAllCommits()
        {            
            string username = "lukalopusina";
            string repo = "flask-microservices-main";

            var github = new GitHubClient(new ProductHeaderValue("MyAmazingApp"));
            var repository = await github.Repository.Get(username, repo);
            var commits = await github.Repository.Commit.GetAll(repository.Id);

            List<GitHubCommit> commitList = new List<GitHubCommit>();

            foreach(GitHubCommit commit in commits) {
                commitList.Add(commit);
            }

            return commitList;
        }

    }
}

And I have main function which call getAllCommits method:

using System;
using Octokit;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace ReadRepo
{
    class MainClass
    {

        public static void Main(string[] args)
        {            

            GitHub github = new GitHub();

            Task<List<GitHubCommit>> commits = github.getAllCommits();
            commits.Wait(10000);

            foreach(GitHubCommit commit in commits.Result) {                
                foreach (GitHubCommitFile file in commit.Files)
                    Console.WriteLine(file.Filename);    
            }

        }
    }
}

When I run this i get following error:

enter image description here

Problem is because this variable commit.Files is Null probably because of async call but I am not sure how to solve it. Please some help?


Solution

  • My guess is if you need to get a list of files for all the commits you will need to get each commit separately by using

    foreach(GitHubCommit commit in commits) 
    {
        var commitDetails = github.Repository.Commit.Get(commit.Sha);
        var files = commitDetails.Files;
    }
    

    Take a look at this. There's also decribed another approach to reach your goal - at first get the list of all files in a repository and then get the list of commits for each file.