eslint.lint 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. import json
  6. import os
  7. import platform
  8. import re
  9. import signal
  10. import subprocess
  11. import sys
  12. from distutils.version import LooseVersion
  13. import which
  14. from mozprocess import ProcessHandler
  15. from mozlint import result
  16. ESLINT_ERROR_MESSAGE = """
  17. An error occurred running eslint. Please check the following error messages:
  18. {}
  19. """.strip()
  20. ESLINT_NOT_FOUND_MESSAGE = """
  21. Could not find eslint! We looked at the --binary option, at the ESLINT
  22. environment variable, and then at your local node_modules path. Please Install
  23. eslint and needed plugins with:
  24. mach eslint --setup
  25. and try again.
  26. """.strip()
  27. NODE_NOT_FOUND_MESSAGE = """
  28. nodejs v4.2.3 is either not installed or is installed to a non-standard path.
  29. Please install nodejs from https://nodejs.org and try again.
  30. Valid installation paths:
  31. """.strip()
  32. NPM_NOT_FOUND_MESSAGE = """
  33. Node Package Manager (npm) is either not installed or installed to a
  34. non-standard path. Please install npm from https://nodejs.org (it comes as an
  35. option in the node installation) and try again.
  36. Valid installation paths:
  37. """.strip()
  38. VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")
  39. CARET_VERSION_RANGE_RE = re.compile(r"^\^((\d+)\.\d+\.\d+)$")
  40. EXTENSIONS = ['.js', '.jsm', '.jsx', '.xml', '.html', '.xhtml']
  41. project_root = None
  42. def eslint_setup():
  43. """Ensure eslint is optimally configured.
  44. This command will inspect your eslint configuration and
  45. guide you through an interactive wizard helping you configure
  46. eslint for optimal use on Mozilla projects.
  47. """
  48. orig_cwd = os.getcwd()
  49. sys.path.append(os.path.dirname(__file__))
  50. module_path = get_eslint_module_path()
  51. # npm sometimes fails to respect cwd when it is run using check_call so
  52. # we manually switch folders here instead.
  53. os.chdir(module_path)
  54. npm_path = get_node_or_npm_path("npm")
  55. if not npm_path:
  56. return 1
  57. # Install ESLint and external plugins
  58. cmd = [npm_path, "install"]
  59. print("Installing eslint for mach using \"%s\"..." % (" ".join(cmd)))
  60. if not call_process("eslint", cmd):
  61. return 1
  62. # Install in-tree ESLint plugin
  63. cmd = [npm_path, "install",
  64. os.path.join(module_path, "eslint-plugin-mozilla")]
  65. print("Installing eslint-plugin-mozilla using \"%s\"..." % (" ".join(cmd)))
  66. if not call_process("eslint-plugin-mozilla", cmd):
  67. return 1
  68. eslint_path = os.path.join(module_path, "node_modules", ".bin", "eslint")
  69. print("\nESLint and approved plugins installed successfully!")
  70. print("\nNOTE: Your local eslint binary is at %s\n" % eslint_path)
  71. os.chdir(orig_cwd)
  72. def call_process(name, cmd, cwd=None):
  73. try:
  74. with open(os.devnull, "w") as fnull:
  75. subprocess.check_call(cmd, cwd=cwd, stdout=fnull)
  76. except subprocess.CalledProcessError:
  77. if cwd:
  78. print("\nError installing %s in the %s folder, aborting." % (name, cwd))
  79. else:
  80. print("\nError installing %s, aborting." % name)
  81. return False
  82. return True
  83. def expected_eslint_modules():
  84. # Read the expected version of ESLint and external modules
  85. expected_modules_path = os.path.join(get_eslint_module_path(), "package.json")
  86. with open(expected_modules_path, "r") as f:
  87. expected_modules = json.load(f)["dependencies"]
  88. # Also read the in-tree ESLint plugin version
  89. mozilla_json_path = os.path.join(get_eslint_module_path(),
  90. "eslint-plugin-mozilla", "package.json")
  91. with open(mozilla_json_path, "r") as f:
  92. expected_modules["eslint-plugin-mozilla"] = json.load(f)["version"]
  93. return expected_modules
  94. def eslint_module_has_issues():
  95. has_issues = False
  96. node_modules_path = os.path.join(get_eslint_module_path(), "node_modules")
  97. for name, version_range in expected_eslint_modules().iteritems():
  98. path = os.path.join(node_modules_path, name, "package.json")
  99. if not os.path.exists(path):
  100. print("%s v%s needs to be installed locally." % (name, version_range))
  101. has_issues = True
  102. continue
  103. data = json.load(open(path))
  104. if not version_in_range(data["version"], version_range):
  105. print("%s v%s should be v%s." % (name, data["version"], version_range))
  106. has_issues = True
  107. return has_issues
  108. def version_in_range(version, version_range):
  109. """
  110. Check if a module version is inside a version range. Only supports explicit versions and
  111. caret ranges for the moment, since that's all we've used so far.
  112. """
  113. if version == version_range:
  114. return True
  115. version_match = VERSION_RE.match(version)
  116. if not version_match:
  117. raise RuntimeError("mach eslint doesn't understand module version %s" % version)
  118. version = LooseVersion(version)
  119. # Caret ranges as specified by npm allow changes that do not modify the left-most non-zero
  120. # digit in the [major, minor, patch] tuple. The code below assumes the major digit is
  121. # non-zero.
  122. range_match = CARET_VERSION_RANGE_RE.match(version_range)
  123. if range_match:
  124. range_version = range_match.group(1)
  125. range_major = int(range_match.group(2))
  126. range_min = LooseVersion(range_version)
  127. range_max = LooseVersion("%d.0.0" % (range_major + 1))
  128. return range_min <= version < range_max
  129. return False
  130. def get_possible_node_paths_win():
  131. """
  132. Return possible nodejs paths on Windows.
  133. """
  134. if platform.system() != "Windows":
  135. return []
  136. return list({
  137. "%s\\nodejs" % os.environ.get("SystemDrive"),
  138. os.path.join(os.environ.get("ProgramFiles"), "nodejs"),
  139. os.path.join(os.environ.get("PROGRAMW6432"), "nodejs"),
  140. os.path.join(os.environ.get("PROGRAMFILES"), "nodejs")
  141. })
  142. def get_node_or_npm_path(filename, minversion=None):
  143. """
  144. Return the nodejs or npm path.
  145. """
  146. if platform.system() == "Windows":
  147. for ext in [".cmd", ".exe", ""]:
  148. try:
  149. node_or_npm_path = which.which(filename + ext,
  150. path=get_possible_node_paths_win())
  151. if is_valid(node_or_npm_path, minversion):
  152. return node_or_npm_path
  153. except which.WhichError:
  154. pass
  155. else:
  156. try:
  157. node_or_npm_path = which.which(filename)
  158. if is_valid(node_or_npm_path, minversion):
  159. return node_or_npm_path
  160. except which.WhichError:
  161. pass
  162. if filename == "node":
  163. print(NODE_NOT_FOUND_MESSAGE)
  164. elif filename == "npm":
  165. print(NPM_NOT_FOUND_MESSAGE)
  166. if platform.system() == "Windows":
  167. app_paths = get_possible_node_paths_win()
  168. for p in app_paths:
  169. print(" - %s" % p)
  170. elif platform.system() == "Darwin":
  171. print(" - /usr/local/bin/node")
  172. elif platform.system() == "Linux":
  173. print(" - /usr/bin/nodejs")
  174. return None
  175. def is_valid(path, minversion=None):
  176. try:
  177. version_str = subprocess.check_output([path, "--version"],
  178. stderr=subprocess.STDOUT)
  179. if minversion:
  180. # nodejs prefixes its version strings with "v"
  181. version = LooseVersion(version_str.lstrip('v'))
  182. return version >= minversion
  183. return True
  184. except (subprocess.CalledProcessError, OSError):
  185. return False
  186. def get_project_root():
  187. global project_root
  188. return project_root
  189. def get_eslint_module_path():
  190. return os.path.join(get_project_root(), "tools", "lint", "eslint")
  191. def lint(paths, binary=None, fix=None, setup=None, **lintargs):
  192. """Run eslint."""
  193. global project_root
  194. project_root = lintargs['root']
  195. module_path = get_eslint_module_path()
  196. # eslint requires at least node 4.2.3
  197. node_path = get_node_or_npm_path("node", LooseVersion("4.2.3"))
  198. if not node_path:
  199. return 1
  200. if setup:
  201. return eslint_setup()
  202. npm_path = get_node_or_npm_path("npm")
  203. if not npm_path:
  204. return 1
  205. if eslint_module_has_issues():
  206. eslint_setup()
  207. # Valid binaries are:
  208. # - Any provided by the binary argument.
  209. # - Any pointed at by the ESLINT environmental variable.
  210. # - Those provided by mach eslint --setup.
  211. #
  212. # eslint --setup installs some mozilla specific plugins and installs
  213. # all node modules locally. This is the preferred method of
  214. # installation.
  215. if not binary:
  216. binary = os.environ.get('ESLINT', None)
  217. if not binary:
  218. binary = os.path.join(module_path, "node_modules", ".bin", "eslint")
  219. if not os.path.isfile(binary):
  220. binary = None
  221. if not binary:
  222. print(ESLINT_NOT_FOUND_MESSAGE)
  223. return 1
  224. extra_args = lintargs.get('extra_args') or []
  225. cmd_args = [binary,
  226. # Enable the HTML plugin.
  227. # We can't currently enable this in the global config file
  228. # because it has bad interactions with the SublimeText
  229. # ESLint plugin (bug 1229874).
  230. '--plugin', 'html',
  231. # This keeps ext as a single argument.
  232. '--ext', '[{}]'.format(','.join(EXTENSIONS)),
  233. '--format', 'json',
  234. ] + extra_args + paths
  235. # eslint requires that --fix be set before the --ext argument.
  236. if fix:
  237. cmd_args.insert(1, '--fix')
  238. shell = False
  239. if os.environ.get('MSYSTEM') in ('MINGW32', 'MINGW64'):
  240. # The eslint binary needs to be run from a shell with msys
  241. shell = True
  242. orig = signal.signal(signal.SIGINT, signal.SIG_IGN)
  243. proc = ProcessHandler(cmd_args, env=os.environ, stream=None, shell=shell)
  244. proc.run()
  245. signal.signal(signal.SIGINT, orig)
  246. try:
  247. proc.wait()
  248. except KeyboardInterrupt:
  249. proc.kill()
  250. return []
  251. if not proc.output:
  252. return [] # no output means success
  253. try:
  254. jsonresult = json.loads(proc.output[0])
  255. except ValueError:
  256. print(ESLINT_ERROR_MESSAGE.format("\n".join(proc.output)))
  257. return 1
  258. results = []
  259. for obj in jsonresult:
  260. errors = obj['messages']
  261. for err in errors:
  262. err.update({
  263. 'hint': err.get('fix'),
  264. 'level': 'error' if err['severity'] == 2 else 'warning',
  265. 'lineno': err.get('line'),
  266. 'path': obj['filePath'],
  267. 'rule': err.get('ruleId'),
  268. })
  269. results.append(result.from_linter(LINTER, **err))
  270. return results
  271. LINTER = {
  272. 'name': "eslint",
  273. 'description': "JavaScript linter",
  274. # ESLint infra handles its own path filtering, so just include cwd
  275. 'include': ['.'],
  276. 'exclude': [],
  277. 'extensions': EXTENSIONS,
  278. 'type': 'external',
  279. 'payload': lint,
  280. }