@@ -157,7 +157,8 @@ function install (args, cb_) {
157
157
, pretty = prettify ( tree , installed )
158
158
159
159
output . write ( pretty , function ( er ) {
160
- cb_ ( er , installed , tree , pretty )
160
+ if ( er ) return cb_ ( er )
161
+ save ( where , installed , tree , pretty , cb_ )
161
162
} )
162
163
}
163
164
@@ -214,6 +215,49 @@ function install (args, cb_) {
214
215
} )
215
216
}
216
217
218
+ // if the -S|--save option is specified, then write installed packages
219
+ // as dependencies to a package.json file.
220
+ // This is experimental.
221
+ // save(installed, tree, pretty, cb_)
222
+ function save ( where , installed , tree , pretty , cb ) {
223
+ if ( ! npm . config . get ( "save" ) ) {
224
+ return cb ( null , installed , tree , pretty )
225
+ }
226
+ // each item in the tree is a top-level thing that should be saved
227
+ // to the package.json file.
228
+ // The relevant tree shape is { <folder>: {what:<pkg>} }
229
+ var saveTarget = path . resolve ( where , "package.json" )
230
+ , things = Object . keys ( tree ) . map ( function ( k ) {
231
+ //log.warn(k, "k")
232
+ return tree [ k ] . what . split ( "@" )
233
+ } ) . reduce ( function ( set , k ) {
234
+ set [ k [ 0 ] ] = "~" + k [ 1 ]
235
+ return set
236
+ } , { } )
237
+
238
+ //log.warn(things, "things")
239
+
240
+ // don't use readJson, because we don't want to do all the other
241
+ // tricky npm-specific stuff that's in there.
242
+ fs . readFile ( saveTarget , function ( er , data ) {
243
+ // ignore errors here, just don't save it.
244
+ try {
245
+ data = JSON . parse ( data . toString ( "utf8" ) )
246
+ } catch ( ex ) {
247
+ er = ex
248
+ }
249
+ if ( er ) return cb ( null , installed , tree , pretty )
250
+ data . dependencies = data . dependencies || { }
251
+ Object . keys ( things ) . forEach ( function ( t ) {
252
+ data . dependencies [ t ] = things [ t ]
253
+ } )
254
+ fs . writeFile ( saveTarget , JSON . stringify ( data , null , 2 ) , function ( er ) {
255
+ cb ( er , installed , tree , pretty )
256
+ } )
257
+ } )
258
+ }
259
+
260
+
217
261
// Outputting *all* the installed modules is a bit confusing,
218
262
// because the length of the path does not make it clear
219
263
// that the submodules are not immediately require()able.
@@ -270,12 +314,13 @@ function treeify (installed) {
270
314
//log.warn(whatWhere, "whatWhere")
271
315
return Object . keys ( whatWhere ) . reduce ( function ( l , r ) {
272
316
var ww = whatWhere [ r ]
273
- //log.warn(ww )
317
+ //log.warn([r, ww], "r, ww" )
274
318
if ( ! ww . parent ) {
275
319
l [ r ] = ww
276
320
} else {
277
321
var p = whatWhere [ ww . parentDir ]
278
322
if ( p ) p . children . push ( ww )
323
+ else l [ r ] = ww
279
324
}
280
325
return l
281
326
} , { } )
0 commit comments