napi-rs/cli/src/utils/misc.ts
liuyi c9f5ee14b7
fast patches for napi/cli 3.0-alpha (#1553)
* fix(cli): use new napi config field

* fix(cli): avoid using node experimental feature to read self version

* fix(cli): correct linker environment

* fix(cli): missing wasi register env

* fix(cli): remove useless linker preset
2023-04-06 19:21:06 +08:00

50 lines
1.5 KiB
TypeScript

import { readFile, writeFile, copyFile, mkdir, unlink, stat, readdir } from 'fs'
import { createRequire } from 'module'
import { promisify } from 'util'
import { debug } from './log.js'
const require = createRequire(import.meta.url)
// NOTE:
// import pkgJson from '@napi-rs/cli/package.json' assert { type: 'json' }
// is experimental feature now, avoid using it.
// see: https://nodejs.org/api/esm.html#import-assertions
// eslint-disable-next-line import/no-extraneous-dependencies
const pkgJson = require('@napi-rs/cli/package.json')
export const readFileAsync = promisify(readFile)
export const writeFileAsync = promisify(writeFile)
export const unlinkAsync = promisify(unlink)
export const copyFileAsync = promisify(copyFile)
export const mkdirAsync = promisify(mkdir)
export const statAsync = promisify(stat)
export const readdirAsync = promisify(readdir)
export async function fileExists(path: string) {
const exists = await statAsync(path)
.then(() => true)
.catch(() => false)
return exists
}
export function pick<O, K extends keyof O>(o: O, ...keys: K[]): Pick<O, K> {
return keys.reduce((acc, key) => {
acc[key] = o[key]
return acc
}, {} as O)
}
export async function updatePackageJson(
path: string,
partial: Record<string, any>,
) {
const exists = await fileExists(path)
if (!exists) {
debug(`File not exists ${path}`)
return
}
const old = require(path)
await writeFileAsync(path, JSON.stringify({ ...old, ...partial }, null, 2))
}
export const CLI_VERSION = pkgJson.version