class FixJsStyleTest(googletest.TestCase): """Test case to for gjslint auto-fixing.""" def testFixJsStyle(self): input_filename = None try: input_filename = '%s/fixjsstyle.in.js' % (_RESOURCE_PREFIX) golden_filename = '%s/fixjsstyle.out.js' % (_RESOURCE_PREFIX) except IOError, ex: raise IOError('Could not find testdata resource for %s: %s' % (self._filename, ex)) with open(input_filename) as f: for line in f: # Go to last line. pass self.assertTrue(line == line.rstrip(), 'fixjsstyle.js should not end ' 'with a new line.') # Autofix the file, sending output to a fake file. actual = StringIO.StringIO() style_checker = checker.JavaScriptStyleChecker( error_fixer.ErrorFixer(actual)) style_checker.Check(input_filename) # Now compare the files. actual.seek(0) expected = open(golden_filename, 'r') self.assertEqual(actual.readlines(), expected.readlines())
def main(argv=None): """Main function. Args: argv: Sequence of command line arguments. """ if argv is None: argv = flags.FLAGS(sys.argv) suffixes = ['.js', '.k', '.kl', '.htm', '.html'] if FLAGS.additional_extensions: suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] files = fileflags.GetFileList(argv, 'JavaScript', suffixes) style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer()) # Check the list of files. for filename in files: # if we have a js file if (filename.endswith('.js') or filename.endswith('.k') or filename.endswith('.kl')): style_checker.Check(filename) else: # HM: extract the js code from the html page, # run it through the checker, and composite the page again lines = open(filename).read().split('\n') insidejscode = 0 htmlprev = [] htmlpost = [] jscode = [] for line in lines: stripline = line.strip().lower() if (stripline.startswith('<')): stripline = stripline[1:10000].strip() if (insidejscode == 0): htmlprev.append(line) if (stripline.startswith('script') and stripline.find('src') == -1): insidejscode = 1 elif (insidejscode == 1): if (stripline.startswith('/') and stripline[1:10000].strip().startswith('script')): insidejscode = 2 htmlpost.append(line) else: jscode.append(line) else: htmlpost.append(line) jscode = '\n'.join(jscode) open(filename + '.tmp.js', 'w').write(jscode) style_checker.Check(filename + '.tmp.js') jscode = open(filename + '.tmp.js').read() htmlcode = '\n'.join(htmlprev) + '\n' + jscode + '\n' + '\n'.join( htmlpost) open(filename, 'w').write(htmlcode) os.remove(filename + '.tmp.js')
def _AssertFixes(self, original, expected): """Asserts that the error fixer corrects original to expected.""" original = self._GetHeader() + original expected = self._GetHeader() + expected actual = StringIO.StringIO() style_checker = checker.JavaScriptStyleChecker( error_fixer.ErrorFixer(actual)) style_checker.CheckLines('testing.js', original, False) actual.seek(0) expected = [x + '\n' for x in expected] self.assertListEqual(actual.readlines(), expected)
def _RunChecker(start_token, error_handler, limited_doc_checks, is_html, stop_token=None): state_tracker = javascriptstatetracker.JavaScriptStateTracker() style_checker = checker.JavaScriptStyleChecker( state_tracker=state_tracker, error_handler=error_handler) style_checker.Check(start_token, is_html=is_html, limited_doc_checks=limited_doc_checks, stop_token=stop_token)
def main(argv = None): """Main function. Args: argv: Sequence of command line arguments. """ if argv is None: argv = flags.FLAGS(sys.argv) files = fileflags.GetFileList(argv, 'JavaScript', ['.js']) style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer()) # Check the list of files. for filename in files: style_checker.Check(filename)
def _CheckPath(path): """Check a path and return any errors. Args: path: paths to check. Returns: A list of errorrecord.ErrorRecords for any found errors. """ error_accumulator = erroraccumulator.ErrorAccumulator() style_checker = checker.JavaScriptStyleChecker(error_accumulator) style_checker.Check(path) # Return any errors as error records. make_error_record = functools.partial(errorrecord.MakeErrorRecord, path) return map(make_error_record, error_accumulator.GetErrors())
def main(argv=None): """Main function. Args: argv: Sequence of command line arguments. """ if argv is None: argv = flags.FLAGS(sys.argv) suffixes = ['.js'] if FLAGS.additional_extensions: suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] files = fileflags.GetFileList(argv, 'JavaScript', suffixes) style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer()) # Check the list of files. for filename in files: style_checker.Check(filename)
def testFixJsStyle(self): test_cases = [['fixjsstyle.in.js', 'fixjsstyle.out.js'], ['indentation.js', 'fixjsstyle.indentation.out.js']] for [running_input_file, running_output_file] in test_cases: input_filename = None golden_filename = None current_filename = None try: input_filename = '%s/%s' % (_RESOURCE_PREFIX, running_input_file) current_filename = input_filename golden_filename = '%s/%s' % (_RESOURCE_PREFIX, running_output_file) current_filename = golden_filename except IOError, ex: raise IOError('Could not find testdata resource for %s: %s' % (current_filename, ex)) if running_input_file == 'fixjsstyle.in.js': with open(input_filename) as f: for line in f: # Go to last line. pass self.assertTrue( line == line.rstrip(), '%s file should not end ' 'with a new line.' % (input_filename)) # Autofix the file, sending output to a fake file. actual = StringIO.StringIO() style_checker = checker.JavaScriptStyleChecker( error_fixer.ErrorFixer(actual)) style_checker.Check(input_filename) # Now compare the files. actual.seek(0) expected = open(golden_filename, 'r') self.assertEqual(actual.readlines(), expected.readlines())
def RunChecks(self): """Check for violations of the Chromium JavaScript style guide. See http://chromium.org/developers/web-development-style-guide#TOC-JavaScript """ import sys import warnings old_path = sys.path old_filters = warnings.filters try: base_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..')) closure_linter_path = os.path.join( base_path, 'tracing', 'third_party', 'closure_linter') gflags_path = os.path.join( base_path, 'tracing', 'third_party', 'python_gflags') sys.path.insert(0, closure_linter_path) sys.path.insert(0, gflags_path) warnings.filterwarnings('ignore', category=DeprecationWarning) from closure_linter import checker, errors from closure_linter.common import errorhandler finally: sys.path = old_path warnings.filters = old_filters class ErrorHandlerImpl(errorhandler.ErrorHandler): """Filters out errors that don't apply to Chromium JavaScript code.""" def __init__(self): self._errors = [] def HandleFile(self, filename, first_token): self._filename = filename def HandleError(self, error): if (self._valid(error)): error.filename = self._filename self._errors.append(error) def GetErrors(self): return self._errors def HasErrors(self): return bool(self._errors) def _valid(self, error): """Check whether an error is valid. Most errors are valid, with a few exceptions which are listed here. """ is_grit_statement = bool( re.search("</?(include|if)", error.token.line)) return not is_grit_statement and error.code not in [ errors.JSDOC_ILLEGAL_QUESTION_WITH_PIPE, errors.JSDOC_TAG_DESCRIPTION_ENDS_WITH_INVALID_CHARACTER, errors.MISSING_JSDOC_TAG_THIS, ] results = [] try: affected_files = self.input_api.AffectedFiles( file_filter=self.file_filter, include_deletes=False) except: affected_files = [] def ShouldCheck(f): if tracing_project.TracingProject.IsIgnoredFile(f): return False if f.LocalPath().endswith('.js'): return True if f.LocalPath().endswith('.html'): return True return False affected_js_files = filter(ShouldCheck, affected_files) for f in affected_js_files: error_lines = [] for i, line in enumerate(f.NewContents(), start=1): error_lines += filter(None, [ self.ConstCheck(i, line), ]) # Use closure_linter to check for several different errors import gflags as flags flags.FLAGS.strict = True error_handler = ErrorHandlerImpl() js_checker = checker.JavaScriptStyleChecker(error_handler) js_checker.Check(f.AbsoluteLocalPath()) for error in error_handler.GetErrors(): highlight = self.error_highlight( error.token.start_index, error.token.length) error_msg = ' line %d: E%04d: %s\n%s\n%s' % ( error.token.line_number, error.code, error.message, error.token.line.rstrip(), highlight) error_lines.append(error_msg) if error_lines: error_lines = [ 'Found JavaScript style violations in %s:' % f.LocalPath()] + error_lines results.append(self._makeErrorOrWarning( '\n'.join(error_lines), f.LocalPath())) return results
def RunChecks(self): """Check for violations of the Chromium JavaScript style guide. See http://chromium.org/developers/web-development-style-guide#TOC-JavaScript """ import sys import warnings old_path = sys.path old_filters = warnings.filters try: closure_linter_path = self.input_api.os_path.join( self.input_api.change.RepositoryRoot(), "third_party", "closure_linter") gflags_path = self.input_api.os_path.join( self.input_api.change.RepositoryRoot(), "third_party", "python_gflags") sys.path.insert(0, closure_linter_path) sys.path.insert(0, gflags_path) warnings.filterwarnings('ignore', category=DeprecationWarning) from closure_linter import checker, errors from closure_linter.common import errorhandler finally: sys.path = old_path warnings.filters = old_filters class ErrorHandlerImpl(errorhandler.ErrorHandler): """Filters out errors that don't apply to Chromium JavaScript code.""" def __init__(self, re): self._errors = [] self.re = re def HandleFile(self, filename, first_token): self._filename = filename def HandleError(self, error): if (self._valid(error)): error.filename = self._filename self._errors.append(error) def GetErrors(self): return self._errors def HasErrors(self): return bool(self._errors) def _valid(self, error): """Check whether an error is valid. Most errors are valid, with a few exceptions which are listed here. """ is_grit_statement = bool( self.re.search("</?(include|if)", error.token.line)) return not is_grit_statement and error.code not in [ errors.COMMA_AT_END_OF_LITERAL, errors.JSDOC_ILLEGAL_QUESTION_WITH_PIPE, errors.JSDOC_TAG_DESCRIPTION_ENDS_WITH_INVALID_CHARACTER, errors.LINE_TOO_LONG, errors.MISSING_JSDOC_TAG_THIS, ] results = [] affected_files = self.input_api.change.AffectedFiles( file_filter=self.file_filter, include_deletes=False) affected_js_files = filter(lambda f: f.LocalPath().endswith('.js'), affected_files) for f in affected_js_files: error_lines = [] # Check for the following: # * document.getElementById() # * the 'const' keyword # * Passing an empty array to 'chrome.send()' for i, line in enumerate(f.NewContents(), start=1): error_lines += filter(None, [ self.ChromeSendCheck(i, line), self.ConstCheck(i, line), self.GetElementByIdCheck(i, line), self.InheritDocCheck(i, line), self.WrapperTypeCheck(i, line), self.VarNameCheck(i, line), ]) # Use closure_linter to check for several different errors error_handler = ErrorHandlerImpl(self.input_api.re) js_checker = checker.JavaScriptStyleChecker(error_handler) js_checker.Check( self.input_api.os_path.join( self.input_api.change.RepositoryRoot(), f.LocalPath())) for error in error_handler.GetErrors(): highlight = self.error_highlight(error.token.start_index, error.token.length) error_msg = ' line %d: E%04d: %s\n%s\n%s' % ( error.token.line_number, error.code, error.message, error.token.line.rstrip(), highlight) error_lines.append(error_msg) if error_lines: error_lines = [ 'Found JavaScript style violations in %s:' % f.LocalPath() ] + error_lines results.append( self._makeErrorOrWarning('\n'.join(error_lines), f.AbsoluteLocalPath())) if results: results.append( self.output_api.PresubmitNotifyResult( 'See the JavaScript style guide at ' 'http://www.chromium.org/developers/web-development-style-guide' '#TOC-JavaScript and if you have any feedback about the JavaScript ' 'PRESUBMIT check, contact [email protected] or ' '*****@*****.**')) return results
def fix_files(filenames): style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer()) for filename in filenames: style_checker.Check(filename) return 0
#!/usr/bin/env python from settings import * import os try: from closure_linter import checker from closure_linter import error_fixer from closure_linter.common import simplefileflags as fileflags except: raise Exception('Please install the closure linter first') style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer()) style_checker.Check(os.environ['TM_FILEPATH'])