UNPKG

@antfu/ni

Version:

Use the right package manager

100 lines (95 loc) 2.46 kB
import { __dirname, __toESM, init_esm_shims, parseNr, require_prompts, runCli } from "./chunk-A7RNPMI5.mjs"; // src/nr.ts init_esm_shims(); var import_prompts = __toESM(require_prompts()); // src/storage.ts init_esm_shims(); import { existsSync, promises as fs } from "fs"; import { join } from "path"; var storage; var storagePath = join(__dirname, "_storage.json"); async function load(fn) { if (!storage) { storage = existsSync(storagePath) ? JSON.parse(await fs.readFile(storagePath, "utf-8")) || {} : {}; } if (fn) { if (await fn(storage)) await dump(); } return storage; } async function dump() { if (storage) await fs.writeFile(storagePath, JSON.stringify(storage), "utf-8"); } // src/fs.ts init_esm_shims(); import { resolve } from "path"; import fs2 from "fs"; function getPackageJSON(cwd = process.cwd()) { const path = resolve(cwd, "package.json"); if (fs2.existsSync(path)) { try { const raw = fs2.readFileSync(path, "utf-8"); const data = JSON.parse(raw); return data; } catch (e) { console.warn("Failed to parse package.json"); process.exit(0); } } } // src/nr.ts runCli(async (agent, args, ctx) => { const storage2 = await load(); if (args[0] === "-") { if (!storage2.lastRunCommand) { console.error("No last command found"); process.exit(1); } args[0] = storage2.lastRunCommand; } if (args.length === 0) { const pkg = getPackageJSON(ctx == null ? void 0 : ctx.cwd); const scripts = pkg.scripts || {}; const scriptsInfo = pkg["scripts-info"] || {}; const names = Object.entries(scripts); if (!names.length) return; const choices = names.filter((i) => !i[0].startsWith("?")).map(([value, cmd]) => ({ title: value, value, description: scriptsInfo[value] || scripts[`?${value}`] || cmd })); if (storage2.lastRunCommand) { const last = choices.find((i) => i.value === storage2.lastRunCommand); if (last) choices.unshift(last); } try { const { fn } = await (0, import_prompts.default)({ name: "fn", message: "script to run", type: "autocomplete", choices }); if (!fn) return; args.push(fn); } catch (e) { process.exit(1); } } if (storage2.lastRunCommand !== args[0]) { storage2.lastRunCommand = args[0]; dump(); } return parseNr(agent, args); });