🎉 Initial Commit of next version RoadSign CLI

This commit is contained in:
LittleSheep 2024-10-01 22:19:27 +08:00
parent 28d3a3fa06
commit 632d37caf5
12 changed files with 415 additions and 1 deletions

175
cli/.gitignore vendored Normal file
View File

@ -0,0 +1,175 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Caches
.cache
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store

3
cli/README.md Normal file
View File

@ -0,0 +1,3 @@
# RoadSign CLI
RoadSign CLI is a command-line interface (CLI) tool that allows you to manage your RoadSign servers and applications.

BIN
cli/bun.lockb Executable file

Binary file not shown.

24
cli/index.ts Normal file
View File

@ -0,0 +1,24 @@
import { Cli } from "clipanion"
import figlet from "figlet"
import chalk from "chalk"
import { LoginCommand } from "./src/cmd/login.ts"
import { LogoutCommand } from "./src/cmd/logout.ts"
import { ListServerCommand } from "./src/cmd/list.ts"
const [node, app, ...args] = process.argv
console.log(
chalk.yellow(figlet.textSync("RoadSign CLI", { horizontalLayout: "default", verticalLayout: "default" }))
)
const cli = new Cli({
binaryLabel: `RoadSign CLI`,
binaryName: `${node} ${app}`,
binaryVersion: `1.0.0`
})
cli.register(LoginCommand)
cli.register(LogoutCommand)
cli.register(ListServerCommand)
cli.runExit(args)

18
cli/package.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "roadsign-cli",
"module": "index.ts",
"type": "module",
"devDependencies": {
"@types/bun": "latest",
"@types/figlet": "^1.5.8"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"dependencies": {
"chalk": "^5.3.0",
"clipanion": "^4.0.0-rc.4",
"figlet": "^1.7.0",
"ora": "^8.1.0"
}
}

26
cli/src/cmd/list.ts Normal file
View File

@ -0,0 +1,26 @@
import { Command, type Usage } from "clipanion"
import { RsConfig } from "../utils/config.ts"
import chalk from "chalk"
export class ListServerCommand extends Command {
static paths = [[`list`], [`ls`]]
static usage: Usage = {
category: `Networking`,
description: `List all connected RoadSign Sideload Services`,
details: `Listing all servers that already saved in RoadSign CLI configuration file`,
examples: [["List all", `list`]]
}
async execute() {
const config = await RsConfig.getInstance()
for (let idx = 0; idx < config.config.servers.length; idx++) {
const server = config.config.servers[idx]
this.context.stdout.write(`${idx + 1}. ${chalk.bold(server.label)} ${chalk.gray(`(${server.url})`)}\n`)
}
this.context.stdout.write("\n" + chalk.cyan(`Connected ${config.config.servers.length} server(s) in total.`) + "\n")
process.exit(0)
}
}

55
cli/src/cmd/login.ts Normal file
View File

@ -0,0 +1,55 @@
import { Command, Option, type Usage } from "clipanion"
import { createAuthHeader } from "../utils/auth.ts"
import { RsConfig } from "../utils/config.ts"
import ora, { oraPromise } from "ora"
export class LoginCommand extends Command {
static paths = [[`login`]]
static usage: Usage = {
category: `Networking`,
description: `Login to RoadSign Sideload Service`,
details: `Login to RoadSign Server`,
examples: [["Login with credentials", `login <label> <host> <password>`]]
}
label = Option.String({ required: true })
host = Option.String({ required: true })
credentials = Option.String({ required: true })
async execute() {
const config = await RsConfig.getInstance()
const spinner = ora(`Connecting to ${this.host}...`).start()
if (!this.host.includes(":")) {
this.host += ":81"
}
if (!this.host.startsWith("http")) {
this.host = "http://" + this.host
}
try {
const pingRes = await fetch(`${this.host}/cgi/metadata`, {
headers: {
Authorization: createAuthHeader("RoadSign CLI", this.credentials)
}
})
if (pingRes.status !== 200) {
throw new Error(await pingRes.text())
} else {
const info = await pingRes.json()
spinner.succeed(`Connected to ${this.host}, remote version ${info["version"]}`)
config.config.servers.push({
label: this.label,
url: this.host,
credential: this.credentials
})
await oraPromise(config.writeConfig(), { text: "Saving changes..." })
}
} catch (e) {
spinner.fail(`Unable connect to remote: ${e}`)
}
process.exit(0)
}
}

31
cli/src/cmd/logout.ts Normal file
View File

@ -0,0 +1,31 @@
import { Command, Option, type Usage } from "clipanion"
import { RsConfig } from "../utils/config.ts"
import { oraPromise } from "ora"
import chalk from "chalk"
export class LogoutCommand extends Command {
static paths = [[`logout`]]
static usage: Usage = {
category: `Networking`,
description: `Logout from RoadSign Sideload Service`,
details: `Logout from RoadSign Server`,
examples: [["Logout with server label", `logout <label>`]]
}
label = Option.String({ required: true })
async execute() {
const config = await RsConfig.getInstance()
const server = config.config.servers.findIndex(item => item.label === this.label)
if (server === -1) {
this.context.stdout.write(chalk.red(`Server with label ${chalk.bold(this.label)} was not found.\n`))
} else {
config.config.servers.splice(server, 1)
this.context.stdout.write(chalk.green(`Server with label ${chalk.bold(this.label)} was successfully removed.\n`))
await oraPromise(config.writeConfig(), { text: "Saving changes..." })
}
process.exit(0)
}
}

4
cli/src/utils/auth.ts Normal file
View File

@ -0,0 +1,4 @@
export function createAuthHeader(username: string, password: string) {
const credentials = Buffer.from(`${username}:${password}`).toString("base64")
return `Basic ${credentials}`
}

51
cli/src/utils/config.ts Normal file
View File

@ -0,0 +1,51 @@
import * as os from "node:os"
import * as path from "node:path"
import * as fs from "node:fs/promises"
interface RsConfigData {
servers: RsConfigServerData[]
}
interface RsConfigServerData {
label: string
url: string
credential: string
}
class RsConfig {
private static instance: RsConfig
public config: RsConfigData = {
servers: []
}
private constructor() {
}
public static async getInstance(): Promise<RsConfig> {
if (!RsConfig.instance) {
RsConfig.instance = new RsConfig()
await RsConfig.instance.readConfig()
}
return RsConfig.instance
}
public async readConfig() {
const basepath = os.homedir()
const filepath = path.join(basepath, ".roadsignrc")
if (!await fs.exists(filepath)) {
await fs.writeFile(filepath, JSON.stringify(this.config))
}
const data = await fs.readFile(filepath, "utf8")
this.config = JSON.parse(data)
}
public async writeConfig() {
const basepath = os.homedir()
const filepath = path.join(basepath, ".roadsignrc")
await fs.writeFile(filepath, JSON.stringify(this.config))
}
}
export { RsConfig, type RsConfigData, type RsConfigServerData }

27
cli/tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}

View File

@ -42,7 +42,7 @@ func doPublish(c *fiber.Ctx) error {
var instance *warden.AppInstance
if application != nil {
if instance = warden.GetFromPool(application.ID); instance != nil {
instance.Stop()
_ = instance.Stop()
}
} else if destination != nil && destination.GetType() != navi.DestinationStaticFile {
return fiber.ErrUnprocessableEntity