forked from stdlib-js/stdlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostinstall
More file actions
executable file
·345 lines (298 loc) · 10.4 KB
/
postinstall
File metadata and controls
executable file
·345 lines (298 loc) · 10.4 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env node
/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Script to perform a post-install sequence, allowing users to require/import project packages as documented in the repository documentation.
*
* For example,
*
* ```javascript
* var sin = require( '@stdlib/math/base/special/sin' );
* ```
*
* rather than
*
* ```javascript
* var sin = require( '@stdlib/stdlib/lib/node_modules/@stdlib/math/base/special/sin' );
* ```
*
* ## Usage
*
* ```bash
* $ postinstall
* ```
*
* ### Notes
*
* - The script supports the following environment variables:
*
* - `STDLIB_DRY_RUN`: run script in "dry run" mode (i.e., without creating artifacts).
*
* - The script outputs a `.postinstall.json` file which can be used to revert changes introduced by this script (see `preuninstall`).
*/
/* eslint-disable no-sync, no-process-env, no-console */
'use strict';
// MODULES //
var path = require( 'path' );
var fs = require( 'fs' );
var logger = require( 'debug' );
// VARIABLES //
var debug = logger( 'stdlib:post-install' );
// Define a flag for specifying whether to run the script in "dry run" mode:
var DRY_RUN = Boolean( process.env.STDLIB_DRY_RUN );
// Resolve the root project directory (WARNING: this is fragile and likely needs to be updated should this file move!):
var ROOT_DIR = path.resolve( __dirname, '..', '..' );
// Resolve the project package directory:
var PKG_DIR = path.join( ROOT_DIR, 'lib', 'node_modules', '@stdlib' );
// Define the relative path to project packages:
var RELATIVE_PKG_DIR = path.join( 'stdlib', 'lib', 'node_modules', '@stdlib' );
// Resolve the destination directory:
var DEST_DIR = path.resolve( ROOT_DIR, '..' );
// Define an output file path for storing post-install meta data:
var OUTPUT_FILE = path.join( ROOT_DIR, '.postinstall.json' );
// Regular expression to detect whether this script is being executed after this package was installed as a node_modules dependency:
var RE_SCRIPT_CONTEXT = /[\\/]node_modules[\\/]@stdlib[\\/]stdlib[\\/]/;
// Define a list of `package.json` fields to extract when generating meta data:
var PKG_FIELDS = [
'name',
'version',
'description',
'license',
'author',
'contributors',
'homepage',
'repository',
'bugs',
'engines',
'os',
'keywords'
];
// FUNCTIONS //
/**
* Returns a relative path for resolving a package from a destination directory.
*
* @private
* @param {string} dpath - package directory path (e.g., `'utils/copy'`, `'math/base/special/sin'`, etc)
* @returns {string} relative path
*/
function resolvePkg( dpath ) {
var parts;
var p;
var i;
// Initialize the relative path:
p = '.' + path.sep;
// Split the directory path in order to determine folder depth:
parts = dpath.split( path.sep );
for ( i = 0; i < parts.length; i++ ) {
p += '..' + path.sep;
}
// Return the generated path:
return path.join( p, RELATIVE_PKG_DIR, dpath );
}
/**
* Creates directories from a nested path.
*
* @private
* @param {Array} out - output array for tracking changes
* @param {string} root - root directory
* @param {string} dpath - directory path
* @returns {Array} output array
*/
function mkdirp( out, root, dpath ) {
var parts;
var stats;
var p;
var i;
parts = dpath.split( path.sep );
p = root;
for ( i = 0; i < parts.length; i++ ) {
p = path.join( p, parts[ i ] );
if ( fs.existsSync( p ) ) {
stats = fs.statSync( p );
if ( !stats.isDirectory() ) {
if ( DRY_RUN ) {
console.log( 'Created directory: %s', p );
} else {
fs.mkdirSync( p );
}
out.push( [ 'create', p ] );
}
} else {
if ( DRY_RUN ) {
console.log( 'Created directory: %s', p );
} else {
fs.mkdirSync( p );
}
out.push( [ 'create', p ] );
}
}
return out;
}
// MAIN //
/**
* Main execution sequence.
*
* @private
* @returns {void}
*/
function main() {
var findPkgs;
var fopts;
var meta;
var pdir;
var ndir;
var pkgs;
var keys;
var pkg;
var out;
var d;
var f;
var i;
var j;
var k;
fopts = {
'encoding': 'utf8'
};
if ( DRY_RUN ) {
debug( 'Performing a dry run...' );
}
debug( 'Checking file system context...' );
if ( !DRY_RUN && !RE_SCRIPT_CONTEXT.test( __filename ) ) {
debug( 'Detected non-node_modules context. Aborting script execution...' );
return;
}
debug( 'Detected node_modules context.' );
debug( 'Root directory: %s', ROOT_DIR );
debug( 'Package directory: %s', PKG_DIR );
debug( 'Destination directory: %s', DEST_DIR );
out = [];
// Load a package for resolving project packages ('@stdlib/_tools/pkgs/find'):
findPkgs = require( path.join( PKG_DIR, '_tools', 'pkgs', 'find' ) ); // eslint-disable-line stdlib/no-dynamic-require
debug( 'Resolving packages...' );
pkgs = findPkgs.sync({
'dir': PKG_DIR
});
debug( 'Found %d packages.', pkgs.length );
// NOTE: the following creates a "shadow" file tree in the parent directory of the project installation directory. The file tree follows the same folder structure as `PKG_DIR` and only includes `package.json` files which point to the actual implementation packages found in `PKG_DIR`. This allows users to resolve `@stdlib/math/base/special/sin` without having to explicitly walk the project tree. However, some package managers that modify the `node_modules` directory will remove this shadow tree during "pruning" (i.e., `npm` during `npm install`). Accordingly, we have to introduce a workaround later to safeguard against `npm` pruning.
debug( 'Processing packages...' );
for ( i = 0; i < pkgs.length; i++ ) {
pdir = pkgs[ i ].slice( PKG_DIR.length+1 ); // +1 to account for trailing `/`
if ( pdir[ 0 ] === '_' ) {
debug( 'Package directory is private: %s. Skipping...', pdir );
continue;
}
debug( 'Reading package meta data...' );
pkg = require( path.join( pkgs[ i ], 'package.json' ) ); // eslint-disable-line stdlib/no-dynamic-require
debug( 'Package name: %s', pkg.name );
debug( 'Generating package meta data...' );
meta = {};
for ( j = 0; j < PKG_FIELDS.length; j++ ) {
k = PKG_FIELDS[ j ];
if ( pkg.hasOwnProperty( k ) ) { // eslint-disable-line no-prototype-builtins
meta[ k ] = pkg[ k ];
}
}
// We need to empty out the `name` field in order to avoid running afoul of npm package name conventions (e.g., cannot have `'@stdlib/array/buffer'`; see https://docs.npmjs.com/files/package.json#name):
meta.name = '';
// Main entry point:
d = resolvePkg( pdir );
meta.main = path.join( d, pkg.main );
debug( 'Resolved package entry point: %s', meta.main );
// Browser entry point:
if ( pkg.browser ) {
if ( typeof pkg.browser === 'string' ) {
meta.browser = path.join( d, pkg.browser );
debug( 'Resolved package browser entry point: %s', meta.browser );
} else if ( typeof pkg.browser === 'object' ) {
meta.browser = {};
keys = Object.keys( pkg.browser );
for ( j = 0; j < keys.length; j++ ) {
k = keys[ j ];
meta.browser[ k ] = path.join( d, pkg.browser[ k ] );
debug( 'Resolved package browser entry point: %s', meta.browser[ k ] );
}
} else {
debug( 'Unrecognized browser field value type: %s. Skipping field...', JSON.stringify( pkg.browser ) );
}
}
// Package type declarations:
if ( pkg.types ) {
meta.types = path.join( d, pkg.types );
debug( 'Resolved package type declaration directory: %s', meta.types );
}
// Resolve the destination directory:
ndir = path.join( DEST_DIR, pdir );
if ( fs.existsSync( ndir ) ) {
debug( 'Destination directory already exists: %s', ndir );
} else {
debug( 'Creating destination directory: %s', ndir );
mkdirp( out, DEST_DIR, pdir );
}
f = path.join( ndir, 'package.json' );
if ( fs.existsSync( f ) ) {
debug( 'Package meta data already exists: %s. Skipping package...', f );
continue;
}
debug( 'Writing package meta data...' );
if ( DRY_RUN ) {
console.log( 'Created file: %s', f );
} else {
fs.writeFileSync( f, JSON.stringify( meta )+'\n', fopts );
}
out.push( [ 'create', f ] );
debug( 'Finished processing package.' );
}
debug( 'Reading package meta data...' );
pkg = path.join( ROOT_DIR, 'package.json' );
meta = require( pkg ); // eslint-disable-line stdlib/no-dynamic-require
// NOTE: the following is a workaround to address `npm` (and possibly other package managers) pruning during tree idealization. We modify the root `package.json` to include the top-level packages (which are often namespaces) as local dependencies (see https://docs.npmjs.com/cli/install and `npm install <folder>`). When `npm` "installs" a local folder, it creates a symlink. During pruning, `npm` removes the shadow tree created earlier and, upon reading the modified package meta data, creates symlinks to the local dependencies. Accordingly, while we lose the shadow tree, we should still retain the ability to walk the project package tree as, e.g., `@stdlib/utils` will resolve to `@stdlib/stdlib/lib/node_modules/@stdlib/utils`.
debug( 'Modifying package meta data...' );
for ( i = 0; i < pkgs.length; i++ ) {
pdir = pkgs[ i ].slice( PKG_DIR.length+1 ); // +1 to account for trailing `/`
if ( pdir[ 0 ] !== '_' && pdir.split( '/' ).length === 1 ) {
meta.dependencies[ '@stdlib/'+pdir ] = 'file:./lib/node_modules/@stdlib/'+pdir;
}
}
debug( 'Renaming file...' );
f = path.join( ROOT_DIR, '__package__.json' );
if ( DRY_RUN ) {
console.log( 'Renamed file: %s => %s', pkg, f );
} else {
fs.renameSync( pkg, f );
}
out.push( [ 'rename', pkg, f ] );
debug( 'Writing package meta data...' );
if ( DRY_RUN ) {
console.log( 'Modified file: %s', pkg );
console.log( 'Meta data: %s', JSON.stringify( meta ) );
} else {
fs.writeFileSync( pkg, JSON.stringify( meta )+'\n', fopts );
}
out.push( [ 'create', pkg ] );
debug( 'Finished post-install sequence.' );
debug( 'Saving changes...' );
out.push( [ 'create', OUTPUT_FILE ] );
if ( DRY_RUN ) {
debug( 'Changes: %s', JSON.stringify( out ) );
console.log( 'Created file: %s', OUTPUT_FILE );
} else {
fs.writeFileSync( OUTPUT_FILE, JSON.stringify( out )+'\n', fopts );
}
debug( 'Finished saving changes.' );
}
main();