Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | # Copyright (C) 2018 The Android Open Source Project |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the 'License'); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an 'AS IS' BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | |
| 17 | """ |
| 18 | Enforces common Android string best-practices. It ignores lint messages from |
| 19 | a previous strings file, if provided. |
| 20 | |
| 21 | Usage: stringslint.py strings.xml |
| 22 | Usage: stringslint.py strings.xml old_strings.xml |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 23 | |
| 24 | In general: |
| 25 | * Errors signal issues that must be fixed before submitting, and are only |
| 26 | used when there are no false-positives. |
| 27 | * Warnings signal issues that might need to be fixed, but need manual |
| 28 | inspection due to risk of false-positives. |
| 29 | * Info signal issues that should be fixed to match best-practices, such |
| 30 | as providing comments to aid translation. |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 31 | """ |
| 32 | |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 33 | import re, sys, codecs |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 34 | import lxml.etree as ET |
| 35 | |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 36 | reload(sys) |
| 37 | sys.setdefaultencoding('utf8') |
| 38 | |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 39 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) |
| 40 | |
| 41 | def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False): |
| 42 | # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes |
| 43 | codes = [] |
| 44 | if reset: codes.append("0") |
| 45 | else: |
| 46 | if not fg is None: codes.append("3%d" % (fg)) |
| 47 | if not bg is None: |
| 48 | if not bright: codes.append("4%d" % (bg)) |
| 49 | else: codes.append("10%d" % (bg)) |
| 50 | if bold: codes.append("1") |
| 51 | elif dim: codes.append("2") |
| 52 | else: codes.append("22") |
| 53 | return "\033[%sm" % (";".join(codes)) |
| 54 | |
| 55 | warnings = None |
| 56 | |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 57 | def warn(tag, msg, actual, expected, color=YELLOW): |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 58 | global warnings |
| 59 | key = "%s:%d" % (tag.attrib["name"], hash(msg)) |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 60 | value = "%sLine %d: '%s':%s %s" % (format(fg=color, bold=True), |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 61 | tag.sourceline, |
| 62 | tag.attrib["name"], |
| 63 | format(reset=True), |
| 64 | msg) |
| 65 | if not actual is None: value += "\n\tActual: %s%s%s" % (format(dim=True), |
| 66 | actual, |
| 67 | format(reset=True)) |
| 68 | if not expected is None: value += "\n\tExample: %s%s%s" % (format(dim=True), |
| 69 | expected, |
| 70 | format(reset=True)) |
| 71 | warnings[key] = value |
| 72 | |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 73 | |
| 74 | def error(tag, msg, actual, expected): |
| 75 | warn(tag, msg, actual, expected, RED) |
| 76 | |
| 77 | def info(tag, msg, actual, expected): |
| 78 | warn(tag, msg, actual, expected, CYAN) |
| 79 | |
| 80 | # Escaping logic borrowed from https://stackoverflow.com/a/24519338 |
| 81 | ESCAPE_SEQUENCE_RE = re.compile(r''' |
| 82 | ( \\U........ # 8-digit hex escapes |
| 83 | | \\u.... # 4-digit hex escapes |
| 84 | | \\x.. # 2-digit hex escapes |
| 85 | | \\[0-7]{1,3} # Octal escapes |
| 86 | | \\N\{[^}]+\} # Unicode characters by name |
| 87 | | \\[\\'"abfnrtv] # Single-character escapes |
| 88 | )''', re.UNICODE | re.VERBOSE) |
| 89 | |
| 90 | def decode_escapes(s): |
| 91 | def decode_match(match): |
| 92 | return codecs.decode(match.group(0), 'unicode-escape') |
| 93 | |
| 94 | s = re.sub(r"\n\s*", " ", s) |
| 95 | s = ESCAPE_SEQUENCE_RE.sub(decode_match, s) |
| 96 | s = re.sub(r"%(\d+\$)?[a-z]", "____", s) |
| 97 | s = re.sub(r"\^\d+", "____", s) |
| 98 | s = re.sub(r"<br/?>", "\n", s) |
| 99 | s = re.sub(r"</?[a-z]+>", "", s) |
| 100 | return s |
| 101 | |
| 102 | def sample_iter(tag): |
| 103 | if not isinstance(tag, ET._Comment) and re.match("{.*xliff.*}g", tag.tag) and "example" in tag.attrib: |
| 104 | yield tag.attrib["example"] |
| 105 | elif tag.text: |
| 106 | yield decode_escapes(tag.text) |
| 107 | for e in tag: |
| 108 | for v in sample_iter(e): |
| 109 | yield v |
| 110 | if e.tail: |
| 111 | yield decode_escapes(e.tail) |
| 112 | |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 113 | def lint(path): |
| 114 | global warnings |
| 115 | warnings = {} |
| 116 | |
| 117 | with open(path) as f: |
| 118 | raw = f.read() |
| 119 | if len(raw.strip()) == 0: |
| 120 | return warnings |
| 121 | tree = ET.fromstring(raw) |
| 122 | root = tree #tree.getroot() |
| 123 | |
| 124 | last_comment = None |
| 125 | for child in root: |
| 126 | # TODO: handle plurals |
| 127 | if isinstance(child, ET._Comment): |
| 128 | last_comment = child |
| 129 | elif child.tag == "string": |
| 130 | # We always consume comment |
| 131 | comment = last_comment |
| 132 | last_comment = None |
| 133 | |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 134 | # Prepare string for analysis |
| 135 | text = "".join(child.itertext()) |
| 136 | sample = "".join(sample_iter(child)).strip().strip("'\"") |
| 137 | |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 138 | # Validate comment |
| 139 | if comment is None: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 140 | info(child, "Missing string comment to aid translation", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 141 | None, None) |
| 142 | continue |
| 143 | if "do not translate" in comment.text.lower(): |
| 144 | continue |
| 145 | if "translatable" in child.attrib and child.attrib["translatable"].lower() == "false": |
| 146 | continue |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 147 | |
| 148 | limit = re.search("CHAR[ _-]LIMIT=(\d+|NONE|none)", comment.text) |
| 149 | if limit is None: |
| 150 | info(child, "Missing CHAR LIMIT to aid translation", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 151 | repr(comment), "<!-- Description of string [CHAR LIMIT=32] -->") |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 152 | elif re.match("\d+", limit.group(1)): |
| 153 | limit = int(limit.group(1)) |
| 154 | if len(sample) > limit: |
| 155 | warn(child, "Expanded string length is larger than CHAR LIMIT", |
| 156 | sample, None) |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 157 | |
| 158 | # Look for common mistakes/substitutions |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 159 | if "'" in text: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 160 | error(child, "Turned quotation mark glyphs are more polished", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 161 | text, "This doesn\u2019t need to \u2018happen\u2019 today") |
| 162 | if '"' in text and not text.startswith('"') and text.endswith('"'): |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 163 | error(child, "Turned quotation mark glyphs are more polished", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 164 | text, "This needs to \u201chappen\u201d today") |
| 165 | if "..." in text: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 166 | error(child, "Ellipsis glyph is more polished", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 167 | text, "Loading\u2026") |
| 168 | if "wi-fi" in text.lower(): |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 169 | error(child, "Non-breaking glyph is more polished", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 170 | text, "Wi\u2011Fi") |
| 171 | if "wifi" in text.lower(): |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 172 | error(child, "Using non-standard spelling", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 173 | text, "Wi\u2011Fi") |
| 174 | if re.search("\d-\d", text): |
| 175 | warn(child, "Ranges should use en dash glyph", |
| 176 | text, "You will find this material in chapters 8\u201312") |
| 177 | if "--" in text: |
| 178 | warn(child, "Phrases should use em dash glyph", |
| 179 | text, "Upon discovering errors\u2014all 124 of them\u2014they recalled.") |
| 180 | if ". " in text: |
| 181 | warn(child, "Only use single space between sentences", |
| 182 | text, "First idea. Second idea.") |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 183 | if re.match(r"^[A-Z\s]{5,}$", text): |
| 184 | warn(child, "Actions should use android:textAllCaps in layout; ignore if acronym", |
| 185 | text, "Refresh data") |
| 186 | if " phone " in text and "product" not in child.attrib: |
| 187 | warn(child, "Strings mentioning phones should have variants for tablets", |
| 188 | text, None) |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 189 | |
| 190 | # When more than one substitution, require indexes |
| 191 | if len(re.findall("%[^%]", text)) > 1: |
| 192 | if len(re.findall("%[^\d]", text)) > 0: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 193 | error(child, "Substitutions must be indexed", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 194 | text, "Add %1$s to %2$s") |
| 195 | |
| 196 | # Require xliff substitutions |
| 197 | for gc in child.iter(): |
| 198 | badsub = False |
| 199 | if gc.tail and re.search("%[^%]", gc.tail): badsub = True |
| 200 | if re.match("{.*xliff.*}g", gc.tag): |
| 201 | if "id" not in gc.attrib: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 202 | error(child, "Substitutions must define id attribute", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 203 | None, "<xliff:g id=\"domain\" example=\"example.com\">%1$s</xliff:g>") |
| 204 | if "example" not in gc.attrib: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 205 | error(child, "Substitutions must define example attribute", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 206 | None, "<xliff:g id=\"domain\" example=\"example.com\">%1$s</xliff:g>") |
| 207 | else: |
| 208 | if gc.text and re.search("%[^%]", gc.text): badsub = True |
| 209 | if badsub: |
Jeff Sharkey | 47c7924 | 2018-06-05 15:55:45 -0600 | [diff] [blame^] | 210 | error(child, "Substitutions must be inside xliff tags", |
Jeff Sharkey | abe058c | 2018-03-26 09:38:01 -0600 | [diff] [blame] | 211 | text, "<xliff:g id=\"domain\" example=\"example.com\">%1$s</xliff:g>") |
| 212 | |
| 213 | return warnings |
| 214 | |
| 215 | if len(sys.argv) > 2: |
| 216 | before = lint(sys.argv[2]) |
| 217 | else: |
| 218 | before = {} |
| 219 | after = lint(sys.argv[1]) |
| 220 | |
| 221 | for b in before: |
| 222 | if b in after: |
| 223 | del after[b] |
| 224 | |
| 225 | if len(after) > 0: |
| 226 | for a in sorted(after.keys()): |
| 227 | print after[a] |
| 228 | print |
| 229 | sys.exit(1) |