Я пытаюсь прочитать личное git-репо "Я смотрю, а не мое". Я пробовал много онлайн-кодов, но каждый раз, когда я получаю сообщение об ошибке 404, я не могу найти, факт, я могу точно открыть репо вбраузер.
Все еще не могу понять, проблема в том, что это токен?как получить?
Вот код Измените информацию, такую как владелец, имя репо и токен, чтобы заставить его работать
using GitHubRepoGrabber.GithubClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace GitHubRepoGrabber{
class Program
{
static void Main(string[] args)
{
//try 1
var task = Github.getRepo("owner", "repo", "token");
task.Wait();
var dir = task.Result;
//try 2
Task.Factory.StartNew(async () =>
{
var repoOwner = "owner";
var repoName = "name";
var path = "path";
var httpClientResults = await ListContents(repoOwner, repoName, path);
PrintResults("From HttpClient", httpClientResults);
var octokitResults = await ListContentsOctokit(repoOwner, repoName, path);
PrintResults("From Octokit", octokitResults);
}).Wait();
Console.ReadKey();
}
static async Task<IEnumerable<string>> ListContents(string repoOwner, string repoName, string path)
{
using (var client = GetGithubHttpClient())
{
var resp = await client.GetAsync($"repos/{repoOwner}/{repoName}/contents/{path}");
var bodyString = await resp.Content.ReadAsStringAsync();
var bodyJson = JToken.Parse(bodyString);
return bodyJson.SelectTokens("$.[*].name").Select(token => token.Value<string>());
}
}
static async Task<IEnumerable<string>> ListContentsOctokit(string repoOwner, string repoName, string path)
{
var client = new GitHubClient(new Octokit.ProductHeaderValue("Github-API-Test"));
// client.Credentials = ... // Set credentials here, otherwise harsh rate limits apply.
var contents = await client.Repository.Content.GetAllContents(repoOwner, repoName, path);
return contents.Select(content => content.Name);
}
private static HttpClient GetGithubHttpClient()
{
return new HttpClient
{
BaseAddress = new Uri("https://api.github.com"),
DefaultRequestHeaders =
{
// NOTE: You'll have to set up Authentication tokens in real use scenario
// NOTE: as without it you're subject to harsh rate limits.
{"User-Agent", "Github-API-Test"}
}
};
}
static void PrintResults(string source, IEnumerable<string> files)
{
Console.WriteLine(source);
foreach (var file in files)
{
Console.WriteLine($" -{file}");
}
} }namespace GithubClient
{
//JSON parsing methods
struct LinkFields
{
public String self;
}
struct FileInfo
{
public String name;
public String type;
public String download_url;
public LinkFields _links;
}
//Structs used to hold file data
public struct FileData
{
public String name;
public String contents;
}
public struct Directory
{
public String name;
public List<Directory> subDirs;
public List<FileData> files;
}
//Github classes
public class Github
{
//Get all files from a repo
public static async Task<Directory> getRepo(string owner, string name, string access_token)
{
HttpClient client = new HttpClient();
Directory root = await readDirectory("root", client, String.Format("https://api.github.com/repos/{0}/{1}/contents/", owner, name), access_token);
client.Dispose();
return root;
}
//recursively get the contents of all files and subdirectories within a directory
private static async Task<Directory> readDirectory(String name, HttpClient client, string uri, string access_token)
{
//get the directory contents
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", access_token, "x-oauth-basic"))));
request.Headers.Add("User-Agent", "lk-github-client");
//parse result
HttpResponseMessage response = await client.SendAsync(request);
String jsonStr = await response.Content.ReadAsStringAsync(); ;
response.Dispose();
FileInfo[] dirContents = JsonConvert.DeserializeObject<FileInfo[]>(jsonStr);
//read in data
Directory result;
result.name = name;
result.subDirs = new List<Directory>();
result.files = new List<FileData>();
foreach (FileInfo file in dirContents)
{
if (file.type == "dir")
{ //read in the subdirectory
Directory sub = await readDirectory(file.name, client, file._links.self, access_token);
result.subDirs.Add(sub);
}
else
{ //get the file contents;
HttpRequestMessage downLoadUrl = new HttpRequestMessage(HttpMethod.Get, file.download_url);
downLoadUrl.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", access_token, "x-oauth-basic"))));
request.Headers.Add("User-Agent", "lk-github-client");
HttpResponseMessage contentResponse = await client.SendAsync(downLoadUrl);
String content = await contentResponse.Content.ReadAsStringAsync();
contentResponse.Dispose();
FileData data;
data.name = file.name;
data.contents = content;
result.files.Add(data);
}
}
return result;
}
}
}
}