Last active
December 19, 2015 16:38
-
-
Save iamnoah/5984818 to your computer and use it in GitHub Desktop.
Simple JS Shaper plugin to convert all single quoted strings to double quotes.
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
/** | |
* Usage: | |
* 1. git clone git://github.com/olov/jsshaper.git | |
* 2. mv quotes.js plugins/ | |
* 3. node run-shaper.js TARGET_FILE plugins/quotes.js --source > CORRECTLY_QUOTED_FILE | |
*/ | |
if (typeof define !== 'function') { | |
var define = require('amdefine')(module); | |
} | |
define(['../shaper', '../fmt', '../ref', '../tkn'], function(Shaper, Fmt, Ref, tkn) { | |
"use strict"; | |
"use restrict"; | |
var testString = '"embedded "quotes" and \'stuf\''; | |
var testObj = { | |
unquoted: true, | |
"doesnt_need_quotes": true, | |
'need\'s quotes': 'singel quoted value', | |
'doesnt_need_single': 123, | |
'default': "key is a keyword" | |
}; | |
/*jshint newcap:false */ | |
Shaper("quotes", function(root) { | |
return Shaper.traverse(root, { | |
pre: function(node, ref) { | |
if (node.type === tkn.PROPERTY_INIT) { | |
var value = node.children[0].value; | |
value = value.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*$/) ? | |
// don't quote identifiers that don't need it | |
value : | |
JSON.stringify(value); | |
try { | |
value = Shaper.parse(value); | |
} catch(e) { | |
value = Shaper.parse(JSON.stringify(value)); | |
} | |
node.children[0] = value; | |
return node; | |
} | |
if (node.type === tkn.STRING && | |
// don't stringify a string used as an identifier | |
(ref.base.type !== tkn.PROPERTY_INIT || ref.base.children[0] !== node)) { | |
return ref.set(Shaper.parse(JSON.stringify(node.value))); | |
} | |
} | |
}); | |
}); | |
return Shaper.get("quotes"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment