This is an automated email from the ASF dual-hosted git repository.

slawrence pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/daffodil-sbt.git


The following commit(s) were added to refs/heads/main by this push:
     new 26c6262  Remove reflection from DaffodilSaver
26c6262 is described below

commit 26c626242a6b0fe4e0e9f103976d4cd5e6657615
Author: Steve Lawrence <[email protected]>
AuthorDate: Wed Nov 12 10:15:29 2025 -0500

    Remove reflection from DaffodilSaver
    
    The reflection code is messy and hard to maintain. This also is no
    longer the recommended way to create tools that support multiple
    versions of Daffodil--instead we should use sbt-projectmatrix to create
    separate jars with thin shim layers to deal with differences in Daffodil
    APIs.
    
    This commit does just that. We change our build.sbt to add a new "utils"
    subproject that contains code that needs cross Daffodil support. This
    subproject uses sbt-projectmatrix to build three jars, one for Scala
    2.12, 2.13, and 3, which are mapped to the various Daffodil versions.
    This appropriate jar is added as a libraryDependency along with the
    Daffodil version.
    
    DaffodilSaver is moved into this util subproject and rewritten in Scala.
    Scala type inference and similarites in the API in different versions of
    Daffodil allow this code to mostly not need to know anything about the
    Daffodil version being used. In cases where that is needed, we use a new
    DaffodilAPI shim class that provides type alases or helper functions
    that are Scala/Daffodil version speciic.
    
    Closes #135
---
 NOTICE                                             |   2 +-
 build.sbt                                          | 154 ++++++++++-----
 project/plugins.sbt                                |   2 +
 .../java/org/apache/daffodil/DaffodilSaver.java    | 209 ---------------------
 src/main/resources/META-INF/NOTICE                 |   2 +-
 .../scala/org/apache/daffodil/DaffodilPlugin.scala |  42 +++--
 utils/src/main/resources/META-INF/LICENSE          | 202 ++++++++++++++++++++
 NOTICE => utils/src/main/resources/META-INF/NOTICE |   2 +-
 .../scala-2/org/apache/daffodil/DaffodilAPI.scala  |  12 +-
 .../scala-3/org/apache/daffodil/DaffodilAPI.scala  |  12 +-
 .../scala/org/apache/daffodil/DaffodilSaver.scala  | 108 +++++++++++
 11 files changed, 469 insertions(+), 278 deletions(-)

diff --git a/NOTICE b/NOTICE
index 299bf27..ab8017b 100644
--- a/NOTICE
+++ b/NOTICE
@@ -1,5 +1,5 @@
 Apache Daffodil SBT Plugin
-Copyright 2024 The Apache Software Foundation
+Copyright 2025 The Apache Software Foundation
 
 This product includes software developed at
 The Apache Software Foundation (http://www.apache.org/).
diff --git a/build.sbt b/build.sbt
index 5bf37dc..122435a 100644
--- a/build.sbt
+++ b/build.sbt
@@ -15,53 +15,115 @@
  * limitations under the License.
  */
 
-name := "sbt-daffodil"
-
-organization := "org.apache.daffodil"
-
-version := IO.read((ThisBuild / baseDirectory).value / "VERSION").trim
-
-scalaVersion := "2.12.19"
-
-scalacOptions ++= Seq(
-  "-Ywarn-unused:imports"
+val commonSettings = Seq(
+  organization := "org.apache.daffodil",
+  version := IO.read((ThisBuild / baseDirectory).value / "VERSION").trim,
+  scalacOptions ++= {
+    scalaBinaryVersion.value match {
+      case "2.12" | "2.13" =>
+        Seq(
+          "-Werror",
+          "-Ywarn-unused:imports"
+        )
+      case "3" =>
+        Seq(
+          "-no-indent",
+          "-Werror",
+          "-Wunused:imports"
+        )
+    }
+  },
+  scmInfo := Some(
+    ScmInfo(
+      browseUrl = url("https://github.com/apache/daffodil-sbt";),
+      connection = "scm:git:https://github.com/apache/daffodil-sbt";
+    )
+  ),
+  licenses := Seq(License.Apache2),
+  homepage := Some(url("https://daffodil.apache.org";)),
+  releaseNotesURL := 
Some(url(s"https://daffodil.apache.org/sbt/${version.value}/";))
 )
 
-scmInfo := Some(
-  ScmInfo(
-    browseUrl = url("https://github.com/apache/daffodil-sbt";),
-    connection = "scm:git:https://github.com/apache/daffodil-sbt";
+lazy val plugin = (project in file("."))
+  .settings(commonSettings)
+  .settings(
+    name := "sbt-daffodil",
+
+    // SBT plugin settings
+    scalaVersion := "2.12.19",
+    crossSbtVersions := Seq("1.8.0"),
+    scriptedLaunchOpts ++= Seq(
+      "-Xmx1024M",
+      "-Dplugin.version=" + version.value
+    ),
+    scriptedDependencies := {
+      // scripted runs publishLocal for the plugin and its dependencies as 
part of the
+      // scriptedDependencies task. But the utils subprojects aren't actually 
dependencies (so
+      // won't be locally published). We still need the util jars locally 
published so the
+      // scripted tests can find the jars at runtime, so we manually run 
publishLocal for each
+      // of the utils subprojects as part of the scriptedDependencies task
+      publishLocal.all(ScopeFilter(projects = inProjects(utils.projectRefs: 
_*))).value
+      scriptedDependencies.value
+    },
+    Test / test := {
+      // run all scripted tasks as part of testing
+      (Compile / scripted).toTask("").value
+      (Test / test).value
+    },
+
+    // Rat check settings
+    ratExcludes := Seq(
+      file(".git"),
+      file("VERSION")
+    ),
+    ratFailBinaries := true
   )
-)
-
-licenses := Seq(License.Apache2)
-
-homepage := Some(url("https://daffodil.apache.org";))
-
-releaseNotesURL := 
Some(url(s"https://daffodil.apache.org/sbt/${version.value}/";))
-
-// SBT Plugin settings
-
-enablePlugins(SbtPlugin)
+  .enablePlugins(SbtPlugin)
+  .aggregate(utils.projectRefs: _*)
 
-crossSbtVersions := Seq("1.8.0")
-
-scriptedLaunchOpts ++= Seq(
-  "-Xmx1024M",
-  "-Dplugin.version=" + version.value
-)
-
-// Rat check settings
-
-ratExcludes := Seq(
-  file(".git"),
-  file("VERSION")
-)
-
-ratFailBinaries := true
-
-Test / test := {
-  // run all scripted tasks as part of testing
-  (Compile / scripted).toTask("").value
-  (Test / test).value
-}
+lazy val utils = (projectMatrix in file("utils"))
+  .settings(commonSettings)
+  .settings(
+    name := "sbt-daffodil-utils"
+  )
+  .settings(
+    javacOptions ++= {
+      scalaBinaryVersion.value match {
+        case "2.12" => Seq("-target", "8")
+        case "2.13" => Seq("-target", "8")
+        case "3" => Seq("-target", "17")
+      }
+    },
+    scalacOptions ++= {
+      scalaBinaryVersion.value match {
+        case "2.12" => Seq(s"--target:jvm-8")
+        case "2.13" => Seq(s"--release", "8")
+        case "3" => Seq(s"--release", "17")
+      }
+    },
+    libraryDependencies ++= {
+      scalaBinaryVersion.value match {
+        case "2.12" => {
+          Seq(
+            // scala-steward:off
+            "org.apache.daffodil" %% "daffodil-japi" % "3.10.0" % "provided",
+            // scala-steward:on
+            "org.scala-lang.modules" %% "scala-collection-compat" % "2.14.0"
+          )
+        }
+        case "2.13" => {
+          Seq(
+            // scala-steward:off
+            "org.apache.daffodil" %% "daffodil-japi" % "3.11.0" % "provided"
+            // scala-steward:on
+          )
+        }
+        case "3" => {
+          Seq(
+            "org.apache.daffodil" %% "daffodil-core" % "4.0.0" % "provided"
+          )
+        }
+      }
+    }
+  )
+  .jvmPlatform(scalaVersions = Seq("2.12.20", "2.13.16", "3.3.6"))
diff --git a/project/plugins.sbt b/project/plugins.sbt
index 2456b0a..6c4c432 100644
--- a/project/plugins.sbt
+++ b/project/plugins.sbt
@@ -18,3 +18,5 @@
 addSbtPlugin("org.musigma" % "sbt-rat" % "0.7.0")
 
 addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.4")
+
+addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.11.0")
diff --git a/src/main/java/org/apache/daffodil/DaffodilSaver.java 
b/src/main/java/org/apache/daffodil/DaffodilSaver.java
deleted file mode 100644
index 03e9a06..0000000
--- a/src/main/java/org/apache/daffodil/DaffodilSaver.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.daffodil;
-
-import java.lang.reflect.Method;
-import java.nio.channels.FileChannel;
-import java.nio.channels.WritableByteChannel;
-import java.nio.file.Paths;
-import java.nio.file.StandardOpenOption;
-import java.net.URI;
-import java.net.URL;
-import java.util.List;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.DocumentBuilder;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Node;
-
-// We need a special customized classpath, and the easiest way to do that 
within SBT is by
-// forking. But the only thing that can save a parser via forking is the 
Daffodil CLI, which we
-// do not publish. So instead we create this class that has a static main that 
we can fork to
-// compile and save schemas using the version of Daffodil that is on the 
classpath. Note that it
-// also uses reflection so that it is not tied to any specific version of 
Daffodil. This is
-// fragile, but the Daffodil Jave API is pretty set in stone at this point, so 
this reflection
-// shouldn't break. We also write this in Java so it is not tied to a specific 
Scala version,
-// since different versions of Daffodil use different versions of Scala.
-public class DaffodilSaver {
-
-  /**
-   * Usage: daffodilSaver <apiVersion> <schemaResource> <outputFile> <root> 
<config>
-   *
-   * If <root> or <config> is unknown/not-provided, they must be the empty 
string
-   */
-  public static void main(String[] args) {
-    try {
-      run(args);
-    } catch (Exception e) {
-      e.printStackTrace();
-      System.exit(1);
-    }
-  }
-
-  private static void run(String[] args) throws Exception {
-    assert args.length == 5 : "DaffodilPlugin did not provide the correct 
number of arguments when forking DaffodilSaver";
-
-    // the "version" of the Daffodil API to use. Note that this is not the 
same as the Daffodil
-    // version, but is related. See the "daffodilInternalAPIVersionMapping" in 
the plugin code
-    // for an explanation of why we have this and what version of Daffodil it 
represents.
-    int apiVersion = Integer.parseInt(args[0]);
-
-    String schemaResource = args[1];
-    URL schemaUrl = DaffodilSaver.class.getResource(schemaResource);
-    if (schemaUrl == null) {
-      System.err.println("failed to find schema resource: " + schemaResource);
-      System.exit(1);
-    }
-
-    WritableByteChannel output = FileChannel.open(
-      Paths.get(args[2]),
-      StandardOpenOption.CREATE,
-      StandardOpenOption.WRITE);
-    String root = !args[3].isEmpty() ? args[3] : null;
-    String config = !args[4].isEmpty() ? args[4] : null;
-
-    // parameter types
-    Class<?> cURI = URI.class;
-    Class<?> cString = String.class;
-    Class<?> cWritableByteChannel = WritableByteChannel.class;
-
-    String baseApiPackage = null;
-    switch (apiVersion) {
-      case 1:
-      case 2:
-        baseApiPackage = "org.apache.daffodil.japi";
-        break;
-      case 3:
-        baseApiPackage = "org.apache.daffodil.api";
-        break;
-    }
-
-    // get the Compiler, ProcessorFactory, and DataProcessor classes and the 
functions we need
-    // to invoke on those classes. Note that we use JAPI because its easier to 
use via
-    // reflection than the Scala API and it is much smaller and easier to use 
than the lib API
-    Class<?> daffodilClass = Class.forName(baseApiPackage + ".Daffodil");
-    Method daffodilCompiler = daffodilClass.getMethod("compiler");
-
-    Class<?> compilerClass = Class.forName(baseApiPackage + ".Compiler");
-    Method compilerWithTunable = compilerClass.getMethod("withTunable", 
cString, cString);
-    // the compileResource method added in Daffodil 3.9.0 allows for 
depersonalized diagnostics
-    // and better reproducibility of saved parsers--use it instead of 
compileSource for newer
-    // versions of Daffodil
-    Method compilerCompile = null;
-    switch (apiVersion) {
-      case 1:
-        compilerCompile = compilerClass.getMethod("compileSource", cURI, 
cString, cString);
-        break;
-      case 2:
-      case 3:
-        compilerCompile = compilerClass.getMethod("compileResource", cString, 
cString, cString);
-        break;
-    }
-
-    Class<?> processorFactoryClass = Class.forName(baseApiPackage + 
".ProcessorFactory");
-    Method processorFactoryIsError = 
processorFactoryClass.getMethod("isError");
-    Method processorFactoryOnPath = processorFactoryClass.getMethod("onPath", 
cString);
-    Method processorFactoryGetDiagnostics = 
processorFactoryClass.getMethod("getDiagnostics");
-
-    Class<?> dataProcessorClass = Class.forName(baseApiPackage + 
".DataProcessor");
-    Method dataProcessorIsError = dataProcessorClass.getMethod("isError");
-    Method dataProcessorSave = dataProcessorClass.getMethod("save", 
cWritableByteChannel);
-    Method dataProcessorGetDiagnostics = 
processorFactoryClass.getMethod("getDiagnostics");
-
-    Class<?> diagnosticClass = Class.forName(baseApiPackage + ".Diagnostic");
-    Method diagnosticIsError = diagnosticClass.getMethod("isError");
-    Method diagnosticToString = diagnosticClass.getMethod("toString");
-
-    // val compiler = Daffodil.compiler()
-    Object compiler = daffodilCompiler.invoke(null);
-
-    // compiler = compiler.withTunable(...)
-    if (config != null) {
-      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-      factory.setNamespaceAware(true);
-      DocumentBuilder builder = factory.newDocumentBuilder();
-      Document document = builder.parse(config);
-      NodeList tunables = 
document.getElementsByTagNameNS("urn:ogf:dfdl:2013:imp:daffodil.apache.org:2018:ext",
 "tunables");
-      for (int i = 0; i < tunables.getLength(); i++) {
-        Node tunablesNode = tunables.item(i);
-        NodeList children = tunablesNode.getChildNodes();
-        for (int j = 0; j < children.getLength(); j++) {
-          Node node = children.item(j);
-          if (node.getNodeType() != Node.ELEMENT_NODE) {
-            // ignore text nodes
-            continue;
-          }
-          compiler = compilerWithTunable.invoke(compiler, node.getLocalName(), 
node.getTextContent().trim());
-        }
-      }
-    }
-
-    // val processorFactory = compiler.compileSource(schemaUrl.toURI, root, 
None)  // < 3.9.0
-    // val processorFactory = compiler.compileResource(name, root, None)       
// >= 3.9.0
-    Object schemaArg = null;
-    switch (apiVersion) {
-      case 1:
-        schemaArg = schemaUrl.toURI();
-        break;
-      case 2:
-      case 3:
-        schemaArg = schemaResource;
-        break;
-    }
-    Object processorFactory = compilerCompile.invoke(compiler, schemaArg, 
root, null);
-
-    // val processorFactoryDiags = processorFactory.getDiagnostics()
-    List<?> processorFactoryDiags = (List<?>) 
processorFactoryGetDiagnostics.invoke(processorFactory);
-    printDiagnostics(processorFactoryDiags, diagnosticClass, 
diagnosticIsError, diagnosticToString);
-
-    // if (processorFactory.isError) System.exit(1)
-    if ((boolean) processorFactoryIsError.invoke(processorFactory)) 
System.exit(1);
-
-    // val dataProcessor = processorFactory.onPath("/")
-    Object dataProcessor = processorFactoryOnPath.invoke(processorFactory, 
"/");
-
-    // val dataProcessorDiags = dataProcessor.getDiagnostics()
-    List<?> dataProcessorDiags = (List<?>) 
dataProcessorGetDiagnostics.invoke(dataProcessor);
-    printDiagnostics(dataProcessorDiags, diagnosticClass, diagnosticIsError, 
diagnosticToString);
-
-    // if (dataProcessor.isError) System.exit(1)
-    if ((boolean) dataProcessorIsError.invoke(dataProcessor)) System.exit(1);
-
-    // dataProcessor.save(output)
-    dataProcessorSave.invoke(dataProcessor, output);
-
-    System.exit(0);
-  }
-
-
-  static private void printDiagnostics(List<?> diags,
-      Class<?> diagnosticClass,
-      Method diagnosticIsError,
-      Method diagnosticToString) throws Exception {
-
-    for (Object d : diags) {
-      String msg = (String) diagnosticToString.invoke(d);
-      boolean isError = (boolean) diagnosticIsError.invoke(d);
-      String level = isError ? "error" : "warning";
-      System.err.println("[" + level + "] " + msg);
-    }
-  }
-
-}
diff --git a/src/main/resources/META-INF/NOTICE 
b/src/main/resources/META-INF/NOTICE
index 299bf27..ab8017b 100644
--- a/src/main/resources/META-INF/NOTICE
+++ b/src/main/resources/META-INF/NOTICE
@@ -1,5 +1,5 @@
 Apache Daffodil SBT Plugin
-Copyright 2024 The Apache Software Foundation
+Copyright 2025 The Apache Software Foundation
 
 This product includes software developed at
 The Apache Software Foundation (http://www.apache.org/).
diff --git a/src/main/scala/org/apache/daffodil/DaffodilPlugin.scala 
b/src/main/scala/org/apache/daffodil/DaffodilPlugin.scala
index 823b9c8..fe6f7ad 100644
--- a/src/main/scala/org/apache/daffodil/DaffodilPlugin.scala
+++ b/src/main/scala/org/apache/daffodil/DaffodilPlugin.scala
@@ -101,6 +101,8 @@ object DaffodilPlugin extends AutoPlugin {
     }
   }
 
+  val sbtDaffodilPluginVersion = 
this.getClass.getPackage.getImplementationVersion()
+
   /**
    * With the way SemanticVersion works by default it treats SNAPSHOT versions
    * as less than non-SNAPSHOT versions, ie 4.0.0-SNAPSHOT < 4.0.0.  That makes
@@ -450,9 +452,18 @@ object DaffodilPlugin extends AutoPlugin {
         // the Daffodil dependency must ignore the scalaVersion setting and 
instead use
         // the specific version of scala used for the binDaffodilVersion.
         val daffodilToPackageBinDep = Map(
-          ">=4.0.0 " -> "org.apache.daffodil" % "daffodil-core_3" % 
binDaffodilVersion % cfg,
-          "=3.11.0 " -> "org.apache.daffodil" % "daffodil-japi_2.13" % 
binDaffodilVersion % cfg,
-          "<=3.10.0 " -> "org.apache.daffodil" % "daffodil-japi_2.12" % 
binDaffodilVersion % cfg
+          ">=4.0.0 " -> Seq(
+            "org.apache.daffodil" % "daffodil-core_3" % binDaffodilVersion % 
cfg,
+            "org.apache.daffodil" % "sbt-daffodil-utils_3" % 
sbtDaffodilPluginVersion % cfg
+          ),
+          "=3.11.0 " -> Seq(
+            "org.apache.daffodil" % "daffodil-japi_2.13" % binDaffodilVersion 
% cfg,
+            "org.apache.daffodil" % "sbt-daffodil-utils_2.13" % 
sbtDaffodilPluginVersion % cfg
+          ),
+          "<=3.10.0" -> Seq(
+            "org.apache.daffodil" % "daffodil-japi_2.12" % binDaffodilVersion 
% cfg,
+            "org.apache.daffodil" % "sbt-daffodil-utils_2.12" % 
sbtDaffodilPluginVersion % cfg
+          )
         )
         val dafDep = filterVersions(binDaffodilVersion, 
daffodilToPackageBinDep).head
         // Add logging backends used when packageDaffodilBin outputs log 
messages
@@ -461,7 +472,7 @@ object DaffodilPlugin extends AutoPlugin {
           "<3.5.0" -> "org.apache.logging.log4j" % "log4j-core" % "2.20.0" % 
cfg
         )
         val logDep = filterVersions(binDaffodilVersion, 
daffodilToLogDependency).head
-        Seq(dafDep, logDep)
+        dafDep :+ logDep
       }.toSeq
     },
 
@@ -493,15 +504,10 @@ object DaffodilPlugin extends AutoPlugin {
       // options to provide to the forked JVM process used to save a processor
       val jvmArgs = (packageDaffodilBin / javaOptions).value
 
-      // this plugin jar includes a forkable main class that does the actual 
schema compilation
-      // and saving.
-      val pluginJar =
-        new 
File(this.getClass.getProtectionDomain.getCodeSource.getLocation.toURI)
-
       // get all dependencies and resources of this project
       val projectClasspath = (Compile / fullClasspath).value.files
 
-      val mainClass = classOf[DaffodilSaver].getCanonicalName
+      val mainClass = "org.apache.daffodil.DaffodilSaver"
 
       // schema compilation can be expensive, so we only want to fork and 
compile the schema if
       // any of the project classpath files change
@@ -539,8 +545,10 @@ object DaffodilPlugin extends AutoPlugin {
           // Note that order matters here. The projectClasspath might have 
daffodil jars on it if
           // Daffodil is a compile dependency, which could be a different 
version from the version
           // of Daffodil we are compiling the schema for. So when we fork 
Java, daffodilJars must be
-          // on the classpath before projectClasspath jars
-          val classpathFiles = Seq(pluginJar) ++ daffodilJars ++ 
projectClasspath
+          // on the classpath before projectClasspath jars. Also note that 
daffodilJars
+          // includes both the Daffodil jars and the sbt-daffodil-utils jar 
that contains the
+          // DaffodilSaver we are going to fork
+          val classpathFiles = daffodilJars ++ projectClasspath
 
           daffodilPackageBinInfos.value.map { dbi =>
             val classifier = classifierName(dbi.name, daffodilVersion)
@@ -559,11 +567,13 @@ object DaffodilPlugin extends AutoPlugin {
             // SBT libraries on the classpath, so it can't easily use the 
SemanticVersion to
             // compare versions. So we map each Daffodil version to an 
"internal API" version,
             // which is just a simple number that is easier to use in the 
Saver and signify
-            // where API functions to use. This is the mapping for which 
Daffodil API should be
-            // used for a particular "internal API"
+            // which API functions to use. This is the mapping for which 
Daffodil API should be
+            // used for a particular "internal API". Note that the 
DaffodilSaver uses
+            // sbt-projectmagic to handle changes to Daffodil package 
namespaces, so this
+            // doesn't need different numbers for those. It's only really 
needed when we want to
+            // use new API functions that aren't available with older verisons 
of Daffodil.
             val daffodilInternalApiVersionMapping = Map(
-              ">=4.0.0" -> "3",
-              ">=3.9.0 <=3.11.0" -> "2",
+              ">=3.9.0" -> "2",
               "<=3.8.0" -> "1"
             )
             val internalApiVersion =
diff --git a/utils/src/main/resources/META-INF/LICENSE 
b/utils/src/main/resources/META-INF/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/utils/src/main/resources/META-INF/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/NOTICE b/utils/src/main/resources/META-INF/NOTICE
similarity index 73%
copy from NOTICE
copy to utils/src/main/resources/META-INF/NOTICE
index 299bf27..ab8017b 100644
--- a/NOTICE
+++ b/utils/src/main/resources/META-INF/NOTICE
@@ -1,5 +1,5 @@
 Apache Daffodil SBT Plugin
-Copyright 2024 The Apache Software Foundation
+Copyright 2025 The Apache Software Foundation
 
 This product includes software developed at
 The Apache Software Foundation (http://www.apache.org/).
diff --git a/project/plugins.sbt 
b/utils/src/main/scala-2/org/apache/daffodil/DaffodilAPI.scala
similarity index 71%
copy from project/plugins.sbt
copy to utils/src/main/scala-2/org/apache/daffodil/DaffodilAPI.scala
index 2456b0a..057bd9b 100644
--- a/project/plugins.sbt
+++ b/utils/src/main/scala-2/org/apache/daffodil/DaffodilAPI.scala
@@ -15,6 +15,14 @@
  * limitations under the License.
  */
 
-addSbtPlugin("org.musigma" % "sbt-rat" % "0.7.0")
+package org.apache.daffodil
 
-addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.4")
+/**
+ * Defines type aliases and helper functions used by our plugin utilties to 
provide
+ * compatability with Scala 2.x and Daffodil 3.x
+ */
+object DaffodilAPI {
+  type Diagnostic = org.apache.daffodil.japi.Diagnostic
+
+  def compiler() = org.apache.daffodil.japi.Daffodil.compiler()
+}
diff --git a/project/plugins.sbt 
b/utils/src/main/scala-3/org/apache/daffodil/DaffodilAPI.scala
similarity index 72%
copy from project/plugins.sbt
copy to utils/src/main/scala-3/org/apache/daffodil/DaffodilAPI.scala
index 2456b0a..05c1c69 100644
--- a/project/plugins.sbt
+++ b/utils/src/main/scala-3/org/apache/daffodil/DaffodilAPI.scala
@@ -15,6 +15,14 @@
  * limitations under the License.
  */
 
-addSbtPlugin("org.musigma" % "sbt-rat" % "0.7.0")
+package org.apache.daffodil
 
-addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.4")
+/**
+ * Defines type aliases and helper functions used by our plugin utilties to 
provide
+ * compatability with Scala 3.x and Daffodil 4.x
+ */
+object DaffodilAPI {
+  type Diagnostic = org.apache.daffodil.api.Diagnostic
+
+  def compiler() = org.apache.daffodil.api.Daffodil.compiler()
+}
diff --git a/utils/src/main/scala/org/apache/daffodil/DaffodilSaver.scala 
b/utils/src/main/scala/org/apache/daffodil/DaffodilSaver.scala
new file mode 100644
index 0000000..bce8e06
--- /dev/null
+++ b/utils/src/main/scala/org/apache/daffodil/DaffodilSaver.scala
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License") you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.daffodil
+
+import java.nio.channels.FileChannel
+import java.nio.file.Paths
+import java.nio.file.StandardOpenOption
+import scala.jdk.CollectionConverters._
+
+// When creating saved parsers using packageDaffodilBin, we need to create a 
saved parser for a
+// different version of Daffodil than is added to libraryDependencies. For 
this reason, we have
+// this DaffodilSaver class, which can be forked with a Different versionof 
Daffodil on the
+// classpath. Note that we use sbt-projectmatrix to compile this class into 
three separate jars
+// for each version of Scala/Daffodil (Scala 2.12 is used for Daffodil 3.10.0 
and older, Scala
+// 2.13 is used for Daffodil 3.11.0, and Scala 3.x is used for Daffodil 4.0.0 
and newer. WWe
+// expect the sbt plugin to set up the classpath to include the correct jar 
for the version of
+// Daffodil being used when forking this class.
+object DaffodilSaver {
+
+  /**
+   * Usage: daffodilSaver <apiVersion> <schemaResource> <outputFile> <root> 
<config>
+   *
+   * If <root> or <config> is unknown/not-provided, they must be the empty 
string
+   */
+  def main(args: Array[String]): Unit = {
+
+    if (args.length != 5) {
+      throw new Exception(
+        "DaffodilPlugin did not provide the correct number of arguments when 
forking DaffodilSaver"
+      )
+    }
+
+    // the "version" of the Daffodil API to use. Note that this is not the 
same as the Daffodil
+    // version, but is related. See the "daffodilInternalAPIVersionMapping" in 
the plugin code
+    // for an explanation of why we have this and what version of Daffodil it 
represents.
+    val apiVersion = Integer.parseInt(args(0))
+
+    val schemaResource = args(1)
+    val schemaUrl = this.getClass.getResource(schemaResource)
+    if (schemaUrl == null) {
+      System.err.println("failed to find schema resource: " + schemaResource)
+      System.exit(1)
+    }
+
+    val output =
+      FileChannel.open(Paths.get(args(2)), StandardOpenOption.CREATE, 
StandardOpenOption.WRITE)
+    val root = if (!args(3).isEmpty()) args(3) else null
+    val config = if (!args(4).isEmpty()) args(4) else null
+
+    val tunables =
+      if (config != null) {
+        val configXml = scala.xml.Utility.trim(scala.xml.XML.loadFile(config))
+        (configXml \ "tunables").flatMap { tunablesNode =>
+          tunablesNode.child.map { node => (node.label, node.text) }
+        }.toMap
+      } else {
+        Map.empty[String, String]
+      }
+    val jTunables = new java.util.HashMap[String, String](tunables.asJava)
+
+    val compiler = DaffodilAPI
+      .compiler()
+      .withTunables(jTunables)
+
+    val processorFactory = apiVersion match {
+      case 1 => compiler.compileSource(schemaUrl.toURI, root, null)
+      case 2 => compiler.compileResource(schemaResource, root, null)
+    }
+    if (processorFactory.isError()) {
+      printDiagnostics(processorFactory.getDiagnostics.asScala.toSeq)
+      System.exit(1)
+    }
+
+    val dataProcessor = processorFactory.onPath("/")
+    if (dataProcessor.isError()) {
+      printDiagnostics(dataProcessor.getDiagnostics.asScala.toSeq)
+      System.exit(1)
+    }
+
+    // print warning diagnostics if they exist
+    printDiagnostics(dataProcessor.getDiagnostics.asScala.toSeq)
+
+    dataProcessor.save(output)
+  }
+
+  private def printDiagnostics(diags: Seq[DaffodilAPI.Diagnostic]): Unit = {
+    diags.foreach { d =>
+      val msg = d.toString()
+      val level = if (d.isError) "error" else "warning"
+      System.err.println(s"[$level] $msg")
+    }
+  }
+}


Reply via email to