CLI 플래그에 if 문 작성을 그만두세요
洪 民憙 (Hong Minhee) @hongminhee@hackers.pub
CLI 도구를 만들어 보셨다면, 이런 코드를 작성해 보셨을 겁니다:
if (opts.reporter === "junit" && !opts.outputFile) {
throw new Error("--output-file is required for junit reporter");
}
if (opts.reporter === "html" && !opts.outputFile) {
throw new Error("--output-file is required for html reporter");
}
if (opts.reporter === "console" && opts.outputFile) {
console.warn("--output-file is ignored for console reporter");
}
몇 달 전, 저는 CLI 유효성 검사 작성을 그만두세요. 처음부터 올바르게 파싱하세요. 라는 글에서 개별 옵션 값을 올바르게 파싱하는 방법에 대해 썼습니다. 하지만 그 글에서는 옵션 간의 관계를 다루지 않았습니다.
위 코드에서 --output-file은 --reporter가 junit이나 html일 때만 의미가 있습니다. console일 때는 이 옵션이 아예 존재하지 않아야 합니다.
우리는 TypeScript를 사용하고 있습니다. 강력한 타입 시스템이 있습니다. 그런데도 여기서는 컴파일러가 도울 수 없는 런타임 검사를 작성하고 있습니다. 새로운 리포터 타입을 추가할 때마다 이러한 검사를 업데이트해야 합니다. 리팩토링할 때마다 하나라도 놓치지 않았기를 바랄 뿐입니다.
TypeScript CLI 파서의 현재 상태
Commander, yargs, minimist와 같은 오래된 라이브러리들은 TypeScript가 주류가 되기 전에 만들어졌습니다. 이들은 문자열 묶음을 제공하고 타입 안전성은 사용자의 몫으로 남겨둡니다.
하지만 우리는 발전했습니다. cmd-ts와 Clipanion(Yarn Berry를 지원하는 라이브러리)과 같은 현대적인 TypeScript 우선 라이브러리들은 타입을 진지하게 다룹니다:
// cmd-ts
const app = command({
args: {
reporter: option({ type: string, long: 'reporter' }),
outputFile: option({ type: string, long: 'output-file' }),
},
handler: (args) => {
// args.reporter: string
// args.outputFile: string
},
});
// Clipanion
class TestCommand extends Command {
reporter = Option.String('--reporter');
outputFile = Option.String('--output-file');
}
이러한 라이브러리들은 개별 옵션에 대한 타입을 추론합니다. --port는 number입니다. --verbose는 boolean입니다. 이는 실질적인 발전입니다.
하지만 이들이 할 수 없는 것이 있습니다: --reporter가 junit일 때 --output-file이 필요하고, --reporter가 console일 때는 금지된다는 옵션 간의 관계를 표현하는 것입니다. 옵션 간의 관계는 타입 시스템에 포착되지 않습니다.
그래서 결국 유효성 검사 코드를 작성하게 됩니다:
handler: (args) => {
// Both cmd-ts and Clipanion need this
if (args.reporter === "junit" && !args.outputFile) {
throw new Error("--output-file required for junit");
}
// args.outputFile is still string | undefined
// TypeScript doesn't know it's definitely string when reporter is "junit"
}
Rust의 clap과 Python의 Click은 requires와 conflicts_with 속성을 가지고 있지만, 이것들도 런타임 검사일 뿐입니다. 결과 타입을 변경하지는 않습니다.
파서 구성이 옵션 간의 관계를 알고 있다면, 왜 그 지식이 결과 타입에 나타나지 않을까요?
conditional()로 관계 모델링하기
Optique는 옵션 간의 관계를 일급 개념으로 취급합니다. 다음은 테스트 리포터 시나리오입니다:
import { conditional, object } from "@optique/core/constructs";
import { option } from "@optique/core/primitives";
import { choice, string } from "@optique/core/valueparser";
import { run } from "@optique/run";
const parser = conditional(
option("--reporter", choice(["console", "junit", "html"])),
{
console: object({}),
junit: object({
outputFile: option("--output-file", string()),
}),
html: object({
outputFile: option("--output-file", string()),
openBrowser: option("--open-browser"),
}),
}
);
const [reporter, config] = run(parser);
conditional() 컴비네이터는 구분자 옵션(--reporter)과 분기 맵을 받습니다. 각 분기는 해당 구분자 값에 대해 유효한 다른 옵션들을 정의합니다.
TypeScript는 결과 타입을 자동으로 추론합니다:
type Result =
| ["console", {}]
| ["junit", { outputFile: string }]
| ["html", { outputFile: string; openBrowser: boolean }];
reporter가 "junit"일 때, outputFile은 string | undefined가 아닌 string입니다. 관계가 타입에 인코딩되어 있습니다.
이제 비즈니스 로직에 진정한 타입 안전성이 생깁니다:
const [reporter, config] = run(parser);
switch (reporter) {
case "console":
runWithConsoleOutput();
break;
case "junit":
// TypeScript는 config.outputFile이 string임을 알고 있습니다
writeJUnitReport(config.outputFile);
break;
case "html":
// TypeScript는 config.outputFile과 config.openBrowser가 존재함을 알고 있습니다
writeHtmlReport(config.outputFile);
if (config.openBrowser) openInBrowser(config.outputFile);
break;
}
유효성 검사 코드가 없습니다. 런타임 검사도 없습니다. 새 리포터 타입을 추가하고 switch문에서 처리하는 것을 잊어버리면 컴파일러가 알려줍니다.
더 복잡한 예: 데이터베이스 연결
테스트 리포터는 좋은 예시지만, 더 다양한 변형이 있는 것을 시도해 봅시다. 데이터베이스 연결 문자열:
myapp --db=sqlite --file=./data.db
myapp --db=postgres --host=localhost --port=5432 --user=admin
myapp --db=mysql --host=localhost --port=3306 --user=root --ssl
각 데이터베이스 유형은 완전히 다른 옵션이 필요합니다:
- SQLite는 파일 경로만 필요합니다
- PostgreSQL은 호스트, 포트, 사용자, 그리고 선택적으로 비밀번호가 필요합니다
- MySQL은 호스트, 포트, 사용자가 필요하고 SSL 플래그가 있습니다
이를 모델링하는 방법은 다음과 같습니다:
import { conditional, object } from "@optique/core/constructs";
import { withDefault, optional } from "@optique/core/modifiers";
import { option } from "@optique/core/primitives";
import { choice, string, integer } from "@optique/core/valueparser";
const dbParser = conditional(
option("--db", choice(["sqlite", "postgres", "mysql"])),
{
sqlite: object({
file: option("--file", string()),
}),
postgres: object({
host: option("--host", string()),
port: withDefault(option("--port", integer()), 5432),
user: option("--user", string()),
password: optional(option("--password", string())),
}),
mysql: object({
host: option("--host", string()),
port: withDefault(option("--port", integer()), 3306),
user: option("--user", string()),
ssl: option("--ssl"),
}),
}
);
추론된 타입:
type DbConfig =
| ["sqlite", { file: string }]
| ["postgres", { host: string; port: number; user: string; password?: string }]
| ["mysql", { host: string; port: number; user: string; ssl: boolean }];
세부 사항을 주목하세요: PostgreSQL은 기본 포트가 5432, MySQL은 3306입니다. PostgreSQL은 선택적 비밀번호가 있고, MySQL은 SSL 플래그가 있습니다. 각 데이터베이스 유형은 필요한 옵션만 정확히 가지고 있습니다 - 더도 말고 덜도 말고.
이 구조에서는 모드가 sqlite일 때 dbConfig.ssl을 작성하는 것은 런타임 오류가 아니라 컴파일 타임에 불가능한 일입니다.
requires_if 속성으로 이것을 표현해 보세요. 할 수 없습니다. 관계가 너무 복잡합니다.
이 패턴은 어디에나 있습니다
한 번 보면, 많은 CLI 도구에서 이 패턴을 발견할 수 있습니다:
인증 모드:
const authParser = conditional(
option("--auth", choice(["none", "basic", "token", "oauth"])),
{
none: object({}),
basic: object({
username: option("--username", string()),
password: option("--password", string()),
}),
token: object({
token: option("--token", string()),
}),
oauth: object({
clientId: option("--client-id", string()),
clientSecret: option("--client-secret", string()),
tokenUrl: option("--token-url", url()),
}),
}
);
배포 대상, 출력 형식, 연결 프로토콜 - 다른 옵션의 유효성을 결정하는 모드 선택기가 있는 모든 곳에서 이 패턴을 볼 수 있습니다.
conditional()이 존재하는 이유
Optique에는 이미 상호 배타적인 대안을 위한 or() 컴비네이터가 있습니다. 왜 conditional()이 필요할까요?
or() 컴비네이터는 구조에 기반하여 분기를 구분합니다 - 어떤 옵션이 존재하는지에 따라 달라집니다. 이는 git commit과 git push와 같이 인수가 완전히 다른 하위 명령에 잘 작동합니다.
하지만 리포터 예제에서는 구조가 동일합니다: 모든 분기에 --reporter 플래그가 있습니다. 차이점은 플래그의 존재가 아니라 값에 있습니다.
// 이렇게 하면 의도한 대로 작동하지 않습니다
const parser = or(
object({ reporter: option("--reporter", choice(["console"])) }),
object({
reporter: option("--reporter", choice(["junit", "html"])),
outputFile: option("--output-file", string())
}),
);
--reporter junit을 전달하면, or()는 어떤 옵션이 존재하는지에 기반하여 분기를 선택하려고 합니다. 두 분기 모두 --reporter를 가지고 있으므로 구조적으로 구분할 수 없습니다.
conditional()은 먼저 구분자의 값을 읽은 다음 적절한 분기를 선택하여 이 문제를 해결합니다. 이는 구조적 파싱과 값 기반 결정 사이의 간극을 메웁니다.
구조가 제약 조건입니다
옵션을 느슨한 타입으로 파싱한 다음 관계를 검증하는 대신, 구조 자체가 제약 조건인 파서를 정의하세요.
| 전통적인 접근 방식 | Optique 접근 방식 |
|---|---|
| 파싱 → 검증 → 사용 | 파싱 (제약 조건 포함) → 사용 |
| 타입과 검증 로직이 별도로 유지됨 | 타입이 제약 조건을 반영함 |
| 불일치가 런타임에 발견됨 | 불일치가 컴파일 타임에 발견됨 |
파서 정의가 단일 진실 소스가 됩니다. 새 리포터 타입을 추가하시나요? 파서 정의가 변경되고, 추론된 타입이 변경되며, 컴파일러는 업데이트가 필요한 모든 곳을 보여줍니다.
시도해 보세요
이것이 여러분이 구축 중인 CLI와 공감된다면:
다음에 옵션 관계를 확인하는 if 문을 작성하려고 할 때, 이렇게 물어보세요: 파서가 이 제약 조건을 대신 표현할 수 있을까요?
파서의 구조가 제약 조건입니다. 검증 코드가 전혀 필요하지 않을 수도 있습니다.