Created
September 15, 2016 15:30
-
-
Save wayspurrchen/b8879003a0cd3b6c703aa8e09cb6ad4f to your computer and use it in GitHub Desktop.
Strip IIFEs from files in a directory. You'll need minimist and recursive-readdir. Doesn't work on IIFEs that have args passed in
This file contains 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
var fs = require('fs'); | |
var path = require('path'); | |
var recursive = require('recursive-readdir'); | |
var argv = require('minimist')(process.argv.slice(2)); | |
var iifepath = path.resolve(process.cwd(), argv.path); | |
function isIIFEStart (string) { | |
// whatever you don't know my life | |
return string === '(function () {' || | |
string === '(function(){' || | |
string === '(function() {' || | |
string === '(function (){'; | |
} | |
function isIIFEEnd (string) { | |
return string === '})();' || string === '})()'; | |
} | |
recursive(iifepath, function (err, files) { | |
files.forEach((file) => { | |
if (path.extname(file) !== '.js') { | |
return; | |
} | |
if (file.indexOf('test.js') !== -1) { | |
return; | |
} | |
if (file.indexOf('tests.js') !== -1) { | |
return; | |
} | |
if (file.indexOf('spec.js') !== -1) { | |
return; | |
} | |
if (file.indexOf('legacy/tests') !== -1) { | |
return; | |
} | |
var contents = fs.readFileSync(file, 'utf8'); | |
var lines = contents.split('\n'); | |
// Find the first line with content | |
let firstLineWithContent; | |
let i = 0; | |
while (i < lines.length) { | |
firstLineWithContent = lines[i]; | |
if (firstLineWithContent !== '') { | |
break; | |
} | |
i++; | |
} | |
// If it's not an IIFE, abandon | |
if (!isIIFEStart(firstLineWithContent)) { | |
return; | |
} | |
let lastLineWithContent; | |
// Find the last line with content | |
let k = lines.length - 1; | |
while (k > 0) { | |
lastLineWithContent = lines[k]; | |
if (lastLineWithContent !== '') { | |
break; | |
} | |
k--; | |
} | |
// If it's not an IIFE, abandon | |
if (!isIIFEEnd(lastLineWithContent)) { | |
return; | |
} | |
// Remove first line | |
lines.splice(i, 1); | |
// Remove last line (-1 for the removed first line) | |
lines.splice(k - 1, 1); | |
var strippedFile = lines.join('\n'); | |
fs.writeFileSync(file, strippedFile, 'utf8'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment