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

... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...
NoWriterDateCnt.TitleFile(s)
12549정성태3/4/20217462오류 유형: 700. VsixPublisher를 이용한 등록 시 다양한 오류 유형 해결책
12548정성태3/4/20218238개발 환경 구성: 546. github workflow/actions에서 nuget 패키지 등록하는 방법
12547정성태3/3/20218749오류 유형: 699. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly.
12546정성태3/3/20218377개발 환경 구성: 545. github workflow/actions에서 빌드시 snk 파일 다루는 방법 - Encrypted secrets
12545정성태3/2/202111094.NET Framework: 1026. 닷넷 5에 추가된 POH (Pinned Object Heap) [10]
12544정성태2/26/202111268.NET Framework: 1025. C# - Control의 Invalidate, Update, Refresh 차이점 [2]
12543정성태2/26/20219687VS.NET IDE: 158. C# - 디자인 타임(design-time)과 런타임(runtime)의 코드 실행 구분
12542정성태2/20/202112014개발 환경 구성: 544. github repo의 Release 활성화 및 Actions를 이용한 자동화 방법 [1]
12541정성태2/18/20219269개발 환경 구성: 543. 애저듣보잡 - Github Workflow/Actions 소개
12540정성태2/17/20219583.NET Framework: 1024. C# - Win32 API에 대한 P/Invoke를 대신하는 Microsoft.Windows.CsWin32 패키지
12539정성태2/16/20219459Windows: 189. WM_TIMER의 동작 방식 개요파일 다운로드1
12538정성태2/15/20219870.NET Framework: 1023. C# - GC 힙이 아닌 Native 힙에 인스턴스 생성 - 0SuperComicLib.LowLevel 라이브러리 소개 [2]
12537정성태2/11/202110836.NET Framework: 1022. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! - 두 번째 이야기 [2]
12536정성태2/9/20219877개발 환경 구성: 542. BDP(Bandwidth-delay product)와 TCP Receive Window
12535정성태2/9/20219014개발 환경 구성: 541. Wireshark로 확인하는 LSO(Large Send Offload), RSC(Receive Segment Coalescing) 옵션
12534정성태2/8/20219636개발 환경 구성: 540. Wireshark + C/C++로 확인하는 TCP 연결에서의 closesocket 동작 [1]파일 다운로드1
12533정성태2/8/20219279개발 환경 구성: 539. Wireshark + C/C++로 확인하는 TCP 연결에서의 shutdown 동작파일 다운로드1
12532정성태2/6/20219801개발 환경 구성: 538. Wireshark + C#으로 확인하는 ReceiveBufferSize(SO_RCVBUF), SendBufferSize(SO_SNDBUF) [3]
12531정성태2/5/20218762개발 환경 구성: 537. Wireshark + C#으로 확인하는 PSH flag와 Nagle 알고리듬파일 다운로드1
12530정성태2/4/202112904개발 환경 구성: 536. Wireshark + C#으로 확인하는 TCP 통신의 Receive Window
12529정성태2/4/202110032개발 환경 구성: 535. Wireshark + C#으로 확인하는 TCP 통신의 MIN RTO [1]
12528정성태2/1/20219410개발 환경 구성: 534. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 윈도우 환경
12527정성태2/1/20219634개발 환경 구성: 533. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 리눅스 환경파일 다운로드1
12526정성태2/1/20217494개발 환경 구성: 532. Azure Devops의 파이프라인 빌드 시 snk 파일 다루는 방법 - Secure file
12525정성태2/1/20217202개발 환경 구성: 531. Azure Devops - 파이프라인 실행 시 빌드 이벤트를 생략하는 방법
12524정성태1/31/20218241개발 환경 구성: 530. 기존 github 프로젝트를 Azure Devops의 빌드 Pipeline에 연결하는 방법 [1]
... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...