1# Copyright 2016 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5import os 6import subprocess 7import sys 8 9 10_CATAPULT_PATH = os.path.join( 11 os.path.dirname(os.path.abspath(__file__)), 12 os.path.pardir, os.path.pardir, os.path.pardir) 13 14 15def _AddToPathIfNeeded(path): 16 if path not in sys.path: 17 sys.path.insert(0, path) 18 19 20def _UpdateSysPathIfNeeded(): 21 _AddToPathIfNeeded(os.path.join(_CATAPULT_PATH, 'common', 'node_runner')) 22 _AddToPathIfNeeded(os.path.join(_CATAPULT_PATH, 'common', 'py_utils')) 23 24 25_UpdateSysPathIfNeeded() 26 27 28import py_utils 29from node_runner import node_util 30 31 32BASE_ESLINT_CMD = [ 33 node_util.GetNodePath(), 34 os.path.join(node_util.GetNodeModulesPath(), 'eslint', 'bin', 'eslint.js'), 35 '--color' 36] 37 38 39DEFAULT_ESLINT_RULES_DIR = os.path.join( 40 py_utils.GetCatapultDir(), 'common', 'eslint', 'rules') 41 42 43def _CreateEslintCommand(rulesdir, extra_args): 44 eslint_cmd = BASE_ESLINT_CMD + [ 45 '--rulesdir', rulesdir, '--ext', '.js,.html' 46 ] 47 if extra_args: 48 eslint_cmd.extend(extra_args.strip().split(' ')) 49 return eslint_cmd 50 51 52def RunEslint(paths, rules_dir=DEFAULT_ESLINT_RULES_DIR, extra_args=None): 53 """Runs eslint on a list of paths. 54 55 Args: 56 paths: A list of paths to run eslint on. 57 rules_dir: A directory of custom eslint rules. 58 extra_args: A string to append to the end of the eslint command. 59 """ 60 if type(paths) is not list or len(paths) == 0: 61 raise ValueError('Must specify a non-empty list of paths to lint.') 62 63 try: 64 eslint_cmd = _CreateEslintCommand(rules_dir, extra_args) 65 return True, subprocess.check_output(eslint_cmd + paths, 66 stderr=subprocess.STDOUT).rstrip() 67 except subprocess.CalledProcessError as e: 68 return False, e.output.rstrip() 69