Microsoft MVP성태의 닷넷 이야기
.NET Framework: 629. .NET Core의 dotnet.exe CLI 명령어 확장 방법 [링크 복사], [링크+제목 복사],
조회: 15681
글쓴 사람
정성태 (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

... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
11821정성태2/20/201912088오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915235오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913905Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912830VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199988오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201912489Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201911383오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910201오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911806.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199631오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913418오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911484.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201912994.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201914049디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201912359Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201912110디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201913945.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201911982Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201911488디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201912872.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201913908개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201813193오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201813992.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201813224개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201810582개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201810230개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...