google_java_format.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. # Copyright 2014 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. """Redirects to the version of google-java-format checked into the Chrome tree.
  6. google-java-format executable is pulled down from the cipd storage whenever
  7. you sync Chrome. This script finds and runs the executable.
  8. """
  9. import gclient_paths
  10. import os
  11. import subprocess
  12. import sys
  13. def FindGoogleJavaFormat():
  14. """Returns the path to the google-java-format executable."""
  15. # Allow non-chromium projects to use a custom location.
  16. primary_solution_path = gclient_paths.GetPrimarySolutionPath()
  17. if primary_solution_path:
  18. override = os.environ.get('GOOGLE_JAVA_FORMAT_PATH')
  19. if override:
  20. # Make relative to solution root if not an absolute path.
  21. return os.path.join(primary_solution_path, override)
  22. bin_path = os.path.join(primary_solution_path, 'third_party',
  23. 'google-java-format', 'google-java-format')
  24. cipd_path = os.path.join(primary_solution_path, 'third_party',
  25. 'google-java-format', 'cipd',
  26. 'google-java-format.jar')
  27. # Check that the .jar exists, since it is conditionally downloaded via
  28. # DEPS conditions.
  29. # TODO(b/345761161): Remove old os.path.exists(path + '.jar') check,
  30. # when third_party/google-java-format
  31. # -> third_party/google-java-format/cipd is fully rolled out.
  32. if os.path.exists(bin_path) and (os.path.exists(bin_path + '.jar')
  33. or os.path.exists(cipd_path)):
  34. return bin_path
  35. return None
  36. def main(args):
  37. google_java_format = FindGoogleJavaFormat()
  38. if google_java_format is None:
  39. # Fail silently. It could be we are on an old chromium revision,
  40. # or that it is a non-chromium project. https://crbug.com/1491627.
  41. print('google-java-format not found, skipping java formatting.')
  42. return 0
  43. # Add some visibility to --help showing where the tool lives, since this
  44. # redirection can be a little opaque.
  45. help_syntax = ('-h', '--help', '-help', '-help-list', '--help-list')
  46. if any(match in args for match in help_syntax):
  47. print('\nDepot tools redirects you to the google-java-format at:\n' +
  48. ' %s\n' % google_java_format)
  49. return subprocess.call([google_java_format] + args)
  50. if __name__ == '__main__':
  51. try:
  52. sys.exit(main(sys.argv[1:]))
  53. except KeyboardInterrupt:
  54. sys.stderr.write('interrupted\n')
  55. sys.exit(1)