dineshr93 commented on code in PR #14093:
URL: https://github.com/apache/maven/pull/14093#discussion_r4657960336
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/MavenInvoker.java:
##########
@@ -570,6 +571,14 @@ protected int doExecute(MavenContext context,
MavenExecutionRequest request) thr
context.eventSpyDispatcher.close();
}
+ context.options().sbomFile().ifPresent(file -> {
+ try {
+
SbomReportWriter.write(request.getTopDirectory().resolve(file), result);
+ } catch (IOException e) {
+ context.logger.warn("Failed to write SBOM report: " +
e.getMessage());
+ }
+ });
Review Comment:
Fixed in `2b36806`: the SBOM write is now gated by `!result.hasExceptions()`.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * component name, version and a synthesised purl. Supplier, license and hash
are
+ * omitted, never fabricated. Components are sorted by purl and the timestamp
+ * honours {@code SOURCE_DATE_EPOCH}, so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> components = new TreeMap<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ addComponent(components, project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ for (Artifact artifact : project.getArtifacts()) {
+ addComponent(components, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"sbomFormat\": \"protobom-json\",\n");
Review Comment:
Fixed in `2b36806`: output is now CycloneDX 1.6 JSON (`bomFormat`,
`specVersion`, `components`, `dependencies`) instead of `protobom-json`.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * component name, version and a synthesised purl. Supplier, license and hash
are
+ * omitted, never fabricated. Components are sorted by purl and the timestamp
+ * honours {@code SOURCE_DATE_EPOCH}, so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> components = new TreeMap<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ addComponent(components, project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ for (Artifact artifact : project.getArtifacts()) {
+ addComponent(components, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"sbomFormat\": \"protobom-json\",\n");
+ sb.append(" \"metadata\": {\n");
+ sb.append(" \"authors\": [\"Apache Maven\"],\n");
+ sb.append(" \"tools\": [\"mvn\"],\n");
+ sb.append(" \"date\": \"").append(timestamp()).append("\"\n");
+ sb.append(" },\n");
+ sb.append(" \"components\": [\n");
+ int i = 0;
+ for (String[] c : components.values()) {
+ sb.append(" {\"name\": \"").append(escape(c[0]))
+ .append("\", \"version\": \"").append(escape(c[1]))
+ .append("\", \"purl\":
\"").append(escape(c[2])).append("\"}");
+ sb.append(++i < components.size() ? ",\n" : "\n");
+ }
+ sb.append(" ]\n");
+ sb.append("}\n");
+ Files.writeString(file, sb.toString(), StandardCharsets.UTF_8);
+ }
+
+ private static void addComponent(Map<String, String[]> components, String
groupId, String artifactId, String version) {
+ if (groupId == null || artifactId == null || version == null) {
+ return;
+ }
+ String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" +
version;
+ components.putIfAbsent(purl, new String[] {artifactId, version, purl});
Review Comment:
Fixed in `2b36806`: each component now emits separate `group` and `name`;
the purl disambiguates artifacts with the same artifactId.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * component name, version and a synthesised purl. Supplier, license and hash
are
+ * omitted, never fabricated. Components are sorted by purl and the timestamp
+ * honours {@code SOURCE_DATE_EPOCH}, so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> components = new TreeMap<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ addComponent(components, project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ for (Artifact artifact : project.getArtifacts()) {
+ addComponent(components, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"sbomFormat\": \"protobom-json\",\n");
+ sb.append(" \"metadata\": {\n");
+ sb.append(" \"authors\": [\"Apache Maven\"],\n");
+ sb.append(" \"tools\": [\"mvn\"],\n");
+ sb.append(" \"date\": \"").append(timestamp()).append("\"\n");
+ sb.append(" },\n");
+ sb.append(" \"components\": [\n");
+ int i = 0;
+ for (String[] c : components.values()) {
+ sb.append(" {\"name\": \"").append(escape(c[0]))
+ .append("\", \"version\": \"").append(escape(c[1]))
+ .append("\", \"purl\":
\"").append(escape(c[2])).append("\"}");
+ sb.append(++i < components.size() ? ",\n" : "\n");
+ }
+ sb.append(" ]\n");
+ sb.append("}\n");
+ Files.writeString(file, sb.toString(), StandardCharsets.UTF_8);
+ }
+
+ private static void addComponent(Map<String, String[]> components, String
groupId, String artifactId, String version) {
+ if (groupId == null || artifactId == null || version == null) {
+ return;
+ }
+ String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" +
version;
+ components.putIfAbsent(purl, new String[] {artifactId, version, purl});
+ }
+
+ private static String timestamp() {
+ String epoch = System.getenv("SOURCE_DATE_EPOCH");
+ Instant instant = epoch != null ?
Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now();
Review Comment:
Fixed in `2b36806`: invalid `SOURCE_DATE_EPOCH` falls back to
`Instant.now()`.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * component name, version and a synthesised purl. Supplier, license and hash
are
+ * omitted, never fabricated. Components are sorted by purl and the timestamp
+ * honours {@code SOURCE_DATE_EPOCH}, so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> components = new TreeMap<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ addComponent(components, project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ for (Artifact artifact : project.getArtifacts()) {
+ addComponent(components, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"sbomFormat\": \"protobom-json\",\n");
+ sb.append(" \"metadata\": {\n");
+ sb.append(" \"authors\": [\"Apache Maven\"],\n");
+ sb.append(" \"tools\": [\"mvn\"],\n");
+ sb.append(" \"date\": \"").append(timestamp()).append("\"\n");
+ sb.append(" },\n");
+ sb.append(" \"components\": [\n");
+ int i = 0;
+ for (String[] c : components.values()) {
+ sb.append(" {\"name\": \"").append(escape(c[0]))
+ .append("\", \"version\": \"").append(escape(c[1]))
+ .append("\", \"purl\":
\"").append(escape(c[2])).append("\"}");
+ sb.append(++i < components.size() ? ",\n" : "\n");
+ }
+ sb.append(" ]\n");
+ sb.append("}\n");
+ Files.writeString(file, sb.toString(), StandardCharsets.UTF_8);
+ }
+
+ private static void addComponent(Map<String, String[]> components, String
groupId, String artifactId, String version) {
+ if (groupId == null || artifactId == null || version == null) {
+ return;
+ }
+ String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" +
version;
+ components.putIfAbsent(purl, new String[] {artifactId, version, purl});
+ }
+
+ private static String timestamp() {
+ String epoch = System.getenv("SOURCE_DATE_EPOCH");
+ Instant instant = epoch != null ?
Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now();
+ return instant.atOffset(ZoneOffset.UTC).toInstant().toString();
+ }
+
+ private static String escape(String value) {
+ return value.replace("\\", "\\\\").replace("\"", "\\\"");
+ }
Review Comment:
Fixed in `2b36806`: `escape()` now escapes control characters U+0000-U+001F.
##########
api/maven-api-cli/src/main/java/org/apache/maven/api/cli/mvn/MavenOptions.java:
##########
@@ -253,4 +253,17 @@ public interface MavenOptions extends Options {
*/
@Nonnull
Optional<Boolean> listAliases();
+
+ /**
+ * Indicates that an SBOM report should be written after the build
completes.
+ * The report is written to {@code sbom.json} in the top-level project
directory.
+ * The report lists the resolved dependencies of every built project as
protobom-style
+ * components; supplier, license and hash are omitted as Maven does not
retain them
+ * in the resolved artifact set.
+ *
+ * @return an {@link Optional} containing the report file name, or empty
if not specified
Review Comment:
Fixed in `2b36806`: Javadoc now says the report path is relative to the
top-level project directory.
##########
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/CommonsCliMavenOptionsSbomTest.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.maven.cling.invoker.mvn;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Guards the {@code --sbom} option: it takes no argument, so a following goal
must
+ * not be swallowed as its value.
+ */
+class CommonsCliMavenOptionsSbomTest {
+
+ @Test
+ void testSbomFlagDoesNotSwallowFollowingGoal() throws Exception {
+ CommonsCliMavenOptions options = CommonsCliMavenOptions.parse("test",
new String[] {"--sbom", "package"});
+
+ assertTrue(options.sbomFile().isPresent(), "sbomFile must be present");
+ assertEquals("sbom.json", options.sbomFile().get());
+ assertEquals(java.util.List.of("package"),
options.goals().orElseThrow(), "goal must survive");
+ }
+
+ @Test
+ void testSbomAbsentByDefault() throws Exception {
+ CommonsCliMavenOptions options = CommonsCliMavenOptions.parse("test",
new String[] {"package"});
+
+ assertTrue(options.sbomFile().isEmpty(), "sbomFile must be empty
without the flag");
+ }
+}
Review Comment:
Fixed in `2b36806`: added `SbomReportWriterTest`; Docker Maven tests pass
3/3.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]