summaryrefslogtreecommitdiffstats
path: root/browser/base/content/test/static/browser_misused_characters_in_strings.js
blob: 42be3b439297b3d6d511c61bdb16620625a735c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

/* This list allows pre-existing or 'unfixable' issues to remain, while we
 * detect newly occurring issues in shipping files. It is a list of objects
 * specifying conditions under which an error should be ignored.
 *
 * As each issue is found in the exceptions list, it is removed from the list.
 * At the end of the test, there is an assertion that all items have been
 * removed from the exceptions list, thus ensuring there are no stale
 * entries. */
let gExceptionsList = [
  {
    file: "layout_errors.properties",
    key: "ImageMapRectBoundsError",
    type: "double-quote",
  },
  {
    file: "layout_errors.properties",
    key: "ImageMapCircleWrongNumberOfCoords",
    type: "double-quote",
  },
  {
    file: "layout_errors.properties",
    key: "ImageMapCircleNegativeRadius",
    type: "double-quote",
  },
  {
    file: "layout_errors.properties",
    key: "ImageMapPolyWrongNumberOfCoords",
    type: "double-quote",
  },
  {
    file: "layout_errors.properties",
    key: "ImageMapPolyOddNumberOfCoords",
    type: "double-quote",
  },
  {
    file: "dom.properties",
    key: "PatternAttributeCompileFailure",
    type: "single-quote",
  },
  // dom.properties is packaged twice so we need to have two exceptions for this string.
  {
    file: "dom.properties",
    key: "PatternAttributeCompileFailure",
    type: "single-quote",
  },
  {
    file: "dom.properties",
    key: "ImportMapExternalNotSupported",
    type: "single-quote",
  },
  // dom.properties is packaged twice so we need to have two exceptions for this string.
  {
    file: "dom.properties",
    key: "ImportMapExternalNotSupported",
    type: "single-quote",
  },
];

/**
 * Check if an error should be ignored due to matching one of the exceptions
 * defined in gExceptionsList.
 *
 * @param filepath The URI spec of the locale file
 * @param key The key of the entity that is being checked
 * @param type The type of error that has been found
 * @return true if the error should be ignored, false otherwise.
 */
function ignoredError(filepath, key, type) {
  for (let index in gExceptionsList) {
    let exceptionItem = gExceptionsList[index];
    if (
      filepath.endsWith(exceptionItem.file) &&
      key == exceptionItem.key &&
      type == exceptionItem.type
    ) {
      gExceptionsList.splice(index, 1);
      return true;
    }
  }
  return false;
}

function testForError(filepath, key, str, pattern, type, helpText) {
  if (str.match(pattern) && !ignoredError(filepath, key, type)) {
    ok(false, `${filepath} with key=${key} has a misused ${type}. ${helpText}`);
  }
}

function testForErrors(filepath, key, str) {
  testForError(
    filepath,
    key,
    str,
    /(\w|^)'\w/,
    "apostrophe",
    "Strings with apostrophes should use foo\u2019s instead of foo's."
  );
  testForError(
    filepath,
    key,
    str,
    /\w\u2018\w/,
    "incorrect-apostrophe",
    "Strings with apostrophes should use foo\u2019s instead of foo\u2018s."
  );
  testForError(
    filepath,
    key,
    str,
    /'.+'/,
    "single-quote",
    "Single-quoted strings should use Unicode \u2018foo\u2019 instead of 'foo'."
  );
  testForError(
    filepath,
    key,
    str,
    /"/,
    "double-quote",
    'Double-quoted strings should use Unicode \u201cfoo\u201d instead of "foo".'
  );
  testForError(
    filepath,
    key,
    str,
    /\.\.\./,
    "ellipsis",
    "Strings with an ellipsis should use the Unicode \u2026 character instead of three periods."
  );
}

async function getAllTheFiles(extension) {
  let appDirGreD = Services.dirsvc.get("GreD", Ci.nsIFile);
  let appDirXCurProcD = Services.dirsvc.get("XCurProcD", Ci.nsIFile);
  if (appDirGreD.contains(appDirXCurProcD)) {
    return generateURIsFromDirTree(appDirGreD, [extension]);
  }
  if (appDirXCurProcD.contains(appDirGreD)) {
    return generateURIsFromDirTree(appDirXCurProcD, [extension]);
  }
  let urisGreD = await generateURIsFromDirTree(appDirGreD, [extension]);
  let urisXCurProcD = await generateURIsFromDirTree(appDirXCurProcD, [
    extension,
  ]);
  return Array.from(new Set(urisGreD.concat(urisXCurProcD)));
}

add_task(async function checkAllTheProperties() {
  // This asynchronously produces a list of URLs (sadly, mostly sync on our
  // test infrastructure because it runs against jarfiles there, and
  // our zipreader APIs are all sync)
  let uris = await getAllTheFiles(".properties");
  ok(
    uris.length,
    `Found ${uris.length} .properties files to scan for misused characters`
  );

  for (let uri of uris) {
    let bundle = Services.strings.createBundle(uri.spec);

    for (let entity of bundle.getSimpleEnumeration()) {
      testForErrors(uri.spec, entity.key, entity.value);
    }
  }
});

var checkDTD = async function (aURISpec) {
  let rawContents = await fetchFile(aURISpec);
  // The regular expression below is adapted from:
  // https://hg.mozilla.org/mozilla-central/file/68c0b7d6f16ce5bb023e08050102b5f2fe4aacd8/python/compare-locales/compare_locales/parser.py#l233
  let entities = rawContents.match(
    /<!ENTITY\s+([\w\.]*)\s+("[^"]*"|'[^']*')\s*>/g
  );
  if (!entities) {
    // Some files have no entities defined.
    return;
  }
  for (let entity of entities) {
    let [, key, str] = entity.match(
      /<!ENTITY\s+([\w\.]*)\s+("[^"]*"|'[^']*')\s*>/
    );
    // The matched string includes the enclosing quotation marks,
    // we need to slice them off.
    str = str.slice(1, -1);
    testForErrors(aURISpec, key, str);
  }
};

add_task(async function checkAllTheDTDs() {
  let uris = await getAllTheFiles(".dtd");
  ok(
    uris.length,
    `Found ${uris.length} .dtd files to scan for misused characters`
  );
  for (let uri of uris) {
    await checkDTD(uri.spec);
  }

  // This support DTD file supplies a string with a newline to make sure
  // the regex in checkDTD works correctly for that case.
  let dtdLocation = gTestPath.replace(
    /\/[^\/]*$/i,
    "/bug1262648_string_with_newlines.dtd"
  );
  await checkDTD(dtdLocation);
});

add_task(async function checkAllTheFluents() {
  let uris = await getAllTheFiles(".ftl");
  let { FluentParser, Visitor } = ChromeUtils.import(
    "resource://testing-common/FluentSyntax.jsm"
  );

  class TextElementVisitor extends Visitor {
    constructor() {
      super();
      let domParser = new DOMParser();
      domParser.forceEnableDTD();

      this.domParser = domParser;
      this.uri = null;
      this.id = null;
      this.attr = null;
    }

    visitMessage(node) {
      this.id = node.id.name;
      this.attr = null;
      this.genericVisit(node);
    }

    visitTerm(node) {
      this.id = node.id.name;
      this.attr = null;
      this.genericVisit(node);
    }

    visitAttribute(node) {
      this.attr = node.id.name;
      this.genericVisit(node);
    }

    get key() {
      if (this.attr) {
        return `${this.id}.${this.attr}`;
      }
      return this.id;
    }

    visitTextElement(node) {
      const stripped_val = this.domParser.parseFromString(
        "<!DOCTYPE html>" + node.value,
        "text/html"
      ).documentElement.textContent;
      testForErrors(this.uri, this.key, stripped_val);
    }
  }

  const ftlParser = new FluentParser({ withSpans: false });
  const visitor = new TextElementVisitor();

  for (let uri of uris) {
    let rawContents = await fetchFile(uri.spec);
    let ast = ftlParser.parse(rawContents);

    visitor.uri = uri.spec;
    visitor.visit(ast);
  }
});

add_task(async function ensureExceptionsListIsEmpty() {
  is(gExceptionsList.length, 0, "No remaining exceptions exist");
});