Created
March 3, 2014 23:26
-
-
Save skeggse/9336837 to your computer and use it in GitHub Desktop.
npm git ignore node_modules: ignores npm modules in the node_modules directory by consulting the devDependencies field in the package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var fs = require('fs'); | |
var path = require('path'); | |
var hasOwn = Object.prototype.hasOwnProperty; | |
// seaches recursively upwards to find the package.json | |
function load(start, name) { | |
var exists, full; | |
do { | |
exists = fs.existsSync(full = path.join(start, name)); | |
start = path.dirname(start); | |
} while (!exists && start !== path.dirname(start)); | |
if (!exists) | |
throw new Error('cannot locate ' + name); | |
var obj = require(full); | |
if (!obj || typeof obj !== 'object') | |
throw new TypeError('expected object'); | |
return { | |
path: path.dirname(full), | |
full: full, | |
file: obj | |
}; | |
} | |
var obj = load(process.cwd(), 'package.json'), package = obj.file; | |
var ignore = package.devDependencies; | |
var gitignore = path.join(obj.path, '.gitignore'); | |
if (!ignore || typeof ignore !== 'object') | |
return console.warn('no development dependencies'); | |
for (var key in ignore) { | |
ignore['/node_modules/' + key] = ignore[key]; | |
delete ignore[key]; | |
} | |
var lines; | |
if (!fs.existsSync(gitignore)) | |
lines = []; | |
else { | |
lines = fs.readFileSync(gitignore, 'utf-8').split(/\r?\n/g); | |
lines.forEach(function(line) { | |
line = line && line.trim(); | |
if (line && hasOwn.call(ignore, line)) { | |
delete ignore[line]; | |
} | |
}); | |
} | |
lines = lines.concat(Object.keys(ignore), ['']).join('\n'); | |
if (~process.argv.indexOf('--print')) | |
return console.log(lines); | |
fs.writeFileSync(gitignore, lines); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment