@@ -157,7 +157,8 @@ function install (args, cb_) {
157157 , pretty = prettify ( tree , installed )
158158
159159 output . write ( pretty , function ( er ) {
160- cb_ ( er , installed , tree , pretty )
160+ if ( er ) return cb_ ( er )
161+ save ( where , installed , tree , pretty , cb_ )
161162 } )
162163 }
163164
@@ -214,6 +215,49 @@ function install (args, cb_) {
214215 } )
215216}
216217
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+
217261// Outputting *all* the installed modules is a bit confusing,
218262// because the length of the path does not make it clear
219263// that the submodules are not immediately require()able.
@@ -270,12 +314,13 @@ function treeify (installed) {
270314 //log.warn(whatWhere, "whatWhere")
271315 return Object . keys ( whatWhere ) . reduce ( function ( l , r ) {
272316 var ww = whatWhere [ r ]
273- //log.warn(ww )
317+ //log.warn([r, ww], "r, ww" )
274318 if ( ! ww . parent ) {
275319 l [ r ] = ww
276320 } else {
277321 var p = whatWhere [ ww . parentDir ]
278322 if ( p ) p . children . push ( ww )
323+ else l [ r ] = ww
279324 }
280325 return l
281326 } , { } )
0 commit comments