import os

analyzers = ['infer', 'eradicate']

original_java_library = java_library
def java_library(
    name,
    srcs=[],
    **kwargs
    ):

  original_java_library(
    name=name,
    srcs=srcs,
    **kwargs
  )

  create_genrules(name, srcs)

original_android_library = android_library
def android_library(
    name,
    srcs=[],
    **kwargs
    ):

  original_android_library(
    name=name,
    srcs=srcs,
    **kwargs
  )

  create_genrules(name, srcs)

def create_genrules(
    name,
    srcs
    ):
  if 'GENERATE_INFER_GENRULES' in os.environ and srcs:
    for analyzer in analyzers:
      analyzer_name = name + '_{}'.format(analyzer)
      genrule(
        name = analyzer_name,
        srcs=srcs,
        cmd = ' '.join([
          os.getenv('INFER_BIN', 'infer'),
          '-a', analyzer,
          '--results-dir', '$OUT',
          '--classpath', '$(classpath :{})'.format(name),
          '--sourcepath', '$SRCDIR',
          '--generated-classes', '$(location :{})'.format(name),
        ]),
        out = '{}_out'.format(analyzer),
      )
