From 96a6a5da09511eeae95c3bde88682907aeab78d4 Mon Sep 17 00:00:00 2001 From: Albert Meltzer <7529386+kitbellew@users.noreply.github.com> Date: Tue, 30 Nov 2021 11:07:21 -0800 Subject: [PATCH] ScalafmtSession: add formatOrError() --- .../dynamic/ScalafmtDynamicSession.scala | 3 +++ .../org/scalafmt/interfaces/ScalafmtResult.java | 16 ++++++++++++++++ .../org/scalafmt/interfaces/ScalafmtSession.java | 10 ++++++++++ 3 files changed, 29 insertions(+) create mode 100644 scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtResult.java diff --git a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala index 94cb09768b..ddc7045360 100644 --- a/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala +++ b/scalafmt-dynamic/src/main/scala/org/scalafmt/dynamic/ScalafmtDynamicSession.scala @@ -18,6 +18,9 @@ final case class ScalafmtDynamicSession( override def format(file: Path, code: String): String = tryFormat(file, code).getOrElse(code) + override def formatOrError(file: Path, code: String): ScalafmtResult = + tryFormat(file, code).fold(new ScalafmtResult(_), new ScalafmtResult(_)) + override def matchesProjectFilters(file: Path): Boolean = cfg.isIncludedInProject(file) diff --git a/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtResult.java b/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtResult.java new file mode 100644 index 0000000000..a66223f3f7 --- /dev/null +++ b/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtResult.java @@ -0,0 +1,16 @@ +package org.scalafmt.interfaces; + +public final class ScalafmtResult { + public final String value; + public final Throwable exception; + + public ScalafmtResult(String value) { + this.value = value; + this.exception = null; + } + + public ScalafmtResult(Throwable exception) { + this.exception = exception; + this.value = null; + } +} diff --git a/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtSession.java b/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtSession.java index 0b1c77fe20..a486d71d28 100644 --- a/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtSession.java +++ b/scalafmt-interfaces/src/main/java/org/scalafmt/interfaces/ScalafmtSession.java @@ -19,6 +19,16 @@ public interface ScalafmtSession { String format(Path file, String code); + /** + * Format a single file with the given configuration. + * + * @param file relative or absolute path to the file being formatted. Used only for the path + * name, the file does not have to exist on disk. + * @param code the text contents to format. + * @return the formatted contents if formatting was successful, otherwise an error. + */ + ScalafmtResult formatOrError(Path file, String code); + /** * Whether the path matches the 'project.{excludeFilters,includeFilters}' setting. * @param file path to match