1const Arborist = require('../')
2
3const printTree = require('./lib/print-tree.js')
4const log = require('./lib/logging.js')
5
6const printDiff = diff => {
7  const { depth } = require('treeverse')
8  depth({
9    tree: diff,
10    visit: d => {
11      if (d.location === '') {
12        return
13      }
14      switch (d.action) {
15        case 'REMOVE':
16          log.info('REMOVE', d.actual.location)
17          break
18        case 'ADD':
19          log.info('ADD', d.ideal.location, d.ideal.resolved)
20          break
21        case 'CHANGE':
22          log.info('CHANGE', d.actual.location, {
23            from: d.actual.resolved,
24            to: d.ideal.resolved,
25          })
26          break
27      }
28    },
29    getChildren: d => d.children,
30  })
31}
32
33module.exports = (options, time) => {
34  const arb = new Arborist(options)
35  return arb
36    .reify(options)
37    .then(time)
38    .then(async ({ timing, result: tree }) => {
39      printTree(tree)
40      if (options.dryRun) {
41        printDiff(arb.diff)
42      }
43      if (tree.meta && options.save) {
44        await tree.meta.save()
45      }
46      return `resolved ${tree.inventory.size} deps in ${timing.seconds}`
47    })
48}
49