aboutsummaryrefslogtreecommitdiff
path: root/catapult/common/eslint/eslint/__init__.py
blob: fdd377c35bfd23f879cc8c4cdb96dca30ae0a239 (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
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import subprocess
import sys


_CATAPULT_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    os.path.pardir, os.path.pardir, os.path.pardir)


def _AddToPathIfNeeded(path):
  if path not in sys.path:
    sys.path.insert(0, path)


def _UpdateSysPathIfNeeded():
  _AddToPathIfNeeded(os.path.join(_CATAPULT_PATH, 'common', 'node_runner'))
  _AddToPathIfNeeded(os.path.join(_CATAPULT_PATH, 'common', 'py_utils'))


_UpdateSysPathIfNeeded()


import py_utils
from node_runner import node_util


BASE_ESLINT_CMD = [
  node_util.GetNodePath(),
  os.path.join(node_util.GetNodeModulesPath(), 'eslint', 'bin', 'eslint.js'),
  '--color'
]


DEFAULT_ESLINT_RULES_DIR = os.path.join(
    py_utils.GetCatapultDir(), 'common', 'eslint', 'rules')


def _CreateEslintCommand(rulesdir, extra_args):
  eslint_cmd = BASE_ESLINT_CMD + [
      '--rulesdir', rulesdir, '--ext', '.js,.html'
  ]
  if extra_args:
    eslint_cmd += [extra_args]
  return eslint_cmd


def RunEslint(paths, rules_dir=DEFAULT_ESLINT_RULES_DIR, extra_args=None):
  if type(paths) is not list or len(paths) == 0:
    raise ValueError('Must specify a non-empty list of paths to lint.')

  try:
    eslint_cmd = _CreateEslintCommand(rules_dir, extra_args)
    return True, subprocess.check_output(eslint_cmd + paths,
                                         stderr=subprocess.STDOUT).rstrip()
  except subprocess.CalledProcessError as e:
    return False, e.output.rstrip()