UNPKG

1.8 kBJavaScriptView Raw
1import fs from "fs";
2import path from "path";
3
4import chalk from "chalk";
5import execa from "execa";
6
7const NNRM = path.join(process.env.HOME, ".nnrm");
8const NNRM_REGISTRIES = path.join(NNRM, "registries.json");
9
10async function getCustomRegistry() {
11 let customRegistries = {};
12 try {
13 customRegistries = JSON.parse(fs.readFileSync(NNRM_REGISTRIES));
14 } catch (e) {
15 const msg = `\nWe will create '${chalk.yellow(
16 NNRM_REGISTRIES
17 )}' to record your custom registries.\n`;
18 console.log(msg);
19
20 if (!fs.existsSync(NNRM)) {
21 try {
22 fs.mkdirSync(NNRM, { recursive: true });
23 } catch (e) {
24 // permission denied
25 console.log(e.message);
26 await execa("mkdir", [NNRM]).catch((e) => {
27 console.log(e.message);
28 });
29 }
30 }
31 setCustomRegistry(customRegistries);
32 }
33 return customRegistries;
34}
35
36/**
37 * write ~/.nnrm/registries.json
38 * @param {object} registries
39 */
40function setCustomRegistry(registries) {
41 return fs.writeFileSync(NNRM_REGISTRIES, JSON.stringify(registries, null, 2));
42}
43
44/**
45 * add custom registry
46 * @param {string} name
47 * @param {string} registry url
48 * @param {string} home
49 */
50function addCustomRegistry(name, url, home) {
51 let customRegistries = getCustomRegistry();
52
53 // npm config set registry auto add '/'
54 if (url.slice(-1) !== "/") {
55 url += "/";
56 }
57
58 customRegistries[name] = {
59 home,
60 registry: url,
61 };
62 setCustomRegistry(customRegistries);
63}
64
65/**
66 * remove a custom registry
67 * @param {string} name
68 */
69function removeCustomRegistry(name) {
70 let customRegistries = getCustomRegistry();
71 if (customRegistries[name]) {
72 delete customRegistries[name];
73 }
74 setCustomRegistry(customRegistries);
75}
76
77export { getCustomRegistry, addCustomRegistry, removeCustomRegistry };