From ff2c04b774b81b849c60a46c18dde2555c51b61e Mon Sep 17 00:00:00 2001 From: yieldray Date: Mon, 11 Mar 2024 19:02:05 +0800 Subject: [PATCH] feat: initial commit --- .github/workflows/release.yml | 26 +++++++++ LICENSE | 21 +++++++ README.md | 35 ++++++++++- add.mjs | 8 --- add.test.mjs | 8 --- cli.mjs | 106 ++++++++++++++++++++++++++-------- config.mjs | 55 ++++++++++++++++++ config.test.mjs | 7 +++ index.mjs | 3 +- package.json | 41 +++++++++---- registry.mjs | 49 ++++++++++++++++ registry.test.mjs | 31 ++++++++++ tsconfig.json | 2 +- tty.mjs | 49 ++++++++++++++++ utils.mjs | 9 +++ 15 files changed, 394 insertions(+), 56 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 LICENSE delete mode 100644 add.mjs delete mode 100644 add.test.mjs create mode 100644 config.mjs create mode 100644 config.test.mjs create mode 100644 registry.mjs create mode 100644 registry.test.mjs create mode 100644 tty.mjs create mode 100644 utils.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..42af8fb --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,26 @@ +name: Release + +permissions: + contents: write + +on: + push: + tags: + - 'v*' + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set node + uses: actions/setup-node@v3 + with: + node-version: 16.x + + - run: npx changelogithub + env: + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c42de8b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 YieldRay + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 57a645f..4949c7a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,33 @@ -# nodejs-purejs-template +# nrm-lite -Build a nodejs package in pure javascript, -but use [JSDoc](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) to enable typescript check! +Simple and lightweight replacement for nrm. +Like [dnrm](https://github.com/markthree/dnrm), but in pure Node.js + +## Features + +- Super lightweight, pure Node.js with NO dependency +- Fast, DO NOT parse the `.npmrc` file (slightly slower that `dnrm`, due to the runtime) +- Correct, follow the rules of the `.npmrc` file + +## Install + +```sh +# install `nrml` command globally +npm install -g nrm-lite + +nrml --help +``` + +## Usage + +```sh +nrm-lite v0.1.0 + +Usage: + nrml ls List registry + nrml use [name] Use registry + nrml rc Open .npmrc file + nrml help Show this help +Global Options: + --local Use local .npmrc file, rather than the global one (default: false) +``` diff --git a/add.mjs b/add.mjs deleted file mode 100644 index 02fcb90..0000000 --- a/add.mjs +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @template {number} T - * @param {T} a - * @param {T} b - */ -export function add(a, b) { - return a + b -} diff --git a/add.test.mjs b/add.test.mjs deleted file mode 100644 index 97fe994..0000000 --- a/add.test.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import { test } from 'node:test' -import { add } from './add.mjs' -import * as assert from 'node:assert' - -test('test add()', async () => { - assert.equal(add(1, 1), 2) - assert.equal(add(1, -1), 0) -}) diff --git a/cli.mjs b/cli.mjs index 8036f99..8186497 100644 --- a/cli.mjs +++ b/cli.mjs @@ -1,6 +1,13 @@ -import { parseArgs } from 'node:util' +#!/usr/bin/env node import process from 'node:process' -import pkg from './package.json' assert { type: 'json' } +import { parseArgs } from 'node:util' +import { execSync } from 'node:child_process' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname } from 'node:path' +import { getRegistry, setRegistry, getConfigPath } from './config.mjs' +import { REGISTRIES } from './registry.mjs' +import c, { printRegistries } from './tty.mjs' // https://nodejs.org/api/util.html#utilparseargsconfig const { values, positionals } = parseArgs({ @@ -11,50 +18,101 @@ const { values, positionals } = parseArgs({ short: 'h', default: false, }, - lhs: { - type: 'string', - short: 'a', - default: '0', + local: { + type: 'boolean', + short: 'l', + default: false, }, - rhs: { - type: 'string', - short: 'b', - default: '0', + version: { + type: 'boolean', + short: 'v', + default: false, }, }, strict: true, allowPositionals: true, }) -if (positionals.length < 1 || values.help) { +if (values.help) { help() } -const command = positionals[0] +const command = positionals[0] || 'ls' +const { local } = values switch (command) { + case 'h': case 'help': help() break - case 'add': - const { lhs, rhs } = values - const sum = Number.parseFloat(lhs) + Number.parseFloat(rhs) - console.log('%s + %s = %s', lhs, rhs, sum) + case 'ls': + ls() + break + case 'rc': + rc() + break + case 'use': + const name = positionals[1] + use(name) break default: - process.stderr.write(`Unknown command ${command}\n`) + console.error(`Unknown command ${command}\n`) process.exit(1) } function help() { - process.stdout.write(`\x1b[32m${pkg.name}\x1b[0m v${pkg.version} + // assert json will cause ExperimentalWarning. so we use this instead + // import pkg from './package.json' assert { type: 'json' } + const __filename = fileURLToPath(import.meta.url) + const __dirname = dirname(__filename) + const pkg = JSON.parse(readFileSync(`${__dirname}/package.json`, 'utf-8')) + console.error(`${c.green(pkg.name)} v${pkg.version} - A nodejs template in pure javascript +${c.bold('Usage:')} + nrml ls List registry + nrml use ${c.gray('[name]')} Use registry + nrml rc Open .npmrc file + nrml help Show this help +${c.bold('Global Options:')} + --local Use local .npmrc file, rather than the global one (default: false)`) + process.exit(1) +} - \x1b[1mUsage:\x1b[0m +async function ls() { + const currentRegistry = await getRegistry(local) + printRegistries(currentRegistry) +} - cli-name add --lhs [number] --rhs [number] Get sum of lhs and rhs - cli-name help Show this help -`) - process.exit(1) +/** + * @param {string} name + */ +async function use(name) { + if (!name) { + console.error(`Please provide a name!`) + process.exit(-1) + } + + const names = Object.keys(REGISTRIES) + if (!names.includes(name)) { + console.error(`'${name}' is not in ${c.gray(`[${names.join('|')}]`)}`) + process.exit(-1) + } + + const registryUrl = REGISTRIES[name] + await setRegistry(local, registryUrl) + printRegistries(registryUrl) +} + +async function rc() { + const filePath = await getConfigPath(local) + try { + execSync(`code ${filePath}`) + } catch { + console.error( + `You do not have vscode installed!\nPlease open ${c.gray( + filePath + )} manually.` + ) + process.exit(-1) + } } diff --git a/config.mjs b/config.mjs new file mode 100644 index 0000000..aa5e695 --- /dev/null +++ b/config.mjs @@ -0,0 +1,55 @@ +import * as fs from 'node:fs' +import { writeFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { REGISTRIES, findRegistryFromStream } from './registry.mjs' +import { isFile } from './utils.mjs' + +/** + * @param {boolean|undefined} local + * @param {string} registryUrl + */ +export async function setRegistry(local, registryUrl) { + const filePath = await getConfigPath(local) + + const fileStream = fs.createReadStream(filePath) + const { registry, lines, registryLineNumber } = + await findRegistryFromStream(fileStream) + const newRegistryLine = `registry=${registryUrl}` + + if (!registry) { + lines.push(newRegistryLine) + } else if (registry === registryUrl) { + // same, do nothing + return + } else { + // number-1 is index + lines[registryLineNumber - 1] = newRegistryLine + } + + const result = lines.join('\n') + return writeFile(filePath, result) +} + +/** + * @param {boolean|undefined} local + */ +export async function getRegistry(local) { + const filePath = await getConfigPath(local) + const fileStream = fs.createReadStream(filePath) + const { registry } = await findRegistryFromStream(fileStream) + return registry || REGISTRIES['npm'] +} + +/** + * If `local` is not provided, check if local npmrc file exists + * @param {boolean|undefined} local + * @noexcept + */ +export async function getConfigPath(local) { + const rc = '.npmrc' + const detectLocal = typeof local !== 'boolean' && (await isFile(rc)) + if (local || detectLocal) { + return rc + } + return `${homedir().replaceAll('\\', '/')}/${rc}` +} diff --git a/config.test.mjs b/config.test.mjs new file mode 100644 index 0000000..d123232 --- /dev/null +++ b/config.test.mjs @@ -0,0 +1,7 @@ +import { test } from 'node:test' +import * as assert from 'node:assert' +import { getConfigPath } from './config.mjs' + +test('test getConfigPath()', async () => { + assert.ok((await getConfigPath(false)).endsWith('/.npmrc')) +}) diff --git a/index.mjs b/index.mjs index bc37dd2..d36d219 100644 --- a/index.mjs +++ b/index.mjs @@ -1 +1,2 @@ -export * from './add.mjs' +export * from './config.mjs' +export * from './registry.mjs' diff --git a/package.json b/package.json index bd9170c..45c6862 100644 --- a/package.json +++ b/package.json @@ -1,25 +1,44 @@ { - "name": "nodejs-purejs-template", - "private": true, + "name": "nrm-lite", "version": "0.1.0", "type": "module", - "description": "", + "description": "simple and lightweight replacement for nrm", "main": "index.mjs", "scripts": { "test": "node --test", - "watch": "tsc --watch" + "watch": "tsc --watch", + "format": "prettier --write ." }, - "keywords": [], - "author": "", - "license": "", "engines": { "node": ">16" }, + "files": [ + "*.js", + "*.mjs", + "!*.test.*" + ], "bin": { - "cli-name": "./cli.mjs" + "nrml": "cli.mjs" }, "devDependencies": { - "@types/node": "^20.10.6", - "typescript": "^5.3.3" - } + "@types/node": "^20.11.25", + "typescript": "^5.4.2" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org" + }, + "keywords": [ + "nrm", + "registry" + ], + "author": "YieldRay", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/YieldRay/nrm-lite.git" + }, + "bugs": { + "url": "https://github.com/YieldRay/nrm-lite/issues" + }, + "homepage": "https://github.com/YieldRay/nrm-lite#readme" } diff --git a/registry.mjs b/registry.mjs new file mode 100644 index 0000000..3ae1011 --- /dev/null +++ b/registry.mjs @@ -0,0 +1,49 @@ +import * as readline from 'node:readline' + +/** + * @type { Record} + */ +export const REGISTRIES = { + npm: 'https://registry.npmjs.org/', + yarn: 'https://registry.yarnpkg.com/', + github: 'https://npm.pkg.github.com/', + taobao: 'https://registry.npmmirror.com/', + npmMirror: 'https://skimdb.npmjs.com/registry/', + tencent: 'https://mirrors.cloud.tencent.com/npm/', +} + +/** + * + * Note that `registryLineNumber` is index + 1 + * + * @param {NodeJS.ReadableStream} stream + * @returns {Promise<{registry:string,lines:string[],registryLineNumber:number}| + * {registry:null,lines:string[],registryLineNumber:null}>} + * @see https://docs.npmjs.com/cli/configuring-npm/npmrc + * + * @example + * const fileStream = fs.createReadStream(path) + * findRegistryFromStream(fileStream) + */ +export async function findRegistryFromStream(stream) { + const rl = readline.createInterface(stream) + /** + * @type {string[]} + */ + const lines = [] + + for await (const entireLine of rl) { + lines.push(entireLine) + + let currLine = entireLine.trim() + const keyName = 'registry' + if (!currLine.startsWith(keyName)) continue + currLine = currLine.slice(keyName.length).trimStart() + if (!currLine.startsWith('=')) continue + currLine = currLine.slice(1).trimStart() + + // now that current line is the registry url + return { registry: currLine, lines, registryLineNumber: lines.length } + } + return { registry: null, registryLineNumber: null, lines } +} diff --git a/registry.test.mjs b/registry.test.mjs new file mode 100644 index 0000000..3faf3e7 --- /dev/null +++ b/registry.test.mjs @@ -0,0 +1,31 @@ +import { test } from 'node:test' +import * as assert from 'node:assert' +import { Readable } from 'node:stream' +import { findRegistryFromStream } from './registry.mjs' + +test('test findRegistryFromStream()', async () => { + assert.deepStrictEqual(await findRegistryFromStream(Readable.from('')), { + lines: [], + registry: null, + registryLineNumber: null, + }) + + const text2 = `registry=https://registry.npmmirror.com/` + + assert.deepStrictEqual(await findRegistryFromStream(Readable.from(text2)), { + registry: 'https://registry.npmmirror.com/', + registryLineNumber: 1, + lines: [text2], + }) + + const text3 = `//registry.npmjs.org/:_authToken=npm_123456 + +# strict-ssl=false +registry= https://registry.npmmirror.com/` + + assert.deepStrictEqual(await findRegistryFromStream(Readable.from(text3)), { + registry: 'https://registry.npmmirror.com/', + registryLineNumber: 4, + lines: text3.split(/\n/g), + }) +}) diff --git a/tsconfig.json b/tsconfig.json index 44956c9..aa43d25 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,7 @@ "checkJs": true, // Type Checking - "strict": false, // (without TS it's hard to express some type) + "strict": true, "noFallthroughCasesInSwitch": true, "noPropertyAccessFromIndexSignature": true } diff --git a/tty.mjs b/tty.mjs new file mode 100644 index 0000000..19e3b6e --- /dev/null +++ b/tty.mjs @@ -0,0 +1,49 @@ +import { REGISTRIES } from './registry.mjs' + +/** + * @param {string} str + * @param {number} begin + * @param {number} end + */ +const color = (str, begin, end) => `\u001b[${begin}m${str}\u001b[${end}m` + +const c = { + /** @param {string} str*/ + blue: (str) => color(str, 34, 39), + /** @param {string} str*/ + red: (str) => color(str, 31, 39), + /** @param {string} str*/ + green: (str) => color(str, 32, 39), + /** @param {string} str*/ + yellow: (str) => color(str, 33, 39), + /** @param {string} str*/ + magenta: (str) => color(str, 35, 39), + /** @param {string} str*/ + cyan: (str) => color(str, 36, 39), + /** @param {string} str*/ + gray: (str) => color(str, 90, 39), + + /** @param {string} str*/ + bold: (str) => color(str, 1, 22), + /** @param {string} str*/ + italic: (str) => color(str, 3, 23), +} + +export default c + +/** + * @param {string} registryUrl + */ +export function printRegistries(registryUrl) { + let maxNameLength = 0 + + const registries = Object.entries(REGISTRIES).map(([name, url]) => { + maxNameLength = Math.max(maxNameLength, name.length) + return { name, url, highlight: url === registryUrl } + }) + + for (const { name, url, highlight } of registries) { + const row = `${name.padEnd(maxNameLength)} → ${url}` + console.log(highlight ? c.blue(row) : row) + } +} diff --git a/utils.mjs b/utils.mjs new file mode 100644 index 0000000..f402982 --- /dev/null +++ b/utils.mjs @@ -0,0 +1,9 @@ +import { stat } from 'node:fs/promises' +/** + * @param {string} filePath + * @noexcept + */ +export const isFile = async (filePath) => + await stat(filePath) + .then((stat) => stat.isFile()) + .catch((_) => false)