Skip to content

Commit

Permalink
feat: string transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
moontai0724 committed Oct 7, 2024
1 parent 36c72e9 commit 68f49fa
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
79 changes: 79 additions & 0 deletions src/transformers/string.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { Type } from "@sinclair/typebox";
import { expect, it } from "vitest";
import type { Options } from "yargs";

import { getStringOption } from "./string";

it("should transform TString to yargs option", () => {
const schema = Type.String();

const result = getStringOption(schema);

expect(result).toEqual({
type: "string",
requiresArg: true,
});
});

it("should transform TString with truthy default value to yargs option", () => {
const schema = Type.String({ default: "foo" });

const result = getStringOption(schema);

expect(result).toEqual({
type: "string",
requiresArg: false,
default: "foo",
});
});

it("should transform TString with falsy default value to yargs option", () => {
const schema = Type.String({ default: "" });

const result = getStringOption(schema);

expect(result).toEqual({
type: "string",
requiresArg: false,
default: "",
});
});

it("should transform TString with description to yargs option", () => {
const schema = Type.String({ description: "foo" });

const result = getStringOption(schema);

expect(result).toEqual({
type: "string",
requiresArg: true,
description: "foo",
});
});

it("should transform TString with override to yargs option", () => {
const schema = Type.String();
const overwrite: Options = {
requiresArg: false,
alias: "aliased",
};

const result = getStringOption(schema, overwrite);

expect(result).toEqual({
type: "string",
requiresArg: false,
alias: "aliased",
});
});

it("should detect if it is optional", () => {
const schema = Type.Optional(Type.String());

const result = getStringOption(schema);

expect(result).toEqual({
type: "string",
requiresArg: false,
});
});
22 changes: 22 additions & 0 deletions src/transformers/string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { type TString, TypeGuard } from "@sinclair/typebox";
import type { Options } from "yargs";

export function getStringOption(
schema: TString,
override: Options = {},
): Options {
const hasDefaultValue = schema.default !== undefined;
const options = {
type: "string" as const,
requiresArg: !TypeGuard.IsOptional(schema) && !hasDefaultValue,
};

if (hasDefaultValue)
Object.assign(options, { default: schema.default as string });
if (schema.description)
Object.assign(options, { description: schema.description });

Object.assign(options, override);

return options;
}

0 comments on commit 68f49fa

Please sign in to comment.