You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicecomb.apache.org by ni...@apache.org on 2019/06/21 07:09:32 UTC
[servicecomb-toolkit] 16/49: Support contract verify
This is an automated email from the ASF dual-hosted git repository.
ningjiang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/servicecomb-toolkit.git
commit 990ea5e67968817eeb8e18c423710c6912bce3c0
Author: MabinGo <bi...@huawei.com>
AuthorDate: Sat May 25 00:52:34 2019 +0800
Support contract verify
Signed-off-by: MabinGo <bi...@huawei.com>
---
.../toolkit/common/CompareAlgorithm.java | 25 ++++
.../toolkit/common/ComparisionType.java | 33 +++++
.../servicecomb/toolkit/common/Comparison.java | 40 +++++
.../toolkit/common/ContractComparator.java | 81 ++++++++++
.../servicecomb/toolkit/common/MyersAlgorithm.java | 73 +++++++++
.../toolkit/common/SplitDiffFormatter.java | 163 +++++++++++++++++++++
.../servicecomb/toolkit/cli/CodeGenerate.java | 2 +-
.../servicecomb/toolkit/cli/DocGenerate.java | 2 +-
.../apache/servicecomb/toolkit/cli/CliTest.java | 4 +-
.../toolkit/plugin/GenerateContractsDocMojo.java | 6 +-
...tractsDocMojo.java => VerifyContractsMojo.java} | 50 ++++---
11 files changed, 449 insertions(+), 30 deletions(-)
diff --git a/common/src/main/java/org/apache/servicecomb/toolkit/common/CompareAlgorithm.java b/common/src/main/java/org/apache/servicecomb/toolkit/common/CompareAlgorithm.java
new file mode 100755
index 0000000..b049054
--- /dev/null
+++ b/common/src/main/java/org/apache/servicecomb/toolkit/common/CompareAlgorithm.java
@@ -0,0 +1,25 @@
+/*
+ * 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.servicecomb.toolkit.common;
+
+import java.util.List;
+
+public interface CompareAlgorithm {
+
+ List<Comparison> compare(String source, String dest);
+}
diff --git a/common/src/main/java/org/apache/servicecomb/toolkit/common/ComparisionType.java b/common/src/main/java/org/apache/servicecomb/toolkit/common/ComparisionType.java
new file mode 100755
index 0000000..eae9c3e
--- /dev/null
+++ b/common/src/main/java/org/apache/servicecomb/toolkit/common/ComparisionType.java
@@ -0,0 +1,33 @@
+/*
+ * 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.servicecomb.toolkit.common;
+
+public enum ComparisionType {
+
+ /** insert new content */
+ INSERT,
+
+ /** delete content */
+ DELETE,
+
+ /** replace old content */
+ REPLACE,
+
+ /** not change */
+ EQUAL;
+}
diff --git a/common/src/main/java/org/apache/servicecomb/toolkit/common/Comparison.java b/common/src/main/java/org/apache/servicecomb/toolkit/common/Comparison.java
new file mode 100755
index 0000000..6708669
--- /dev/null
+++ b/common/src/main/java/org/apache/servicecomb/toolkit/common/Comparison.java
@@ -0,0 +1,40 @@
+/*
+ * 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.servicecomb.toolkit.common;
+
+public class Comparison {
+
+ public final ComparisionType type;
+
+ public final int originalPointBegin;
+
+ public final int originalPointEnd;
+
+ public final int destinationPointBegin;
+
+ public final int destinationPointEnd;
+
+ public Comparison(ComparisionType type, int originalPointBegin, int originalPointEnd, int destinationPointBegin,
+ int destinationPointEnd) {
+ this.type = type;
+ this.originalPointBegin = originalPointBegin;
+ this.originalPointEnd = originalPointEnd;
+ this.destinationPointBegin = destinationPointBegin;
+ this.destinationPointEnd = destinationPointEnd;
+ }
+}
diff --git a/common/src/main/java/org/apache/servicecomb/toolkit/common/ContractComparator.java b/common/src/main/java/org/apache/servicecomb/toolkit/common/ContractComparator.java
new file mode 100755
index 0000000..dba8dd9
--- /dev/null
+++ b/common/src/main/java/org/apache/servicecomb/toolkit/common/ContractComparator.java
@@ -0,0 +1,81 @@
+/*
+ * 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.servicecomb.toolkit.common;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ContractComparator {
+
+ private final static Logger LOGGER = LoggerFactory.getLogger(ContractComparator.class);
+
+ private CompareAlgorithm algorithm;
+
+ private String source;
+
+ private String dest;
+
+ private List<Comparison> comparisonList;
+
+ public ContractComparator(String source, String dest) {
+ this(source, dest, new MyersAlgorithm());
+ }
+
+ public ContractComparator(String source, String dest, CompareAlgorithm algorithm) {
+ this.source = source;
+ this.dest = dest;
+ this.algorithm = algorithm;
+ this.comparisonList = compare();
+ }
+
+ public void setAlgorithm(CompareAlgorithm algorithm) {
+ this.algorithm = algorithm;
+ }
+
+ public CompareAlgorithm getAlgorithm() {
+ return algorithm;
+ }
+
+ public List<Comparison> compare() {
+ return algorithm.compare(source, dest);
+ }
+
+ public boolean equals() {
+ if (comparisonList.size() > 0) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void splitPrintToScreen() {
+ splitPrint(System.out);
+ }
+
+ public void splitPrint(OutputStream outputStream) {
+ try {
+ new SplitDiffFormatter(outputStream).format(comparisonList, source, dest);
+ } catch (IOException e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/servicecomb/toolkit/common/MyersAlgorithm.java b/common/src/main/java/org/apache/servicecomb/toolkit/common/MyersAlgorithm.java
new file mode 100755
index 0000000..6300b38
--- /dev/null
+++ b/common/src/main/java/org/apache/servicecomb/toolkit/common/MyersAlgorithm.java
@@ -0,0 +1,73 @@
+/*
+ * 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.servicecomb.toolkit.common;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jgit.diff.EditList;
+import org.eclipse.jgit.diff.MyersDiff;
+import org.eclipse.jgit.diff.RawText;
+import org.eclipse.jgit.diff.RawTextComparator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class MyersAlgorithm implements CompareAlgorithm {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(MyersAlgorithm.class);
+
+ @Override
+ public List<Comparison> compare(String source, String dest) {
+
+ if (source == null) {
+ LOGGER.error("source must not be null");
+ throw new RuntimeException("source must not be null");
+ }
+ if (source == null) {
+ LOGGER.error("dest must not be null");
+ throw new RuntimeException("dest must not be null");
+ }
+
+ EditList diffList = new EditList();
+ diffList.addAll(MyersDiff.INSTANCE.diff(RawTextComparator.DEFAULT,
+ new RawText(source.getBytes()), new RawText(dest.getBytes())));
+
+ List<Comparison> comparisonList = new ArrayList<>();
+
+ diffList.stream().forEachOrdered(edit -> {
+ ComparisionType comparisionType;
+ switch (edit.getType()) {
+ case INSERT:
+ comparisionType = ComparisionType.INSERT;
+ break;
+ case DELETE:
+ comparisionType = ComparisionType.DELETE;
+ break;
+ case REPLACE:
+ comparisionType = ComparisionType.REPLACE;
+ break;
+ default:
+ comparisionType = ComparisionType.EQUAL;
+ break;
+ }
+ comparisonList
+ .add(new Comparison(comparisionType, edit.getBeginA(), edit.getEndA(), edit.getBeginB(), edit.getEndB()));
+ });
+ return comparisonList;
+ }
+}
diff --git a/common/src/main/java/org/apache/servicecomb/toolkit/common/SplitDiffFormatter.java b/common/src/main/java/org/apache/servicecomb/toolkit/common/SplitDiffFormatter.java
new file mode 100755
index 0000000..b72384d
--- /dev/null
+++ b/common/src/main/java/org/apache/servicecomb/toolkit/common/SplitDiffFormatter.java
@@ -0,0 +1,163 @@
+/*
+ * 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.servicecomb.toolkit.common;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.jgit.diff.DiffFormatter;
+
+public class SplitDiffFormatter extends DiffFormatter {
+
+ private int radius = 3;
+
+ private final OutputStream out;
+
+ private static final String noNewLine = "\nthis is end of compare\n";
+
+ private static String outputFormat = "%-20s";
+
+ private static String numberFormat = "%-4s";
+
+ public SplitDiffFormatter(OutputStream out) {
+ super(out);
+ this.out = out;
+ }
+
+ public void format(List<Comparison> comparisons, String source, String dest) throws IOException {
+
+ outputFormat = "%-" + (getMaxLineSize(source) + 10) + "s";
+
+ List<String> sourceLines = readStringAsLines(source);
+ List<String> destLines = readStringAsLines(dest);
+
+ for (int currentIndex = 0; currentIndex < comparisons.size(); ) {
+ Comparison currentComparison = comparisons.get(currentIndex);
+ final int endIndex = findOutputEndIndex(comparisons, currentIndex);
+ final Comparison endComparison = comparisons.get(endIndex);
+
+ int originalBegin = (int) Math.max(0, (long) currentComparison.originalPointBegin - radius);
+ int destinationBegin = (int) Math.max(0, (long) currentComparison.destinationPointBegin - radius);
+ int originalEnd = (int) Math.min(sourceLines.size(), (long) endComparison.originalPointEnd + radius);
+ int destinationEnd = (int) Math.min(destLines.size(), (long) endComparison.destinationPointEnd + radius);
+
+ writeHunkHeader(originalBegin, originalEnd, destinationBegin, destinationEnd);
+
+ while (originalBegin < originalEnd || destinationBegin < destinationEnd) {
+
+ if (originalBegin < currentComparison.originalPointBegin || endIndex + 1 < currentIndex) {
+ writeContextLine(sourceLines, originalBegin, destLines, destinationBegin);
+ originalBegin++;
+ destinationBegin++;
+ } else if (originalBegin < currentComparison.originalPointEnd) {
+
+ if (destinationBegin < currentComparison.destinationPointEnd) {
+ writeReplaceLine(sourceLines, originalBegin, destLines, destinationBegin);
+ destinationBegin++;
+ } else {
+ writeRemovedLine(sourceLines, originalBegin, destLines, destinationBegin);
+ }
+ originalBegin++;
+ } else if (destinationBegin < currentComparison.destinationPointEnd) {
+
+ writeAddedLine(sourceLines, originalBegin, destLines, destinationBegin);
+ destinationBegin++;
+ }
+
+ if (end(currentComparison, originalBegin, destinationBegin) && ++currentIndex < comparisons.size()) {
+ currentComparison = comparisons.get(currentIndex);
+ }
+ }
+
+ writeLine(noNewLine);
+ }
+ }
+
+ public int getMaxLineSize(String text) {
+ final int[] maxLen = {0};
+ readStringAsLines(text).forEach(line -> {
+ int temp = line.length();
+ if (temp > maxLen[0]) {
+ maxLen[0] = temp;
+ }
+ });
+ return maxLen[0];
+ }
+
+ private List<String> readStringAsLines(String text) {
+ return Arrays.asList(text.split("\\r?\\n"));
+ }
+
+ protected void writeReplaceLine(List<String> text, int line, List<String> textB, int bCur) throws IOException {
+ writeLine(buildFormatLineLeft(text, line, " -") + buildFormatLineRight(textB, bCur, " +") + "\n");
+ }
+
+ protected void writeContextLine(List<String> text, int line, List<String> textB, int bCur) throws IOException {
+ writeLine(buildFormatLineLeft(text, line, " ") + buildFormatLineRight(textB, bCur, " ") + "\n");
+ }
+
+ protected void writeRemovedLine(List<String> text, int line, List<String> textB, int bCur) throws IOException {
+ writeLine(buildFormatLineLeft(text, line, " -") + "\n");
+ }
+
+ protected void writeAddedLine(List<String> text, int line, List<String> textB, int bCur) throws IOException {
+ writeLine(
+ String.format(numberFormat, " ") + String.format(outputFormat, " ") + buildFormatLineRight(textB, bCur, " +")
+ + "\n");
+ }
+
+ protected void writeLine(final String content) throws IOException {
+ out.write(content.getBytes());
+ }
+
+ private String buildFormatLineLeft(List<String> text, int line, String prefix) {
+ return String.format(numberFormat, (line + 1)) + String.format(outputFormat, prefix + text.get(line));
+ }
+
+ private String buildFormatLineRight(List<String> text, int line, String prefix) {
+ return String.format(numberFormat, (line + 1)) + String
+ .format(getOutputFormat(text.get(line).length()), prefix + text.get(line));
+ }
+
+ private String getOutputFormat(int len) {
+ return "%-" + len + "s";
+ }
+
+ private static boolean end(Comparison edit, int a, int b) {
+ return edit.originalPointEnd <= a && edit.destinationPointEnd <= b;
+ }
+
+ private int findOutputEndIndex(List<Comparison> edits, int i) {
+ int end = i + 1;
+ while (end < edits.size()
+ && (isOriginalEnd(edits, end) || isDestinationEnd(edits, end))) {
+ end++;
+ }
+ return end - 1;
+ }
+
+ private boolean isOriginalEnd(List<Comparison> e, int i) {
+ return e.get(i).originalPointBegin - e.get(i - 1).originalPointEnd <= 2 * radius;
+ }
+
+ private boolean isDestinationEnd(List<Comparison> e, int i) {
+ return e.get(i).destinationPointBegin - e.get(i - 1).destinationPointEnd <= 2 * radius;
+ }
+}
diff --git a/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/CodeGenerate.java b/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/CodeGenerate.java
index 6700110..074f7f9 100755
--- a/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/CodeGenerate.java
+++ b/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/CodeGenerate.java
@@ -34,7 +34,7 @@ import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.config.CodegenConfigurator;
-@Command(name = "generate",
+@Command(name = "codegenerate",
description = "Generate multiple models of microservice project by OpenAPI specification file")
public class CodeGenerate implements Runnable {
diff --git a/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/DocGenerate.java b/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/DocGenerate.java
index f3089e9..e468973 100755
--- a/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/DocGenerate.java
+++ b/toolkit-cli/src/main/java/org/apache/servicecomb/toolkit/cli/DocGenerate.java
@@ -32,7 +32,7 @@ import org.apache.servicecomb.swagger.SwaggerUtils;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
-@Command(name = "docGenerate", description = "Generate document by OpenAPI specification file")
+@Command(name = "docgenerate", description = "Generate document by OpenAPI specification file")
public class DocGenerate implements Runnable {
@Option(name = {"-i", "--input"}, title = "OpenAPI specification file", required = true,
diff --git a/toolkit-cli/src/test/java/org/apache/servicecomb/toolkit/cli/CliTest.java b/toolkit-cli/src/test/java/org/apache/servicecomb/toolkit/cli/CliTest.java
index cf0d047..647be5c 100755
--- a/toolkit-cli/src/test/java/org/apache/servicecomb/toolkit/cli/CliTest.java
+++ b/toolkit-cli/src/test/java/org/apache/servicecomb/toolkit/cli/CliTest.java
@@ -38,7 +38,7 @@ public class CliTest {
Path tempFile = Paths.get(tempDir.toFile().getCanonicalPath() + "/" + model + "Server");
CliTest.class.getClassLoader().getResource("swagger.yaml");
String[] args = new String[] {
- "generate",
+ "codegenerate",
"-m",
"ServiceComb",
"-i",
@@ -93,7 +93,7 @@ public class CliTest {
Path tempDir = Files.createTempDirectory(null);
Path tempFile = Paths.get(tempDir.toFile().getCanonicalPath() + "/ServiceComb");
String[] args = new String[] {
- "generate",
+ "codegenerate",
"-i",
Paths.get("./src/test/resources/contracts").toFile().getCanonicalPath(),
"--artifact-id",
diff --git a/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java b/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java
index c36cd3a..3c5d975 100755
--- a/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java
+++ b/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java
@@ -35,8 +35,8 @@ import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
-import org.apache.servicecomb.toolkit.docgen.DocGeneratorManager;
import org.apache.servicecomb.swagger.SwaggerUtils;
+import org.apache.servicecomb.toolkit.docgen.DocGeneratorManager;
@Mojo(name = "generateDoc", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)
@Execute(goal = "generateDoc",
@@ -71,8 +71,8 @@ public class GenerateContractsDocMojo extends AbstractMojo {
DocGeneratorManager.generate(SwaggerUtils.parseSwagger(file.toUri().toURL()),
docOutputDir + File.separator
- + file.toFile().getName().substring(0, file.toFile().getName().indexOf(".")) + ".html",
- "html");
+ + file.toFile().getName().substring(0, file.toFile().getName().indexOf(".")),
+ format);
return super.visitFile(file, attrs);
}
});
diff --git a/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java b/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/VerifyContractsMojo.java
similarity index 59%
copy from toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java
copy to toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/VerifyContractsMojo.java
index c36cd3a..1617034 100755
--- a/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/GenerateContractsDocMojo.java
+++ b/toolkit-maven-plugin/src/main/java/org/apache/servicecomb/toolkit/plugin/VerifyContractsMojo.java
@@ -17,14 +17,8 @@
package org.apache.servicecomb.toolkit.plugin;
-import java.io.File;
import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Map;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
@@ -35,14 +29,15 @@ import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
-import org.apache.servicecomb.toolkit.docgen.DocGeneratorManager;
-import org.apache.servicecomb.swagger.SwaggerUtils;
+import org.apache.servicecomb.toolkit.common.ContractComparator;
+import org.apache.servicecomb.toolkit.common.ContractsUtils;
-@Mojo(name = "generateDoc", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)
-@Execute(goal = "generateDoc",
+@Mojo(name = "verifyContracts", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)
+@Execute(goal = "verifyContracts",
phase = LifecyclePhase.COMPILE
)
-public class GenerateContractsDocMojo extends AbstractMojo {
+public class VerifyContractsMojo extends AbstractMojo {
+
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject project;
@@ -53,31 +48,40 @@ public class GenerateContractsDocMojo extends AbstractMojo {
@Parameter(defaultValue = ".yaml")
private String format;
- @Parameter(defaultValue = "build/doc")
- private String docOutputDir;
+ @Parameter(defaultValue = "sourceContracts")
+ private String sourceContractsDir;
+
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
+ getLog().info("outputDir : " + outputDir);
+
ContractGenerator contractGenerator = new ContractGenerator(project);
+
contractGenerator.generateAndOutput(outputDir, format);
try {
- Files.walkFileTree(Paths.get(outputDir), new SimpleFileVisitor<Path>() {
+ Map<String, byte[]> currentContracts = ContractsUtils.getFilesGroupByFilename(outputDir);
+ Map<String, byte[]> sourceContracts = ContractsUtils.getFilesGroupByFilename(sourceContractsDir);
+
+ currentContracts.forEach((contractName, swagger) -> {
+
+ byte[] sourceSwagger = sourceContracts.get(contractName);
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ ContractComparator contractComparator = new ContractComparator(new String(sourceSwagger), new String(swagger));
- DocGeneratorManager.generate(SwaggerUtils.parseSwagger(file.toUri().toURL()),
- docOutputDir + File.separator
- + file.toFile().getName().substring(0, file.toFile().getName().indexOf(".")) + ".html",
- "html");
- return super.visitFile(file, attrs);
+ if (!contractComparator.equals()) {
+ getLog().info("契约文件不匹配,差异如下");
+ getLog().info(sourceContractsDir + "/" + contractName + " vs " + outputDir + "/" + contractName);
+ contractComparator.splitPrintToScreen();
+ } else {
+ getLog().info("恭喜你,契约校验通过");
}
});
} catch (IOException e) {
- getLog().error(e.getMessage());
+ e.printStackTrace();
}
}
}