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

... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12413정성태11/17/202010643.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202012885.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/20209872오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209796디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011196.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022650도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011458.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202013068.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010513.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202011028.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202011093.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011688.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010600VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207595오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011267.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209756오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/20209898.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208258VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209589오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20207989오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208474오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012594.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202010830디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010629.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010068오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202010818.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...