checkmozstyle.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Script to run the linter for source code of WebKit."""
  31. import os
  32. import os.path
  33. import re
  34. import sys
  35. import modules.cpplint as cpplint
  36. from modules.diff_parser import DiffParser
  37. from modules.scm import detect_scm_system
  38. # Override the usage of the lint tool.
  39. cpplint._USAGE = """
  40. Syntax: %(program_name)s [--verbose=#] [--git-commit=<COMMITISH>] [--output=vs7] [--filter=-x,+y,...]
  41. The style guidelines this tries to follow are those in
  42. http://webkit.org/coding/coding-style.html
  43. Every problem is given a confidence score from 1-5, with 5 meaning we are
  44. certain of the problem, and 1 meaning it could be a legitimate construct.
  45. This will miss some errors, and is not a substitute for a code review.
  46. To prevent specific lines from being linted, add a '// NOLINT' comment to the
  47. end of the line.
  48. Linted extensions are .cpp, .c and .h. Other file types will be ignored.
  49. Flags:
  50. verbose=#
  51. Specify a number 0-5 to restrict errors to certain verbosity levels.
  52. git-commit=<COMMITISH>
  53. Check style for a specified git commit.
  54. Note that the program checks style based on current local file
  55. instead of actual diff of the git commit. So, if the files are
  56. updated after the specified git commit, the information of line
  57. number may be wrong.
  58. output=vs7
  59. By default, the output is formatted to ease emacs parsing. Visual Studio
  60. compatible output (vs7) may also be used. Other formats are unsupported.
  61. filter=-x,+y,...
  62. Specify a comma-separated list of category-filters to apply: only
  63. error messages whose category names pass the filters will be printed.
  64. (Category names are printed with the message and look like
  65. "[whitespace/indent]".) Filters are evaluated left to right.
  66. "-FOO" and "FOO" means "do not print categories that start with FOO".
  67. "+FOO" means "do print categories that start with FOO".
  68. Examples: --filter=-whitespace,+whitespace/braces
  69. --filter=whitespace,runtime/printf,+runtime/printf_format
  70. --filter=-,+build/include_what_you_use
  71. To see a list of all the categories used in %(program_name)s, pass no arg:
  72. --filter=
  73. """ % {'program_name': sys.argv[0]}
  74. def process_patch(patch_string, root, cwd, scm):
  75. """Does lint on a single patch.
  76. Args:
  77. patch_string: A string of a patch.
  78. """
  79. patch = DiffParser(patch_string.splitlines())
  80. if not len(patch.files):
  81. cpplint.error("patch", 0, "patch/notempty", 3,
  82. "Patch does not appear to diff against any file.")
  83. return
  84. if not patch.status_line:
  85. cpplint.error("patch", 0, "patch/nosummary", 3,
  86. "Patch does not have a summary.")
  87. else:
  88. proper_format = re.match(r"^Bug [0-9]+ - ", patch.status_line)
  89. if not proper_format:
  90. proper_format = re.match(r"^No bug - ", patch.status_line)
  91. cpplint.error("patch", 0, "patch/bugnumber", 3,
  92. "Patch summary should begin with 'Bug XXXXX - ' " +
  93. "or 'No bug -'.")
  94. if not patch.patch_description:
  95. cpplint.error("patch", 0, "patch/nodescription", 3,
  96. "Patch does not have a description.")
  97. for filename, diff in patch.files.iteritems():
  98. file_extension = os.path.splitext(filename)[1]
  99. if file_extension in ['.cpp', '.c', '.h']:
  100. line_numbers = set()
  101. orig_filename = filename
  102. def error_for_patch(filename, line_number, category, confidence,
  103. message):
  104. """Wrapper function of cpplint.error for patches.
  105. This function outputs errors only if the line number
  106. corresponds to lines which are modified or added.
  107. """
  108. if not line_numbers:
  109. for line in diff.lines:
  110. # When deleted line is not set, it means that
  111. # the line is newly added.
  112. if not line[0]:
  113. line_numbers.add(line[1])
  114. if line_number in line_numbers:
  115. cpplint.error(orig_filename, line_number,
  116. category, confidence, message)
  117. cpplint.process_file(os.path.join(root, filename),
  118. relative_name=orig_filename,
  119. error=error_for_patch)
  120. def main():
  121. cpplint.use_mozilla_styles()
  122. (args, flags) = cpplint.parse_arguments(sys.argv[1:], ["git-commit="])
  123. if args:
  124. sys.stderr.write("ERROR: We don't support files as arguments for " +
  125. "now.\n" + cpplint._USAGE)
  126. sys.exit(1)
  127. cwd = os.path.abspath('.')
  128. scm = detect_scm_system(cwd)
  129. root = scm.find_checkout_root(cwd)
  130. if "--git-commit" in flags:
  131. process_patch(scm.create_patch_from_local_commit(flags["--git-commit"]), root, cwd, scm)
  132. else:
  133. process_patch(scm.create_patch(), root, cwd, scm)
  134. sys.stderr.write('Total errors found: %d\n' % cpplint.error_count())
  135. sys.exit(cpplint.error_count() > 0)
  136. if __name__ == "__main__":
  137. main()