Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 200 lines (175 sloc) 5.642 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
#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    colors = require('colors'),
    winston = require('winston'),
    argv = require('optimist').argv,
    eyes = require('eyes'),
    analyzer = require('../lib/require-analyzer');

var help = [
  'usage: require-analyzer [options] [directory]',
  '',
  'Analyzes the node.js requirements for the target directory. If no directory',
  'is supplied then the current directory is used',
  '',
  'options:',
  ' -d, --dir Directory to check for package.json',
  ' --update Update versions for existing dependencies',
  ' -f, --file File to check for instead of package.json.',
  ' --safe display existing dependencies but do change package.json',
  ' -h, --help You\'re staring at it'
].join('\n');

if (argv.h || argv.help) {
  return console.log(help);
}

//
// Create an `eyes` inspector for pretty printing dependencies.
//
var inspect = eyes.inspector({ stream: null,
  styles: { // Styles applied to stdout
    all: null, // Overall style applied to everything
    label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]`
    other: 'inverted', // Objects which don't have a literal representation, such as functions
    key: 'grey', // The keys in object literals, like 'a' in `{a: 1}`
    special: 'grey', // null, undefined...
    number: 'blue', // 1, 2, 3, etc
    bool: 'magenta', // true false
    regexp: 'green', // /\d+/
    string: 'yellow'
  }
});

//
// Configure winston to pretty print in a similar style
// to `jitsu`.
//
winston.cli();

//
// ### function listDependencies (pkg, msg)
// #### @pkg {Object} Valid package.json
// #### @msg {string} Message to print before listing
// Lists the dependencies in `pkg` using `eyes` for
// pretty printing the output consistently.
//
function listDependencies (pkg, msgs) {
  pkg = pkg || {};
  pkg.dependencies = pkg.dependencies || {};
  
  var keys = Object.keys(pkg.dependencies),
      list = inspect(pkg.dependencies);
  
  if (keys.length === 0) {
    return winston.warn(msgs.error);
  }
  else if (keys.length <= 2) {
    list = list.replace(/\{\s/, '{ \n')
               .replace(/\}/, '\n}')
               .replace('\033[90m', ' \033[90m')
               .replace(/, /ig, ',\n ');
  }
  else {
    list = list.replace(/\n\s{4}/ig, '\n ');
  }
  
  winston.info(msgs.success);
  list.split('\n').forEach(function (line) {
    winston.data(line);
  });
}

var dir = process.cwd(),
    source = argv._[0],
    pkgFile;

if (source) {
  dir = source[0] === '/' ? source : path.join(argv.d || argv.dir || dir, source);
}

pkgFile = path.join(dir, argv.f || argv.file || 'package.json');

winston.info('require-analyzer starting in ' + dir.magenta);
fs.readFile(pkgFile, function (err, data) {
  if (err) {
    if (err.errno === 34 && err.code === 'ENOENT') {
      data = "{}";
    }
    else {
      winston.error('Error reading package.json');
      winston.error(err.message.red);
      return;
    }
  }
 
  var pkg, updated, options = {
    target: dir,
    reduce: true
  };
  if (argv.f || argv.file) {
     options.f = argv.f || argv.file;
  }
  
  //
  // Attempt to parse the package.json from the current directory.
  //
  try {
    pkg = JSON.parse(data.toString());
    listDependencies(pkg, {
      error: 'No dependencies found',
      success: 'Found existing dependencies'
    });
  }
  catch (ex) {
    winston.error('Error parsing package.json');
    winston.error(ex.message.red);
    return;
  }
  
  //
  // ### function mergeResults (results)
  // #### @results {Object} Set of results returned from `npm`
  // Formats the results according to the `version` of each package.
  //
  function mergeResults (results) {
    var all = analyzer.extractVersions(results);
    return analyzer.updates(pkg.dependencies, all);
  }
  
  winston.info('Analyzing dependencies...');
  var emitter = analyzer.analyze(options, function (err, packages) {
    if (err) {
      winston.error('Error analyzing dependencies'.red);
      err.message.split('\n').forEach(function (line) {
        winston.error(line);
      });
      return;
    }
  });
  
  emitter.on('dependencies', function (deps) {
    winston.info('Done analyzing raw dependencies');
  });
  
  emitter.on('search', function (results) {
    winston.info('Retrieved packages from npm');
    updated = mergeResults(results).updated;
  });
  
  emitter.on('reduce', function (reduced) {
    var added = mergeResults(reduced).added,
        newpkg = {
          dependencies: analyzer.merge({}, added)
        };
    
    if (argv.update) {
      newpkg.dependencies = analyzer.merge({}, newpkg.dependencies, updated);
    }
    
    listDependencies(newpkg, {
      error: 'No additional dependencies found',
      success: 'Additional dependencies found'
    });
    
    //
    // If require-analyzer found new dependencies then update the `package.json`
    // file in the target `dir`.
    //
    if (argv.safe) {
      winston.info('did not update package.json');
      return;
    }
    if (Object.keys(newpkg.dependencies).length > 0) {
      winston.info('Updating ' + pkgFile.magenta);
      pkg.dependencies = analyzer.merge({}, pkg.dependencies, newpkg.dependencies);
      fs.writeFile(pkgFile, JSON.stringify(pkg, null, 2), function (err) {
        if (err) {
          winston.error('Error writing package.json');
          winston.error(err.message.red);
          return;
        }
        
        winston.info('require-analyzer updated package.json dependencies');
      });
    }
  });
});
Something went wrong with that request. Please try again.