#!/usr/bin/env python
# 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 argparse
import os
import sys


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


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


DIRECTORIES_TO_LINT = [
  os.path.join(_CATAPULT_PATH, 'dashboard', 'dashboard'),
  os.path.join(_CATAPULT_PATH, 'tracing', 'tracing')
]


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


if __name__ == '__main__':
  _AddToPathIfNeeded(_ESLINT_PATH)
  import eslint

  parser = argparse.ArgumentParser(
      description='Wrapper script to run eslint on Catapult code')
  parser.add_argument('--paths', '-p', default=None, nargs='+', metavar='PATH',
                      help='List of paths to lint')
  parser.add_argument('--all', default=None, action='store_true',
                      help='Runs eslint on all applicable Catapult code')
  parser.add_argument('--extra-args', default=None, type=str,
                      help='A string of extra arguments to pass to eslint')

  args = parser.parse_args(sys.argv[1:])
  if ((args.paths is not None and args.all is not None) or
      (args.paths is None and args.all is None)):
    print 'Either --paths or --all must be used, but not both.\n'
    parser.print_help()
    sys.exit(1)

  paths = DIRECTORIES_TO_LINT if args.all else args.paths
  success, output = eslint.RunEslint(paths, extra_args=args.extra_args)
  print output
  sys.exit(not success)