Microsoft MVP성태의 닷넷 이야기
.NET Framework: 629. .NET Core의 dotnet.exe CLI 명령어 확장 방법 [링크 복사], [링크+제목 복사],
조회: 23137
글쓴 사람
정성태 (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)
13718정성태8/27/20247418오류 유형: 921. Visual C++ - error C1083: Cannot open include file: 'float.h': No such file or directory [2]
13717정성태8/26/20247022VS.NET IDE: 192. Visual Studio 2022 - Windows XP / 2003용 C/C++ 프로젝트 빌드
13716정성태8/21/20246757C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [1]
13715정성태8/19/20247361Linux: 78. 리눅스 C/C++ - 특정 버전의 glibc 빌드 (docker-glibc-builder)
13714정성태8/19/20246750닷넷: 2295. C# 12 - 기본 생성자(Primary constructors) (책 오타 수정) [3]
13713정성태8/16/20247464개발 환경 구성: 721. WSL 2에서의 Hyper-V Socket 연동
13712정성태8/14/20247223개발 환경 구성: 720. Synology NAS - docker 원격 제어를 위한 TCP 바인딩 추가
13711정성태8/13/20248062Linux: 77. C# / Linux - zombie process (defunct process) [1]파일 다운로드1
13710정성태8/8/20247981닷넷: 2294. C# 13 - (6) iterator 또는 비동기 메서드에서 ref와 unsafe 사용을 부분적으로 허용파일 다운로드1
13709정성태8/7/20247752닷넷: 2293. C# - safe/unsafe 문맥에 대한 C# 13의 (하위 호환을 깨는) 변화파일 다운로드1
13708정성태8/7/20247533개발 환경 구성: 719. ffmpeg / YoutubeExplode - mp4 동영상 파일로부터 Audio 파일 추출
13707정성태8/6/20247772닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/20247894개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/20248153닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용 [2]파일 다운로드1
13704정성태8/2/20248110닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/20247437닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/20247841닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/20248109닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/20247716디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/20248237닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/20248194닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/20247920닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/20247454오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/20247438닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/20247905닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/20247233개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...