presubmit.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. #!/usr/bin/python
  2. # Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Enables directory-specific presubmit checks to run at upload and/or commit.
  6. """
  7. __version__ = '1.0'
  8. # TODO(joi) Add caching where appropriate/needed. The API is designed to allow
  9. # caching (between all different invocations of presubmit scripts for a given
  10. # change). We should add it as our presubmit scripts start feeling slow.
  11. import cPickle # Exposed through the API.
  12. import cStringIO # Exposed through the API.
  13. import exceptions
  14. import fnmatch
  15. import glob
  16. import marshal # Exposed through the API.
  17. import optparse
  18. import os # Somewhat exposed through the API.
  19. import pickle # Exposed through the API.
  20. import re # Exposed through the API.
  21. import subprocess # Exposed through the API.
  22. import sys # Parts exposed through API.
  23. import tempfile # Exposed through the API.
  24. import types
  25. import urllib2 # Exposed through the API.
  26. # Local imports.
  27. # TODO(joi) Would be cleaner to factor out utils in gcl to separate module, but
  28. # for now it would only be a couple of functions so hardly worth it.
  29. import gcl
  30. import presubmit_canned_checks
  31. # Matches key/value (or "tag") lines in changelist descriptions.
  32. _tag_line_re = re.compile(
  33. '^\s*(?P<key>[A-Z][A-Z_0-9]*)\s*=\s*(?P<value>.*?)\s*$')
  34. # Friendly names may be used for certain keys. All values for key-value pairs
  35. # in change descriptions (like BUG=123) can be retrieved from a change object
  36. # directly as if they were attributes, e.g. change.R (or equivalently because
  37. # we have a friendly name for it, change.Reviewers), change.BUG (or
  38. # change.BugIDs) and so forth.
  39. #
  40. # Add to this mapping as needed/desired.
  41. SPECIAL_KEYS = {
  42. 'Reviewers' : 'R',
  43. 'BugIDs' : 'BUG',
  44. 'Tested': 'TESTED'
  45. }
  46. class NotImplementedException(Exception):
  47. """We're leaving placeholders in a bunch of places to remind us of the
  48. design of the API, but we have not implemented all of it yet. Implement as
  49. the need arises.
  50. """
  51. pass
  52. def normpath(path):
  53. '''Version of os.path.normpath that also changes backward slashes to
  54. forward slashes when not running on Windows.
  55. '''
  56. # This is safe to always do because the Windows version of os.path.normpath
  57. # will replace forward slashes with backward slashes.
  58. path = path.replace(os.sep, '/')
  59. return os.path.normpath(path)
  60. class OutputApi(object):
  61. """This class (more like a module) gets passed to presubmit scripts so that
  62. they can specify various types of results.
  63. """
  64. class PresubmitResult(object):
  65. """Base class for result objects."""
  66. def __init__(self, message, items=None, long_text=''):
  67. """
  68. message: A short one-line message to indicate errors.
  69. items: A list of short strings to indicate where errors occurred.
  70. long_text: multi-line text output, e.g. from another tool
  71. """
  72. self._message = message
  73. self._items = []
  74. if items:
  75. self._items = items
  76. self._long_text = long_text.rstrip()
  77. def _Handle(self, output_stream, input_stream, may_prompt=True):
  78. """Writes this result to the output stream.
  79. Args:
  80. output_stream: Where to write
  81. Returns:
  82. True if execution may continue, False otherwise.
  83. """
  84. output_stream.write(self._message)
  85. output_stream.write('\n')
  86. for item in self._items:
  87. output_stream.write(' %s\n' % item)
  88. if self._long_text:
  89. output_stream.write('\n***************\n%s\n***************\n\n' %
  90. self._long_text)
  91. if self.ShouldPrompt() and may_prompt:
  92. output_stream.write('Are you sure you want to continue? (y/N): ')
  93. response = input_stream.readline()
  94. if response.strip().lower() != 'y':
  95. return False
  96. return not self.IsFatal()
  97. def IsFatal(self):
  98. """An error that is fatal stops g4 mail/submit immediately, i.e. before
  99. other presubmit scripts are run.
  100. """
  101. return False
  102. def ShouldPrompt(self):
  103. """Whether this presubmit result should result in a prompt warning."""
  104. return False
  105. class PresubmitError(PresubmitResult):
  106. """A hard presubmit error."""
  107. def IsFatal(self):
  108. return True
  109. class PresubmitPromptWarning(PresubmitResult):
  110. """An warning that prompts the user if they want to continue."""
  111. def ShouldPrompt(self):
  112. return True
  113. class PresubmitNotifyResult(PresubmitResult):
  114. """Just print something to the screen -- but it's not even a warning."""
  115. pass
  116. class MailTextResult(PresubmitResult):
  117. """A warning that should be included in the review request email."""
  118. def __init__(self, *args, **kwargs):
  119. raise NotImplementedException() # TODO(joi) Implement.
  120. class InputApi(object):
  121. """An instance of this object is passed to presubmit scripts so they can
  122. know stuff about the change they're looking at.
  123. """
  124. def __init__(self, change, presubmit_path):
  125. """Builds an InputApi object.
  126. Args:
  127. change: A presubmit.GclChange object.
  128. presubmit_path: The path to the presubmit script being processed.
  129. """
  130. self.change = change
  131. # We expose various modules and functions as attributes of the input_api
  132. # so that presubmit scripts don't have to import them.
  133. self.basename = os.path.basename
  134. self.cPickle = cPickle
  135. self.cStringIO = cStringIO
  136. self.os_path = os.path
  137. self.pickle = pickle
  138. self.marshal = marshal
  139. self.re = re
  140. self.subprocess = subprocess
  141. self.tempfile = tempfile
  142. self.urllib2 = urllib2
  143. # InputApi.platform is the platform you're currently running on.
  144. self.platform = sys.platform
  145. # The local path of the currently-being-processed presubmit script.
  146. self.current_presubmit_path = presubmit_path
  147. # We carry the canned checks so presubmit scripts can easily use them.
  148. self.canned_checks = presubmit_canned_checks
  149. def PresubmitLocalPath(self):
  150. """Returns the local path of the presubmit script currently being run.
  151. This is useful if you don't want to hard-code absolute paths in the
  152. presubmit script. For example, It can be used to find another file
  153. relative to the PRESUBMIT.py script, so the whole tree can be branched and
  154. the presubmit script still works, without editing its content.
  155. """
  156. return self.current_presubmit_path
  157. @staticmethod
  158. def DepotToLocalPath(depot_path):
  159. """Translate a depot path to a local path (relative to client root).
  160. Args:
  161. Depot path as a string.
  162. Returns:
  163. The local path of the depot path under the user's current client, or None
  164. if the file is not mapped.
  165. Remember to check for the None case and show an appropriate error!
  166. """
  167. local_path = gcl.GetSVNFileInfo(depot_path).get('Path')
  168. if not local_path:
  169. return None
  170. else:
  171. return local_path
  172. @staticmethod
  173. def LocalToDepotPath(local_path):
  174. """Translate a local path to a depot path.
  175. Args:
  176. Local path (relative to current directory, or absolute) as a string.
  177. Returns:
  178. The depot path (SVN URL) of the file if mapped, otherwise None.
  179. """
  180. depot_path = gcl.GetSVNFileInfo(local_path).get('URL')
  181. if not depot_path:
  182. return None
  183. else:
  184. return depot_path
  185. @staticmethod
  186. def FilterTextFiles(affected_files, include_deletes=True):
  187. """Filters out all except text files and optionally also filters out
  188. deleted files.
  189. Args:
  190. affected_files: List of AffectedFiles objects.
  191. include_deletes: If false, deleted files will be filtered out.
  192. Returns:
  193. Filtered list of AffectedFiles objects.
  194. """
  195. output_files = []
  196. for af in affected_files:
  197. if include_deletes or af.Action() != 'D':
  198. path = af.AbsoluteLocalPath()
  199. mime_type = gcl.GetSVNFileProperty(path, 'svn:mime-type')
  200. if not mime_type or mime_type.startswith('text/'):
  201. output_files.append(af)
  202. return output_files
  203. def AffectedFiles(self, include_dirs=False, include_deletes=True):
  204. """Same as input_api.change.AffectedFiles() except only lists files
  205. (and optionally directories) in the same directory as the current presubmit
  206. script, or subdirectories thereof.
  207. """
  208. output_files = []
  209. dir_with_slash = normpath(
  210. "%s/" % os.path.dirname(self.current_presubmit_path))
  211. if len(dir_with_slash) == 1:
  212. dir_with_slash = ''
  213. for af in self.change.AffectedFiles(include_dirs, include_deletes):
  214. af_path = normpath(af.LocalPath())
  215. if af_path.startswith(dir_with_slash):
  216. output_files.append(af)
  217. return output_files
  218. def LocalPaths(self, include_dirs=False):
  219. """Returns local paths of input_api.AffectedFiles()."""
  220. return [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
  221. def AbsoluteLocalPaths(self, include_dirs=False):
  222. """Returns absolute local paths of input_api.AffectedFiles()."""
  223. return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
  224. def ServerPaths(self, include_dirs=False):
  225. """Returns server paths of input_api.AffectedFiles()."""
  226. return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
  227. def AffectedTextFiles(self, include_deletes=True):
  228. """Same as input_api.change.AffectedTextFiles() except only lists files
  229. in the same directory as the current presubmit script, or subdirectories
  230. thereof.
  231. Warning: This function retrieves the svn property on each file so it can be
  232. slow for large change lists.
  233. """
  234. return InputApi.FilterTextFiles(self.AffectedFiles(include_dirs=False),
  235. include_deletes)
  236. def RightHandSideLines(self):
  237. """An iterator over all text lines in "new" version of changed files.
  238. Only lists lines from new or modified text files in the change that are
  239. contained by the directory of the currently executing presubmit script.
  240. This is useful for doing line-by-line regex checks, like checking for
  241. trailing whitespace.
  242. Yields:
  243. a 3 tuple:
  244. the AffectedFile instance of the current file;
  245. integer line number (1-based); and
  246. the contents of the line as a string.
  247. """
  248. return InputApi._RightHandSideLinesImpl(
  249. self.AffectedTextFiles(include_deletes=False))
  250. @staticmethod
  251. def _RightHandSideLinesImpl(affected_files):
  252. """Implements RightHandSideLines for InputApi and GclChange."""
  253. for af in affected_files:
  254. lines = af.NewContents()
  255. line_number = 0
  256. for line in lines:
  257. line_number += 1
  258. yield (af, line_number, line)
  259. class AffectedFile(object):
  260. """Representation of a file in a change."""
  261. def __init__(self, path, action, repository_root=''):
  262. self.path = path
  263. self.action = action.strip()
  264. self.repository_root = repository_root
  265. def ServerPath(self):
  266. """Returns a path string that identifies the file in the SCM system.
  267. Returns the empty string if the file does not exist in SCM.
  268. """
  269. return gcl.GetSVNFileInfo(self.AbsoluteLocalPath()).get('URL', '')
  270. def LocalPath(self):
  271. """Returns the path of this file on the local disk relative to client root.
  272. """
  273. return normpath(self.path)
  274. def AbsoluteLocalPath(self):
  275. """Returns the absolute path of this file on the local disk.
  276. """
  277. return normpath(os.path.join(self.repository_root, self.LocalPath()))
  278. def IsDirectory(self):
  279. """Returns true if this object is a directory."""
  280. if os.path.exists(self.path):
  281. # Retrieve directly from the file system; it is much faster than querying
  282. # subversion, especially on Windows.
  283. return os.path.isdir(self.path)
  284. else:
  285. return gcl.GetSVNFileInfo(self.path).get('Node Kind') == 'directory'
  286. def SvnProperty(self, property_name):
  287. """Returns the specified SVN property of this file, or the empty string
  288. if no such property.
  289. """
  290. return gcl.GetSVNFileProperty(self.AbsoluteLocalPath(), property_name)
  291. def Action(self):
  292. """Returns the action on this opened file, e.g. A, M, D, etc."""
  293. return self.action
  294. def NewContents(self):
  295. """Returns an iterator over the lines in the new version of file.
  296. The new version is the file in the user's workspace, i.e. the "right hand
  297. side".
  298. Contents will be empty if the file is a directory or does not exist.
  299. """
  300. if self.IsDirectory():
  301. return []
  302. else:
  303. return gcl.ReadFile(self.AbsoluteLocalPath()).splitlines()
  304. def OldContents(self):
  305. """Returns an iterator over the lines in the old version of file.
  306. The old version is the file in depot, i.e. the "left hand side".
  307. """
  308. raise NotImplementedError() # Implement when needed
  309. def OldFileTempPath(self):
  310. """Returns the path on local disk where the old contents resides.
  311. The old version is the file in depot, i.e. the "left hand side".
  312. This is a read-only cached copy of the old contents. *DO NOT* try to
  313. modify this file.
  314. """
  315. raise NotImplementedError() # Implement if/when needed.
  316. class GclChange(object):
  317. """A gcl change. See gcl.ChangeInfo for more info."""
  318. def __init__(self, change_info, repository_root=''):
  319. self.name = change_info.name
  320. self.full_description = change_info.description
  321. self.repository_root = repository_root
  322. # From the description text, build up a dictionary of key/value pairs
  323. # plus the description minus all key/value or "tag" lines.
  324. self.description_without_tags = []
  325. self.tags = {}
  326. for line in change_info.description.splitlines():
  327. m = _tag_line_re.match(line)
  328. if m:
  329. self.tags[m.group('key')] = m.group('value')
  330. else:
  331. self.description_without_tags.append(line)
  332. # Change back to text and remove whitespace at end.
  333. self.description_without_tags = '\n'.join(self.description_without_tags)
  334. self.description_without_tags = self.description_without_tags.rstrip()
  335. self.affected_files = [AffectedFile(info[1], info[0], repository_root) for
  336. info in change_info.files]
  337. def Change(self):
  338. """Returns the change name."""
  339. return self.name
  340. def Changelist(self):
  341. """Synonym for Change()."""
  342. return self.Change()
  343. def DescriptionText(self):
  344. """Returns the user-entered changelist description, minus tags.
  345. Any line in the user-provided description starting with e.g. "FOO="
  346. (whitespace permitted before and around) is considered a tag line. Such
  347. lines are stripped out of the description this function returns.
  348. """
  349. return self.description_without_tags
  350. def FullDescriptionText(self):
  351. """Returns the complete changelist description including tags."""
  352. return self.full_description
  353. def RepositoryRoot(self):
  354. """Returns the repository root for this change, as an absolute path."""
  355. return self.repository_root
  356. def __getattr__(self, attr):
  357. """Return keys directly as attributes on the object.
  358. You may use a friendly name (from SPECIAL_KEYS) or the actual name of
  359. the key.
  360. """
  361. if attr in SPECIAL_KEYS:
  362. key = SPECIAL_KEYS[attr]
  363. if key in self.tags:
  364. return self.tags[key]
  365. if attr in self.tags:
  366. return self.tags[attr]
  367. def AffectedFiles(self, include_dirs=False, include_deletes=True):
  368. """Returns a list of AffectedFile instances for all files in the change.
  369. Args:
  370. include_deletes: If false, deleted files will be filtered out.
  371. include_dirs: True to include directories in the list
  372. Returns:
  373. [AffectedFile(path, action), AffectedFile(path, action)]
  374. """
  375. if include_dirs:
  376. affected = self.affected_files
  377. else:
  378. affected = filter(lambda x: not x.IsDirectory(), self.affected_files)
  379. if include_deletes:
  380. return affected
  381. else:
  382. return filter(lambda x: x.Action() != 'D', affected)
  383. def AffectedTextFiles(self, include_deletes=True):
  384. """Return a list of the text files in a change.
  385. It's common to want to iterate over only the text files.
  386. Args:
  387. include_deletes: Controls whether to return files with "delete" actions,
  388. which commonly aren't relevant to presubmit scripts.
  389. """
  390. return InputApi.FilterTextFiles(self.AffectedFiles(include_dirs=False),
  391. include_deletes)
  392. def LocalPaths(self, include_dirs=False):
  393. """Convenience function."""
  394. return [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
  395. def AbsoluteLocalPaths(self, include_dirs=False):
  396. """Convenience function."""
  397. return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
  398. def ServerPaths(self, include_dirs=False):
  399. """Convenience function."""
  400. return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
  401. def RightHandSideLines(self):
  402. """An iterator over all text lines in "new" version of changed files.
  403. Lists lines from new or modified text files in the change.
  404. This is useful for doing line-by-line regex checks, like checking for
  405. trailing whitespace.
  406. Yields:
  407. a 3 tuple:
  408. the AffectedFile instance of the current file;
  409. integer line number (1-based); and
  410. the contents of the line as a string.
  411. """
  412. return InputApi._RightHandSideLinesImpl(
  413. self.AffectedTextFiles(include_deletes=False))
  414. def ListRelevantPresubmitFiles(files):
  415. """Finds all presubmit files that apply to a given set of source files.
  416. Args:
  417. files: An iterable container containing file paths.
  418. Return:
  419. ['foo/blat/PRESUBMIT.py', 'mat/gat/PRESUBMIT.py']
  420. """
  421. checked_dirs = {} # Keys are directory paths, values are ignored.
  422. source_dirs = [os.path.dirname(f) for f in files]
  423. presubmit_files = []
  424. for dir in source_dirs:
  425. while (True):
  426. if dir in checked_dirs:
  427. break # We've already walked up from this directory.
  428. test_path = os.path.join(dir, 'PRESUBMIT.py')
  429. if os.path.isfile(test_path):
  430. presubmit_files.append(normpath(test_path))
  431. checked_dirs[dir] = ''
  432. if dir in ['', '.']:
  433. break
  434. else:
  435. dir = os.path.dirname(dir)
  436. return presubmit_files
  437. class PresubmitExecuter(object):
  438. def __init__(self, change_info, committing):
  439. """
  440. Args:
  441. change_info: The ChangeInfo object for the change.
  442. committing: True if 'gcl commit' is running, False if 'gcl upload' is.
  443. """
  444. self.change = GclChange(change_info, gcl.GetRepositoryRoot())
  445. self.committing = committing
  446. def ExecPresubmitScript(self, script_text, presubmit_path):
  447. """Executes a single presubmit script.
  448. Args:
  449. script_text: The text of the presubmit script.
  450. presubmit_path: The path to the presubmit file (this will be reported via
  451. input_api.PresubmitLocalPath()).
  452. Return:
  453. A list of result objects, empty if no problems.
  454. """
  455. input_api = InputApi(self.change, presubmit_path)
  456. context = {}
  457. exec script_text in context
  458. # These function names must change if we make substantial changes to
  459. # the presubmit API that are not backwards compatible.
  460. if self.committing:
  461. function_name = 'CheckChangeOnCommit'
  462. else:
  463. function_name = 'CheckChangeOnUpload'
  464. if function_name in context:
  465. context['__args'] = (input_api, OutputApi())
  466. result = eval(function_name + '(*__args)', context)
  467. if not (isinstance(result, types.TupleType) or
  468. isinstance(result, types.ListType)):
  469. raise exceptions.RuntimeError(
  470. 'Presubmit functions must return a tuple or list')
  471. for item in result:
  472. if not isinstance(item, OutputApi.PresubmitResult):
  473. raise exceptions.RuntimeError(
  474. 'All presubmit results must be of types derived from '
  475. 'output_api.PresubmitResult')
  476. else:
  477. result = () # no error since the script doesn't care about current event.
  478. return result
  479. def DoPresubmitChecks(change_info,
  480. committing,
  481. verbose,
  482. output_stream,
  483. input_stream,
  484. default_presubmit):
  485. """Runs all presubmit checks that apply to the files in the change.
  486. This finds all PRESUBMIT.py files in directories enclosing the files in the
  487. change (up to the repository root) and calls the relevant entrypoint function
  488. depending on whether the change is being committed or uploaded.
  489. Prints errors, warnings and notifications. Prompts the user for warnings
  490. when needed.
  491. Args:
  492. change_info: The ChangeInfo object for the change.
  493. committing: True if 'gcl commit' is running, False if 'gcl upload' is.
  494. verbose: Prints debug info.
  495. output_stream: A stream to write output from presubmit tests to.
  496. input_stream: A stream to read input from the user.
  497. default_presubmit: A default presubmit script to execute in any case.
  498. Return:
  499. True if execution can continue, False if not.
  500. """
  501. presubmit_files = ListRelevantPresubmitFiles(change_info.FileList())
  502. if not presubmit_files and verbose:
  503. print "Warning, no presubmit.py found."
  504. results = []
  505. executer = PresubmitExecuter(change_info, committing)
  506. if default_presubmit:
  507. if verbose:
  508. print "Running default presubmit script"
  509. results += executer.ExecPresubmitScript(default_presubmit, 'PRESUBMIT.py')
  510. for filename in presubmit_files:
  511. if verbose:
  512. print "Running %s" % filename
  513. presubmit_script = gcl.ReadFile(filename)
  514. results += executer.ExecPresubmitScript(presubmit_script, filename)
  515. errors = []
  516. notifications = []
  517. warnings = []
  518. for result in results:
  519. if not result.IsFatal() and not result.ShouldPrompt():
  520. notifications.append(result)
  521. elif result.ShouldPrompt():
  522. warnings.append(result)
  523. else:
  524. errors.append(result)
  525. error_count = 0
  526. for name, items in (('Messages', notifications),
  527. ('Warnings', warnings),
  528. ('ERRORS', errors)):
  529. if items:
  530. output_stream.write('\n** Presubmit %s **\n\n' % name)
  531. for item in items:
  532. if not item._Handle(output_stream, input_stream,
  533. may_prompt=False):
  534. error_count += 1
  535. output_stream.write('\n')
  536. if not errors and warnings:
  537. output_stream.write(
  538. 'There were presubmit warnings. Sure you want to continue? (y/N): ')
  539. response = input_stream.readline()
  540. if response.strip().lower() != 'y':
  541. error_count += 1
  542. return (error_count == 0)
  543. def ScanSubDirs(mask, recursive):
  544. if not recursive:
  545. return [x for x in glob.glob(mask) if '.svn' not in x]
  546. else:
  547. results = []
  548. for root, dirs, files in os.walk('.'):
  549. if '.svn' in dirs:
  550. dirs.remove('.svn')
  551. for name in files:
  552. if fnmatch.fnmatch(name, mask):
  553. results.append(os.path.join(root, name))
  554. return results
  555. def ParseFiles(args, recursive):
  556. files = []
  557. for arg in args:
  558. files.extend([('M', file) for file in ScanSubDirs(arg, recursive)])
  559. return files
  560. def Main(argv):
  561. parser = optparse.OptionParser(usage="%prog [options]",
  562. version="%prog " + str(__version__))
  563. parser.add_option("-c", "--commit", action="store_true",
  564. help="Use commit instead of upload checks")
  565. parser.add_option("-r", "--recursive", action="store_true",
  566. help="Act recursively")
  567. parser.add_option("-v", "--verbose", action="store_true",
  568. help="Verbose output")
  569. options, args = parser.parse_args(argv[1:])
  570. files = ParseFiles(args, options.recursive)
  571. if options.verbose:
  572. print "Found %d files." % len(files)
  573. return not DoPresubmitChecks(gcl.ChangeInfo(name='temp', files=files),
  574. options.commit,
  575. options.verbose,
  576. sys.stdout,
  577. sys.stdin,
  578. default_presubmit=None)
  579. if __name__ == '__main__':
  580. sys.exit(Main(sys.argv))