1# Copyright (c) 2012 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 5"""Checks protobuf files for illegal imports.""" 6 7 8 9import codecs 10import os 11import re 12 13import results 14from rules import Rule, MessageRule 15 16 17class ProtoChecker(object): 18 19 EXTENSIONS = [ 20 '.proto', 21 ] 22 23 # The maximum number of non-import lines we can see before giving up. 24 _MAX_UNINTERESTING_LINES = 50 25 26 # The maximum line length, this is to be efficient in the case of very long 27 # lines (which can't be import). 28 _MAX_LINE_LENGTH = 128 29 30 # This regular expression will be used to extract filenames from import 31 # statements. 32 _EXTRACT_IMPORT_PATH = re.compile( 33 r'[ \t]*[ \t]*import[ \t]+"(.*)"') 34 35 def __init__(self, verbose, resolve_dotdot=False, root_dir=''): 36 self._verbose = verbose 37 self._resolve_dotdot = resolve_dotdot 38 self._root_dir = root_dir 39 40 def IsFullPath(self, import_path): 41 """Checks if the given path is a valid path starting from |_root_dir|.""" 42 match = re.match(r'(.*)/([^/]*\.proto)', import_path) 43 if not match: 44 return False 45 return os.path.isdir(self._root_dir + "/" + match.group(1)) 46 47 def CheckLine(self, rules, line, dependee_path, fail_on_temp_allow=False): 48 """Checks the given line with the given rule set. 49 50 Returns a tuple (is_import, dependency_violation) where 51 is_import is True only if the line is an import 52 statement, and dependency_violation is an instance of 53 results.DependencyViolation if the line violates a rule, or None 54 if it does not. 55 """ 56 found_item = self._EXTRACT_IMPORT_PATH.match(line) 57 if not found_item: 58 return False, None # Not a match 59 60 import_path = found_item.group(1) 61 62 if '\\' in import_path: 63 return True, results.DependencyViolation( 64 import_path, 65 MessageRule('Import paths may not include backslashes.'), 66 rules) 67 68 if '/' not in import_path: 69 # Don't fail when no directory is specified. We may want to be more 70 # strict about this in the future. 71 if self._verbose: 72 print(' WARNING: import specified with no directory: ' + import_path) 73 return True, None 74 75 if self._resolve_dotdot and '../' in import_path: 76 dependee_dir = os.path.dirname(dependee_path) 77 import_path = os.path.join(dependee_dir, import_path) 78 import_path = os.path.relpath(import_path, self._root_dir) 79 80 if not self.IsFullPath(import_path): 81 return True, None 82 83 rule = rules.RuleApplyingTo(import_path, dependee_path) 84 85 if (rule.allow == Rule.DISALLOW or 86 (fail_on_temp_allow and rule.allow == Rule.TEMP_ALLOW)): 87 return True, results.DependencyViolation(import_path, rule, rules) 88 return True, None 89 90 def CheckFile(self, rules, filepath): 91 if self._verbose: 92 print('Checking: ' + filepath) 93 94 dependee_status = results.DependeeStatus(filepath) 95 last_import = 0 96 with codecs.open(filepath, encoding='utf-8') as f: 97 for line_num, line in enumerate(f): 98 if line_num - last_import > self._MAX_UNINTERESTING_LINES: 99 break 100 101 line = line.strip() 102 103 is_import, violation = self.CheckLine(rules, line, filepath) 104 if is_import: 105 last_import = line_num 106 if violation: 107 dependee_status.AddViolation(violation) 108 109 return dependee_status 110 111 @staticmethod 112 def IsProtoFile(file_path): 113 """Returns True iff the given path ends in one of the extensions 114 handled by this checker. 115 """ 116 return os.path.splitext(file_path)[1] in ProtoChecker.EXTENSIONS 117 118 def ShouldCheck(self, file_path): 119 """Check if the new #include file path should be presubmit checked. 120 121 Args: 122 file_path: file path to be checked 123 124 Return: 125 bool: True if the file should be checked; False otherwise. 126 """ 127 return self.IsProtoFile(file_path) 128