Microsoft MVP성태의 닷넷 이야기
닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색 [링크 복사], [링크+제목 복사],
조회: 2447
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 2개 있습니다.)
.NET Framework: 1040. C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
; https://www.sysnet.pe.kr/2/0/12601

닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색
; https://www.sysnet.pe.kr/2/0/13450




C# - Octokit을 이용한 GitHub Issue 검색

Octokit은 예전에도 한번 소개한 적이 있는데요,

C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
; https://www.sysnet.pe.kr/2/0/12601

그때는 Release를 이용해 가장 최신의 태그 이름을 가져왔었고, 이번에는 이슈와 관련된 정보를 가져오는 예제를 소개합니다.




사실, 제가 작성한 것은 아니고 ^^ 마침 .NET Conf 2023 동영상을 보다가,

Build Intelligent Apps with .NET and Azure
; https://youtu.be/xEFO1sQ2bUc?t=27773

OpenAI를 다루면서 예제 데이터를 GitHub 프로젝트의 이슈로 다루길래 간단하게 베껴 봅니다. ^^

자, 그럼 제가 만들어 두었던 rasp_vusb repo를 대상으로 이슈를 가져올 텐데요, 동영상에서는 GitHub API 키를 이용해야 하는 걸로 오해할 수 있지만,

string githubKey = "...GitHub API Key...";

var githubClient = new GitHubClient(new ProductHeaderValue("octokit_sample"));

if (!string.IsNullOrEmpty(githubKey))
{
    Console.WriteLine("Using GitHub API Token");
    var tokenAuth = new Credentials(githubKey);
    githubClient.Credentials = tokenAuth;
}
else
{
    Console.WriteLine("Using anonymous GitHub API");
}

접근하려는 repository가 public이라면 굳이 PAT 키를 받지 않아도 됩니다. 실제로 이 글에서 예를 들게 될 rasp_vusb repo는 PAT 설정 없이 곧바로,

var options = new ApiOptions();
var githubClient = new GitHubClient(new ProductHeaderValue("octokit_sample"));

사용할 수 있습니다. 이렇게 초기화한 githubClient 인스턴스로, 이제 프로젝트의 "Label" 목록을 다음과 같이 가져올 수 있습니다.

var options = new ApiOptions();
var allLabels = await githubClient.Issue.Labels.GetAllForRepository(org, repoName, options);
Console.WriteLine($"Labels: {allLabels.Count}"); // 출력 결과: Labels: 8

이것은 "https://github.com/stjeong/rasp_vusb/labels" 경로에서 확인할 수 있는, 등록된 라벨 이름을 가져오는데, 특별하게 설정하지 않았다면 8개 정도(bug, duplicate, enhancement, good first issue, help wanted, invalid, question, wontfix)를 반환할 것입니다.




이후 동영상에서는 각각의 Label에 해당하는 이슈를 50개만 가져오는데요,

var repoName = "rasp_vusb"; // repo 이름
var org = "stjeong";        // 소유자 이름

var allIssues = new List<Issue>();

foreach (var label in allLabels)
{
    var request = new RepositoryIssueRequest()
    {
        Filter = IssueFilter.All,
        State = ItemStateFilter.All, // Open, Closed, All (기본값: Open)
    };

    request.Labels.Add(label.Name);

    var apiOptions = new ApiOptions()
    {
        PageSize = 50,
        PageCount = 1,
    };

    var issues = await githubClient.Issue.GetAllForRepository(org, repoName, request, apiOptions);
    allIssues.AddRange(issues);
}

굳이 Label로 그룹핑을 시킬 필요가 없다면 그냥 이렇게 모든 이슈를 가져올 수 있습니다. (너무 많으면 위의 예제에서 페이징 옵션만 가져와 추가하면 됩니다.)

var allIssues = new List<Issue>();

var request = new RepositoryIssueRequest()
{
    Filter = IssueFilter.All,
    State = ItemStateFilter.All,
};

var issues = await githubClient.Issue.GetAllForRepository(org, repoName, request);

allIssues.AddRange(issues);
Console.WriteLine($"All issues: {allIssues.Count()}");




자, 그렇게 해서 이슈를 모두 가져왔으면 적절하게 가공해 저장할 수 있습니다.

var dataCollection = allIssues
        .Select(issue => new GitHubIssue(
                                issue.Title,
                                issue.Body,
                                issue.HtmlUrl)
                            );            

await SaveIssuesToFileAsync(dataCollection, "issues.json");

public static async Task SaveIssuesToFileAsync(IEnumerable<GitHubIssue> data, string fileName)
{
    var filePath = Path.Combine("..", "..", "..", fileName);
    var issuesJson = JsonSerializer.Serialize(data, new JsonSerializerOptions(
        JsonSerializerOptions.Default) { WriteIndented = true });
    await File.WriteAllTextAsync(filePath, issuesJson);
} 

public record GitHubIssue(string Title, string Text, string Url);

저장한 issues.json 파일은 대충 다음과 같은 내용을 담고 있으니,

[
  {
    "Title": "Increase hold of left click",
    "Text": "Hello, thank you for making this project open source. I ran succefully in a raspberry pi zero w. However, I need to hold the left click for around 3-4 seconds. Could you please give a general instruction on how I can achieve this?\r\n\r\nI was trying to add a sleep at the end of MouseDevice::SendRelative function inside the rasp_vusb_server but I\u0027m having some trouble building this project. Could you please inform If I\u0027m in the right path.",
    "Url": "https://github.com/stjeong/rasp_vusb/issues/16"
  },

  // ...[생략]...
]

향후 다시 쿼리를 하지 않고 재사용하시면 되겠습니다. ^^

이 정도면 대충 감이 오시죠. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, 위의 예제 코드로 private Repo에 접근하는 경우에는 다음과 같은 식으로 예외가 발생할 것입니다.

Unhandled exception. Octokit.NotFoundException: repos/...[org].../...[repo_name]..../labels was not found.
   at Octokit.ApiPagination.GetAllPages[T](Func`1 getFirstPage, Uri uri) in /_/Octokit/Clients/ApiPagination.cs:line 34
   at octokit_sample.Program.Main(String[] args) in C:\c:\temp\octokit_sample\Program.cs:line 49
   at octokit_sample.Program.<Main>(String[] args)

심지어 PAT 키를 설정했어도 예외가 여전히 발생할 수 있는데요, 해당 PAT의 권한에 ("Full control of private repositories"라는 이름에서 알 수 있듯이) "repo" 항목이,

octokit_issue_1.png

설정되어 있는지 확인해 보셔야 합니다. ^^ (기본값은 off입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/21/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13595정성태4/13/20241111닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241136닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241147닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241622C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동 [1]
13591정성태4/2/20241536닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241405Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241504닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241874닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241482오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241879Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241584Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241537개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241580Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241694Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241806개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241338닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241533오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241716닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20242040닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241657닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241835닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241953닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241836닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241835닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241942닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241889닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...