<commit_before>/*
 * Original:
 * https://github.com/thesamet/scalariform-intellij-plugin/blob/8e974a2c927db35f95b710b7498d5a5dba08de5e/src/com/thesamet/intellij/ScalariformFormatAction.scala
 */
package org.scalafmt.intellij

import scala.collection.mutable
import scala.meta.parsers.ParseException

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.awt.RelativePoint
import org.scalafmt.FormatResult
import org.scalafmt.Scalafmt
import org.scalafmt.ScalafmtStyle
import org.scalafmt.cli.StyleCache
import org.scalafmt.util.FileOps

case class FileDocument(file: VirtualFile, document: Document) {
  def isScala: Boolean = file.getFileType.getName == "Scala"
}

object StyleChangedCache {
  val styleCache = mutable.Map.empty[String, ScalafmtStyle]
}

class ScalafmtAction extends AnAction {

  override def actionPerformed(event: AnActionEvent): Unit = {
    val style = getStyle(event)
    getCurrentFileDocument(event).filter(_.isScala).foreach { fileDoc =>
      val source = fileDoc.document.getText()
      Scalafmt.format(source, style = style) match {
        case _: FormatResult.Incomplete =>
        case FormatResult.Failure(e: ParseException) =>
          displayMessage(
              event, "Parse error: " + e.getMessage, MessageType.ERROR)
        case FormatResult.Failure(e) =>
          displayMessage(event, e.getMessage.take(100), MessageType.ERROR)
        case FormatResult.Success(formatted) =>
          if (source != formatted) {
            ApplicationManager.getApplication.runWriteAction(new Runnable {
              override def run(): Unit = {
                CommandProcessor
                  .getInstance()
                  .runUndoTransparentAction(new Runnable {
                    override def run(): Unit =
                      fileDoc.document.setText(formatted)
                  })
              }
            })
          }
      }
    }
  }

  private def getStyle(event: AnActionEvent): ScalafmtStyle = {
    val customStyle = for {
      project <- Option(event.getData(CommonDataKeys.PROJECT))
      configFile = FileOps.getFile(project.getBasePath, ".scalafmt")
          if configFile.isFile
      style <- StyleCache.getStyleForFile(configFile.getAbsolutePath)
    } yield {
      val key = configFile.getAbsolutePath
      if (!StyleChangedCache.styleCache.get(key).contains(style)) {
        displayMessage(event,
                       "scalafmt picked up new style configuration",
                       MessageType.INFO)
        StyleChangedCache.styleCache.update(key, style)
      }
      style
    }
    customStyle.getOrElse(ScalafmtStyle.default)
  }

  private def getCurrentFileDocument(
      event: AnActionEvent): Option[FileDocument] = {
    for {
      project <- Option(event.getData(CommonDataKeys.PROJECT))
      editor <- Option(
          FileEditorManager.getInstance(project).getSelectedTextEditor)
      document <- Option(editor.getDocument)
      vfile <- Option(FileDocumentManager.getInstance().getFile(document))
    } yield FileDocument(vfile, document)
  }<commit_msg>fallback to config file in home dir<commit_after>/*
 * Original:
 * https://github.com/thesamet/scalariform-intellij-plugin/blob/8e974a2c927db35f95b710b7498d5a5dba08de5e/src/com/thesamet/intellij/ScalariformFormatAction.scala
 */
package org.scalafmt.intellij

import scala.collection.mutable
import scala.meta.parsers.ParseException

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.awt.RelativePoint
import org.scalafmt.FormatResult
import org.scalafmt.Scalafmt
import org.scalafmt.ScalafmtStyle
import org.scalafmt.cli.StyleCache
import org.scalafmt.util.FileOps

case class FileDocument(file: VirtualFile, document: Document) {
  def isScala: Boolean = file.getFileType.getName == "Scala"
}

object StyleChangedCache {
  val styleCache = mutable.Map.empty[String, ScalafmtStyle]
}

class ScalafmtAction extends AnAction {

  override def actionPerformed(event: AnActionEvent): Unit = {
    val style = getStyle(event)
    getCurrentFileDocument(event).filter(_.isScala).foreach { fileDoc =>
      val source = fileDoc.document.getText()
      Scalafmt.format(source, style = style) match {
        case _: FormatResult.Incomplete =>
        case FormatResult.Failure(e: ParseException) =>
          displayMessage(
              event, "Parse error: " + e.getMessage, MessageType.ERROR)
        case FormatResult.Failure(e) =>
          displayMessage(event, e.getMessage.take(100), MessageType.ERROR)
        case FormatResult.Success(formatted) =>
          if (source != formatted) {
            ApplicationManager.getApplication.runWriteAction(new Runnable {
              override def run(): Unit = {
                CommandProcessor
                  .getInstance()
                  .runUndoTransparentAction(new Runnable {
                    override def run(): Unit =
                      fileDoc.document.setText(formatted)
                  })
              }
            })
          }
      }
    }
  }

  private def getConfigFileInPath(path: String) = {
    val file = FileOps.getFile(path, ".scalafmt")
    if (file.isFile)
      Some(file.getAbsolutePath)
    else
      None
  }

  private val homeDir = System.getProperty("user.home")

  private def getStyle(event: AnActionEvent): ScalafmtStyle = {
    val customStyle = for {
      project <- Option(event.getData(CommonDataKeys.PROJECT))
      localConfig = getConfigFileInPath(project.getBasePath)
      globalConfig = getConfigFileInPath(homeDir)
      configFile <- localConfig orElse globalConfig
      style <- StyleCache.getStyleForFile(configFile)
    } yield {
      if (!StyleChangedCache.styleCache.get(configFile).contains(style)) {
        displayMessage(event,
                       "scalafmt picked up new style configuration",
                       MessageType.INFO)
        StyleChangedCache.styleCache.update(configFile, style)
      }
      style
    }
    customStyle.getOrElse(ScalafmtStyle.default)
  }

  private def getCurrentFileDocument(
      event: AnActionEvent): Option[FileDocument] = {
    for {
      project <- Option(event.getData(CommonDataKeys.PROJECT))
      editor <- Option(
          FileEditorManager.getInstance(project).getSelectedTextEditor)
      document <- Option(editor.getDocument)
      vfile <- Option(FileDocumentManager.getInstance().getFile(document))
    } yield FileDocument(vfile, document)
  }
{'fraction_non_alphanumeric': 0.09286833855799373, 'fraction_numerical': 0.007053291536050157, 'mean_word_length': 3.249167591564928, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 13, 'https://': 2, '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': '6739790', 'n_tokens_mistral': 2264, 'n_tokens_neox': 2199, 'n_words': 373}