OLD | NEW |
(Empty) | |
| 1 # Copyright 2015 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 import os |
| 6 import sys |
| 7 import logging |
| 8 import shutil |
| 9 |
| 10 import diff_util |
| 11 |
| 12 sys.path.insert(1, os.path.join(sys.path[0], '..', '..', 'python')) |
| 13 from google import path_utils |
| 14 |
| 15 def DoPresubmitMain(argv, original_filename, backup_filename, script_name, |
| 16 prettyFn): |
| 17 """Execute presubmit/pretty printing for the target file. |
| 18 |
| 19 Args: |
| 20 argv: command line arguments |
| 21 original_filename: The filename to read from. |
| 22 backup_filename: When pretty printing, move the old file contents here. |
| 23 script_name: The name of the script to run for pretty printing. |
| 24 prettyFn: A function which takes the original xml content and produces |
| 25 pretty printed xml. |
| 26 |
| 27 Returns: |
| 28 An exit status. Non-zero indicates errors. |
| 29 """ |
| 30 logging.basicConfig(level=logging.INFO) |
| 31 presubmit = ('--presubmit' in argv) |
| 32 |
| 33 # If there is a description xml in the current working directory, use that. |
| 34 # Otherwise, use the one residing in the same directory as this script. |
| 35 xml_dir = os.getcwd() |
| 36 if not os.path.isfile(os.path.join(xml_dir, original_filename)): |
| 37 xml_dir = path_utils.ScriptDir() |
| 38 |
| 39 xml_path = os.path.join(xml_dir, original_filename) |
| 40 |
| 41 # Save the original file content. |
| 42 logging.info('Loading %s...', os.path.relpath(xml_path)) |
| 43 with open(xml_path, 'rb') as f: |
| 44 original_xml = f.read() |
| 45 |
| 46 # Check there are no CR ('\r') characters in the file. |
| 47 if '\r' in original_xml: |
| 48 logging.error('DOS-style line endings (CR characters) detected - these are ' |
| 49 'not allowed. Please run dos2unix %s', original_filename) |
| 50 return 1 |
| 51 |
| 52 try: |
| 53 pretty = prettyFn(original_xml) |
| 54 except Error: |
| 55 logging.error('Aborting parsing due to fatal errors.') |
| 56 return 1 |
| 57 |
| 58 if original_xml == pretty: |
| 59 logging.info('%s is correctly pretty-printed.', original_filename) |
| 60 return 0 |
| 61 if presubmit: |
| 62 logging.error('%s is not formatted correctly; run %s to fix.', |
| 63 original_filename, script_name) |
| 64 return 1 |
| 65 |
| 66 # Prompt user to consent on the change. |
| 67 if not diff_util.PromptUserToAcceptDiff( |
| 68 original_xml, pretty, 'Is the new version acceptable?'): |
| 69 logging.error('Diff not accepted. Aborting.') |
| 70 return 1 |
| 71 |
| 72 logging.info('Creating backup file: %s', backup_filename) |
| 73 shutil.move(xml_path, os.path.join(xml_dir, backup_filename)) |
| 74 |
| 75 with open(xml_path, 'wb') as f: |
| 76 f.write(pretty) |
| 77 logging.info('Updated %s. Don\'t forget to add it to your changelist', |
| 78 xml_path) |
| 79 return 0 |
OLD | NEW |