Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created January 16, 2018 11:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/78f1832e97978d4db7aae44b653e4f61 to your computer and use it in GitHub Desktop.
Save WebReflection/78f1832e97978d4db7aae44b653e4f61 to your computer and use it in GitHub Desktop.
fix allman style with brackets losing initial padding
function fixEslintAllman(code) {
return code.replace(/^{/mg, function ($0, $1) {
var newLine = code.lastIndexOf('\n', $1 - 2);
var spaces = code.slice(newLine + 1, $1 - 1).match(/^(\s*)/)[1];
return spaces + '{';
});
}
@WebReflection
Copy link
Author

WebReflection commented Jan 16, 2018

I ended up calling this file eslint-fix-allman and making it an executable hooked to Run on Save extension.

#!/usr/bin/env node

var file = process.argv[2];

if (/\.js$/.test(file)) {
  var fs = require('fs');
  require('child_process')
    .spawn('eslint', ['--fix', file])
    .on('close', function (code) {
      if (code === 0) {
        var code = fs.readFileSync(file).toString();
        fs.writeFileSync(file, fixEslintAllman(code));
      }
      process.exit(code);
    });
}

function fixEslintAllman(code) {
  return code.replace(/^{/mg, function ($0, $1) {
    var newLine = code.lastIndexOf('\n', $1 - 2);
    var spaces = code.slice(newLine + 1, $1 - 1).match(/^(\s*)/)[1];
    return spaces + '{';
  });
}
#!/usr/bin/env bash

file=$1

if [ "${file:$((${#file} - 3)):${#file}}" = ".js" ]; then
  eslint --fix $file && node -e "
  let f='$file';
  if (f.slice(-3) === '.js') require('fs').writeFileSync(
    f,
    (s => s.replace(/^{/mg, (z, p) => s.slice(s.lastIndexOf('\n', p - 2) + 1, p - 1).match(/^(\s*)/)[1] + '{'))(
      require('fs').readFileSync(f).toString()
    )
  );";
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment