Created
January 23, 2016 22:50
-
-
Save smirea/95fb2126e8c30f071513 to your computer and use it in GitHub Desktop.
Re-indents given files to have 4 spaces of indentation
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
var fs = require('fs'); | |
var path = require('path'); | |
process.argv.slice(2).forEach(function (file) { | |
var content = fs.readFileSync(file).toString(); | |
var indent = get_indentation(content); | |
if (isNaN(indent)) throw new Error('NaN:' + file); | |
if (!indent || indent === 4) { | |
console.log('Skip:', file); | |
return; | |
} | |
console.log('Reindent from %d:', indent, file); | |
fs.writeFileSync(file, reindent(indent, 4, content)); | |
}); | |
function repeat (times, str) { | |
var result = ''; | |
for (var index = 0; index < times; ++index) { result = result + str; } | |
return result; | |
} | |
function reindent (from, to, content) { | |
var indent = repeat(to, ' '); | |
var reg = new RegExp('^' + repeat(from, '\\s')); | |
return content.split('\n').map(function (line) { | |
line = line.replace(/\s+$/, ''); | |
var match = line.match(/^\s+/); | |
if (match && match.length) { | |
line = repeat(Math.ceil(match[0].length / from), indent) + line.slice(match[0].length); | |
} | |
return line; | |
}).join('\n'); | |
} | |
function get_indentation (str) { | |
var indent = {}; | |
str.split('\n').forEach(function (line, index) { | |
var match = line.replace(/\t/g, ' ').match(/^\s+/); | |
if (!match || !match.length || match[0].length % 2 !== 0) return; | |
indent[match[0].length] = indent[match[0].length] || []; | |
indent[match[0].length].push(index); | |
}); | |
var indent_size = Object.keys(indent).reduce(function (sum, key) { | |
return gcd(sum, parseInt(key, 10)); | |
}, 0); | |
return indent_size; | |
} | |
function gcd (a, b) { | |
if (!b) return a; | |
return gcd(b, a % b); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment