forked from sindresorhus/np
/
util.js
197 lines (168 loc) · 5.23 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
'use strict';
const fs = require('fs');
const path = require('path');
const execa = require('execa');
const pTimeout = require('p-timeout');
const ow = require('ow');
const npmName = require('npm-name');
const chalk = require('chalk');
const pkgDir = require('pkg-dir');
const ignoreWalker = require('ignore-walk');
const minimatch = require('minimatch');
const {verifyRequirementSatisfied} = require('../version');
exports.checkConnection = () => pTimeout(
(async () => {
try {
await execa('npm', ['ping']);
return true;
} catch (_) {
throw new Error('Connection to npm registry failed');
}
})(),
15000,
'Connection to npm registry timed out'
);
exports.username = async ({externalRegistry}) => {
const args = ['whoami'];
if (externalRegistry) {
args.push('--registry', externalRegistry);
}
try {
const {stdout} = await execa('npm', args);
return stdout;
} catch (error) {
throw new Error(/ENEEDAUTH/.test(error.stderr) ?
'You must be logged in. Use `npm login` and try again.' :
'Authentication error. Use `npm whoami` to troubleshoot.');
}
};
exports.collaborators = async pkg => {
const packageName = pkg.name;
ow(packageName, ow.string);
const args = ['access', 'ls-collaborators', packageName];
if (exports.isExternalRegistry(pkg)) {
args.push('--registry', pkg.publishConfig.registry);
}
try {
const {stdout} = await execa('npm', args);
return stdout;
} catch (error) {
// Ignore non-existing package error
if (error.stderr.includes('code E404')) {
return false;
}
throw error;
}
};
exports.prereleaseTags = async packageName => {
ow(packageName, ow.string);
let tags = [];
try {
const {stdout} = await execa('npm', ['view', '--json', packageName, 'dist-tags']);
tags = Object.keys(JSON.parse(stdout))
.filter(tag => tag !== 'latest');
} catch (error) {
if (((JSON.parse(error.stdout) || {}).error || {}).code !== 'E404') {
throw error;
}
}
if (tags.length === 0) {
tags.push('next');
}
return tags;
};
exports.isPackageNameAvailable = async pkg => {
const args = [pkg.name];
const availability = {
isAvailable: false,
isUnknown: false
};
if (exports.isExternalRegistry(pkg)) {
args.push({
registryUrl: pkg.publishConfig.registry
});
}
try {
availability.isAvailable = await npmName(...args) || false;
} catch {
availability.isUnknown = true;
}
return availability;
};
exports.isExternalRegistry = pkg => typeof pkg.publishConfig === 'object' && typeof pkg.publishConfig.registry === 'string';
exports.version = async () => {
const {stdout} = await execa('npm', ['--version']);
return stdout;
};
exports.verifyRecentNpmVersion = async () => {
const npmVersion = await exports.version();
verifyRequirementSatisfied('npm', npmVersion);
};
exports.checkIgnoreStrategy = ({files}) => {
if (!files && !npmignoreExistsInPackageRootDir()) {
console.log(`
\n${chalk.bold.yellow('Warning:')} No ${chalk.bold.cyan('files')} field specified in ${chalk.bold.magenta('package.json')} nor is a ${chalk.bold.magenta('.npmignore')} file present. Having one of those will prevent you from accidentally publishing development-specific files along with your package's source code to npm.
`);
}
};
function npmignoreExistsInPackageRootDir() {
const rootDir = pkgDir.sync();
return fs.existsSync(path.resolve(rootDir, '.npmignore'));
}
async function getFilesIgnoredByDotnpmignore(fileList) {
const whiteList = await ignoreWalker({
path: pkgDir.sync(),
ignoreFiles: ['.npmignore']
});
return fileList.filter(minimatch.filter(getIgnoredFilesGlob(whiteList), {matchBase: true}));
}
function getFilesNotIncludedInFilesProperty(globArrayFromFilesProperty, fileList) {
const globArrayForFilesAndDirs = [...globArrayFromFilesProperty];
const rootDir = pkgDir.sync();
for (const glob of globArrayFromFilesProperty) {
try {
if (fs.statSync(path.resolve(rootDir, glob)).isDirectory()) {
globArrayForFilesAndDirs.push(`${glob}/**/*`);
}
} catch (_) {}
}
return fileList.filter(minimatch.filter(getIgnoredFilesGlob(globArrayForFilesAndDirs), {matchBase: true}));
}
function getIgnoredFilesGlob(globArrayFromFilesProperty) {
/* According to https://docs.npmjs.com/files/package.json#files
npm's default behavior is to ignore these files. */
const filesIgnoredByDefault = ['.*.swp',
'.npmignore',
'._*',
'.DS_Store',
'.hg',
'.npmrc',
'.lock-wscript',
'.svn',
'.wafpickle-N',
'*.orig',
'config.gypi',
'CVS',
'node_modules/**/*',
'npm-debug.log',
'package-lock.json'];
return `!{${globArrayFromFilesProperty.join(',')},${filesIgnoredByDefault.join(',')}}`;
}
// Get all files which will be ignored by either `.npmignore` or the `files` property in `package.json` (if defined).
exports.getNewAndUnpublishedFiles = async (globArrayFromFilesProperty, newFiles = []) => {
if (globArrayFromFilesProperty) {
return getFilesNotIncludedInFilesProperty(globArrayFromFilesProperty, newFiles);
}
if (npmignoreExistsInPackageRootDir()) {
return getFilesIgnoredByDotnpmignore(newFiles);
}
};
exports.getRegistryUrl = async (pkgManager, pkg) => {
const args = ['config', 'get', 'registry'];
if (exports.isExternalRegistry(pkg)) {
args.push('--registry');
args.push(pkg.publishConfig.registry);
}
const {stdout} = await execa(pkgManager, args);
return stdout;
};