class LinkageMonitor {

  @VisibleForTesting
  static ImmutableMap<String, String> findLocalArtifacts(
      RepositorySystem repositorySystem, RepositorySystemSession session, Path projectDirectory) {
    ImmutableMap.Builder<String, String> artifactToVersion = ImmutableMap.builder();
    Iterable<Path> paths = MoreFiles.fileTraverser().breadthFirst(projectDirectory);

    for (Path path : paths) {
      if (!path.getFileName().endsWith("pom.xml")) {
        continue;
      }

      // This path element check should not depend on directory name outside the project
      Path relativePath = path.isAbsolute() ? projectDirectory.relativize(path) : path;
      ImmutableSet<Path> elements = ImmutableSet.copyOf(relativePath);
      if (elements.contains(Paths.get("build")) || elements.contains(Paths.get("target"))) {
        // Exclude Gradle's build directory and Maven's target directory, which would contain irrelevant pom.xml such as
        // gax/build/tmp/expandedArchives/(... omit ...)/META-INF/maven/org.jacoco/org.jacoco.agent/pom.xml
        continue;
      }

      ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
      modelRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
      modelRequest.setProcessPlugins(false);
      modelRequest.setTwoPhaseBuilding(false);
      modelRequest.setPomFile(path.toFile());
      modelRequest.setModelResolver(
          new ProjectModelResolver(
              session,
              null,
              repositorySystem,
              new DefaultRemoteRepositoryManager(),
              ImmutableList.of(CENTRAL), // Needed when parent pom is not locally available
              null,
              null));
      // Profile activation needs JDK version through system properties
      // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/923
      modelRequest.setSystemProperties(System.getProperties());

      try {
        ModelBuildingResult modelBuildingResult = modelBuilder.build(modelRequest);
        Model model = modelBuildingResult.getEffectiveModel();
        artifactToVersion.put(model.getGroupId() + ":" + model.getArtifactId(), model.getVersion());
      } catch (ModelBuildingException ex) {
        // Maven may fail to build pom.xml files found in irrelevant directories, such as "target"
        // and "test" directories of the project. Such failures can be ignored.
        logger.info("Ignoring bad model: " + path + ": " + ex.getMessage());
      }
    }
    return artifactToVersion.build();
  }

}