Microsoft MVP성태의 닷넷 이야기
닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색 [링크 복사], [링크+제목 복사],
조회: 2448
글쓴 사람
정성태 (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)
13367정성태6/10/20233690오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233439.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233150오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233988.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233571스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233540.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233883오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233239오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233566오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233968.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233804.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20234143DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20234083.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234249.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233896.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234379VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233660오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233988.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233896.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234306.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234139오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235564.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236670.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234584디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234451.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234196닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...