UNPKG

2.08 kBJavaScriptView Raw
1/**
2 * @fileoverview A rule to choose between single and double quote marks
3 * @author Matt DuVall <http://www.mattduvall.com/>, Brandon Payton
4 */
5
6//------------------------------------------------------------------------------
7// Constants
8//------------------------------------------------------------------------------
9
10var QUOTE_SETTINGS = {
11 "double": {
12 quote: "\"",
13 alternateQuote: "'",
14 description: "doublequote"
15 },
16 "single": {
17 quote: "'",
18 alternateQuote: "\"",
19 description: "singlequote"
20 }
21};
22
23var AVOID_ESCAPE = "avoid-escape";
24
25//------------------------------------------------------------------------------
26// Rule Definition
27//------------------------------------------------------------------------------
28
29module.exports = function(context) {
30
31 "use strict";
32
33 /**
34 * Validate that a string passed in is surrounded by the specified character
35 * @param {string} val The text to check.
36 * @param {string} character The character to see if it's surrounded by.
37 * @returns {boolean} True if the text is surrounded by the character, false if not.
38 */
39 function isSurroundedBy(val, character) {
40 return val[0] === character && val[val.length - 1] === character;
41 }
42
43 return {
44
45 "Literal": function(node) {
46 var val = node.value,
47 rawVal = node.raw,
48 quoteOption = context.options[0],
49 settings = QUOTE_SETTINGS[quoteOption],
50 avoidEscape = context.options[1] === AVOID_ESCAPE,
51 isValid;
52
53 if (settings && typeof val === "string") {
54 isValid = isSurroundedBy(rawVal, settings.quote);
55
56 if (!isValid && avoidEscape) {
57 isValid = isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
58 }
59
60 if (!isValid){
61 context.report(node, "Strings must use " + settings.description + ".");
62 }
63 }
64 }
65 };
66
67};