🔥 도움말 제공하기

223자
3분

ArgumentParser는 사용자가 -h 또는 --help 플래그를 사용하면 모든 명령에 대한 도움말을 자동 생성합니다.

shell
% count --help
USAGE: count --input <input> --output <output> [--verbose]
 
 
OPTIONS:
  -i, --input <input>
  -o, --output <output>
  -v, --verbose
  -h, --help              Show help information.
 
shell
% count --help
USAGE: count --input <input> --output <output> [--verbose]
 
 
OPTIONS:
  -i, --input <input>
  -o, --output <output>
  -v, --verbose
  -h, --help              Show help information.
 

이는 좋은 출발점입니다. 개발자가 정의한 모든 옵션 이름이 표시되고, 도움말에는 --input--output 옵션에 값이 필요하다는 걸 보여줍니다. 하지만 커스텀 옵션과 플래그에는 설명이 없습니다. 이제 문자열을 help 매개변수로 전달하여 설명을 추가해 봅시다.

swift
@main
struct Count: ParsableCommand {
    // 입력 파일 경로를 받는 옵션
    @Option(name: [.short, .customLong("input")], help: "A file to read.")
    var inputFile: String
 
    // 출력 파일 경로를 받는 옵션
    @Option(name: [.short, .customLong("output")], help: "A file to save word counts to.")
    var outputFile: String
 
    // 자세한 출력 여부를 지정하는 플래그
    @Flag(name: .shortAndLong, help: "Print status updates while counting.")
    var verbose = false
 
    // 실제 코드가 실행되는 부분
    mutating func run() throws { ... }
}
 
swift
@main
struct Count: ParsableCommand {
    // 입력 파일 경로를 받는 옵션
    @Option(name: [.short, .customLong("input")], help: "A file to read.")
    var inputFile: String
 
    // 출력 파일 경로를 받는 옵션
    @Option(name: [.short, .customLong("output")], help: "A file to save word counts to.")
    var outputFile: String
 
    // 자세한 출력 여부를 지정하는 플래그
    @Flag(name: .shortAndLong, help: "Print status updates while counting.")
    var verbose = false
 
    // 실제 코드가 실행되는 부분
    mutating func run() throws { ... }
}
 

이제 도움말 화면이 각 매개변수에 대한 설명을 포함합니다.

shell
% count -h
USAGE: count --input <input> --output <output> [--verbose]
 
 
OPTIONS:
  -i, --input <input>     A file to read.
  -o, --output <output>   A file to save word counts to.
  -v, --verbose           Print status updates while counting.
  -h, --help              Show help information.
 
shell
% count -h
USAGE: count --input <input> --output <output> [--verbose]
 
 
OPTIONS:
  -i, --input <input>     A file to read.
  -o, --output <output>   A file to save word counts to.
  -v, --verbose           Print status updates while counting.
  -h, --help              Show help information.
 

코드를 자세히 살펴보면 @Option@Flag 속성의 help 인자로 각 옵션과 플래그에 대한 설명을 제공했습니다. 이렇게 하면 사용자가 프로그램을 어떻게 사용해야 할지 더 잘 이해할 수 있겠죠?

YouTube 영상

채널 보기
입력을 전처리하는 Functor - Contravariant와 contramap 이해하기 | 프로그래머를 위한 카테고리 이론
매번 ValidationPipe 복붙하세요? NestJS 전역 파이프로 한 번에 해결하기 | NestJS 가이드
함수 타입과 Hom-Set 이해하기 | 프로그래머를 위한 카테고리 이론
Writer 펑터와 클라이슬리 카테고리 | 프로그래머를 위한 카테고리 이론
존 매카시가 들려주는 인공지능의 탄생 이야기
class-validator 와 DTO | NestJS 가이드
NestJS 역할 기반 접근 권한 부여 - Guard, Reflector | NestJS 가이드
Git Worktree로 여러 피처 동시에 개발하기 | AI 코딩 시대의 필수 스킬