Skip to content

Commit

Permalink
Merge pull request #16 from hanabi-rest/feat/private-token
Browse files Browse the repository at this point in the history
Update CLI tool usage and add config command
  • Loading branch information
yutakobayashidev authored Mar 27, 2024
2 parents 719db24 + 60a6342 commit 2b3a661
Show file tree
Hide file tree
Showing 8 changed files with 180 additions and 18 deletions.
5 changes: 5 additions & 0 deletions .changeset/poor-eggs-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hanabi.rest/cli": minor
---

Add token access for private applications
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ $ npx @hanabi/cli <version-id>

## Options

```
Usage: @hanabi/cli <version-id> [options]
```bash
Usage: @hanabi.rest/cli <version-id> [options]

Options:
-v, --version display the version number
--dir <project-directory> directory name
--skip-code-package Skip installation of npm packages imported in the code
--main-only Dumps API code only.
-h, --help display help for command

Commands:
config Configure the CLI tool
```

## Documents
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
},
"dependencies": {
"@babel/parser": "^7.23.6",
"@iarna/toml": "^2.2.5",
"chalk": "^5.3.0",
"commander": "^11.1.0",
"cross-spawn": "^7.0.3",
Expand All @@ -48,7 +49,8 @@
"package-json": "^9.0.0",
"prompts": "^2.4.2",
"ts-morph": "^21.0.1",
"validate-npm-package-name": "^5.0.0"
"validate-npm-package-name": "^5.0.0",
"xdg-app-paths": "^8.3.0"
},
"devDependencies": {
"@biomejs/biome": "1.5.3",
Expand Down
40 changes: 39 additions & 1 deletion pnpm-lock.yaml

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

46 changes: 46 additions & 0 deletions src/helpers/config-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import xdgAppPaths from "xdg-app-paths";
import path from "node:path";
import { mkdirSync, chmodSync, writeFileSync, readFileSync } from "node:fs";
import TOML from "@iarna/toml";

export const USER_AUTH_CONFIG_FILE = "config.toml";

type AuthConfig = {
api_token: string;
};

export function getGlobalConfigPath() {

return xdgAppPaths(".hanabi").config();
}

export function writeAuthConfigFile(config: AuthConfig) {
const authConfigFilePath = path.join(
getGlobalConfigPath(),
USER_AUTH_CONFIG_FILE
);
mkdirSync(path.dirname(authConfigFilePath), {
recursive: true,
});
writeFileSync(
path.join(authConfigFilePath),
TOML.stringify(config as TOML.JsonMap),
{ encoding: "utf-8" }
);

chmodSync(path.join(authConfigFilePath), 0o600);

}
export function readConfig() {
const authConfigFilePath = path.join(
getGlobalConfigPath(),
USER_AUTH_CONFIG_FILE
);
try {
const normalizedInput = readFileSync(authConfigFilePath, { encoding: "utf-8" }).replace(/\r\n/g, "\n");

return TOML.parse(normalizedInput) as AuthConfig;
} catch (e) {
return null;
}
}
36 changes: 28 additions & 8 deletions src/helpers/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@
import fetch from "node-fetch";
import { readConfig } from "./config-path";

const API_ROOT = process.env.API_ROOT || "https://api.hanabi.rest";

const config = readConfig();

const handleResponseStatus = (status: number) => {
const messages: { [key: number]: string } = {
404: "Application not found.",
403: config?.api_token ? "You cannot access this application. Please check if the access token is set correctly." : "You need to set an access token to access this application. Please set the token with `@hanabi.rest/cli config set`.",
};

if (status !== 200) {
console.error(messages[status] || "Failed to fetch application. Please try again later.");
process.exit(1);
}
};

export async function getFiles(version_id: string) {

const headers: { "Content-Type": string; Authorization?: string } = {
"Content-Type": "application/json",
};

if (config?.api_token) {
headers.Authorization = `Bearer ${config.api_token}`;
}

const res = await fetch(
`${API_ROOT}/applications/versions/${version_id}/files`
`${API_ROOT}/applications/versions/${version_id}/files`, {
headers
}
);

if (res.status === 404) {
console.error("Application not found. Please make sure it is published.");
process.exit(1);
} else if (res.status !== 200) {
console.error("Failed to fetch application. Please try again later.");
process.exit(1);
}
handleResponseStatus(res.status);

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const filesData: any = await res.json();
Expand Down
57 changes: 52 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env node

import path from "path";
import path from "node:path";
import { getFiles } from "@/src/helpers/fetch";
import chalk from "chalk";
import { Command } from "commander";
Expand All @@ -12,6 +12,7 @@ import { getOnline } from "./helpers/get-online";
import { getPkgManager } from "./helpers/get-pkg-manager";
import { validateNpmName } from "./helpers/validate-pkg";
import packageJson from "../package.json";
import { readConfig, writeAuthConfigFile } from "./helpers/config-path";

process.on("SIGINT", () => process.exit(0));
process.on("SIGTERM", () => process.exit(0));
Expand Down Expand Up @@ -55,6 +56,18 @@ async function main() {
process.exit(1);
}

const config = readConfig();

if (!config?.api_token) {
console.info(chalk.yellow(`Warning: To access a private application, set the token with ${chalk.bold("@hanabi.rest/cli config set")}`));
console.info();
}

if (!name) {
console.error("Please provide a version id.");
process.exit(1);
}

if (options.mainOnly) {
const { source } = await getFiles(name);

Expand All @@ -80,10 +93,10 @@ async function main() {
const packageManager = options.useNpm
? "npm"
: options.usePnpm
? "pnpm"
: options.useYarn
? "yarn"
: getPkgManager();
? "pnpm"
: options.useYarn
? "yarn"
: getPkgManager();

projectPath = options.dir;

Expand Down Expand Up @@ -146,6 +159,40 @@ async function main() {
})
.allowUnknownOption();

const configCommand = program.command('config')
.description('Configure the CLI tool');

// config setサブコマンドを追加
configCommand
.command('set')
.description('Set a configuration option')
.option('--api-key [key]', 'Set the access token for authentication')
.action(async (options) => {
let apiKey: string = options.apiKey;

if (!apiKey) {

console.info(chalk.blue("To get your access token, visit: https://hanabi.rest/settings/tokens"))
console.info()

const response = await prompts({
type: 'password',
name: 'key',
message: 'Enter your Access token:',
});
apiKey = response.key;
}

if (apiKey) {
writeAuthConfigFile({ api_token: apiKey });

console.info()
console.info(chalk.green('access token saved successfully.'));
} else {
console.error(chalk.red('access token is required.'));
}
});

program.parse();
}

Expand Down
3 changes: 2 additions & 1 deletion templates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const installTemplate = async ({
appId: string;
}) => {
console.info(`Using ${packageManager}`);
console.info()

const { md, sql, source } = await getFiles(appId);

Expand Down Expand Up @@ -90,7 +91,7 @@ export const installTemplate = async ({
JSON.stringify(packageJson, null, 2) + os.EOL
);

console.info("\nInstalling dependencies:");
console.info("Installing dependencies:");
for (const dependency in packageJson.dependencies)
console.info(`- ${chalk.cyan(dependency)}`);

Expand Down

0 comments on commit 2b3a661

Please sign in to comment.