Microsoft MVP성태의 닷넷 이야기
.NET Framework: 629. .NET Core의 dotnet.exe CLI 명령어 확장 방법 [링크 복사], [링크+제목 복사],
조회: 15391
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

.NET Core의 dotnet.exe CLI 명령어 확장 방법

아래와 같은 글이 있군요. ^^

Building a custom dotnet cli tool
; http://dotnetthoughts.net/building-a-custom-dotnet-cli-tool/

위의 글대로 실습을 하면서, dotnet.exe CLI 명령어 확장이 어떤 것인지 알아보겠습니다. ^^ (물론, 이 글을 안 보고 간단하게 원문을 보셔도 됩니다.)




"Building a custom dotnet cli tool" 글에서 만든 것과 똑같은 확장을 만들면 재미없으니 ^^ 이 글에서는 닷넷 프로젝트의 "/bin", "/obj" 폴더를 정리해 주는 "clean" 기능을 구현해 보겠습니다.

우선, dotnet.exe CLI의 확장 명령어에 대응하는 "Console Application (.NET Core)" 프로젝트를 Visual Studio 2015에서 생성합니다. (또는, Visual Studio Code로 콘솔 프로젝트에 대응하는 구성을 해도 됩니다.)

그다음, 기본 생성된 콘솔 프로젝트의 project.json 파일에 다음의 내용들을 추가해 줍니다.

{
    "version": "1.0.1-*",
    "title": "BuildClean",
    "description": "A dotnet CLI tool for cleaning projects.",
    "authors": [
        "stjeong"
    ],
    "packOptions": {
        "projectUrl": "https://github.com/stjeong/BuildClean",
        "licenseUrl": "https://github.com/stjeong/BuildClean/blob/master/LICENSE"

    },
    "copyright": "Copyright (C) stjeong 2017",

    "buildOptions": {
        "debugType": "portable",
        "emitEntryPoint": true,
        "outputName": "dotnet-clean"
    },

    "dependencies": {
        "Microsoft.NETCore.App": {
            "type": "platform",
            "version": "1.0.0"
        }
    },

    "frameworks": {
        "netcoreapp1.0": {
            "imports": "dnxcore50"
        }
    }
}

이제 "dotnet.exe clean" 명령어 시에 실행될 코드를 Program.cs 파일의 Main 함수에 추가해 줍니다.

using System;
using System.IO;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            char separator = Path.DirectorySeparatorChar;

            foreach (string dirPath in Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*.*", SearchOption.AllDirectories))
            {
                if (dirPath.EndsWith(separator + "bin", StringComparison.CurrentCultureIgnoreCase) == true
                    || dirPath.EndsWith(separator + "obj", StringComparison.CurrentCultureIgnoreCase) == true)
                {
                    try
                    {
                        foreach (string filePath in Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories))
                        {
                            try
                            {
                                File.Delete(filePath);
                            }
                            catch { }
                        }

                        Directory.Delete(dirPath, true);
                    }
                    catch { }
                }
            }
        }
    }
}

기능 구현이 끝났으니, 이 프로젝트를 Nuget 패키지로 만들어 NuGet Gallery에 배포해 줍니다. 이에 대한 자세한 방법은 아래의 글에서 한번 설명한 적이 있습니다. ^^

.NET Core 프로젝트를 NuGet Gallery에 배포하는 방법
; https://www.sysnet.pe.kr/2/0/11034

위의 글에서 설명한 대로, project.json 파일이 있는 폴더에서 "dotnet pack" 명령을 실행한 후 정상적으로 "BuildClean.1.0.1.nupkg" 패키지 파일이 생성된 \src\BuildClean\bin\Debug" 폴더에서 "nuget push"를 실행해서 등록을 완료합니다.

nuget push BuildClean.1.0.1.nupkg -Source https://www.nuget.org/api/v2/package

여기까지는, "dotnet.exe 확장 명령어"를 구현하는 개발자가 해주어야 할 일입니다.




이제, NuGet에 올려진 "확장 명령어"를 여러분들의 프로젝트에서 사용하는 방법을 알아보겠습니다.

실습을 위한 프로젝트를 하나 만들어야 하는데, 간단하게 이번에도 "Console Application (.NET Core)" 프로젝트를 만듭니다. 그다음 project.json에 다음과 같이 "tools"를 추가해 줍니다.

{
    "version": "1.0.0-*",
    "buildOptions": {
        "emitEntryPoint": true
    },

    "dependencies": {
        "Microsoft.NETCore.App": {
            "type": "platform",
            "version": "1.0.0"
        }
    },

    "frameworks": {
        "netcoreapp1.0": {
            "imports": "dnxcore50"
        }
    },

    "tools": {
        "BuildClean": "1.0.1"
    }
}

이후 "dotnet restore" 명령어를 실행해 주면 다음과 같은 식으로 NuGet 갤러리로부터 BuildClean 바이너리가 로컬 PC에 구성됩니다.

C:\ConsoleApp1\src\ConsoleApp1>dotnet restore
log  : Restoring packages for C:\ConsoleApp1\src\ConsoleApp1\project.json...
log  : Restoring packages for tool 'BuildClean' in C:\ConsoleApp1\src\ConsoleApp1\project.json...
log  : Installing BuildClean 1.0.1.
log  : Writing lock file to disk. Path: C:\ConsoleApp1\src\ConsoleApp1\project.lock.json
log  : C:\ConsoleApp1\src\ConsoleApp1\project.json
log  : Restore completed in 3720ms.

C:\ConsoleApp1\src\ConsoleApp1>

이제부터는, "tools"에 "BuildClean" 항목을 포함한 프로젝트라면 다음과 같이 "clean" 명령을 내리는 것이 가능합니다.

dotnet clean

테스트를 위해 ConsoleApp1 프로젝트를 빌드해 보고,

C:\ConsoleApp1\src\ConsoleApp1>dotnet build
Project ConsoleApp1 (.NETCoreApp,Version=v1.0) will be compiled because expected outputs are missing
Compiling ConsoleApp1 for .NETCoreApp,Version=v1.0

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

Time elapsed 00:00:01.0991770

다시 "dotnet clean" 명령어를 내려 보면,

C:\ConsoleApp1\src\ConsoleApp1>dotnet clean

이전 "dotnet build" 명령어로 생성되었던 "/bin", "/obj" 폴더가 삭제된 것을 알 수 있습니다.




원문으로 돌아가서 "Building a custom dotnet cli tool" 글의 작성자가 만든 "Imageoptimize"를 한번 볼까요? ^^

이 도구를 여러분의 "project.json"에 포함시키면,

"tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Imageoptimize": "1.0.0"
}

이후부터 "dotnet imgopt"라는 명령어를 실행할 수 있습니다. 이 명령어를 내리면 여러분들의 프로젝트 하위에 있는 모든 PNG 파일의 화질을 낮춰서(즉, 파일 용량을 줄여) 저장해 줍니다.

이렇게 "dotnet.exe 확장 명령어"를 만들어 두어 좋은 점이 또 하나 있다면, "빌드 스크립트" 과정에 명시해 이 과정을 자동화할 수 있다는 것입니다. 즉, 다음과 같이 "project.json" 파일에 "scripts"로 등록시켜 두면,

"scripts": {
    "precompile": [ "dotnet imgopt" ],
}

"dotnet build" 명령어를 내렸을 때, 자동으로 컴파일 이전 단계에서 "dotnet imgopt" 명령을 실행해 이미지 크기를 줄여주는 것입니다. 따라서, 활용 방안에 따라 여러분들의 귀찮은 pre/post 작업들을 자동화하는 것이 가능합니다.

물론, 기존의 Visual Studio에서도 빌드 이벤트를 걸어서 이런저런 작업들을 할 수 있었지만 NuGet 갤러리를 활용한 "빌드 작업" 바이너리를 모두 공유할 수 있도록 체계화시켰다는 점에서 한 발짝 더 진보한 셈이 됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/4/2017]

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

비밀번호

댓글 작성자
 



2017-01-05 02시19분
좋은 정보 감사합니다^^
Beren Ko

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13439정성태11/10/20233100닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232670닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232854닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233107닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233005닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232781스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232470스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232551오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232935스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232765닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233053닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233160닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233341닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233490스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233256닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233237스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233396닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233482닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235797스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233286스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233999닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233531닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233299오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233802닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233580디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233777닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...