Ejemplo n.º 1
0
def usage():
    print "usage: {0} [args] ".format(sys.argv[0])
    print "Prints all the properties defined in a pom.xml in bash variable syntax."
    print ""
    print "-?,-h         Show this message"
    PomUtils.common_usage()
    sys.exit(1)
Ejemplo n.º 2
0
def main(sourceFile):
    """Builds a dependency graph,  searches the graph for all transitive dependencies
     of the module defined in sourceFile and prints them out as <groupId>.<artifactId>
  """
    # Fetch the group/artifact for the source file
    finder = DependencyInfo(sourceFile)
    query = "{group_id}.{artifact_id}".format(group_id=finder.groupId,
                                              artifact_id=finder.artifactId)
    logger.debug(
        "Looking for all dependencies of: {query}".format(query=query))

    dependency_edges = build_dependency_graph()

    results = set()
    recursive_find_deps(query, dependency_edges, results)
    logger.debug(
        "Found {num_results} results.".format(num_results=len(results)))
    sorted_results = sorted(results)

    # Sort the output with local deps first
    for dep_target in sorted_results:
        if PomUtils.is_local_dep(dep_target):
            print dep_target
    for dep_target in sorted_results:
        if not PomUtils.is_local_dep(dep_target):
            print dep_target
Ejemplo n.º 3
0
def usage():
  print "usage: {0} [args] ".format(sys.argv[0])
  print "Prints all the properties defined in a pom.xml in bash variable syntax."
  print ""
  print "-?,-h         Show this message"
  PomUtils.common_usage()
  sys.exit(1)
  def __init__(self, repo_dir):
    # Clear the cache before analyzing the repo
    PomUtils.reset_caches()
    self.repo_dir = repo_dir
    self._top_pom = PomUtils.top_pom_content_handler(rootdir=repo_dir)

    self._pom_details = {}
    # Parse oll of the poms for the modules [ plus the top level pom.xml ]
    module_list = self._top_pom.modules + ['']
    while len(module_list):
      module = module_list.pop()
      if module in self._pom_details.keys():
        continue
      full_source_path = os.path.join(repo_dir, module, 'pom.xml')
      pom_handler = _DFPomContentHandler()
      try:
        with open(full_source_path) as source:
          xml.sax.parse(source, pom_handler)
      except IOError:
        # assume this file has been removed for a good reason and just continue normally
        continue
      self._pom_details[module] = PomDetails(repo_dir, module, pom_handler)
      # Don't forget to also add in the parent poms
      if 'relativePath' in pom_handler.parent:
        parent_module = os.path.join(module, pom_handler.parent['relativePath'])
        if os.path.basename(parent_module) == 'pom.xml':
          parent_module = os.path.dirname(parent_module)
        parent_module =os.path.normpath(parent_module)
        if parent_module not in self._pom_details.keys():
          module_list.append(parent_module)
Ejemplo n.º 5
0
def usage():
  print "usage: %s [args] " % sys.argv[0]
  print "Checks to see if the BUILD.* files should be recomputed for the repo"
  print ""
  print "-?,-h         Show this message"
  print "--rebuild     unconditionally rebuild the BUILD files from pom.xml"
  print "-f, --force   force the use of a seemingly incompatible index version"
  PomUtils.common_usage()
Ejemplo n.º 6
0
def usage():
    print "usage: %s [args] " % sys.argv[0]
    print "Checks to see if the BUILD.* files should be recomputed for the repo"
    print ""
    print "-?,-h         Show this message"
    print "--rebuild     unconditionally rebuild the BUILD files from pom.xml"
    print "-f, --force   force the use of a seemingly incompatible index version"
    PomUtils.common_usage()
Ejemplo n.º 7
0
  def _convert_poms(self):
    modules = PomUtils.get_modules()
    logger.debug('Re-generating {count} modules'.format(count=len(modules)))
    # Convert pom files to BUILD files
    context = GenerationContext()
    for module_name in modules:
      if not module_name in _MODULES_TO_SKIP:
        pom_file_name = os.path.join(module_name, 'pom.xml')
        PomToBuild().convert_pom(pom_file_name, rootdir=self.baseroot, generation_context=context)
    context.os_to_java_homes = JavaHomesInfo.from_pom('parents/base/pom.xml',
                                                      self.baseroot).home_map
    # Write jvm platforms and distributions.
    with open(context.generated_ini_file, 'w+') as f:
      f.write('# Generated by regenerate_all.py. Do not hand-edit.\n\n')
      f.write('\n'.join(context.get_pants_ini_gen()))

    local_ini = 'pants-local.ini'
    if not os.path.exists(local_ini):
      with open(local_ini, 'w') as f:
        f.write('\n'.join([
          '# Local pants.ini file, not tracked by git.',
          '# Use this to make your own custom changes/overrides to pants settings.',
          '# Note: This is for local settings only.  Changes you make here will',
          '# not be used in CI (use pants.ini for that).',
          '',
          '# Uncomment to use local build cache ',
          '# (Saves time when switching between branches frequently.)',
          '#[cache]',
          '#read_from: ["~/.cache/pants/local-build-cache"]',
          '#read: True',
          '#write_to: ["~/.cache/pants/local-build-cache"]',
          '#write: True',
          '',
        ]))
Ejemplo n.º 8
0
def main():
    arguments = PomUtils.parse_common_args(sys.argv[1:])
    flags = set(arg for arg in arguments if arg.startswith('-'))

    for f in flags:
        if f == '-h' or f == '-?':
            usage()
            return
        else:
            print("Unknown flag {0}".format(f))
            usage()
            return

    path_args = list(set(arguments) - flags)
    if len(path_args) != 1:
        print("Expected a single project path that contains a pom.xml file.")
        usage()

    pom_file_path = os.path.join(os.path.realpath(path_args[0]), 'pom.xml')

    if not os.path.exists(pom_file_path):
        print("Couldn't find {0}".format(pom_file_path))
        usage()

    PomProperties().write_properties(pom_file_path, sys.stdout)
Ejemplo n.º 9
0
  def _rebuild_everything(self, gens_dir, builds_index):
    # The cached BUILD files are now invalid. Remove them first
    rmtree(gens_dir, ignore_errors=True)

    poms = [x + '/pom.xml' for x in PomUtils.get_modules()]
    # Convert pom files to BUILD files
    for pom_file_name in poms:
      PomToBuild().convert_pom(pom_file_name, rootdir=self.baseroot)

    logger.info('Re-generating 3rdparty/BUILD.gen')
    with open('3rdparty/BUILD.gen', 'w') as build_file:
      build_file.write(ThirdPartyBuildGenerator().generate())

    new_gens = find_files([self.baseroot], _GEN_NAMES)
    logger.info('Caching {num_build_files} regenerated BUILD.* files. '
                .format(num_build_files=len(new_gens)))
    os.makedirs(gens_dir)
    gen_pairs = set()
    for gen in new_gens:
      if gen == '':
        continue
      cache_name = sha1(gen).hexdigest()
      index = 0
      while os.path.exists(os.path.join(gens_dir, cache_name+str(index))):
        index += 1
      cache_name += str(index)
      cache_path = os.path.join(gens_dir, cache_name)
      copyfile(gen, cache_path)
      gen_pairs.add((cache_path, gen))
    write_index(builds_index, gen_pairs)
Ejemplo n.º 10
0
def main():

  arguments = PomUtils.parse_common_args(sys.argv[1:])

  flags = set(arg for arg in arguments if arg.startswith('-'))

  paths = list(set(arguments) - flags)
  paths = paths or [os.getcwd()]
  if len(paths) > 1:
    logger.error('Multiple repo root paths not supported.')
    return

  path = os.path.realpath(paths[0])

  for f in flags:
    if f == '-h' or f == '-?':
      usage()
      return
    elif f == '--rebuild':
      pass
    elif f == '-f' or f == '--force':
      pass
    else:
      print ("Unknown flag %s" % f)
      usage()
      return
  main_run = Task('main', lambda: CheckPoms(path, flags).execute())
  main_run()
  logger.info('Finish checking BUILD.* health in %0.3f seconds.' % main_run.duration)
Ejemplo n.º 11
0
    def _rebuild_everything(self, gens_dir, builds_index):
        # The cached BUILD files are now invalid. Remove them first
        rmtree(gens_dir, ignore_errors=True)

        poms = [x + '/pom.xml' for x in PomUtils.get_modules()]
        # Convert pom files to BUILD files
        for pom_file_name in poms:
            PomToBuild().convert_pom(pom_file_name, rootdir=self.baseroot)

        logger.info('Re-generating 3rdparty/BUILD.gen')
        with open('3rdparty/BUILD.gen', 'w') as build_file:
            build_file.write(ThirdPartyBuildGenerator().generate())

        new_gens = find_files([self.baseroot], _GEN_NAMES)
        logger.info(
            'Caching {num_build_files} regenerated BUILD.* files. '.format(
                num_build_files=len(new_gens)))
        os.makedirs(gens_dir)
        gen_pairs = set()
        for gen in new_gens:
            if gen == '':
                continue
            cache_name = sha1(gen).hexdigest()
            index = 0
            while os.path.exists(
                    os.path.join(gens_dir, cache_name + str(index))):
                index += 1
            cache_name += str(index)
            cache_path = os.path.join(gens_dir, cache_name)
            copyfile(gen, cache_path)
            gen_pairs.add((cache_path, gen))
        write_index(builds_index, gen_pairs)
Ejemplo n.º 12
0
def main():

    arguments = PomUtils.parse_common_args(sys.argv[1:])

    flags = set(arg for arg in arguments if arg.startswith('-'))

    paths = list(set(arguments) - flags)
    paths = paths or [os.getcwd()]
    if len(paths) > 1:
        logger.error('Multiple repo root paths not supported.')
        return

    path = os.path.realpath(paths[0])

    for f in flags:
        if f == '-h' or f == '-?':
            usage()
            return
        elif f == '--rebuild':
            pass
        elif f == '-f' or f == '--force':
            pass
        else:
            print("Unknown flag %s" % f)
            usage()
            return
    main_run = Task('main', lambda: CheckPoms(path, flags).execute())
    main_run()
    logger.info('Finish checking BUILD.* health in %0.3f seconds.' %
                main_run.duration)
Ejemplo n.º 13
0
def main():
  arguments = PomUtils.parse_common_args(sys.argv[1:])
  flags = set(arg for arg in arguments if arg.startswith('-'))

  for f in flags:
    if f == '-h' or f == '-?':
      usage()
      return
    else:
      print ("Unknown flag {0}".format(f))
      usage()
      return

  path_args = list(set(arguments) - flags)
  if len(path_args) != 1 :
    print("Expected a single project path that contains a pom.xml file.")
    usage()

  pom_file_path = os.path.join(os.path.realpath(path_args[0]), 'pom.xml')

  if not os.path.exists(pom_file_path):
    print ("Couldn't find {0}".format(pom_file_path))
    usage()

  PomProperties().write_properties(pom_file_path, sys.stdout)
Ejemplo n.º 14
0
  def generate(self):
    modules = PomUtils.get_modules()

    contents = "# Automatically generated by {0}\n\n".format(os.path.basename(sys.argv[0]))
    for module in modules:
      contents += "square_maven_layout('{0}')\n".format(module)

    return contents
Ejemplo n.º 15
0
def main(sourceFileName):
  start_ms = int(round(time.time() * 1000))
  pants_refs =  DepsFromPom(PomUtils.pom_provides_target()).get(sourceFileName)
  elapsed_ms = int(round(time.time() * 1000)) - start_ms
  for pants_ref in pants_refs:
    print("      {ref}".format(ref=pants_ref))
  print
  print("Parsed %d pom.xml files in %dms." % (PomContentHandler.num_invocations(), elapsed_ms))
def main():
  """Test driver that spits out <dependencyManagement> contents.
     Run from ~/Development/java
  """

  deps = PomUtils.dependency_management_finder().find_dependencies("parents/base/pom.xml")
  for dependency in deps:
    print(dependency["groupId"] + "." + dependency["artifactId"] + "-" + dependency["version"])
Ejemplo n.º 17
0
 def _generate_module_list_file(self):
   modules = PomUtils.get_modules()
   context = GenerationContext()
   with open(context.module_list_file, 'w+') as f:
     f.write("# List of modules for pants's reference. This are currently generated directly\n"
             "# from pom.xml, but in the future we can simply use\n"
             "# ./pants filter --target-type=jvm_binary ::\n\n")
     for module in modules:
       f.write('{}\n'.format(module.strip()))
    def generate(self):
        modules = PomUtils.get_modules()

        contents = "# Automatically generated by {0}\n\n".format(
            os.path.basename(sys.argv[0]))
        for module in modules:
            contents += "square_maven_layout('{0}')\n".format(module)

        return contents
Ejemplo n.º 19
0
 def _get_parsed_pom_data(self, generation_context):
   self.deps_from_pom = DepsFromPom(PomUtils.pom_provides_target(rootdir=self.root_directory),
     rootdir=self.root_directory,
     exclude_project_targets=generation_context.exclude_project_targets
   )
   self.wire_info = WireInfo.from_pom(self.path, self.root_directory)
   self.signed_jar_info = SignedJarInfo.from_pom(self.path, self.root_directory)
   self.java_options_info = JavaOptionsInfo.from_pom(self.path, self.root_directory)
   self.shading_info = ShadingInfo.from_pom(self.path, self.root_directory)
   self.jooq_info = JooqInfo.from_pom(self.path, self.root_directory)
Ejemplo n.º 20
0
 def _generate_module_list_file(self):
     modules = PomUtils.get_modules()
     context = GenerationContext()
     with open(context.module_list_file, 'w+') as f:
         f.write(
             "# List of modules for pants's reference. This are currently generated directly\n"
             "# from pom.xml, but in the future we can simply use\n"
             "# ./pants filter --target-type=jvm_binary ::\n\n")
         for module in modules:
             f.write('{}\n'.format(module.strip()))
Ejemplo n.º 21
0
def main():
    """Test driver that spits out <dependencyManagement> contents.
     Run from ~/Development/java
  """

    deps = PomUtils.dependency_management_finder().find_dependencies(
        "parents/base/pom.xml")
    for dependency in deps:
        print(dependency["groupId"] + "." + dependency["artifactId"] + "-" +
              dependency["version"])
Ejemplo n.º 22
0
def main(sourceFileName):
    start_ms = int(round(time.time() * 1000))
    pants_refs = DepsFromPom(
        PomUtils.pom_provides_target()).get(sourceFileName)
    elapsed_ms = int(round(time.time() * 1000)) - start_ms
    for pants_ref in pants_refs:
        print("      {ref}".format(ref=pants_ref))
    print
    print("Parsed %d pom.xml files in %dms." %
          (PomContentHandler.num_invocations(), elapsed_ms))
Ejemplo n.º 23
0
def main(args):
    """Searches all known modules for an artifactId
     of the module defined in sourceFile and prints them out as <groupId>.<artifactId>
  """

    usage = """usage: %prog [options]
  Searches all known modules for an artifactId or <groupId>.<artifactId>
  and prints out the name of pom.xml files that provide them

  e.g. %prog --target=com.squareup.service.exemplar
       %prog --artifactId=annotations
  """
    parser = OptionParser(usage=usage)
    parser.add_option("-a",
                      "--artifactId",
                      dest="artifactId",
                      help="<artifactId> from maven pom file")
    parser.add_option("-t",
                      "--target",
                      dest="target",
                      help="<groupId>.<artifactId> from maven pom file ")
    (options, args) = parser.parse_args(args)

    if not options.artifactId and not options.target:
        parser.print_help()
        PomUtils.common_usage()
        sys.exit(1)

    if options.artifactId:
        poms = PomUtils.pom_provides_target().find_artifact(options.artifactId)
    elif options.target:
        poms = PomUtils.pom_provides_target().find_target(options.target)

    if len(poms) == 0:
        logger.critical("*** No pom.xml file found")
        sys.exit(1)

    for pom in poms:
        print pom
Ejemplo n.º 24
0
def main(args):
  """Searches all known modules for an artifactId
     of the module defined in sourceFile and prints them out as <groupId>.<artifactId>
  """

  usage = """usage: %prog [options]
  Searches all known modules for an artifactId or <groupId>.<artifactId>
  and prints out the name of pom.xml files that provide them

  e.g. %prog --target=com.squareup.service.exemplar
       %prog --artifactId=annotations
  """
  parser = OptionParser(usage=usage)
  parser.add_option("-a", "--artifactId", dest="artifactId",
                    help="<artifactId> from maven pom file")
  parser.add_option("-t", "--target", dest="target",
                    help="<groupId>.<artifactId> from maven pom file ")
  (options, args) = parser.parse_args(args)

  if not options.artifactId and not options.target:
    parser.print_help()
    PomUtils.common_usage()
    sys.exit(1)


  if options.artifactId:
    poms = PomUtils.pom_provides_target().find_artifact(options.artifactId)
  elif options.target:
    poms = PomUtils.pom_provides_target().find_target(options.target)

  if len(poms) == 0:
    logger.critical("*** No pom.xml file found")
    sys.exit(1)

  for pom in poms:
    print pom
Ejemplo n.º 25
0
def main(sourceFile):
  """Builds a dependency graph,  searches the graph for all transitive dependencies
     of the module defined in sourceFile and prints them out as <groupId>.<artifactId>
  """
  # Fetch the group/artifact for the source file
  finder = DependencyInfo(sourceFile)
  query =  "{group_id}.{artifact_id}".format(group_id=finder.groupId,
                                             artifact_id=finder.artifactId)
  logger.debug("Looking for all dependencies of: {query}".format(query=query))

  dependency_edges = build_dependency_graph()

  results = set()
  recursive_find_deps(query, dependency_edges, results)
  logger.debug("Found {num_results} results.".format(num_results=len(results)))
  sorted_results = sorted(results)

  # Sort the output with local deps first
  for dep_target in sorted_results:
    if PomUtils.is_local_dep(dep_target):
      print dep_target
  for dep_target in sorted_results:
    if not PomUtils.is_local_dep(dep_target):
      print dep_target
Ejemplo n.º 26
0
def build_dependency_graph():
  dependency_edges = {}
  for module in PomUtils.top_pom_content_handler().modules:
    logger.debug("found module: " + module)
    finder = CachedDependencyInfos.get(module + "/pom.xml")
    deps = finder.dependencies
    target = "{group_id}.{artifact_id}".format(group_id=finder.groupId,
                                               artifact_id=finder.artifactId)
    logger.debug("Adding dependencies for {target}".format(target=target))
    dependency_edges[target] = []
    for dep in deps:
      dep_target = "{group_id}.{artifact_id}".format(group_id=dep['groupId'],
                                                     artifact_id=dep['artifactId'])
      logger.debug("{target} => {dep_target}".format(target=target, dep_target=dep_target))
      dependency_edges[target].append(dep_target)
  return dependency_edges
Ejemplo n.º 27
0
def build_dependency_graph():
    dependency_edges = {}
    for module in PomUtils.top_pom_content_handler().modules:
        logger.debug("found module: " + module)
        finder = CachedDependencyInfos.get(module + "/pom.xml")
        deps = finder.dependencies
        target = "{group_id}.{artifact_id}".format(
            group_id=finder.groupId, artifact_id=finder.artifactId)
        logger.debug("Adding dependencies for {target}".format(target=target))
        dependency_edges[target] = []
        for dep in deps:
            dep_target = "{group_id}.{artifact_id}".format(
                group_id=dep['groupId'], artifact_id=dep['artifactId'])
            logger.debug("{target} => {dep_target}".format(
                target=target, dep_target=dep_target))
            dependency_edges[target].append(dep_target)
    return dependency_edges
  def generate(self):
    handler = PomUtils.external_protos_content_handler()
    pom_file = PomFile('parents/external-protos/pom.xml')
    jar_dep = Target.jar.format(org='com.squareup.protos',
                                name='all-protos',
                                rev=handler.properties['external-protos.all-protos-latest'],
                                symbols=pom_file.properties,
                                file_name=pom_file.path)
    template = dedent("""\
          # Automatically generated by {script}
          # The jar version is used the majority of BUILD files in external-protos as the latest version of all-protos to extract .proto sources from
          # Seeded from the external-protos.all-protos-latest property defined in external/protos/pom.xml
          {target}

          target(name='test')
          """)
    return template.format(script=os.path.basename(sys.argv[0]),
                           target=Target.jar_library.format(name='latest-all-protos',
                                                            jars=[jar_dep],))
Ejemplo n.º 29
0
def main():
    arguments = PomUtils.parse_common_args(sys.argv[1:])
    flags = set(arg for arg in arguments if arg.startswith('-'))
    paths = list(set(arguments) - flags)
    paths = paths or [os.getcwd()]
    if len(paths) > 1:
        logger.error('Multiple repo root paths not supported.')
        return

    path = os.path.realpath(paths[0])

    for f in flags:
        if f == '-h' or f == '-?':
            usage()
            return
        else:
            print("Unknown flag %s" % f)
            usage()
            return
    check_pex_health(path, flags)
Ejemplo n.º 30
0
def main():
  arguments = PomUtils.parse_common_args(sys.argv[1:])
  flags = set(arg for arg in arguments if arg.startswith('-'))
  paths = list(set(arguments) - flags)
  paths = paths or [os.getcwd()]
  if len(paths) > 1:
    logger.error('Multiple repo root paths not supported.')
    return

  path = os.path.realpath(paths[0])

  for f in flags:
    if f == '-h' or f == '-?':
      usage()
      return
    else:
      print ("Unknown flag %s" % f)
      usage()
      return
  check_pex_health(path, flags)
Ejemplo n.º 31
0
    def generate(self):
        handler = PomUtils.external_protos_content_handler()
        pom_file = PomFile('parents/external-protos/pom.xml')
        jar_dep = Target.jar.format(
            org='com.squareup.protos',
            name='all-protos',
            rev=handler.properties['external-protos.all-protos-latest'],
            symbols=pom_file.properties,
            file_name=pom_file.path)
        template = dedent("""\
          # Automatically generated by {script}
          # The jar version is used the majority of BUILD files in external-protos as the latest version of all-protos to extract .proto sources from
          # Seeded from the external-protos.all-protos-latest property defined in external/protos/pom.xml
          {target}

          target(name='test')
          """)
        return template.format(script=os.path.basename(sys.argv[0]),
                               target=Target.jar_library.format(
                                   name='latest-all-protos',
                                   jars=[jar_dep],
                               ))
Ejemplo n.º 32
0
def _main():
  global _exit_on_fail
  arguments = PomUtils.parse_common_args(sys.argv[1:])

  flags = set(arg for arg in arguments if arg.startswith('-'))
  paths = list(set(arguments) - flags)
  paths = paths or [os.getcwd()]

  for i, path in enumerate(paths):
    paths[i] = os.path.realpath(path)

  for f in flags:
    if f == '-x':
      _exit_on_fail = True
    elif f == '-?' or f == '-h':
      _usage()
      return
    else:
      print("Unknown flag %s" % f)
      _usage()
      return

  run_tests()
Ejemplo n.º 33
0
def main():
    arguments = PomUtils.parse_common_args(sys.argv[1:])
    flags = set(arg for arg in arguments if arg.startswith('-'))
    paths = list(set(arguments) - flags)
    paths = paths or [os.getcwd()]
    if len(paths) > 1:
        logger.error('Multiple repo root paths not supported.')
        return

    path = os.path.realpath(paths[0])

    for f in flags:
        if f == '-h' or f == '-?':
            usage()
            return
        else:
            print("Unknown flag {0}".format(f))
            usage()
            return
    main_run = Task('main', lambda: RegenerateAll(path, flags).execute())
    main_run()
    logger.info('Regenerated BUILD files in {duration:0.3f} seconds.'.format(
        duration=main_run.duration))
Ejemplo n.º 34
0
def main():
  arguments = PomUtils.parse_common_args(sys.argv[1:])
  flags = set(arg for arg in arguments if arg.startswith('-'))
  paths = list(set(arguments) - flags)
  paths = paths or [os.getcwd()]
  if len(paths) > 1:
    logger.error('Multiple repo root paths not supported.')
    return

  path = os.path.realpath(paths[0])

  for f in flags:
    if f == '-h' or f == '-?':
      usage()
      return
    else:
      print ("Unknown flag {0}".format(f))
      usage()
      return
  main_run = Task('main', lambda: RegenerateAll(path, flags).execute())
  main_run()
  logger.info('Regenerated BUILD files in {duration:0.3f} seconds.'
              .format(duration=main_run.duration))
Ejemplo n.º 35
0
    def _convert_poms(self):
        modules = PomUtils.get_modules()
        logger.debug(
            'Re-generating {count} modules'.format(count=len(modules)))
        # Convert pom files to BUILD files
        context = GenerationContext()
        for module_name in modules:
            if not module_name in _MODULES_TO_SKIP:
                pom_file_name = os.path.join(module_name, 'pom.xml')
                PomToBuild().convert_pom(pom_file_name,
                                         rootdir=self.baseroot,
                                         generation_context=context)
        context.os_to_java_homes = JavaHomesInfo.from_pom(
            'parents/base/pom.xml', self.baseroot).home_map
        # Write jvm platforms and distributions.
        with open(context.generated_ini_file, 'w+') as f:
            f.write('# Generated by regenerate_all.py. Do not hand-edit.\n\n')
            f.write('\n'.join(context.get_pants_ini_gen()))

        local_ini = 'pants-local.ini'
        if not os.path.exists(local_ini):
            with open(local_ini, 'w') as f:
                f.write('\n'.join([
                    '# Local pants.ini file, not tracked by git.',
                    '# Use this to make your own custom changes/overrides to pants settings.',
                    '# Note: This is for local settings only.  Changes you make here will',
                    '# not be used in CI (use pants.ini for that).',
                    '',
                    '# Uncomment to use local build cache ',
                    '# (Saves time when switching between branches frequently.)',
                    '#[cache]',
                    '#read_from: ["~/.cache/pants/local-build-cache"]',
                    '#read: True',
                    '#write_to: ["~/.cache/pants/local-build-cache"]',
                    '#write: True',
                    '',
                ]))
Ejemplo n.º 36
0
 def _compute_dependencies(self):
     return PomUtils.dependency_management_finder().find_dependencies(
         'parents/base/pom.xml')
Ejemplo n.º 37
0
def _usage():
  usage()
  print("-x        Exit immediately on failure")
  PomUtils.common_usage()
#!/usr/bin/python
#
# Looks through <dependencyManagement> tags and extracts dependencies
# Used to automatically pull in external dependencies defined in Maven into Pants' 3rdparty BUILD

import sys

from pom_utils import PomUtils


# Test driver
def main():
  """Test driver that spits out <dependencyManagement> contents.
     Run from ~/Development/java
  """

  deps = PomUtils.dependency_management_finder().find_dependencies("parents/base/pom.xml")
  for dependency in deps:
    print(dependency["groupId"] + "." + dependency["artifactId"] + "-" + dependency["version"])

if __name__ == "__main__":
  args = PomUtils.parse_common_args(sys.argv[1:])
  main()
Ejemplo n.º 39
0
 def _compute_dependencies(self):
     return PomUtils.dependency_management_finder().find_dependencies("parents/base/pom.xml")
Ejemplo n.º 40
0
      bc = component(pom_file, generation_context=generation_context)
      if bc.exists:
        try:
          gen_code = bc.generate()
        except Exception as e:
          raise PomConversionError('Failed to generate component {} for pom file {}.\n{}'
                                   .format(component.__name__, pom_file_name, e))
        if gen_code:
          contents += gen_code

    try:
      generation_context.write_build_file(pom_file.directory, contents)
    except Exception as e:
      raise PomConversionError('Failed to write generated build data for {}:\n{}'
                               .format(pom_file_name, e))


def main(poms):
  for pom_file_name in poms:
    PomToBuild().convert_pom(pom_file_name)

if __name__ == "__main__":
  args = PomUtils.parse_common_args(sys.argv[1:])
  poms = []
  if (len(args) > 0):
    main(args)
  else:
    print "usage: {0} path/to/pom.xml".format(os.path.basename(sys.argv[0]))
    PomUtils.common_usage()
    sys.exit(1)
Ejemplo n.º 41
0
def usage():
  print "usage: %s [args] " % sys.argv[0]
  print "Checks the pants.pex file to see if it has changed.  If so, runs a clean-all."
  print ""
  print "-?,-h         Show this message"
  PomUtils.common_usage()
Ejemplo n.º 42
0
def usage():
  print "usage: {0} [args] ".format(sys.argv[0])
  print "Regenerates the BUILD.* files for the repo"
  print ""
  print "-?,-h         Show this message"
  PomUtils.common_usage()
Ejemplo n.º 43
0
  def build_pants_refs(self, deps):
    # HACK This is horrible but works around a circular dependency.
    from pom_utils import PomUtils
    pants_refs = []
    for dep in deps:
      dep_target = "{groupId}.{artifactId}".format(groupId=dep['groupId'],
                                                   artifactId=dep['artifactId'])
      if PomUtils.is_local_dep(dep_target):
        # find the POM that contains this artifact
        poms = self._pom_provides_target.find_target(dep_target)
        if len(poms) > 0:
          project_root = os.path.dirname(poms[0])
        else:
          project_root = dep['artifactId']
        if project_root in self.exclude_project_targets:
          continue
        if dep.has_key('type') and dep['type'] == 'test-jar':
          target_prefix = 'src/test/'
        else:
          target_prefix = "src/main/"
        target_name = self.get_closest_match(project_root, target_prefix)
        if target_name:
          pants_refs.append("'{0}'".format(target_name))

    # Print 3rdparty dependencies after the local deps
    for dep in deps:
      dep_target = "{groupId}.{artifactId}".format(groupId=dep['groupId'],
                                                   artifactId=dep['artifactId'])
      if PomUtils.is_local_dep(dep_target):
        continue
      is_in_thirdparty = PomUtils.is_third_party_dep(dep_target, rootdir=self._rootdir)
      if is_in_thirdparty and not dep.get('exclusions'):
        logger.debug("dep_target {target} is not local".format(target=dep_target))
        pants_refs.append("'3rdparty:{target}'".format(target=dep_target))
        continue
      if not dep.has_key('version'):
        if is_in_thirdparty:
          dep['version'] = PomUtils.third_party_dep_targets(rootdir=self._rootdir)[dep_target]
        else:
          raise Exception(
            "Expected artifact {artifactId} group {groupId} in pom {pom_file} to have a version."
            .format(artifactId=dep['artifactId'],
                    groupId=dep['groupId'],
                    pom_file=self._source_file_name))
      jar_excludes = []
      for jar_exclude in dep.get('exclusions', ()):
        jar_excludes.append("exclude(org='{groupId}', name='{artifactId}')".format(
          groupId=jar_exclude['groupId'], artifactId=jar_exclude['artifactId']))

      classifier = dep.get('classifier') # Important to use 'get', so we default to None.
      if dep.get('type') == 'test-jar':
        # In our repo, this is special, *or* ivy doesn't translate this correctly.
        # Transform this into a classifier named 'tests' instead
        classifier = 'tests'
        type_ = None
      else:
        type_ = dep.get('type')

      dep_url = dep.get('systemPath')
      if dep_url:
        dep_url = 'file://{}'.format(dep_url)

      pants_refs.append(Target.jar.format(
        org=dep['groupId'],
        name=dep['artifactId'],
        rev=dep['version'],
        classifier=classifier,
        type_=type_,
        url=dep_url,
        excludes=jar_excludes or None,
      ))
    return pants_refs
Ejemplo n.º 44
0
#!/usr/bin/python
#
# Looks through <dependencyManagement> tags and extracts dependencies
# Used to automatically pull in external dependencies defined in Maven into Pants' 3rdparty BUILD

import sys

from pom_utils import PomUtils


# Test driver
def main():
    """Test driver that spits out <dependencyManagement> contents.
     Run from ~/Development/java
  """

    deps = PomUtils.dependency_management_finder().find_dependencies(
        "parents/base/pom.xml")
    for dependency in deps:
        print(dependency["groupId"] + "." + dependency["artifactId"] + "-" +
              dependency["version"])


if __name__ == "__main__":
    args = PomUtils.parse_common_args(sys.argv[1:])
    main()
Ejemplo n.º 45
0
logger = logging.getLogger(__name__)


# Test driver
def main(sourceFileName):
    start_ms = int(round(time.time() * 1000))
    pants_refs = DepsFromPom(
        PomUtils.pom_provides_target()).get(sourceFileName)
    elapsed_ms = int(round(time.time() * 1000)) - start_ms
    for pants_ref in pants_refs:
        print("      {ref}".format(ref=pants_ref))
    print
    print("Parsed %d pom.xml files in %dms." %
          (PomContentHandler.num_invocations(), elapsed_ms))


if __name__ == "__main__":
    pom = ""
    args = PomUtils.parse_common_args(sys.argv[1:])
    if len(args) == 1:
        pom = args[0]
    else:
        pom = "common/pom.xml"
        print "usage: {progname} path/to/pom.xml".format(
            progname=os.path.basename(sys.argv[0]))
        print
        PomUtils.common_usage()
        print
        print "Example with {pom}:".format(pom=pom)
    main(pom)
Ejemplo n.º 46
0
def usage():
    print "usage: {0} [args] ".format(sys.argv[0])
    print "Regenerates the BUILD.* files for the repo"
    print ""
    print "-?,-h         Show this message"
    PomUtils.common_usage()
Ejemplo n.º 47
0
def usage():
    print "usage: %s [args] " % sys.argv[0]
    print "Checks the pants.pex file to see if it has changed.  If so, runs a clean-all."
    print ""
    print "-?,-h         Show this message"
    PomUtils.common_usage()