Пример #1
0
def main():
  build_utils.InitLogging('LINT_DEBUG')
  args = _ParseArgs(sys.argv[1:])

  # TODO(wnwen): Consider removing lint cache now that there are only two lint
  #              invocations.
  # Avoid parallelizing cache creation since lint runs without the cache defeat
  # the purpose of creating the cache in the first place.
  if (not args.create_cache and not args.skip_build_server
      and server_utils.MaybeRunCommand(name=args.target_name,
                                       argv=sys.argv,
                                       stamp_file=args.stamp,
                                       force=args.use_build_server)):
    return

  sources = []
  for java_sources_file in args.java_sources:
    sources.extend(build_utils.ReadSourcesList(java_sources_file))
  resource_sources = []
  for resource_sources_file in args.resource_sources:
    resource_sources.extend(build_utils.ReadSourcesList(resource_sources_file))

  possible_depfile_deps = (args.srcjars + args.resource_zips + sources +
                           resource_sources + [
                               args.baseline,
                               args.manifest_path,
                           ])
  depfile_deps = [p for p in possible_depfile_deps if p]

  _RunLint(args.create_cache,
           args.lint_binary_path,
           args.backported_methods,
           args.config_path,
           args.manifest_path,
           args.extra_manifest_paths,
           sources,
           args.classpath,
           args.cache_dir,
           args.android_sdk_version,
           args.aars,
           args.srcjars,
           args.min_sdk_version,
           resource_sources,
           args.resource_zips,
           args.android_sdk_root,
           args.lint_gen_dir,
           args.baseline,
           testonly_target=args.testonly,
           warnings_as_errors=args.warnings_as_errors)
  logging.info('Creating stamp file')
  build_utils.Touch(args.stamp)

  if args.depfile:
    build_utils.WriteDepfile(args.depfile, args.stamp, depfile_deps)
Пример #2
0
def _RunInstrumentCommand(parser):
    """Instruments class or Jar files using JaCoCo.

  Args:
    parser: ArgumentParser object.

  Returns:
    An exit code.
  """
    args = parser.parse_args()

    source_files = []
    if args.java_sources_file:
        source_files.extend(build_utils.ReadSourcesList(
            args.java_sources_file))

    with build_utils.TempDir() as temp_dir:
        instrument_cmd = [
            build_utils.JAVA_PATH, '-jar', args.jacococli_jar, 'instrument'
        ]

        if not args.files_to_instrument:
            _InstrumentClassFiles(instrument_cmd, args.input_path,
                                  args.output_path, temp_dir)
        else:
            affected_files = build_utils.ReadSourcesList(
                args.files_to_instrument)
            source_set = set(source_files)
            affected_source_files = [
                f for f in affected_files if f in source_set
            ]

            # Copy input_path to output_path and return if no source file affected.
            if not affected_source_files:
                shutil.copyfile(args.input_path, args.output_path)
                # Create a dummy sources_json_file.
                _CreateSourcesJsonFile([], None, args.sources_json_file,
                                       build_utils.DIR_SOURCE_ROOT)
                return 0
            else:
                _InstrumentClassFiles(instrument_cmd, args.input_path,
                                      args.output_path, temp_dir,
                                      affected_source_files)

    source_dirs = _GetSourceDirsFromSourceFiles(source_files)
    # TODO(GYP): In GN, we are passed the list of sources, detecting source
    # directories, then walking them to re-establish the list of sources.
    # This can obviously be simplified!
    _CreateSourcesJsonFile(source_dirs, args.input_path,
                           args.sources_json_file, build_utils.DIR_SOURCE_ROOT)

    return 0
Пример #3
0
 def Generate(self, root_entry):
   # TODO(agrieve): Add an option to use interface jars and see if that speeds
   # things up at all.
   variables = {}
   java_dirs, excludes = self._GenJavaDirs(root_entry)
   java_dirs.extend(
       e.GeneratedJavaSubdir() for e in self._GetEntries(root_entry))
   self.processed_java_dirs.update(java_dirs)
   java_dirs.sort()
   variables['java_dirs'] = self._Relativize(root_entry, java_dirs)
   variables['java_excludes'] = excludes
   variables['jni_libs'] = self._Relativize(
       root_entry, set(self._GenJniLibs(root_entry)))
   prebuilts = set(
       p for e in self._GetEntries(root_entry) for p in e.PrebuiltJars())
   self.processed_prebuilts.update(prebuilts)
   variables['prebuilts'] = self._Relativize(root_entry, prebuilts)
   res_sources_files = _RebasePath(
       set(p for e in self._GetEntries(root_entry) for p in e.ResSources()))
   res_sources = []
   for res_sources_file in res_sources_files:
     res_sources.extend(build_utils.ReadSourcesList(res_sources_file))
   res_dirs = resource_utils.DeduceResourceDirsFromFileList(res_sources)
   # Do not add generated resources for the all module since it creates many
   # duplicates, and currently resources are only used for editing.
   self.processed_res_dirs.update(res_dirs)
   variables['res_dirs'] = self._Relativize(root_entry, res_dirs)
   if self.split_projects:
     deps = [_ProjectEntry.FromBuildConfigPath(p)
             for p in root_entry.Gradle()['dependent_android_projects']]
     variables['android_project_deps'] = [d.ProjectName() for d in deps]
     deps = [_ProjectEntry.FromBuildConfigPath(p)
             for p in root_entry.Gradle()['dependent_java_projects']]
     variables['java_project_deps'] = [d.ProjectName() for d in deps]
   return variables
Пример #4
0
def _CreateJavaSourceDir(output_dir, entry_output_dir, java_sources_file):
  """Computes and constructs when necessary the list of java source directories.

  1. Computes the root java source directories from the list of files.
  2. Determines whether there are any .java files in them that are not included
     in |java_sources_file|.
  3. If not, returns the list of java source directories. If so, constructs a
     tree of symlinks within |entry_output_dir| of all files in
     |java_sources_file|.
  """
  java_dirs = []
  if java_sources_file:
    java_files = _RebasePath(build_utils.ReadSourcesList(java_sources_file))
    java_dirs = _ComputeJavaSourceDirs(java_files)

    found_java_files = build_utils.FindInDirectories(java_dirs, '*.java')
    unwanted_java_files = set(found_java_files) - set(java_files)
    missing_java_files = set(java_files) - set(found_java_files)
    # Warn only about non-generated files that are missing.
    missing_java_files = [p for p in missing_java_files
                          if not p.startswith(output_dir)]
    if unwanted_java_files:
      logging.debug('Target requires .java symlinks: %s', entry_output_dir)
      symlink_dir = os.path.join(entry_output_dir, _JAVA_SUBDIR)
      _CreateSymlinkTree(entry_output_dir, symlink_dir, java_files, java_dirs)
      java_dirs = [symlink_dir]

    if missing_java_files:
      logging.warning('Some java files were not found: %s', missing_java_files)

  return java_dirs
Пример #5
0
def main(argv):
    arg_parser = argparse.ArgumentParser()
    build_utils.AddDepfileOption(arg_parser)

    arg_parser.add_argument('--sources_files',
                            help='A list of .sources files which contain Java '
                            'file paths. Must be used with --output.')
    arg_parser.add_argument('--output', help='The output file path.')
    arg_parser.add_argument(
        '--no_register_java',
        help='A list of Java files which should be ignored '
        'by the parser.')
    args = arg_parser.parse_args(build_utils.ExpandFileArgs(argv[1:]))
    args.sources_files = build_utils.ParseGnList(args.sources_files)

    if not args.sources_files:
        print '\nError: Must specify --sources_files.'
        return 1

    java_file_paths = []
    for f in args.sources_files:
        # java_file_paths stores each Java file path as a string.
        java_file_paths += build_utils.ReadSourcesList(f)
    output_file = args.output
    GenerateJNIHeader(java_file_paths, output_file, args)

    if args.depfile:
        build_utils.WriteDepfile(args.depfile, output_file,
                                 args.sources_files + java_file_paths)
Пример #6
0
def main():
    build_utils.InitLogging('LINT_DEBUG')
    args = _ParseArgs(sys.argv[1:])

    sources = []
    for java_sources_file in args.java_sources:
        sources.extend(build_utils.ReadSourcesList(java_sources_file))

    resource_sources = []
    for resource_sources_file in args.resource_sources:
        resource_sources.extend(
            build_utils.ReadSourcesList(resource_sources_file))

    possible_depfile_deps = (args.srcjars + args.resource_zips + sources +
                             resource_sources + [
                                 args.manifest_path,
                             ])

    depfile_deps = [p for p in possible_depfile_deps if p]

    _RunLint(args.lint_path,
             args.config_path,
             args.manifest_path,
             args.result_path,
             args.product_dir,
             sources,
             args.cache_dir,
             args.android_sdk_version,
             args.srcjars,
             args.min_sdk_version,
             args.manifest_package,
             resource_sources,
             args.resource_zips,
             args.android_sdk_root,
             testonly_target=args.testonly,
             can_fail_build=args.can_fail_build,
             include_unexpected=args.include_unexpected_failures,
             silent=args.silent)
    logging.info('Creating stamp file')
    build_utils.Touch(args.stamp)

    if args.depfile:
        build_utils.WriteDepfile(args.depfile,
                                 args.stamp,
                                 depfile_deps,
                                 add_pydeps=False)  # pydeps listed in GN.
Пример #7
0
 def JavaFiles(self):
     if self._java_files is None:
         java_sources_file = self.DepsInfo().get('java_sources_file')
         java_files = []
         if java_sources_file:
             java_sources_file = _RebasePath(java_sources_file)
             java_files = build_utils.ReadSourcesList(java_sources_file)
         self._java_files = java_files
     return self._java_files
Пример #8
0
def main():
  build_utils.InitLogging('LINT_DEBUG')
  args = _ParseArgs(sys.argv[1:])

  sources = []
  for java_sources_file in args.java_sources:
    sources.extend(build_utils.ReadSourcesList(java_sources_file))
  resource_sources = []
  for resource_sources_file in args.resource_sources:
    resource_sources.extend(build_utils.ReadSourcesList(resource_sources_file))

  possible_depfile_deps = (args.srcjars + args.resource_zips + sources +
                           resource_sources + [
                               args.baseline,
                               args.manifest_path,
                           ])
  depfile_deps = [p for p in possible_depfile_deps if p]

  _RunLint(args.lint_binary_path,
           args.backported_methods,
           args.config_path,
           args.manifest_path,
           args.extra_manifest_paths,
           sources,
           args.classpath,
           args.cache_dir,
           args.android_sdk_version,
           args.aars,
           args.srcjars,
           args.min_sdk_version,
           resource_sources,
           args.resource_zips,
           args.android_sdk_root,
           args.lint_gen_dir,
           args.baseline,
           args.expected_warnings,
           testonly_target=args.testonly,
           warnings_as_errors=args.warnings_as_errors)
  logging.info('Creating stamp file')
  build_utils.Touch(args.stamp)

  if args.depfile:
    build_utils.WriteDepfile(args.depfile, args.stamp, depfile_deps)
Пример #9
0
def main(argv):
  arg_parser = argparse.ArgumentParser()
  build_utils.AddDepfileOption(arg_parser)

  arg_parser.add_argument(
      '--sources-files',
      required=True,
      help='A list of .sources files which contain Java '
      'file paths.')
  arg_parser.add_argument(
      '--header-path', help='Path to output header file (optional).')
  arg_parser.add_argument(
      '--srcjar-path',
      required=True,
      help='Path to output srcjar for GEN_JNI.java.')
  arg_parser.add_argument(
      '--sources-blacklist',
      default=[],
      help='A list of Java files which should be ignored '
      'by the parser.')
  arg_parser.add_argument('--namespace',
                          default='',
                          help='Namespace to wrap the registration functions '
                          'into.')
  arg_parser.add_argument(
      '--use_proxy_hash',
      action='store_true',
      help='Enables hashing of the native declaration '
      'for methods in an @JniNatives interface')
  args = arg_parser.parse_args(build_utils.ExpandFileArgs(argv[1:]))
  args.sources_files = build_utils.ParseGnList(args.sources_files)

  java_file_paths = []
  for f in args.sources_files:
    # java_file_paths stores each Java file path as a string.
    java_file_paths += [
        p for p in build_utils.ReadSourcesList(f)
        if p not in args.sources_blacklist
    ]
  _Generate(
      java_file_paths,
      args.srcjar_path,
      use_proxy_hash=args.use_proxy_hash,
      header_path=args.header_path,
      namespace=args.namespace)

  if args.depfile:
    build_utils.WriteDepfile(
        args.depfile,
        args.srcjar_path,
        args.sources_files + java_file_paths,
        add_pydeps=False)
Пример #10
0
def _RunInstrumentCommand(parser):
    """Instruments jar files using Jacoco.

  Args:
    parser: ArgumentParser object.

  Returns:
    An exit code.
  """
    args = parser.parse_args()

    temp_dir = tempfile.mkdtemp()
    try:
        cmd = [
            'java', '-jar', args.jacococli_jar, 'instrument', args.input_path,
            '--dest', temp_dir
        ]

        build_utils.CheckOutput(cmd)

        jars = os.listdir(temp_dir)
        if len(jars) != 1:
            print('Error: multiple output files in: %s' % (temp_dir))
            return 1

        # Delete output_path first to avoid modifying input_path in the case where
        # input_path is a hardlink to output_path. http://crbug.com/571642
        if os.path.exists(args.output_path):
            os.unlink(args.output_path)
        shutil.move(os.path.join(temp_dir, jars[0]), args.output_path)
    finally:
        shutil.rmtree(temp_dir)

    source_files = []
    if args.java_sources_file:
        source_files.extend(build_utils.ReadSourcesList(
            args.java_sources_file))
    source_dirs = _GetSourceDirsFromSourceFiles(source_files)

    # TODO(GYP): In GN, we are passed the list of sources, detecting source
    # directories, then walking them to re-establish the list of sources.
    # This can obviously be simplified!
    _CreateSourcesListFile(source_dirs, args.sources_list_file,
                           build_utils.DIR_SOURCE_ROOT)

    return 0
def main(argv):
    arg_parser = argparse.ArgumentParser()
    build_utils.AddDepfileOption(arg_parser)

    arg_parser.add_argument('--sources-files',
                            required=True,
                            help='A list of .sources files which contain Java '
                            'file paths.')
    arg_parser.add_argument('--header-path',
                            help='Path to output header file (optional).')
    arg_parser.add_argument(
        '--srcjar-path',
        required=True,
        help='Path to output srcjar for GEN_JNI.java (Or J/N.java if proxy'
        ' hash is enabled).')
    arg_parser.add_argument(
        '--sources-blacklist',
        default=[],
        help='A list of Java files which should be ignored '
        'by the parser.')
    arg_parser.add_argument(
        '--namespace',
        default='',
        help='Namespace to wrap the registration functions '
        'into.')
    # TODO(crbug.com/898261) hook these flags up to the build config to enable
    # mocking in instrumentation tests
    arg_parser.add_argument(
        '--enable_proxy_mocks',
        default=False,
        action='store_true',
        help='Allows proxy native impls to be mocked through Java.')
    arg_parser.add_argument(
        '--require_mocks',
        default=False,
        action='store_true',
        help='Requires all used native implementations to have a mock set when '
        'called. Otherwise an exception will be thrown.')
    arg_parser.add_argument(
        '--use_proxy_hash',
        action='store_true',
        help='Enables hashing of the native declaration for methods in '
        'an @JniNatives interface')
    args = arg_parser.parse_args(build_utils.ExpandFileArgs(argv[1:]))

    if not args.enable_proxy_mocks and args.require_mocks:
        arg_parser.error(
            'Invalid arguments: --require_mocks without --enable_proxy_mocks. '
            'Cannot require mocks if they are not enabled.')

    args.sources_files = build_utils.ParseGnList(args.sources_files)

    proxy_opts = ProxyOptions(use_hash=args.use_proxy_hash,
                              require_mocks=args.require_mocks,
                              enable_mocks=args.enable_proxy_mocks)

    java_file_paths = []
    for f in args.sources_files:
        # Skip generated files, since the GN targets do not declare any deps.
        java_file_paths.extend(
            p for p in build_utils.ReadSourcesList(f)
            if p.startswith('..') and p not in args.sources_blacklist)
    _Generate(java_file_paths,
              args.srcjar_path,
              proxy_opts=proxy_opts,
              header_path=args.header_path,
              namespace=args.namespace)

    if args.depfile:
        build_utils.WriteDepfile(args.depfile,
                                 args.srcjar_path,
                                 args.sources_files + java_file_paths,
                                 add_pydeps=False)
Пример #12
0
def _ParseOptions(argv):
  parser = optparse.OptionParser()
  build_utils.AddDepfileOption(parser)

  parser.add_option(
      '--java-srcjars',
      action='append',
      default=[],
      help='List of srcjars to include in compilation.')
  parser.add_option(
      '--generated-dir',
      help='Subdirectory within target_gen_dir to place extracted srcjars and '
      'annotation processor output for codesearch to find.')
  parser.add_option(
      '--bootclasspath',
      action='append',
      default=[],
      help='Boot classpath for javac. If this is specified multiple times, '
      'they will all be appended to construct the classpath.')
  parser.add_option(
      '--java-version',
      help='Java language version to use in -source and -target args to javac.')
  parser.add_option('--classpath', action='append', help='Classpath to use.')
  parser.add_option(
      '--processors',
      action='append',
      help='GN list of annotation processor main classes.')
  parser.add_option(
      '--processorpath',
      action='append',
      help='GN list of jars that comprise the classpath used for Annotation '
      'Processors.')
  parser.add_option(
      '--processor-arg',
      dest='processor_args',
      action='append',
      help='key=value arguments for the annotation processors.')
  parser.add_option(
      '--provider-configuration',
      dest='provider_configurations',
      action='append',
      help='File to specify a service provider. Will be included '
      'in the jar under META-INF/services.')
  parser.add_option(
      '--additional-jar-file',
      dest='additional_jar_files',
      action='append',
      help='Additional files to package into jar. By default, only Java .class '
      'files are packaged into the jar. Files should be specified in '
      'format <filename>:<path to be placed in jar>.')
  parser.add_option(
      '--jar-info-exclude-globs',
      help='GN list of exclude globs to filter from generated .info files.')
  parser.add_option(
      '--chromium-code',
      type='int',
      help='Whether code being compiled should be built with stricter '
      'warnings for chromium code.')
  parser.add_option(
      '--gomacc-path', help='When set, prefix javac command with gomacc')
  parser.add_option(
      '--errorprone-path', help='Use the Errorprone compiler at this path.')
  parser.add_option(
      '--enable-errorprone',
      action='store_true',
      help='Enable errorprone checks')
  parser.add_option(
      '--warnings-as-errors',
      action='store_true',
      help='Treat all warnings as errors.')
  parser.add_option('--jar-path', help='Jar output path.')
  parser.add_option(
      '--javac-arg',
      action='append',
      default=[],
      help='Additional arguments to pass to javac.')
  parser.add_option(
      '--enable-kythe-annotations',
      action='store_true',
      help='Enable generation of Kythe kzip, used for codesearch. Ensure '
      'proper environment variables are set before using this flag.')
  parser.add_option(
      '--header-jar',
      help='This is the header jar for the current target that contains '
      'META-INF/TRANSITIVE class files to be included on the classpath.')

  options, args = parser.parse_args(argv)
  build_utils.CheckOptions(options, parser, required=('jar_path', ))

  options.bootclasspath = build_utils.ParseGnList(options.bootclasspath)
  options.classpath = build_utils.ParseGnList(options.classpath)
  options.processorpath = build_utils.ParseGnList(options.processorpath)
  options.processors = build_utils.ParseGnList(options.processors)
  options.java_srcjars = build_utils.ParseGnList(options.java_srcjars)
  options.jar_info_exclude_globs = build_utils.ParseGnList(
      options.jar_info_exclude_globs)

  additional_jar_files = []
  for arg in options.additional_jar_files or []:
    filepath, jar_filepath = arg.split(':')
    additional_jar_files.append((filepath, jar_filepath))
  options.additional_jar_files = additional_jar_files

  java_files = []
  for arg in args:
    # Interpret a path prefixed with @ as a file containing a list of sources.
    if arg.startswith('@'):
      java_files.extend(build_utils.ReadSourcesList(arg[1:]))
    else:
      java_files.append(arg)

  return options, java_files
Пример #13
0
def _ParseOptions(argv):
    parser = optparse.OptionParser()
    build_utils.AddDepfileOption(parser)

    parser.add_option('--java-srcjars',
                      action='append',
                      default=[],
                      help='List of srcjars to include in compilation.')
    parser.add_option(
        '--generated-dir',
        help='Subdirectory within target_gen_dir to place extracted srcjars and '
        'annotation processor output for codesearch to find.')
    parser.add_option(
        '--bootclasspath',
        action='append',
        default=[],
        help='Boot classpath for javac. If this is specified multiple times, '
        'they will all be appended to construct the classpath.')
    parser.add_option(
        '--java-version',
        help=
        'Java language version to use in -source and -target args to javac.')
    parser.add_option('--classpath', action='append', help='Classpath to use.')
    parser.add_option('--processors',
                      action='append',
                      help='GN list of annotation processor main classes.')
    parser.add_option(
        '--processorpath',
        action='append',
        help='GN list of jars that comprise the classpath used for Annotation '
        'Processors.')
    parser.add_option(
        '--processor-arg',
        dest='processor_args',
        action='append',
        help='key=value arguments for the annotation processors.')
    parser.add_option(
        '--provider-configuration',
        dest='provider_configurations',
        action='append',
        help='File to specify a service provider. Will be included '
        'in the jar under META-INF/services.')
    parser.add_option(
        '--additional-jar-file',
        dest='additional_jar_files',
        action='append',
        help=
        'Additional files to package into jar. By default, only Java .class '
        'files are packaged into the jar. Files should be specified in '
        'format <filename>:<path to be placed in jar>.')
    parser.add_option(
        '--jar-info-exclude-globs',
        help='GN list of exclude globs to filter from generated .info files.')
    parser.add_option(
        '--chromium-code',
        type='int',
        help='Whether code being compiled should be built with stricter '
        'warnings for chromium code.')
    parser.add_option('--errorprone-path',
                      help='Use the Errorprone compiler at this path.')
    parser.add_option('--enable-errorprone',
                      action='store_true',
                      help='Enable errorprone checks')
    parser.add_option('--jar-path', help='Jar output path.')
    parser.add_option('--javac-arg',
                      action='append',
                      default=[],
                      help='Additional arguments to pass to javac.')

    options, args = parser.parse_args(argv)
    build_utils.CheckOptions(options, parser, required=('jar_path', ))

    options.bootclasspath = build_utils.ParseGnList(options.bootclasspath)
    options.classpath = build_utils.ParseGnList(options.classpath)
    options.processorpath = build_utils.ParseGnList(options.processorpath)
    options.processors = build_utils.ParseGnList(options.processors)
    options.java_srcjars = build_utils.ParseGnList(options.java_srcjars)
    options.jar_info_exclude_globs = build_utils.ParseGnList(
        options.jar_info_exclude_globs)

    if options.java_version == '1.8' and options.bootclasspath:
        # Android's boot jar doesn't contain all java 8 classes.
        # See: https://github.com/evant/gradle-retrolambda/issues/23.
        # Get the path of the jdk folder by searching for the 'jar' executable. We
        # cannot search for the 'javac' executable because goma provides a custom
        # version of 'javac'.
        options.bootclasspath.append(build_utils.RT_JAR_PATH)

    additional_jar_files = []
    for arg in options.additional_jar_files or []:
        filepath, jar_filepath = arg.split(':')
        additional_jar_files.append((filepath, jar_filepath))
    options.additional_jar_files = additional_jar_files

    java_files = []
    for arg in args:
        # Interpret a path prefixed with @ as a file containing a list of sources.
        if arg.startswith('@'):
            java_files.extend(build_utils.ReadSourcesList(arg[1:]))
        else:
            java_files.append(arg)

    return options, java_files
Пример #14
0
def main(argv):
    build_utils.InitLogging('TURBINE_DEBUG')
    argv = build_utils.ExpandFileArgs(argv[1:])
    parser = argparse.ArgumentParser()
    build_utils.AddDepfileOption(parser)
    parser.add_argument('--turbine-jar-path',
                        required=True,
                        help='Path to the turbine jar file.')
    parser.add_argument('--java-srcjars',
                        action='append',
                        default=[],
                        help='List of srcjars to include in compilation.')
    parser.add_argument(
        '--bootclasspath',
        action='append',
        default=[],
        help='Boot classpath for javac. If this is specified multiple times, '
        'they will all be appended to construct the classpath.')
    parser.add_argument(
        '--java-version',
        help=
        'Java language version to use in -source and -target args to javac.')
    parser.add_argument('--classpath',
                        action='append',
                        help='Classpath to use.')
    parser.add_argument('--processors',
                        action='append',
                        help='GN list of annotation processor main classes.')
    parser.add_argument(
        '--processorpath',
        action='append',
        help='GN list of jars that comprise the classpath used for Annotation '
        'Processors.')
    parser.add_argument(
        '--processor-args',
        action='append',
        help='key=value arguments for the annotation processors.')
    parser.add_argument('--jar-path', help='Jar output path.', required=True)
    parser.add_argument('--generated-jar-path',
                        required=True,
                        help='Output path for generated source files.')
    parser.add_argument('--warnings-as-errors',
                        action='store_true',
                        help='Treat all warnings as errors.')
    options, unknown_args = parser.parse_known_args(argv)

    options.bootclasspath = build_utils.ParseGnList(options.bootclasspath)
    options.classpath = build_utils.ParseGnList(options.classpath)
    options.processorpath = build_utils.ParseGnList(options.processorpath)
    options.processors = build_utils.ParseGnList(options.processors)
    options.java_srcjars = build_utils.ParseGnList(options.java_srcjars)

    files = []
    for arg in unknown_args:
        # Interpret a path prefixed with @ as a file containing a list of sources.
        if arg.startswith('@'):
            files.extend(build_utils.ReadSourcesList(arg[1:]))

    cmd = build_utils.JavaCmd(options.warnings_as_errors) + [
        '-classpath', options.turbine_jar_path, 'com.google.turbine.main.Main'
    ]
    javac_cmd = []

    # Turbine reads lists from command line args by consuming args until one
    # starts with double dash (--). Thus command line args should be grouped
    # together and passed in together.
    if options.processors:
        cmd += ['--processors']
        cmd += options.processors

    if options.java_version:
        javac_cmd.extend([
            '-source',
            options.java_version,
            '-target',
            options.java_version,
        ])
    if options.java_version == '1.8':
        # Android's boot jar doesn't contain all java 8 classes.
        options.bootclasspath.append(build_utils.RT_JAR_PATH)

    if options.bootclasspath:
        cmd += ['--bootclasspath']
        for bootclasspath in options.bootclasspath:
            cmd += bootclasspath.split(':')

    if options.processorpath:
        cmd += ['--processorpath']
        cmd += options.processorpath

    if options.processor_args:
        for arg in options.processor_args:
            javac_cmd.extend(['-A%s' % arg])

    if options.classpath:
        cmd += ['--classpath']
        cmd += options.classpath

    if options.java_srcjars:
        cmd += ['--source_jars']
        cmd += options.java_srcjars

    if files:
        # Use jar_path to ensure paths are relative (needed for goma).
        files_rsp_path = options.jar_path + '.files_list.txt'
        with open(files_rsp_path, 'w') as f:
            f.write(' '.join(files))
        # Pass source paths as response files to avoid extremely long command lines
        # that are tedius to debug.
        cmd += ['--sources']
        cmd += ['@' + files_rsp_path]

    if javac_cmd:
        cmd.append('--javacopts')
        cmd += javac_cmd
        cmd.append('--')  # Terminate javacopts

    # Use AtomicOutput so that output timestamps are not updated when outputs
    # are not changed.
    with build_utils.AtomicOutput(options.jar_path) as output_jar, \
        build_utils.AtomicOutput(options.generated_jar_path) as generated_jar:
        cmd += [
            '--output', output_jar.name, '--gensrc_output', generated_jar.name
        ]
        logging.debug('Command: %s', cmd)
        start = time.time()
        build_utils.CheckOutput(cmd,
                                print_stdout=True,
                                fail_on_output=options.warnings_as_errors)
        end = time.time() - start
        logging.info('Header compilation took %ss', end)

    if options.depfile:
        # GN already knows of the java files, so avoid listing individual java files
        # in the depfile.
        depfile_deps = (options.bootclasspath + options.classpath +
                        options.processorpath + options.java_srcjars)
        build_utils.WriteDepfile(options.depfile, options.jar_path,
                                 depfile_deps)
Пример #15
0
def _ParseOptions(argv):
    parser = optparse.OptionParser()
    build_utils.AddDepfileOption(parser)

    parser.add_option('--src-gendirs',
                      help='Directories containing generated java files.')
    parser.add_option('--java-srcjars',
                      action='append',
                      default=[],
                      help='List of srcjars to include in compilation.')
    parser.add_option(
        '--bootclasspath',
        action='append',
        default=[],
        help='Boot classpath for javac. If this is specified multiple times, '
        'they will all be appended to construct the classpath.')
    parser.add_option(
        '--java-version',
        help=
        'Java language version to use in -source and -target args to javac.')
    parser.add_option(
        '--classpath',
        action='append',
        help='Classpath for javac. If this is specified multiple times, they '
        'will all be appended to construct the classpath.')
    parser.add_option(
        '--incremental',
        action='store_true',
        help='Whether to re-use .class files rather than recompiling them '
        '(when possible).')
    parser.add_option(
        '--javac-includes',
        default='',
        help='A list of file patterns. If provided, only java files that match'
        'one of the patterns will be compiled.')
    parser.add_option(
        '--jar-excluded-classes',
        default='',
        help='List of .class file patterns to exclude from the jar.')
    parser.add_option('--processor',
                      dest='processors',
                      action='append',
                      help='Annotation processor to use.')
    parser.add_option(
        '--processor-arg',
        dest='processor_args',
        action='append',
        help='key=value arguments for the annotation processors.')
    parser.add_option(
        '--provider-configuration',
        dest='provider_configurations',
        action='append',
        help='File to specify a service provider. Will be included '
        'in the jar under META-INF/services.')
    parser.add_option(
        '--additional-jar-file',
        dest='additional_jar_files',
        action='append',
        help=
        'Additional files to package into jar. By default, only Java .class '
        'files are packaged into the jar. Files should be specified in '
        'format <filename>:<path to be placed in jar>.')
    parser.add_option(
        '--chromium-code',
        type='int',
        help='Whether code being compiled should be built with stricter '
        'warnings for chromium code.')
    parser.add_option('--use-errorprone-path',
                      help='Use the Errorprone compiler at this path.')
    parser.add_option('--jar-path', help='Jar output path.')
    parser.add_option('--stamp', help='Path to touch on success.')

    options, args = parser.parse_args(argv)
    build_utils.CheckOptions(options, parser, required=('jar_path', ))

    bootclasspath = []
    for arg in options.bootclasspath:
        bootclasspath += build_utils.ParseGnList(arg)
    options.bootclasspath = bootclasspath
    if options.java_version == '1.8' and options.bootclasspath:
        # Android's boot jar doesn't contain all java 8 classes.
        # See: https://github.com/evant/gradle-retrolambda/issues/23.
        javac_path = os.path.realpath(distutils.spawn.find_executable('javac'))
        jdk_dir = os.path.dirname(os.path.dirname(javac_path))
        rt_jar = os.path.join(jdk_dir, 'jre', 'lib', 'rt.jar')
        options.bootclasspath.append(rt_jar)

    classpath = []
    for arg in options.classpath:
        classpath += build_utils.ParseGnList(arg)
    options.classpath = classpath

    java_srcjars = []
    for arg in options.java_srcjars:
        java_srcjars += build_utils.ParseGnList(arg)
    options.java_srcjars = java_srcjars

    additional_jar_files = []
    for arg in options.additional_jar_files or []:
        filepath, jar_filepath = arg.split(':')
        additional_jar_files.append((filepath, jar_filepath))
    options.additional_jar_files = additional_jar_files

    if options.src_gendirs:
        options.src_gendirs = build_utils.ParseGnList(options.src_gendirs)

    options.javac_includes = build_utils.ParseGnList(options.javac_includes)
    options.jar_excluded_classes = (build_utils.ParseGnList(
        options.jar_excluded_classes))

    java_files = []
    for arg in args:
        # Interpret a path prefixed with @ as a file containing a list of sources.
        if arg.startswith('@'):
            java_files.extend(build_utils.ReadSourcesList(arg[1:]))
        else:
            java_files.append(arg)

    return options, java_files
Пример #16
0
def main(argv):
    build_utils.InitLogging('TURBINE_DEBUG')
    argv = build_utils.ExpandFileArgs(argv[1:])
    parser = argparse.ArgumentParser()
    build_utils.AddDepfileOption(parser)
    parser.add_argument('--turbine-jar-path',
                        required=True,
                        help='Path to the turbine jar file.')
    parser.add_argument('--java-srcjars',
                        action='append',
                        default=[],
                        help='List of srcjars to include in compilation.')
    parser.add_argument(
        '--bootclasspath',
        action='append',
        default=[],
        help='Boot classpath for javac. If this is specified multiple times, '
        'they will all be appended to construct the classpath.')
    parser.add_argument(
        '--java-version',
        help=
        'Java language version to use in -source and -target args to javac.')
    parser.add_argument('--classpath',
                        action='append',
                        help='Classpath to use.')
    parser.add_argument('--processors',
                        action='append',
                        help='GN list of annotation processor main classes.')
    parser.add_argument(
        '--processorpath',
        action='append',
        help='GN list of jars that comprise the classpath used for Annotation '
        'Processors.')
    parser.add_argument(
        '--processor-args',
        action='append',
        help='key=value arguments for the annotation processors.')
    parser.add_argument('--jar-path', help='Jar output path.', required=True)
    parser.add_argument('--generated-jar-path',
                        required=True,
                        help='Output path for generated source files.')
    options, unknown_args = parser.parse_known_args(argv)

    options.bootclasspath = build_utils.ParseGnList(options.bootclasspath)
    options.classpath = build_utils.ParseGnList(options.classpath)
    options.processorpath = build_utils.ParseGnList(options.processorpath)
    options.processors = build_utils.ParseGnList(options.processors)
    options.java_srcjars = build_utils.ParseGnList(options.java_srcjars)

    files = []
    for arg in unknown_args:
        # Interpret a path prefixed with @ as a file containing a list of sources.
        if arg.startswith('@'):
            files.extend(build_utils.ReadSourcesList(arg[1:]))

    cmd = [
        build_utils.JAVA_PATH, '-classpath', options.turbine_jar_path,
        'com.google.turbine.main.Main'
    ]
    javac_cmd = []

    # Turbine reads lists from command line args by consuming args until one
    # starts with double dash (--). Thus command line args should be grouped
    # together and passed in together.
    if options.processors:
        cmd += ['--processors']
        cmd += options.processors

    if options.java_version:
        javac_cmd.extend([
            '-source',
            options.java_version,
            '-target',
            options.java_version,
        ])
    if options.java_version == '1.8':
        # Android's boot jar doesn't contain all java 8 classes.
        options.bootclasspath.append(build_utils.RT_JAR_PATH)

    if options.bootclasspath:
        cmd += ['--bootclasspath']
        for bootclasspath in options.bootclasspath:
            cmd += bootclasspath.split(':')

    if options.processorpath:
        cmd += ['--processorpath']
        cmd += options.processorpath

    if options.processor_args:
        for arg in options.processor_args:
            javac_cmd.extend(['-A%s' % arg])

    classpath_inputs = (options.bootclasspath + options.classpath +
                        options.processorpath)

    # GN already knows of the java files, so avoid listing individual java files
    # in the depfile.
    depfile_deps = classpath_inputs + options.java_srcjars
    input_paths = depfile_deps + files

    output_paths = [
        options.jar_path,
        options.generated_jar_path,
    ]

    input_strings = cmd + options.classpath + files

    md5_check.CallAndWriteDepfileIfStale(
        lambda: _OnStaleMd5(options, cmd, javac_cmd, files, options.classpath),
        options,
        depfile_deps=depfile_deps,
        input_paths=input_paths,
        input_strings=input_strings,
        output_paths=output_paths)
Пример #17
0
def main():
  parser = argparse.ArgumentParser()
  build_utils.AddDepfileOption(parser)

  parser.add_argument('--lint-path', required=True,
                      help='Path to lint executable.')
  parser.add_argument('--product-dir', required=True,
                      help='Path to product dir.')
  parser.add_argument('--result-path', required=True,
                      help='Path to XML lint result file.')
  parser.add_argument('--cache-dir', required=True,
                      help='Path to the directory in which the android cache '
                           'directory tree should be stored.')
  parser.add_argument('--platform-xml-path', required=True,
                      help='Path to api-platforms.xml')
  parser.add_argument('--android-sdk-version',
                      help='Version (API level) of the Android SDK used for '
                           'building.')
  parser.add_argument('--can-fail-build', action='store_true',
                      help='If set, script will exit with nonzero exit status'
                           ' if lint errors are present')
  parser.add_argument('--include-unexpected-failures', action='store_true',
                      help='If set, script will exit with nonzero exit status'
                           ' if lint itself crashes with unexpected failures.')
  parser.add_argument('--config-path',
                      help='Path to lint suppressions file.')
  parser.add_argument('--disable',
                      help='List of checks to disable.')
  parser.add_argument('--jar-path',
                      help='Jar file containing class files.')
  parser.add_argument('--java-sources-file',
                      help='File containing a list of java files.')
  parser.add_argument('--manifest-path',
                      help='Path to AndroidManifest.xml')
  parser.add_argument('--classpath', default=[], action='append',
                      help='GYP-list of classpath .jar files')
  parser.add_argument('--processed-config-path',
                      help='Path to processed lint suppressions file.')
  parser.add_argument('--resource-dir',
                      help='Path to resource dir.')
  parser.add_argument('--resource-sources', default=[], action='append',
                      help='GYP-list of resource sources (directories with '
                      'resources or archives created by resource-generating '
                      'tasks.')
  parser.add_argument('--silent', action='store_true',
                      help='If set, script will not log anything.')
  parser.add_argument('--src-dirs',
                      help='Directories containing java files.')
  parser.add_argument('--srcjars',
                      help='GN list of included srcjars.')
  parser.add_argument(
      '--min-sdk-version',
      required=True,
      help='Minimal SDK version to lint against.')
  parser.add_argument(
      '--manifest-package', help='Package name of the AndroidManifest.xml.')

  args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:]))

  sources = []
  if args.src_dirs:
    src_dirs = build_utils.ParseGnList(args.src_dirs)
    sources = _FindInDirectories(src_dirs, '*.java')
  elif args.java_sources_file:
    sources.extend(build_utils.ReadSourcesList(args.java_sources_file))

  if args.config_path and not args.processed_config_path:
    parser.error('--config-path specified without --processed-config-path')
  elif args.processed_config_path and not args.config_path:
    parser.error('--processed-config-path specified without --config-path')

  input_paths = [
      args.lint_path,
      args.platform_xml_path,
  ]
  if args.config_path:
    input_paths.append(args.config_path)
  if args.jar_path:
    input_paths.append(args.jar_path)
  if args.manifest_path:
    input_paths.append(args.manifest_path)
  if sources:
    input_paths.extend(sources)
  classpath = []
  for gyp_list in args.classpath:
    classpath.extend(build_utils.ParseGnList(gyp_list))
  input_paths.extend(classpath)

  resource_sources = []
  if args.resource_dir:
    # Backward compatibility with GYP
    resource_sources += [ args.resource_dir ]

  for gyp_list in args.resource_sources:
    resource_sources += build_utils.ParseGnList(gyp_list)

  for resource_source in resource_sources:
    if os.path.isdir(resource_source):
      input_paths.extend(build_utils.FindInDirectory(resource_source, '*'))
    else:
      input_paths.append(resource_source)

  input_strings = [
    args.can_fail_build,
    args.include_unexpected_failures,
    args.silent,
  ]
  if args.android_sdk_version:
    input_strings.append(args.android_sdk_version)
  if args.processed_config_path:
    input_strings.append(args.processed_config_path)

  disable = []
  if args.disable:
    disable = build_utils.ParseGnList(args.disable)
    input_strings.extend(disable)

  output_paths = [args.result_path, args.processed_config_path]

  build_utils.CallAndWriteDepfileIfStale(
      lambda: _OnStaleMd5(args.lint_path,
                          args.config_path,
                          args.processed_config_path,
                          args.manifest_path, args.result_path,
                          args.product_dir, sources,
                          args.jar_path,
                          args.cache_dir,
                          args.android_sdk_version,
                          args.srcjars,
                          args.min_sdk_version,
                          args.manifest_package,
                          resource_sources,
                          disable=disable,
                          classpath=classpath,
                          can_fail_build=args.can_fail_build,
                          include_unexpected=args.include_unexpected_failures,
                          silent=args.silent),
      args,
      input_paths=input_paths,
      input_strings=input_strings,
      output_paths=output_paths,
      depfile_deps=classpath)
Пример #18
0
def _RunInstrumentCommand(_command, options, _, option_parser):
    """Instruments jar files using EMMA.

  Args:
    command: String indicating the command that was received to trigger
        this function.
    options: optparse options dictionary.
    args: List of extra args from optparse.
    option_parser: optparse.OptionParser object.

  Returns:
    An exit code.
  """
    if not (options.input_path and options.output_path
            and options.coverage_file and options.sources_list_file and
            (options.source_files or options.source_dirs
             or options.java_sources_file) and options.src_root
            and options.emma_jar):
        option_parser.error('All arguments are required.')

    if os.path.exists(options.coverage_file):
        os.remove(options.coverage_file)
    temp_dir = tempfile.mkdtemp()
    try:
        cmd = [
            'java', '-cp', options.emma_jar, 'emma', 'instr', '-ip',
            options.input_path, '-ix', options.filter_string, '-d', temp_dir,
            '-out', options.coverage_file, '-m', 'fullcopy'
        ]
        build_utils.CheckOutput(cmd)

        # File is not generated when filter_string doesn't match any files.
        if not os.path.exists(options.coverage_file):
            build_utils.Touch(options.coverage_file)

        temp_jar_dir = os.path.join(temp_dir, 'lib')
        jars = os.listdir(temp_jar_dir)
        if len(jars) != 1:
            print('Error: multiple output files in: %s' % (temp_jar_dir))
            return 1

        # Delete output_path first to avoid modifying input_path in the case where
        # input_path is a hardlink to output_path. http://crbug.com/571642
        if os.path.exists(options.output_path):
            os.unlink(options.output_path)
        shutil.move(os.path.join(temp_jar_dir, jars[0]), options.output_path)
    finally:
        shutil.rmtree(temp_dir)

    if options.source_dirs:
        source_dirs = build_utils.ParseGnList(options.source_dirs)
    else:
        source_files = []
        if options.source_files:
            source_files += build_utils.ParseGnList(options.source_files)
        if options.java_sources_file:
            source_files.extend(
                build_utils.ReadSourcesList(options.java_sources_file))
        source_dirs = _GetSourceDirsFromSourceFiles(source_files)

    # TODO(GYP): In GN, we are passed the list of sources, detecting source
    # directories, then walking them to re-establish the list of sources.
    # This can obviously be simplified!
    _CreateSourcesListFile(source_dirs, options.sources_list_file,
                           options.src_root)

    if options.stamp:
        build_utils.Touch(options.stamp)

    if options.depfile:
        build_utils.WriteDepfile(options.depfile, options.output_path)

    return 0
Пример #19
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--output-directory',
                      help='Path to the root build directory.')
  parser.add_argument('-v',
                      '--verbose',
                      dest='verbose_count',
                      default=0,
                      action='count',
                      help='Verbose level')
  parser.add_argument('--target',
                      dest='targets',
                      action='append',
                      help='GN target to generate project for. '
                           'May be repeated.')
  parser.add_argument('--project-dir',
                      help='Root of the output project.',
                      default=os.path.join('$CHROMIUM_OUTPUT_DIR', 'gradle'))
  parser.add_argument('--all',
                      action='store_true',
                      help='Generate all java targets (slows down IDE)')
  parser.add_argument('--use-gradle-process-resources',
                      action='store_true',
                      help='Have gradle generate R.java rather than ninja')
  args = parser.parse_args()
  if args.output_directory:
    constants.SetOutputDirectory(args.output_directory)
  constants.CheckOutputDirectory()
  output_dir = constants.GetOutDirectory()
  devil_chromium.Initialize(output_directory=output_dir)
  run_tests_helper.SetLogLevel(args.verbose_count)

  gradle_output_dir = os.path.abspath(
      args.project_dir.replace('$CHROMIUM_OUTPUT_DIR', output_dir))
  logging.warning('Creating project at: %s', gradle_output_dir)

  if args.all:
    # Run GN gen if necessary (faster than running "gn gen" in the no-op case).
    _RunNinja(output_dir, ['build.ninja'])
    # Query ninja for all __build_config targets.
    targets = _QueryForAllGnTargets(output_dir)
  else:
    targets = args.targets or _DEFAULT_TARGETS
    # TODO(agrieve): See if it makes sense to utilize Gradle's test constructs
    # for our instrumentation tests.
    targets = [re.sub(r'_test_apk$', '_test_apk__apk', t) for t in targets]
    targets = [re.sub(r'_junit_tests$', '_junit_tests__java_binary', t)
               for t in targets]

  main_entries = [_ProjectEntry(t) for t in targets]

  logging.warning('Building .build_config files...')
  _RunNinja(output_dir, [e.NinjaBuildConfigTarget() for e in main_entries])

  # There are many unused libraries, so restrict to those that are actually used
  # when using --all.
  if args.all:
    main_entries = [e for e in main_entries if e.GetType() == 'android_apk']

  all_entries = _FindAllProjectEntries(main_entries)
  logging.info('Found %d dependent build_config targets.', len(all_entries))

  logging.warning('Writing .gradle files...')
  jinja_processor = jinja_template.JinjaProcessor(host_paths.DIR_SOURCE_ROOT)
  build_vars = _ReadBuildVars(output_dir)
  project_entries = []
  srcjar_tuples = []
  generated_inputs = []
  for entry in all_entries:
    if entry.GetType() not in ('android_apk', 'java_library', 'java_binary'):
      continue

    entry_output_dir = os.path.join(gradle_output_dir, entry.GradleSubdir())
    relativize = lambda x, d=entry_output_dir: _RebasePath(x, d)
    build_config = entry.BuildConfig()

    srcjars = _RebasePath(build_config['gradle'].get('bundled_srcjars', []))
    if not args.use_gradle_process_resources:
      srcjars += _RebasePath(build_config['javac']['srcjars'])

    java_sources_file = build_config['gradle'].get('java_sources_file')
    java_files = []
    if java_sources_file:
      java_sources_file = _RebasePath(java_sources_file)
      java_files = build_utils.ReadSourcesList(java_sources_file)

    java_dirs = _CreateJavaSourceDir(output_dir, entry_output_dir, java_files)
    if srcjars:
      java_dirs.append(os.path.join(entry_output_dir, _SRCJARS_SUBDIR))

    data = _GenerateGradleFile(build_config, build_vars, java_dirs, relativize,
                               args.use_gradle_process_resources,
                               jinja_processor)
    if data:
      project_entries.append(entry)
      # Build all paths references by .gradle that exist within output_dir.
      generated_inputs.extend(srcjars)
      generated_inputs.extend(p for p in java_files if not p.startswith('..'))
      generated_inputs.extend(build_config['gradle']['dependent_prebuilt_jars'])

      srcjar_tuples.extend(
          (s, os.path.join(entry_output_dir, _SRCJARS_SUBDIR)) for s in srcjars)
      _WriteFile(os.path.join(entry_output_dir, 'build.gradle'), data)

  _WriteFile(os.path.join(gradle_output_dir, 'build.gradle'),
             _GenerateRootGradle(jinja_processor))

  _WriteFile(os.path.join(gradle_output_dir, 'settings.gradle'),
             _GenerateSettingsGradle(project_entries))

  sdk_path = _RebasePath(build_vars['android_sdk_root'])
  _WriteFile(os.path.join(gradle_output_dir, 'local.properties'),
             _GenerateLocalProperties(sdk_path))

  if generated_inputs:
    logging.warning('Building generated source files...')
    targets = _RebasePath(generated_inputs, output_dir)
    _RunNinja(output_dir, targets)

  if srcjar_tuples:
    _ExtractSrcjars(gradle_output_dir, srcjar_tuples)

  logging.warning('Project created! (%d subprojects)', len(project_entries))
  logging.warning('Generated projects work best with Android Studio 2.2')
  logging.warning('For more tips: https://chromium.googlesource.com/chromium'
                  '/src.git/+/master/docs/android_studio.md')
Пример #20
0
def _ParseOptions(argv):
  parser = optparse.OptionParser()
  build_utils.AddDepfileOption(parser)

  parser.add_option(
      '--java-srcjars',
      action='append',
      default=[],
      help='List of srcjars to include in compilation.')
  parser.add_option(
      '--bootclasspath',
      action='append',
      default=[],
      help='Boot classpath for javac. If this is specified multiple times, '
      'they will all be appended to construct the classpath.')
  parser.add_option(
      '--java-version',
      help='Java language version to use in -source and -target args to javac.')
  parser.add_option(
      '--full-classpath',
      action='append',
      help='Classpath to use when annotation processors are present.')
  parser.add_option(
      '--interface-classpath',
      action='append',
      help='Classpath to use when no annotation processors are present.')
  parser.add_option(
      '--incremental',
      action='store_true',
      help='Whether to re-use .class files rather than recompiling them '
           '(when possible).')
  parser.add_option(
      '--processors',
      action='append',
      help='GN list of annotation processor main classes.')
  parser.add_option(
      '--processorpath',
      action='append',
      help='GN list of jars that comprise the classpath used for Annotation '
           'Processors.')
  parser.add_option(
      '--processor-arg',
      dest='processor_args',
      action='append',
      help='key=value arguments for the annotation processors.')
  parser.add_option(
      '--provider-configuration',
      dest='provider_configurations',
      action='append',
      help='File to specify a service provider. Will be included '
           'in the jar under META-INF/services.')
  parser.add_option(
      '--additional-jar-file',
      dest='additional_jar_files',
      action='append',
      help='Additional files to package into jar. By default, only Java .class '
           'files are packaged into the jar. Files should be specified in '
           'format <filename>:<path to be placed in jar>.')
  parser.add_option(
      '--chromium-code',
      type='int',
      help='Whether code being compiled should be built with stricter '
      'warnings for chromium code.')
  parser.add_option(
      '--use-errorprone-path',
      help='Use the Errorprone compiler at this path.')
  parser.add_option('--jar-path', help='Jar output path.')
  parser.add_option(
      '--javac-arg',
      action='append',
      default=[],
      help='Additional arguments to pass to javac.')
  parser.add_option(
      '--apk-jar-info-path',
      help='Coalesced jar.info files for the apk')

  options, args = parser.parse_args(argv)
  build_utils.CheckOptions(options, parser, required=('jar_path',))

  options.bootclasspath = _ParseAndFlattenGnLists(options.bootclasspath)
  options.full_classpath = _ParseAndFlattenGnLists(options.full_classpath)
  options.interface_classpath = _ParseAndFlattenGnLists(
      options.interface_classpath)
  options.processorpath = _ParseAndFlattenGnLists(options.processorpath)
  options.processors = _ParseAndFlattenGnLists(options.processors)
  options.java_srcjars = _ParseAndFlattenGnLists(options.java_srcjars)

  if options.java_version == '1.8' and options.bootclasspath:
    # Android's boot jar doesn't contain all java 8 classes.
    # See: https://github.com/evant/gradle-retrolambda/issues/23.
    # Get the path of the jdk folder by searching for the 'jar' executable. We
    # cannot search for the 'javac' executable because goma provides a custom
    # version of 'javac'.
    jar_path = os.path.realpath(distutils.spawn.find_executable('jar'))
    jdk_dir = os.path.dirname(os.path.dirname(jar_path))
    rt_jar = os.path.join(jdk_dir, 'jre', 'lib', 'rt.jar')
    options.bootclasspath.append(rt_jar)

  additional_jar_files = []
  for arg in options.additional_jar_files or []:
    filepath, jar_filepath = arg.split(':')
    additional_jar_files.append((filepath, jar_filepath))
  options.additional_jar_files = additional_jar_files

  java_files = []
  for arg in args:
    # Interpret a path prefixed with @ as a file containing a list of sources.
    if arg.startswith('@'):
      java_files.extend(build_utils.ReadSourcesList(arg[1:]))
    else:
      java_files.append(arg)

  return options, java_files
Пример #21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--lint-path',
                        required=True,
                        help='Path to lint executable.')
    parser.add_argument('--product-dir',
                        required=True,
                        help='Path to product dir.')
    parser.add_argument('--result-path',
                        required=True,
                        help='Path to XML lint result file.')
    parser.add_argument(
        '--cache-dir',
        required=True,
        help='Path to the directory in which the android cache '
        'directory tree should be stored.')
    parser.add_argument('--platform-xml-path',
                        required=True,
                        help='Path to api-platforms.xml')
    parser.add_argument('--android-sdk-version',
                        help='Version (API level) of the Android SDK used for '
                        'building.')
    parser.add_argument(
        '--can-fail-build',
        action='store_true',
        help='If set, script will exit with nonzero exit status'
        ' if lint errors are present')
    parser.add_argument(
        '--include-unexpected-failures',
        action='store_true',
        help='If set, script will exit with nonzero exit status'
        ' if lint itself crashes with unexpected failures.')
    parser.add_argument('--config-path',
                        help='Path to lint suppressions file.')
    parser.add_argument('--disable', help='List of checks to disable.')
    parser.add_argument('--java-sources-file',
                        help='File containing a list of java files.')
    parser.add_argument('--manifest-path', help='Path to AndroidManifest.xml')
    parser.add_argument('--processed-config-path',
                        help='Path to processed lint suppressions file.')
    parser.add_argument('--resource-dir', help='Path to resource dir.')
    parser.add_argument('--resource-sources',
                        default=[],
                        action='append',
                        help='GYP-list of resource sources (directories with '
                        'resources or archives created by resource-generating '
                        'tasks.')
    parser.add_argument('--silent',
                        action='store_true',
                        help='If set, script will not log anything.')
    parser.add_argument('--src-dirs',
                        help='Directories containing java files.')
    parser.add_argument('--srcjars', help='GN list of included srcjars.')
    parser.add_argument('--stamp', help='Path to stamp upon success.')
    parser.add_argument('--min-sdk-version',
                        required=True,
                        help='Minimal SDK version to lint against.')
    parser.add_argument('--manifest-package',
                        help='Package name of the AndroidManifest.xml.')

    args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:]))

    sources = []
    if args.src_dirs:
        src_dirs = build_utils.ParseGnList(args.src_dirs)
        sources = _FindInDirectories(src_dirs, '*.java')
    elif args.java_sources_file:
        sources.extend(build_utils.ReadSourcesList(args.java_sources_file))

    if args.config_path and not args.processed_config_path:
        parser.error('--config-path specified without --processed-config-path')
    elif args.processed_config_path and not args.config_path:
        parser.error('--processed-config-path specified without --config-path')

    resource_sources = []
    if args.resource_dir:
        # Backward compatibility with GYP
        resource_sources += [args.resource_dir]

    for gyp_list in args.resource_sources:
        resource_sources += build_utils.ParseGnList(gyp_list)

    disable = []
    if args.disable:
        disable = build_utils.ParseGnList(args.disable)

    _RunLint(args.lint_path,
             args.config_path,
             args.processed_config_path,
             args.manifest_path,
             args.result_path,
             args.product_dir,
             sources,
             args.cache_dir,
             args.android_sdk_version,
             args.srcjars,
             args.min_sdk_version,
             args.manifest_package,
             resource_sources,
             disable=disable,
             can_fail_build=args.can_fail_build,
             include_unexpected=args.include_unexpected_failures,
             silent=args.silent)

    build_utils.Touch(args.stamp)