Microsoft MVP성태의 닷넷 이야기
닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색 [링크 복사], [링크+제목 복사],
조회: 5265
글쓴 사람
정성태 (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)
13736정성태9/20/2024500오류 유형: 923. Visual Studio Code - Could not establish connection to "...": Port forwarding is disabled.
13735정성태9/20/2024483개발 환경 구성: 726. ARM 플랫폼용 Visual C++ 리눅스 프로젝트 빌드
13734정성태9/19/2024511개발 환경 구성: 725. ssh를 이용한 원격 docker 서비스 사용
13733정성태9/19/2024471VS.NET IDE: 194. Visual Studio - Cross Platform / "Authentication Type: Private Key"로 접속하는 방법
13732정성태9/17/2024616개발 환경 구성: 724. ARM + docker 환경에서 .NET 8 설치
13731정성태9/15/20241018개발 환경 구성: 723. C# / Visual C++ - Control Flow Guard (CFG) 활성화 [1]파일 다운로드2
13730정성태9/10/20241098오류 유형: 922. docker - RULE_APPEND failed (No such file or directory): rule in chain DOCKER
13729정성태9/9/20241364C/C++: 173. Windows / C++ - AllocConsole로 할당한 콘솔과 CRT 함수 연동파일 다운로드1
13728정성태9/7/20241409C/C++: 172. Windows - C 런타임에서 STARTUPINFO의 cbReserved2, lpReserved2 멤버를 사용하는 이유파일 다운로드1
13727정성태9/6/20241681개발 환경 구성: 722. ARM 플랫폼 빌드를 위한 미니 PC(?) - Khadas VIM4 [1]
13726정성태9/5/20241424C/C++: 171. C/C++ - 윈도우 운영체제에서의 file descriptor와 HANDLE파일 다운로드1
13725정성태9/4/20241165디버깅 기술: 201. WinDbg - sos threads 명령어 실행 시 "Failed to request ThreadStore"
13724정성태9/3/20241439닷넷: 2296. Win32/C# - 자식 프로세스로 HANDLE 상속파일 다운로드1
13723정성태9/2/20242863C/C++: 170. Windows - STARTUPINFO의 cbReserved2, lpReserved2 멤버 사용자 정의파일 다운로드2
13722정성태9/2/20241230C/C++: 169. C/C++ - CRT(C Runtime) 함수에 의존성이 없는 프로젝트 생성
13721정성태8/30/20241374C/C++: 168. Visual C++ CRT(C Runtime DLL: msvcr...dll)에 대한 의존성 제거 - 두 번째 이야기
13720정성태8/29/20241238VS.NET IDE: 193. C# - Visual Studio의 자식 프로세스 디버깅
13719정성태8/28/20241283Linux: 79. C++ - pthread_mutexattr_destroy가 없다면 메모리 누수가 발생할까요?
13718정성태8/27/20241933오류 유형: 921. Visual C++ - error C1083: Cannot open include file: 'float.h': No such file or directory [2]
13717정성태8/26/20241457VS.NET IDE: 192. Visual Studio 2022 - Windows XP / 2003용 C/C++ 프로젝트 빌드
13716정성태8/21/20241483C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작
13715정성태8/19/20241566Linux: 78. 리눅스 C/C++ - 특정 버전의 glibc 빌드 (docker-glibc-builder)
13714정성태8/19/20241681닷넷: 2295. C# 12 - 기본 생성자(Primary constructors) (책 오타 수정) [3]
13713정성태8/16/20242154개발 환경 구성: 721. WSL 2에서의 Hyper-V Socket 연동
13712정성태8/14/20242117개발 환경 구성: 720. Synology NAS - docker 원격 제어를 위한 TCP 바인딩 추가
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...