Microsoft MVP성태의 닷넷 이야기
닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색 [링크 복사], [링크+제목 복사],
조회: 2442
글쓴 사람
정성태 (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)
13266정성태2/20/20234664오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234574.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20236135스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234295개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235340디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234679Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234471오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234597.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234461오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234552.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235312개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234703오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234602Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235342Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20234212오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234625스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236488오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20235312오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234275오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20235177VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234353개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234922.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234298VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20235100디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234558디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20234002디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...