Microsoft MVP성태의 닷넷 이야기
.NET Framework: 793. C# - REST API를 이용해 NuGet 저장소 제어 [링크 복사], [링크+제목 복사]
조회: 12141
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 4개 있습니다.)
개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법
; https://www.sysnet.pe.kr/2/0/11034

.NET Framework: 793. C# - REST API를 이용해 NuGet 저장소 제어
; https://www.sysnet.pe.kr/2/0/11696

개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법
; https://www.sysnet.pe.kr/2/0/11793

개발 환경 구성: 494. NuGet - nuspec의 패키지 스키마 버전(네임스페이스) 업데이트 방법
; https://www.sysnet.pe.kr/2/0/12234




C# - REST API를 이용해 NuGet 저장소 제어

NuGet 저장소의 REST API는 다음의 공식 문서에서 자세하게 설명하고 있습니다.

NuGet API
; https://learn.microsoft.com/en-us/nuget/api/overview

물론 다음과 같은 잘 정리된 라이브러리를 이용해 제어하는 것도 가능하지만,

NuGet.Protocol
; https://www.nuget.org/packages/NuGet.Protocol/4.8.0

이 글에서는 그냥 HTTP 통신으로 만들어 보겠습니다. ^^




우선, 시작점은 다음의 JSON 결과물로부터 출발합니다.

https://api.nuget.org/v3/index.json

[index.json 파일 내용]

{
  "version": "3.0.0",
  "resources": [
    {
      "@id": "https://api-v2v3search-0.nuget.org/query",
      "@type": "SearchQueryService",
      "comment": "Query endpoint of NuGet Search service (primary)"
    },
    {
      "@id": "https://api-v2v3search-1.nuget.org/query",
      "@type": "SearchQueryService",
      "comment": "Query endpoint of NuGet Search service (secondary)"
    },

    ...[생략]...

    {
      "@id": "https://api.nuget.org/v3/registration3-gz-semver2/",
      "@type": "RegistrationsBaseUrl/Versioned",
      "clientVersion": "4.3.0-alpha",
      "comment": "Base URL of Azure storage where NuGet package registration info is stored in GZIP format. This base URL includes SemVer 2.0.0 packages."
    },
    {
      "@id": "https://api.nuget.org/v3/catalog0/index.json",
      "@type": "Catalog/3.0.0",
      "comment": "Index of the NuGet package catalog."
    }
  ],
  "@context": {
    "@vocab": "http://schema.nuget.org/services#",
    "comment": "http://www.w3.org/2000/01/rdf-schema#comment"
  }
}

보는 바와 같이 "@type"에 해당하는 기능을 "@id"에서 제공하는 링크를 통해 서비스를 제공합니다. 따라서, 다음과 같은 코드로 시작할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace NugetRestClient
{
    class NugetClient
    {
        const string _sourceUrl = "https://api.nuget.org/v3/index.json";
        CookieContainer _cookies;
        HttpClient _httpClient;
        ServiceIndex _serviceIndex;

        private string GetServiceEndPoint(string serviceTypeName)
        {
            foreach (var item in _serviceIndex.resources)
            {
                if (item.type == serviceTypeName)
                {
                    return item.id;
                }
            }

            throw new ApplicationException("ServiceNotFound: " + serviceTypeName);
        }

        public NugetClient()
        {
            HttpClientHandler handler = new HttpClientHandler();
            _cookies = new CookieContainer();
            handler.CookieContainer = _cookies;

            HttpClient hc = new HttpClient(handler);
            _httpClient = hc;
        }

        public async Task GetFeedAsync()
        {
            string text = await _httpClient.GetStringAsync(_sourceUrl);
            _serviceIndex = Newtonsoft.Json.JsonConvert.DeserializeObject<ServiceIndex>(text);
        }
    }
}

위의 코드를 이용해 다음과 같이 service index 정보를 가져옵니다.

public static async Task<int> Main(string[] args)
{
    NugetClient client = new NugetClient();
    await client.GetFeedAsync();

    return 0;
}

이제 NuGet으로부터 등록된 패키지의 정보를 다음과 같은 식으로 처리할 수 있습니다.

public async Task<SearchQueryServiceResult> GetPackageInfoAsync(string packageId, bool includePrerelease)
{
    string url = GetServiceEndPoint("SearchQueryService");
    string query = string.Format("{0}?q={1}", url, packageId);

    if (includePrerelease == true)
    {
        query += "&prerelease=true";
    }

    string text = await _httpClient.GetStringAsync(query);
    return Newtonsoft.Json.JsonConvert.DeserializeObject<SearchQueryServiceResult>(text);
}

위의 query 변수는 index.json에 정의된 SearchQueryService 서비스의 url에 대해 다음과 같은 쿼리를,

{servicequery}?q={packageId}

{servicequery}?q={packageId}&prerelease=true

NuGet에 전송합니다. Search와 관련해 어떤 유형의 서비스들이 있는지는 문서에 잘 나와 있습니다.

Docs / NuGet / API - Search
; https://learn.microsoft.com/en-us/nuget/api/search-query-service-resource

위의 문서에 보면, @type으로 다음의 값들이 가능하다고 나옵니다.

SearchQueryService : The initial release
SearchQueryService/3.0.0-beta : Alias of SearchQueryService
SearchQueryService/3.0.0-rc : Alias of SearchQueryService

현재(2018-09-18) 기준으로 정식 서비스는 "SearchQueryService"이므로 이 글에서는 그 옵션을 사용한 것입니다. 이와 함께 query에 전달할 수 있는 인자들을 다음과 같이 소개하고 있습니다.

GET {@id}?q={QUERY}&skip={SKIP}&take={TAKE}&prerelease={PRERELEASE}&semVerLevel={SEMVERLEVEL}

보면 페이징 기능도 있으므로 적절하게 사용하시면 됩니다.




예제 시나리오를 하나 작성해서 구현해 보겠습니다. ^^

빌드 시스템을 통해 생성된 바이너리를 NuGet 패키지의 새 버전에 등록할 때마다 alpha, alpha2, alpha3, alpha4, ...와 같은 식으로 버전을 늘려 가며 등록하는 것입니다. 정식 릴리스는 아니므로 기존 alpha(N) 버전이 있다면 unlist로 만들고 다음 릴리스 번호 값을 구하는 정도까지만 구현해 보겠습니다.

이를 위해서는 다음의 2개 메서드를 추가 구현하면 됩니다.

public async Task<PackageMetadata> GetPackageMetadataAsync(string packageId, string vesrionPostfix)
{
    string url = GetServiceEndPoint("RegistrationsBaseUrl");
    string query = string.Format("{0}{1}/{2}.json", url, packageId.ToLower(), vesrionPostfix);

    HttpResponseMessage hrm = await _httpClient.GetAsync(query);

    if (hrm.StatusCode == HttpStatusCode.NotFound)
    {
        return null;
    }

    string text = await hrm.Content.ReadAsStringAsync();
    PackageMetadata searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PackageMetadata>(text);
    return searchResult;
}

public async Task<bool> UnlistVersionPackageAsync(string packageId, string vesrionPostfix)
{
    string url = GetServiceEndPoint("PackagePublish/2.0.0");
    string query = string.Format("{0}/{1}/{2}", url, packageId.ToLower(), vesrionPostfix);

    HttpResponseMessage hrm = await _httpClient.DeleteAsync(query);
    return hrm.StatusCode == HttpStatusCode.OK;
}

주의할 것은, 등록된 패키지의 특정 버전 상태(Status)를 "Unlisted"로 바꾸기 위해서는 API Key를 HTTP 요청의 "X-NuGet-ApiKey" 헤더에 전송해야 합니다. 이 작업은 HttpClient를 생성할 때 미리 해주는 것으로 처리하면 편리합니다.

public NugetClient(string apiKey = "")
{
    HttpClientHandler handler = new HttpClientHandler();
    _cookies = new CookieContainer();
    handler.CookieContainer = _cookies;

    HttpClient hc = new HttpClient(handler);
    _httpClient = hc;

    if (string.IsNullOrEmpty(apiKey) == false)
    {
        _httpClient.DefaultRequestHeaders.Add("X-NuGet-ApiKey", apiKey);
    }
}

래퍼 API가 만들어졌으니 이제 다음과 같이 사용할 수 있습니다.

string packageId = "MyTestPackage";
string versionPrefix = "1.0.0.0";
string checkPostfix = versionPrefix + "-alpha";
int alphaNumber = 1;

while (true)
{
    PackageMetadata item = await client.GetPackageMetadataAsync(packageId, checkPostfix);
    if (item == null)
    {
        break;
    }

    if (item.listed == true)
    {
        await client.UnlistVersionPackageAsync(packageId, checkPostfix);
    }

    alphaNumber++;
    checkPostfix = $"{versionPrefix}-alpha{alphaNumber}";
}

Console.WriteLine("Next candidate version: " + checkPostfix);

이 정도면 제법 감각을 익히셨을 테니 여러분이 필요한 나머지 기능들도 쉽게 구현할 수 있을 것입니다. ^^

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




참고로, NuGet.exe 프로그램에 대한 배포 목록도 다음의 json 파일로 구할 수 있습니다.

https://dist.nuget.org/tools.json
https://dist.nuget.org/tools.schema.json




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/22/2023]

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

비밀번호

댓글 작성자
 




... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13148정성태10/26/20225656오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224767오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225612.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20225875오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20225715.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226227오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20224964도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20226712.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226095C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20225926.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227214.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225602.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226175.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226405.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225137오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/20225455Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225330스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20227992.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/20225096.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/20225391.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20227971C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226422Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227030.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/20227240.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/20226980.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
13123정성태9/8/20227417.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...