Skip to content

Commit

Permalink
feat: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
YieldRay committed Mar 11, 2024
1 parent dec24e2 commit ff2c04b
Show file tree
Hide file tree
Showing 15 changed files with 394 additions and 56 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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}}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
35 changes: 32 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -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)
```
8 changes: 0 additions & 8 deletions add.mjs

This file was deleted.

8 changes: 0 additions & 8 deletions add.test.mjs

This file was deleted.

106 changes: 82 additions & 24 deletions cli.mjs
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -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)
}
}
55 changes: 55 additions & 0 deletions config.mjs
Original file line number Diff line number Diff line change
@@ -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}`
}
7 changes: 7 additions & 0 deletions config.test.mjs
Original file line number Diff line number Diff line change
@@ -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'))
})
3 changes: 2 additions & 1 deletion index.mjs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './add.mjs'
export * from './config.mjs'
export * from './registry.mjs'
41 changes: 30 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -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"
}
Loading

0 comments on commit ff2c04b

Please sign in to comment.