<commit_before>package com.github.johnynek.bazel_deps

import java.io.{ File, FileOutputStream }
import scala.util.{ Failure, Success, Try }

object Writer {

  def createBuildFiles(pathToRoot: File, ts: List[Target]): Unit = {
    require(pathToRoot.isAbsolute, s"Absolute path required, found: $pathToRoot")
    def fileFor(p: Path): File =
      p.parts.foldLeft(pathToRoot) { (p, element) => new File(p, element) }

    ts.groupBy(_.name.path)
      .foreach { case (path, ts) =>
        val filePath = fileFor(path)
        require(filePath.exists || filePath.mkdirs(), s"failed to create $filePath")
        val buildFile = new File(filePath, "BUILD")
        val os = new FileOutputStream(buildFile)
        try {
          val fileBytes = ts.sortBy(_.name.name)
            .map(_.toBazelString)
            .mkString("\n\n")
            .getBytes("UTF-8")

          os.write(fileBytes)
        } finally {
          os.close()
        }
      }
  }

  def workspace(g: Graph[MavenCoordinate, Unit],
    duplicates: Map[UnversionedCoordinate, Set[Version]],
    shas: Map[MavenCoordinate, Try[Sha1Value]],
    model: Model): String = {
    val nodes = g.nodes

    def replaced(m: MavenCoordinate): Boolean = model.getReplacements.get(m.unversioned).isDefined

    val lines = nodes.filterNot(replaced)
      .toList
      .sortBy(_.asString)
      .map { case coord@MavenCoordinate(g, a, v) =>
        val isRoot = model.dependencies.roots(coord)
        val shaStr = shas.get(coord) match {
          case Some(Success(sha)) => s""", "sha1": "${sha.toHex}""""
          case Some(Failure(err)) =>
            System.err.println(s"failed to find sha of ${coord.asString}: $err")
            throw err
          case None => ""
        }
        val comment = duplicates.get(coord.unversioned) match {
          case Some(vs) =>
            val status =
              if (isRoot) s"fixed to ${v.asString}"
              else if (vs.max == v) s"promoted to ${v.asString}"
              else s"downgraded to ${v.asString}"

            s"""# duplicates in ${coord.unversioned.asString} $status. Versions: ${vs.map(_.asString).toList.sorted.mkString(" ")}\n"""
          case None =>
            ""
        }
        s"""$comment  callback({ "artifact": "${coord.asString}", "name": "${coord.toBazelRepoName}"$shaStr})"""
      }
      .mkString("\n")
    s"""def maven_dependencies(callback):\n$lines"""
  }

  def targets(g: Graph[MavenCoordinate, Unit],
    rootName: DirectoryName,
    model: Model): List[Target] = {
    val pathInRoot = rootName.parts

    val langCache = scala.collection.mutable.Map[MavenCoordinate, Language]()
    def language(c: MavenCoordinate): Language = langCache.getOrElseUpdate(c, {
      import Language.{ Java, Scala }

      model.dependencies.languageOf(c) match {
        case Some(l) => l
        case None =>
          Label.replaced(c, model.getReplacements) match {
            case Some((_, l)) => l
            case None =>
              // if you have any scala dependencies, you have to be handled by the
              // scala rule for now, otherwise we say java
              g.hasSource(c)
                .iterator
                .map(_.destination)
                .map(language(_))
                .collectFirst {<commit_msg>print versions in version-sorted not string sorted order<commit_after>package com.github.johnynek.bazel_deps

import java.io.{ File, FileOutputStream }
import scala.util.{ Failure, Success, Try }

object Writer {

  def createBuildFiles(pathToRoot: File, ts: List[Target]): Unit = {
    require(pathToRoot.isAbsolute, s"Absolute path required, found: $pathToRoot")
    def fileFor(p: Path): File =
      p.parts.foldLeft(pathToRoot) { (p, element) => new File(p, element) }

    ts.groupBy(_.name.path)
      .foreach { case (path, ts) =>
        val filePath = fileFor(path)
        require(filePath.exists || filePath.mkdirs(), s"failed to create $filePath")
        val buildFile = new File(filePath, "BUILD")
        val os = new FileOutputStream(buildFile)
        try {
          val fileBytes = ts.sortBy(_.name.name)
            .map(_.toBazelString)
            .mkString("\n\n")
            .getBytes("UTF-8")

          os.write(fileBytes)
        } finally {
          os.close()
        }
      }
  }

  def workspace(g: Graph[MavenCoordinate, Unit],
    duplicates: Map[UnversionedCoordinate, Set[Version]],
    shas: Map[MavenCoordinate, Try[Sha1Value]],
    model: Model): String = {
    val nodes = g.nodes

    def replaced(m: MavenCoordinate): Boolean = model.getReplacements.get(m.unversioned).isDefined

    val lines = nodes.filterNot(replaced)
      .toList
      .sortBy(_.asString)
      .map { case coord@MavenCoordinate(g, a, v) =>
        val isRoot = model.dependencies.roots(coord)
        val shaStr = shas.get(coord) match {
          case Some(Success(sha)) => s""", "sha1": "${sha.toHex}""""
          case Some(Failure(err)) =>
            System.err.println(s"failed to find sha of ${coord.asString}: $err")
            throw err
          case None => ""
        }
        val comment = duplicates.get(coord.unversioned) match {
          case Some(vs) =>
            val status =
              if (isRoot) s"fixed to ${v.asString}"
              else if (vs.max == v) s"promoted to ${v.asString}"
              else s"downgraded to ${v.asString}"

            s"""# duplicates in ${coord.unversioned.asString} $status. Versions: ${vs.toList.sorted.map(_.asString).mkString(" ")}\n"""
          case None =>
            ""
        }
        s"""$comment  callback({ "artifact": "${coord.asString}", "name": "${coord.toBazelRepoName}"$shaStr})"""
      }
      .mkString("\n")
    s"""def maven_dependencies(callback):\n$lines"""
  }

  def targets(g: Graph[MavenCoordinate, Unit],
    rootName: DirectoryName,
    model: Model): List[Target] = {
    val pathInRoot = rootName.parts

    val langCache = scala.collection.mutable.Map[MavenCoordinate, Language]()
    def language(c: MavenCoordinate): Language = langCache.getOrElseUpdate(c, {
      import Language.{ Java, Scala }

      model.dependencies.languageOf(c) match {
        case Some(l) => l
        case None =>
          Label.replaced(c, model.getReplacements) match {
            case Some((_, l)) => l
            case None =>
              // if you have any scala dependencies, you have to be handled by the
              // scala rule for now, otherwise we say java
              g.hasSource(c)
                .iterator
                .map(_.destination)
                .map(language(_))
                .collectFirst {
{'fraction_non_alphanumeric': 0.13473461363980038, 'fraction_numerical': 0.0009073037955542114, 'mean_word_length': 2.285643318430204, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6982836', 'n_tokens_mistral': 2067, 'n_tokens_neox': 2006, 'n_words': 475}