Optique 0.4.0: 개선된 도움말, 풍부한 문서, 그리고 Temporal 지원

洪 民憙 (Hong Minhee) @hongminhee@hackers.pub

Optique 0.4.0 출시를 발표하게 되어 기쁩니다. 이번 버전은 도움말 텍스트 구성의 중요한 개선, 향상된 문서화 기능, 그리고 포괄적인 Temporal API 지원을 제공합니다.

Optique는 TypeScript를 위한 타입 안전한 조합형 CLI 파서로, 명령줄 인터페이스를 직관적이고 유지보수하기 쉽게 구축할 수 있게 해줍니다. 이번 릴리스는 CLI 애플리케이션을 더 사용자 친화적이고 유지보수하기 쉽게 만드는 데 중점을 두었습니다.

개선된 도움말 텍스트 구성

Optique 0.4.0에서 가장 눈에 띄는 개선 사항 중 하나는 향상된 도움말 텍스트 구성입니다. 이제 옵션을 더 효과적으로 라벨링하고 그룹화할 수 있어, 복잡한 CLI를 사용자가 더 쉽게 접근할 수 있게 되었습니다.

라벨이 있는 병합 그룹

merge() 조합자는 이제 선택적 라벨 매개변수를 받아들입니다. 이는 개발자가 깔끔한 코드 구조와 조직화된 도움말 출력 사이에서 선택해야 했던 일반적인 문제점을 해결합니다:

// 이전: 라벨이 없는 병합된 옵션들은 흩어져 보였습니다
const config = merge(connectionOptions, performanceOptions);

// 이제: 관련 옵션을 명확한 섹션 아래에 그룹화
const config = merge(
  "Server Configuration",  // 새로운 라벨 매개변수
  connectionOptions,
  performanceOptions
);

이 간단한 추가 기능은 특히 여러 재사용 가능한 모듈에 걸쳐 많은 옵션이 있는 CLI의 경우, 도움말 텍스트 가독성에 큰 차이를 만듭니다.

결과적으로 도움말 출력은 Server Configuration 섹션 아래에 옵션을 명확하게 구성합니다:

Demo app showcasing labeled merge groups
Usage: [1mdemo-merge.ts[0m [3m--host[0m [4m[2mSTRING[0m [3m--port[0m [4m[2mINTEGER[0m [3m--timeout[0m [4m[2mINTEGER[0m [3m--retries[0m
       [4m[2mINTEGER[0m

Server Configuration:
  [3m--host[0m [4m[2mSTRING[0m               Server hostname or IP address
  [3m--port[0m [4m[2mINTEGER[0m              Port number for the connection
  [3m--timeout[0m [4m[2mINTEGER[0m           Connection timeout in seconds
  [3m--retries[0m [4m[2mINTEGER[0m           Number of retry attempts

새로운 group() 조합자

merge()가 적용되지 않는 경우, 새로운 group() 조합자를 사용하면 어떤 파서든 문서화 라벨로 감쌀 수 있습니다:

// 상호 배타적인 옵션을 명확한 섹션 아래에 그룹화
const outputFormat = group(
  "Output Format",
  or(
    map(flag("--json"), () => "json"),
    map(flag("--yaml"), () => "yaml"),
    map(flag("--xml"), () => "xml"),
  )
);

이는 상호 배타적인 플래그, 다중 입력 또는 기본적으로 라벨링을 지원하지 않는 모든 파서를 구성하는 데 특히 유용합니다. 결과적으로 도움말 텍스트는 훨씬 더 스캔하기 쉽고 사용자 친화적이 됩니다.

다음은 그룹화된 출력 형식 옵션이 도움말 텍스트에 표시되는 방식입니다:

Demo app showcasing group combinator
Usage: [1mdemo-group.ts[0m [3m--json[0m
       [1mdemo-group.ts[0m [3m--yaml[0m
       [1mdemo-group.ts[0m [3m--xml[0m

Output Format:
  [3m--json[0m                      Output in JSON format
  [3m--yaml[0m                      Output in YAML format
  [3m--xml[0m                       Output in XML format

풍부한 문서화 지원

Optique 0.4.0은 run() 함수를 통해 직접 추가할 수 있는 포괄적인 문서화 필드를 도입하여, 문서화 목적으로 파서 정의를 수정할 필요성을 제거했습니다.

간략한 설명, 상세한 설명 및 푸터

@optique/core/facade@optique/run 모두 이제 run() 함수를 통해 brief, description, 그리고 footer 옵션을 지원합니다:

import { run } from "@optique/run";
import { message } from "@optique/core/message";

const result = run(parser, {
  brief: message`A powerful data processing tool`,
  description: message`This tool provides comprehensive data processing capabilities with support for multiple formats and transformations. It can handle JSON, YAML, and CSV files with automatic format detection.`,
  footer: message`Examples:
  myapp process data.json --format yaml
  myapp validate config.toml --strict

For more information, visit https://example.com/docs`,
  help: "option"
});

이러한 문서화 필드는 도움말 출력과 오류 메시지(구성된 경우) 모두에 표시되어, CLI의 사용자 경험 전반에 걸쳐 일관된 컨텍스트를 제공합니다.

완전한 도움말 출력은 간략한 설명, 상세한 설명, 옵션 설명, 기본값 및 푸터 정보와 함께 풍부한 문서화 기능을 보여줍니다:

A powerful data processing tool
Usage: [1mdemo-rich-docs.ts[0m [2m[[0m[3m--port[0m [4m[2mINTEGER[0m[2m][0m [2m[[0m[3m--format[0m [4m[2mSTRING[0m[2m][0m [3m--verbose[0m [4m[2mSTRING[0m

This tool provides comprehensive data processing capabilities with support for
multiple formats and transformations. It can handle JSON, YAML, and CSV files
with automatic format detection.

  [3m--port[0m [4m[2mINTEGER[0m              Server port number[2m [3000][0m
  [3m--format[0m [4m[2mSTRING[0m             Output format[2m [json][0m
  [3m--verbose[0m [4m[2mSTRING[0m            Verbosity level

Examples:
  myapp process data.json --format yaml
  myapp validate config.toml --strict

For more information, visit https://example.com/docs

이러한 문서화 필드는 도움말 출력과 오류 메시지(구성된 경우) 모두에 표시되어, CLI의 사용자 경험 전반에 걸쳐 일관된 컨텍스트를 제공합니다.

기본값 표시

자주 요청되던 기능이 이제 사용 가능합니다: 도움말 텍스트에 직접 기본값 표시하기. withDefault()를 사용할 때 새로운 showDefault 옵션으로 이 기능을 활성화할 수 있습니다:

const parser = object({
  port: withDefault(
    option("--port", integer(), { description: message`Server port number` }),
    3000,
  ),
  format: withDefault(
    option("--format", string(), { description: message`Output format` }),
    "json",
  ),
});

run(parser, { showDefault: true });

// 또는 사용자 지정 형식으로:
run(parser, {
  showDefault: {
    prefix: " (default: ",
    suffix: ")"
  }  // 표시: --port (default: 3000)
});

색상이 활성화되면 기본값은 자동으로 흐리게 표시되어, 시각적으로 구분되면서도 읽기 쉽게 유지됩니다.

도움말 출력은 각 옵션 옆에 기본값을 명확하게 표시합니다:

Usage: [1mdemo-defaults.ts[0m [2m[[0m[3m--port[0m [4m[2mINTEGER[0m[2m][0m [2m[[0m[3m--format[0m [4m[2mSTRING[0m[2m][0m

  [3m--port[0m [4m[2mINTEGER[0m              Server port number[2m [3000][0m
  [3m--format[0m [4m[2mSTRING[0m             Output format[2m [json][0m

Temporal API 지원

Optique 0.4.0은 새로운 패키지인 @optique/temporal을 도입하여 현대적인 Temporal API에 대한 포괄적인 지원을 제공합니다. 이는 날짜, 시간, 기간 및 시간대에 대한 타입 안전한 파싱을 가능하게 합니다:

import { instant, duration, zonedDateTime } from "@optique/temporal";
import { option } from "@optique/core/parser";

const parser = object({
  // ISO 8601 타임스탬프 파싱
  timestamp: option("--at", instant()),

  // "PT30M" 또는 "P1DT2H"와 같은 기간 파싱
  timeout: option("--timeout", duration()),

  // 시간대 정보가 있는 시간대 날짜시간 파싱
  meeting: option("--meeting", zonedDateTime()),
});

temporal 파서는 완전한 기능을 갖춘 네이티브 Temporal 객체를 반환합니다:

const result = parse(timestampArg, ["2023-12-25T10:30:00Z"]);
if (result.success) {
  const instant = result.value;
  console.log(`UTC: ${instant.toString()}`);
  console.log(`Seoul: ${instant.toZonedDateTimeISO("Asia/Seoul")}`);
}

새 패키지를 다음과 같이 설치하세요:

npm add @optique/temporal

개선된 타입 추론

merge() 조합자는 이제 최대 10개의 파서를 지원하며(이전에는 5개), tuple() 파서는 TypeScript의 const 타입 매개변수를 사용하여 타입 추론이 개선되었습니다. 이러한 개선 사항은 완벽한 타입 안전성을 유지하면서 더 복잡한 CLI 구조를 가능하게 합니다.

주요 변경 사항

대부분의 API에 대해 이전 버전과의 호환성을 유지했지만, 알아두어야 할 몇 가지 변경 사항이 있습니다:

  • Parser.getDocFragments() 메서드는 이제 직접적인 상태 값 대신 DocState<TState>를 사용합니다(사용자 정의 파서 구현에만 영향)
  • merge() 조합자는 이제 컴파일 시간에 더 엄격한 타입 제약을 적용하여 객체를 생성하지 않는 파서를 거부합니다

더 알아보기

변경 사항, 버그 수정 및 개선 사항의 전체 목록은 전체 변경 로그를 참조하세요.

업데이트된 문서를 확인하세요:

설치

Optique 0.4.0으로 업그레이드:

npm update @optique/core @optique/run
# 또는
deno add jsr:@optique/core@^0.4.0 jsr:@optique/run@^0.4.0

temporal 지원 추가(선택 사항):

npm add @optique/temporal
# 또는
deno add jsr:@optique/temporal

이러한 개선 사항들이 Optique를 사용한 CLI 애플리케이션 구축을 더욱 즐겁게 만들어 주기를 바랍니다. 항상 그렇듯이, GitHub에서 여러분의 피드백과 기여를 환영합니다.

1

No comments

If you have a fediverse account, you can comment on this article from your own instance. Search https://hackers.pub/ap/articles/01991aa2-edea-797e-aad6-2f1ece168909 on your instance and reply to it.