Question

I have a project of 100+ javascript files each with 1-5 missing semicolons according to JSHint (as a result multiple people working on the project with different conventions).

I'd like to bulk fix everything as it's not practical to fix each individually. I've found this: https://github.com/jshint/fixmyjs but I don't see a way only fix semicolons without 'fixing' other things (tabs -> spaces, for example).

Does anyone know of way to do this? I'm comfortable with the possibility that it might cause breakage/introduce bugs. I've look over the errors and they look pretty routine.

Was it helpful?

Solution

I really hope you like this as a solution. Be vary careful that you verify with jshint again after you've fixed the issues. And out of curiosity, how did you manage to get so many broken javascript files?

#!/bin/sh
function fixFile {
  for i in `jshint $1 | grep -i "Missing semicolon" \
                      | sed -e 's/\([^0-9]*\)\([0-9]*\)\(.*$\)/\2/'`;
  do
    sed -i $1 -e $i's/\(\s*\)$/;/'
  done
}

fixFile $1

The above uses jshint to produce some error lines, greps them for the missing semicolon errors only, extracts the line number of each error, then seds the file in place on that line to remove any trailing whitespace and replace it with a semicolon.

The file...

var a = 5, c = 4

function helloWorld() {
  if (this == doesntmakesense)
    console.log('hello' + 'world');
}

console.log(a+c);
console.log('finished')   

...becomes...

var a = 5, c = 4;

function helloWorld() {
  if (this == doesntmakesense)
    console.log('hello' + 'world');
}

console.log(a+c);
console.log('finished');

Where petty semantic errors are ignored, and only semicolons treated.

I'd save the bash script as something like fixFile.sh and then run find . -name "*.js" -exec ./fixFile.sh {} \;

But please commit beforehand. All commands are run at your own risk ;)

OTHER TIPS

There is a safer way of adding missing semicolons than using regular expressions. Use the following steps to configure fixmyjs to only fix semicolons as originally asked by Evan:

  1. Install fixmyjs

    npm install fixmyjs -g

  2. Create a fixmyjs config file fixmyjs-config with the following content

    { "asi": false }

  3. Run fixmyjs

    fixmyjs --config [fixmyjs-config] --legacy yourfile.js

Reference: https://github.com/jshint/fixmyjs/issues/86

Google Closure JS Linter has a program that comes with it, able to correct some of the more regular violations such as this one I believe, it's named fixjsstyle (python btw)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top