Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cli #123

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions packages/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env node

import chalk from "chalk";
import { Command } from "commander";
import { execa } from "execa";
import { parse as envParse, config as envConfig } from "dotenv";
import path from "path";

const logger = {
error(...args: unknown[]) {
console.log(chalk.red(...args));
},
warn(...args: unknown[]) {
console.log(chalk.yellow(...args));
},
info(...args: unknown[]) {
console.log(chalk.cyan(...args));
},
success(...args: unknown[]) {
console.log(chalk.green(...args));
},
};

const head = <T>(arr: T[]): T | undefined => {
return arr.length > 0 ? arr[0] : undefined;
};

const tail = <T>(arr: T[]): T[] => {
return arr.slice(1);
};

const printVariable = (name: string) => {
const value = process.env[name];
logger.info(`'${name}' = '${value}'`);
};

const validateCustomVariable = (param: string) => {
const pattern = /^\w+="[a-zA-Z0-9"=^!?%@_&\-/:;.]"+$/;
if (!pattern.test(param)) {
logger.error(
`Unexpected argument '${param}'. Expected variable in the format of name=value`
);
process.exit(2);
}

return param;
};

const assignCustomVariables = (variables: string[]) => {
if (!variables) {
return;
}

const parsedVariables = envParse(
Buffer.from(variables.map(validateCustomVariable).join("\n"))
);

Object.assign(process.env, parsedVariables);
};

const main = async () => {
const program = new Command().name("t3-env");
program
.description("description")
.option(
"-e, --env <path...>",
"parses the file and adds the variables to the environment",
[".env"]
)
.option("-m, --validation <path>", "the `env.mjs` to run for validation")
.option(
"-v, --variables <name=value...>",
"put custom variable <name> with value of <value> into environment"
)
.option(
"-p, --print <name...>",
"print the value of <variable> to the console and exit"
)
.argument(
"[command]",
"`command` is the command you want to run. Best practice is to precede this command with ` -- `"
);

program.parse(process.argv);

const options = program.opts();
const envPaths: string[] = options.env;

envPaths.forEach((env) => {
envConfig({ path: path.resolve(env) });
});

assignCustomVariables(options.variables);

if (options.validation) {
await import(`file://${path.resolve(options.validation)}`);
}

if (options.print) {
options.print.forEach(printVariable);
process.exit(0);
}

const cmd = head(program.args);
if (!cmd) {
program.help();
process.exit(2);
}

try {
await execa(cmd, tail(program.args), {
stdout: "inherit",
});
} catch (error) {
logger.error(error);
process.exit(1);
}

process.exit(0);
};

main().catch((err) => {
if (err instanceof Error) {
logger.error(err);
} else {
logger.error(
"An unknown error has occurred. Please open an issue on github with the below:"
);
console.log(err);
}
process.exit(1);
});
52 changes: 52 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "@t3-oss/env-cli",
"version": "0.1.0",
"keywords": [
"create-t3-app",
"environment variables",
"zod",
"cli"
],
"author": "Julius Marminge",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/t3-oss/t3-env",
"directory": "packages/cli"
},
"type": "module",
"bin": {
"t3-env": "./dist/index.js"
},
"files": [
"dist",
"package.json",
"LICENSE",
"README.md"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"lint": "eslint . --ext .ts",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@t3-oss/env-core": "0.6.1",
"chalk": "^5.3.0",
"commander": "^11.0.0",
"dotenv": "^16.3.1",
"execa": "^8.0.1"
},
"peerDependencies": {
"typescript": ">=4.7.2",
"zod": "^3.0.0"
},
"devDependencies": {
"eslint": "^8.39.0",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"zod": "^3.20.2"
}
}
5 changes: 5 additions & 0 deletions packages/cli/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../tsconfig.json",
"include": ["index.ts", "tsup.config.ts", "test"],
"exclude": ["dist"]
}
13 changes: 13 additions & 0 deletions packages/cli/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineConfig } from "tsup";

export default defineConfig((opts) => ({
entryPoints: ["index.ts"],
splitting: true,
format: ["esm", "cjs"],
dts: true,
clean: !opts.watch,
sourcemap: true,
minify: true,
outDir: "dist",
target: "es2020",
}));
76 changes: 76 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.