UNPKG

2.54 kBJavaScriptView Raw
1const fs = require('fs');
2const ini = require('ini');
3const chalk = require('chalk');
4const process = require('./process');
5
6const { NRMRC, NPMRC, REGISTRY, REGISTRIES } = require('./constants');
7
8async function readFile(file) {
9 return new Promise(resolve => {
10 if (!fs.existsSync(file)) {
11 resolve({});
12 } else {
13 try {
14 const content = ini.parse(fs.readFileSync(file, 'utf-8'));
15 resolve(content);
16 } catch (error) {
17 exit(error);
18 }
19 }
20 });
21}
22
23async function writeFile(path, content) {
24 return new Promise(resolve => {
25 try {
26 fs.writeFileSync(path, ini.stringify(content));
27 resolve();
28 } catch (error) {
29 exit(error);
30 }
31 });
32}
33
34function padding(message = '', before = 1, after = 1) {
35 return new Array(before).fill(' ').join('') + message + new Array(after).fill(' ').join('');
36}
37
38function printSuccess(message) {
39 console.log(chalk.bgGreenBright(padding('SUCCESS')) + ' ' + message);
40}
41
42function printError(error) {
43 console.error(chalk.bgRed(padding('ERROR')) + ' ' + chalk.red(error));
44}
45
46function printMessages(messages) {
47 for (const message of messages) {
48 console.log(message);
49 }
50}
51
52function geneDashLine(message, length) {
53 const finalMessage = new Array(Math.max(2, length - message.length + 2)).join('-');
54 return padding(chalk.dim(finalMessage));
55}
56
57function isLowerCaseEqual(str1, str2) {
58 if (str1 && str2) {
59 return str1.toLowerCase() === str2.toLowerCase();
60 } else {
61 return !str1 && !str2;
62 }
63}
64
65async function getCurrentRegistry() {
66 const npmrc = await readFile(NPMRC);
67 return npmrc[REGISTRY];
68}
69
70async function getRegistries() {
71 const customRegistries = await readFile(NRMRC);
72 return Object.assign({}, REGISTRIES, customRegistries);
73}
74
75async function isRegistryNotFound(name, printErr = true) {
76 const registries = await getRegistries();
77 if (!Object.keys(registries).includes(name)) {
78 printErr && printError(`The registry '${name}' is not found.`);
79 return true;
80 }
81 return false;
82}
83
84async function isInternalRegistry(name, handle) {
85 if (Object.keys(REGISTRIES).includes(name)) {
86 handle && printError(`You cannot ${handle} the nrm internal registry.`);
87 return true;
88 }
89 return false;
90}
91
92function exit(error) {
93 error && printError(error);
94 process.exit(1);
95}
96
97module.exports = {
98 exit,
99 geneDashLine,
100 printError,
101 printSuccess,
102 printMessages,
103 isLowerCaseEqual,
104 readFile,
105 writeFile,
106 getRegistries,
107 getCurrentRegistry,
108 isRegistryNotFound,
109 isInternalRegistry,
110};