UNPKG

3.32 kBtext/coffeescriptView Raw
1
2Pattern = require './Pattern'
3
4# Escaper encapsulates escaping rules for single
5# and double-quoted YAML strings.
6class Escaper
7
8 # Mapping arrays for escaping a double quoted string. The backslash is
9 # first to ensure proper escaping.
10 @LIST_ESCAPEES: ['\\', '\\\\', '\\"', '"',
11 "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
12 "\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f",
13 "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
14 "\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f",
15 (ch = String.fromCharCode)(0x0085), ch(0x00A0), ch(0x2028), ch(0x2029)]
16 @LIST_ESCAPED: ['\\\\', '\\"', '\\"', '\\"',
17 "\\0", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
18 "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
19 "\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17",
20 "\\x18", "\\x19", "\\x1a", "\\e", "\\x1c", "\\x1d", "\\x1e", "\\x1f",
21 "\\N", "\\_", "\\L", "\\P"]
22
23 @MAPPING_ESCAPEES_TO_ESCAPED: do =>
24 mapping = {}
25 for i in [0...@LIST_ESCAPEES.length]
26 mapping[@LIST_ESCAPEES[i]] = @LIST_ESCAPED[i]
27 return mapping
28
29 # Characters that would cause a dumped string to require double quoting.
30 @PATTERN_CHARACTERS_TO_ESCAPE: new Pattern '[\\x00-\\x1f]|\xc2\x85|\xc2\xa0|\xe2\x80\xa8|\xe2\x80\xa9'
31
32 # Other precompiled patterns
33 @PATTERN_MAPPING_ESCAPEES: new Pattern @LIST_ESCAPEES.join('|').split('\\').join('\\\\')
34 @PATTERN_SINGLE_QUOTING: new Pattern '[\\s\'":{}[\\],&*#?]|^[-?|<>=!%@`]'
35
36
37
38 # Determines if a JavaScript value would require double quoting in YAML.
39 #
40 # @param [String] value A JavaScript value value
41 #
42 # @return [Boolean] true if the value would require double quotes.
43 #
44 @requiresDoubleQuoting: (value) ->
45 return @PATTERN_CHARACTERS_TO_ESCAPE.test value
46
47
48 # Escapes and surrounds a JavaScript value with double quotes.
49 #
50 # @param [String] value A JavaScript value
51 #
52 # @return [String] The quoted, escaped string
53 #
54 @escapeWithDoubleQuotes: (value) ->
55 result = @PATTERN_MAPPING_ESCAPEES.replace value, (str) =>
56 return @MAPPING_ESCAPEES_TO_ESCAPED[str]
57 return '"'+result+'"'
58
59
60 # Determines if a JavaScript value would require single quoting in YAML.
61 #
62 # @param [String] value A JavaScript value
63 #
64 # @return [Boolean] true if the value would require single quotes.
65 #
66 @requiresSingleQuoting: (value) ->
67 return @PATTERN_SINGLE_QUOTING.test value
68
69
70 # Escapes and surrounds a JavaScript value with single quotes.
71 #
72 # @param [String] value A JavaScript value
73 #
74 # @return [String] The quoted, escaped string
75 #
76 @escapeWithSingleQuotes: (value) ->
77 return "'"+value.replace(/'/g, "''")+"'"
78
79
80module.exports = Escaper