Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ public void execute(String... args) {
.addSubcommand("source", new CommandLine(new CamelSourceTop(this))))
.addSubcommand("trace", new CommandLine(new CamelTraceAction(this)))
.addSubcommand("transform", new CommandLine(new TransformCommand(this))
.addSubcommand("dataweave", new CommandLine(new TransformDataWeave(this)))
.addSubcommand("message", new CommandLine(new TransformMessageAction(this)))
.addSubcommand("route", new CommandLine(new TransformRoute(this))))
.addSubcommand("update", new CommandLine(new UpdateCommand(this))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* 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.camel.dsl.jbang.core.commands;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import org.apache.camel.dsl.jbang.core.commands.transform.DataWeaveConverter;
import picocli.CommandLine;
import picocli.CommandLine.Command;

@Command(name = "dataweave",
description = "Convert DataWeave scripts to DataSonnet format",
sortOptions = false, showDefaultValues = true)
public class TransformDataWeave extends CamelCommand {

@CommandLine.Option(names = { "--input", "-i" },
description = "Input .dwl file or directory containing .dwl files")
private String input;

@CommandLine.Option(names = { "--output", "-o" },
description = "Output .ds file or directory (defaults to stdout)")
private String output;

@CommandLine.Option(names = { "--expression", "-e" },
description = "Inline DataWeave expression to convert")
private String expression;

@CommandLine.Option(names = { "--include-comments" }, defaultValue = "true",
description = "Include conversion notes as comments in output")
private boolean includeComments = true;

public TransformDataWeave(CamelJBangMain main) {
super(main);
}

@Override
public Integer doCall() throws Exception {
if (expression != null) {
return convertExpression();
}
if (input != null) {
return convertFiles();
}

printer().println("Error: either --input or --expression must be specified");
return 1;
}

private int convertExpression() {
DataWeaveConverter converter = new DataWeaveConverter();
converter.setIncludeComments(includeComments);

String result;
if (expression.contains("%dw") || expression.contains("---")) {
result = converter.convert(expression);
} else {
result = converter.convertExpression(expression);
}

printer().println(result);
printSummary(converter, 1);
return converter.getTodoCount() > 0 ? 1 : 0;
}

private int convertFiles() throws IOException {
Path inputPath = Path.of(input);
if (!Files.exists(inputPath)) {
printer().println("Error: input path does not exist: " + input);
return 1;
}

List<Path> dwlFiles = new ArrayList<>();
if (Files.isDirectory(inputPath)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(inputPath, "*.dwl")) {
for (Path entry : stream) {
dwlFiles.add(entry);
}
}
if (dwlFiles.isEmpty()) {
printer().println("No .dwl files found in: " + input);
return 1;
}
} else {
dwlFiles.add(inputPath);
}

int totalTodos = 0;
int totalConverted = 0;

for (Path dwlFile : dwlFiles) {
DataWeaveConverter converter = new DataWeaveConverter();
converter.setIncludeComments(includeComments);

String dwContent = Files.readString(dwlFile);
String dsContent = converter.convert(dwContent);

totalTodos += converter.getTodoCount();
totalConverted += converter.getConvertedCount();

if (output != null) {
Path outputPath = resolveOutputPath(dwlFile, Path.of(output));
Files.createDirectories(outputPath.getParent());
Files.writeString(outputPath, dsContent);
printer().println("Converted: " + dwlFile + " -> " + outputPath);
} else {
if (dwlFiles.size() > 1) {
printer().println("// === " + dwlFile.getFileName() + " ===");
}
printer().println(dsContent);
}
}

printSummary(totalConverted, totalTodos, dwlFiles.size());
return totalTodos > 0 ? 1 : 0;
}

private Path resolveOutputPath(Path dwlFile, Path outputPath) {
String dsFileName = dwlFile.getFileName().toString().replaceFirst("\\.dwl$", ".ds");
if (Files.isDirectory(outputPath) || output.endsWith("/")) {
return outputPath.resolve(dsFileName);
}
// Single file output
return outputPath;
}

private void printSummary(DataWeaveConverter converter, int fileCount) {
printSummary(converter.getConvertedCount(), converter.getTodoCount(), fileCount);
}

private void printSummary(int converted, int todos, int fileCount) {
StringBuilder sb = new StringBuilder();
sb.append("\n");
if (fileCount > 1) {
sb.append("Files: ").append(fileCount).append(", ");
}
sb.append("Converted: ").append(converted).append(" expressions");
if (todos > 0) {
sb.append(", ").append(todos).append(" require manual review");
}
printer().printErr(sb.toString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/*
* 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.camel.dsl.jbang.core.commands.transform;

import java.util.List;

/**
* AST node types for DataWeave 2.0 expressions.
*/
public sealed interface DataWeaveAst {

record Script(Header header, DataWeaveAst body) implements DataWeaveAst {
}

record Header(String version, String outputType, List<InputDecl> inputs) implements DataWeaveAst {
}

record InputDecl(String name, String mediaType) implements DataWeaveAst {
}

// Literals
record StringLit(String value, boolean singleQuoted) implements DataWeaveAst {
}

record NumberLit(String value) implements DataWeaveAst {
}

record BooleanLit(boolean value) implements DataWeaveAst {
}

record NullLit() implements DataWeaveAst {
}

// Expressions
record Identifier(String name) implements DataWeaveAst {
}

record FieldAccess(DataWeaveAst object, String field) implements DataWeaveAst {
}

record IndexAccess(DataWeaveAst object, DataWeaveAst index) implements DataWeaveAst {
}

record MultiValueSelector(DataWeaveAst object, String field) implements DataWeaveAst {
}

record ObjectLit(List<ObjectEntry> entries) implements DataWeaveAst {
}

record ObjectEntry(DataWeaveAst key, DataWeaveAst value, boolean dynamic) implements DataWeaveAst {
}

record ArrayLit(List<DataWeaveAst> elements) implements DataWeaveAst {
}

record BinaryOp(String op, DataWeaveAst left, DataWeaveAst right) implements DataWeaveAst {
}

record UnaryOp(String op, DataWeaveAst operand) implements DataWeaveAst {
}

record IfElse(DataWeaveAst condition, DataWeaveAst thenExpr, DataWeaveAst elseExpr) implements DataWeaveAst {
}

record DefaultExpr(DataWeaveAst expr, DataWeaveAst fallback) implements DataWeaveAst {
}

record TypeCoercion(DataWeaveAst expr, String type, String format) implements DataWeaveAst {
}

record FunctionCall(String name, List<DataWeaveAst> args) implements DataWeaveAst {
}

record Lambda(List<LambdaParam> params, DataWeaveAst body) implements DataWeaveAst {
}

record LambdaParam(String name, DataWeaveAst defaultValue) implements DataWeaveAst {
}

record LambdaShorthand(List<String> fields) implements DataWeaveAst {
}

// Collection operations
record MapExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

record FilterExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

record ReduceExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

record FlatMapExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

record DistinctByExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

record GroupByExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

record OrderByExpr(DataWeaveAst collection, DataWeaveAst lambda) implements DataWeaveAst {
}

// String postfix operations
record ContainsExpr(DataWeaveAst string, DataWeaveAst substring) implements DataWeaveAst {
}

record StartsWithExpr(DataWeaveAst string, DataWeaveAst prefix) implements DataWeaveAst {
}

record EndsWithExpr(DataWeaveAst string, DataWeaveAst suffix) implements DataWeaveAst {
}

record SplitByExpr(DataWeaveAst string, DataWeaveAst separator) implements DataWeaveAst {
}

record JoinByExpr(DataWeaveAst array, DataWeaveAst separator) implements DataWeaveAst {
}

record ReplaceExpr(DataWeaveAst string, DataWeaveAst target, DataWeaveAst replacement) implements DataWeaveAst {
}

// Variable and function declarations
record VarDecl(String name, DataWeaveAst value, DataWeaveAst body) implements DataWeaveAst {
}

record FunDecl(String name, List<String> params, DataWeaveAst funBody, DataWeaveAst next) implements DataWeaveAst {
}

// Match expression
record MatchExpr(DataWeaveAst expr, String originalText) implements DataWeaveAst {
}

// Type check
record TypeCheck(DataWeaveAst expr, String type) implements DataWeaveAst {
}

// Unsupported construct (kept as raw text)
record Unsupported(String originalText, String reason) implements DataWeaveAst {
}

// Parenthesized expression (for preserving grouping)
record Parens(DataWeaveAst expr) implements DataWeaveAst {
}

// Block of local declarations followed by an expression
record Block(List<DataWeaveAst> declarations, DataWeaveAst expr) implements DataWeaveAst {
}
}
Loading
Loading