• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mybatis / generator / 2230

20 May 2026 08:44PM UTC coverage: 92.537% (+0.7%) from 91.803%
2230

push

github

web-flow
Merge pull request #1519 from mybatis/renovate/junit-framework-monorepo

Update junit-framework monorepo to v6.1.0

2531 of 3209 branches covered (78.87%)

12276 of 13266 relevant lines covered (92.54%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.7
/core/mybatis-generator-core/src/main/java/org/mybatis/generator/merge/java/JavaMergeUtilities.java
1
/*
2
 *    Copyright 2006-2026 the original author or authors.
3
 *
4
 *    Licensed under the Apache License, Version 2.0 (the "License");
5
 *    you may not use this file except in compliance with the License.
6
 *    You may obtain a copy of the License at
7
 *
8
 *       https://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *    Unless required by applicable law or agreed to in writing, software
11
 *    distributed under the License is distributed on an "AS IS" BASIS,
12
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *    See the License for the specific language governing permissions and
14
 *    limitations under the License.
15
 */
16
package org.mybatis.generator.merge.java;
17

18
import static org.mybatis.generator.internal.util.messages.Messages.getString;
19

20
import java.util.Collections;
21
import java.util.List;
22
import java.util.stream.Collectors;
23

24
import com.github.javaparser.JavaParser;
25
import com.github.javaparser.ParseResult;
26
import com.github.javaparser.Problem;
27
import com.github.javaparser.ast.CompilationUnit;
28
import com.github.javaparser.ast.ImportDeclaration;
29
import com.github.javaparser.ast.body.BodyDeclaration;
30
import com.github.javaparser.ast.body.FieldDeclaration;
31
import com.github.javaparser.ast.body.TypeDeclaration;
32
import com.github.javaparser.ast.body.VariableDeclarator;
33
import com.github.javaparser.ast.comments.Comment;
34
import com.github.javaparser.ast.expr.AnnotationExpr;
35
import com.github.javaparser.ast.expr.Expression;
36
import com.github.javaparser.ast.expr.MemberValuePair;
37
import com.github.javaparser.ast.expr.StringLiteralExpr;
38
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
39
import com.github.javaparser.ast.type.ClassOrInterfaceType;
40
import org.jspecify.annotations.Nullable;
41
import org.mybatis.generator.api.MyBatisGenerator;
42
import org.mybatis.generator.config.MergeConstants;
43
import org.mybatis.generator.exception.MergeException;
44

45
public class JavaMergeUtilities {
46
    private JavaMergeUtilities() {
47
        // utility class, no instances
48
    }
49

50
    /**
51
     * Compare two compilation units and find imports that are in the source file but not in the target file.
52
     * We assume this means they are required for some custom method, so we will add them to the target
53
     * file if there are other items to merge. This may create unused imports in the target file if the
54
     * initial assumption is incorrect, but better safe than sorry.
55
     *
56
     * @param sourceCompilationUnit compilation unit representing the source file
57
     * @param targetCompilationUnit compilation unit representing the target file
58
     */
59
    public static void copyMissingImports(CompilationUnit sourceCompilationUnit,
60
                                          CompilationUnit targetCompilationUnit) {
61
        List<String> newFileImports = targetCompilationUnit.getImports().stream()
1✔
62
                .map(JavaMergeUtilities::stringify).toList();
1✔
63

64
        sourceCompilationUnit.getImports().stream()
1✔
65
                .filter(im -> !newFileImports.contains(stringify(im)))
1✔
66
                .forEach(targetCompilationUnit::addImport);
1✔
67
    }
1✔
68

69
    /**
70
     * Compare two members to see if they are "functionally equivalent". This is defined as:
71
     *
72
     * <ul>
73
     *     <li>Members are the same type</li>
74
     *     <li>Members have the same signature or basic declaration</li>
75
     * </ul>
76
     *
77
     * @param member1 the first member
78
     * @param member2 the second member
79
     * @return true if the members are functionally equivalent
80
     */
81
    private static boolean membersMatch(BodyDeclaration<?> member1, BodyDeclaration<?> member2) {
82
        if (member1.isTypeDeclaration() && member2.isTypeDeclaration()) {
1✔
83
            return member1.asTypeDeclaration().getNameAsString()
1✔
84
                    .equals(member2.asTypeDeclaration().getNameAsString());
1✔
85
        } else if (member1.isCallableDeclaration() && member2.isCallableDeclaration()) {
1✔
86
            return member1.asCallableDeclaration().getSignature().asString()
1✔
87
                    .equals(member2.asCallableDeclaration().getSignature().asString());
1✔
88
        } else if (member1.isFieldDeclaration() && member2.isFieldDeclaration()) {
1✔
89
            return stringify(member1.asFieldDeclaration()).equals(stringify(member2.asFieldDeclaration()));
1✔
90
        }
91

92
        return false;
1✔
93
    }
94

95
    public static void copyMissingSuperInterfaces(BodyDeclaration<?> sourceType, BodyDeclaration<?> targetType) {
96
        List<String> targetSuperInterfaces = findSuperInterfaces(targetType).stream()
1✔
97
                .map(NodeWithSimpleName::getNameAsString).toList();
1✔
98

99
        findSuperInterfaces(sourceType).stream()
1✔
100
                .filter(t -> !targetSuperInterfaces.contains(t.getNameAsString()))
1✔
101
                .forEach(t -> addSuperInterface(targetType, t));
1✔
102
    }
1✔
103

104
    private static List<ClassOrInterfaceType> findSuperInterfaces(BodyDeclaration<?> bodyDeclaration) {
105
        if (bodyDeclaration.isClassOrInterfaceDeclaration()) {
1✔
106
            return bodyDeclaration.asClassOrInterfaceDeclaration().getImplementedTypes();
1✔
107
        } else if (bodyDeclaration.isEnumDeclaration()) {
1✔
108
            return bodyDeclaration.asEnumDeclaration().getImplementedTypes();
1✔
109
        } else if (bodyDeclaration.isRecordDeclaration()) {
1!
110
            return bodyDeclaration.asRecordDeclaration().getImplementedTypes();
1✔
111
        }
112

113
        return Collections.emptyList();
×
114
    }
115

116
    private static void addSuperInterface(BodyDeclaration<?> bodyDeclaration, ClassOrInterfaceType superInterface) {
117
        if (bodyDeclaration.isClassOrInterfaceDeclaration()) {
1✔
118
            bodyDeclaration.asClassOrInterfaceDeclaration().addImplementedType(superInterface);
1✔
119
        } else if (bodyDeclaration.isEnumDeclaration()) {
1!
120
            bodyDeclaration.asEnumDeclaration().addImplementedType(superInterface);
×
121
        } else if (bodyDeclaration.isRecordDeclaration()) {
1!
122
            bodyDeclaration.asRecordDeclaration().addImplementedType(superInterface);
1✔
123
        }
124
    }
1✔
125

126
    /**
127
     * Create a string representation of an import that we can use to find matches.
128
     *
129
     * @param importDeclaration the import declaration to stringify
130
     * @return string representation of the import (not a full import statement)
131
     */
132
    private static String stringify(ImportDeclaration importDeclaration) {
133
        StringBuilder sb = new StringBuilder();
1✔
134
        if (importDeclaration.isStatic()) {
1✔
135
            sb.append("static "); //$NON-NLS-1$
1✔
136
        }
137
        if (importDeclaration.isModule()) {
1!
138
            sb.append("module "); //$NON-NLS-1$
×
139
        }
140
        sb.append(importDeclaration.getNameAsString());
1✔
141
        if (importDeclaration.isAsterisk()) {
1!
142
            sb.append(".*"); //$NON-NLS-1$
×
143
        }
144

145
        return sb.toString();
1✔
146
    }
147

148
    private static String stringify(FieldDeclaration fieldDeclaration) {
149
        return fieldDeclaration.getVariables().stream()
1✔
150
                .map(JavaMergeUtilities::stringify)
1✔
151
                .collect(Collectors.joining(",")); //$NON-NLS-1$
1✔
152
    }
153

154
    private static String stringify(VariableDeclarator variableDeclarator) {
155
        return variableDeclarator.getType().toString()
1✔
156
                + " " //$NON-NLS-1$
157
                + variableDeclarator.getName().toString();
1✔
158
    }
159

160
    public static GeneratedType checkForGeneratedAnnotation(BodyDeclaration<?> member) {
161
        return member.getAnnotations().stream()
1✔
162
                .filter(JavaMergeUtilities::isOurGeneratedAnnotation)
1✔
163
                .findFirst()
1✔
164
                .map(a -> {
1✔
165
                    if (hasDoNotDeleteComment(a)) {
1✔
166
                        return GeneratedType.GENERATED_KEEP;
1✔
167
                    } else {
168
                        return GeneratedType.GENERATED_REMOVE;
1✔
169
                    }
170
                })
171
                .orElse(GeneratedType.NOT_GENERATED);
1✔
172
    }
173

174
    private static boolean isOurGeneratedAnnotation(AnnotationExpr annotationExpr) {
175
        if (!isGeneratedAnnotation(annotationExpr)) {
1✔
176
            return false;
1✔
177
        }
178

179
        if (annotationExpr.isSingleMemberAnnotationExpr()) {
1✔
180
            Expression value = annotationExpr.asSingleMemberAnnotationExpr().getMemberValue();
1✔
181
            if (value.isStringLiteralExpr()) {
1!
182
                return annotationValueMatchesMyBatisGenerator(value.asStringLiteralExpr());
1✔
183
            }
184
        } else if (annotationExpr.isNormalAnnotationExpr()) {
1!
185
            return annotationExpr.asNormalAnnotationExpr().getPairs().stream()
1✔
186
                    .filter(JavaMergeUtilities::isValuePair)
1✔
187
                    .map(MemberValuePair::getValue)
1✔
188
                    .filter(Expression::isStringLiteralExpr)
1✔
189
                    .map(Expression::asStringLiteralExpr)
1✔
190
                    .findFirst()
1✔
191
                    .map(JavaMergeUtilities::annotationValueMatchesMyBatisGenerator)
1✔
192
                    .orElse(false);
1✔
193
        }
194

195
        return false;
×
196
    }
197

198
    private static boolean hasDoNotDeleteComment(AnnotationExpr annotationExpr) {
199
        // check the comments value for the do_not_delete marker string
200
        if (annotationExpr.isSingleMemberAnnotationExpr()) {
1✔
201
            // no comments in a single member annotation - only the single "value" member"
202
            return false;
1✔
203
        } else if (annotationExpr.isNormalAnnotationExpr()) {
1!
204
            return annotationExpr.asNormalAnnotationExpr().getPairs().stream()
1✔
205
                    .filter(JavaMergeUtilities::isCommentsPair)
1✔
206
                    .map(MemberValuePair::getValue)
1✔
207
                    .filter(Expression::isStringLiteralExpr)
1✔
208
                    .map(Expression::asStringLiteralExpr)
1✔
209
                    .findFirst()
1✔
210
                    .map(StringLiteralExpr::asString)
1✔
211
                    .map(s -> s.contains(MergeConstants.DO_NOT_DELETE_DURING_MERGE))
1✔
212
                    .orElse(false);
1✔
213
        }
214

215
        return false;
×
216
    }
217

218
    private static boolean isGeneratedAnnotation(AnnotationExpr annotationExpr) {
219
        String annotationName = annotationExpr.getNameAsString();
1✔
220
        // Check for @Generated annotation (both javax and jakarta packages)
221
        return "Generated".equals(annotationName) //$NON-NLS-1$
1✔
222
                || "javax.annotation.Generated".equals(annotationName) //$NON-NLS-1$
1!
223
                || "jakarta.annotation.Generated".equals(annotationName); //$NON-NLS-1$
1!
224
    }
225

226
    private static boolean isValuePair(MemberValuePair pair) {
227
        return pair.getName().asString().equals("value"); //$NON-NLS-1$
1✔
228
    }
229

230
    private static boolean isCommentsPair(MemberValuePair pair) {
231
        return pair.getName().asString().equals("comments"); //$NON-NLS-1$
1✔
232
    }
233

234
    private static boolean annotationValueMatchesMyBatisGenerator(StringLiteralExpr expr) {
235
        return expr.asString().equals(MyBatisGenerator.class.getName());
1✔
236
    }
237

238
    public static GeneratedType checkForGeneratedJavadocTag(BodyDeclaration<?> member) {
239
        return member.getComment()
1✔
240
                .map(Comment::getContent)
1✔
241
                .map(JavaMergeUtilities::checkJavadocTag)
1✔
242
                .orElse(GeneratedType.NOT_GENERATED);
1✔
243
    }
244

245
    // Check if the comment contains any of the javadoc tags
246
    private static GeneratedType checkJavadocTag(String comment) {
247
        for (String tag : MergeConstants.getOldElementTags()) {
1✔
248
            if (comment.contains(tag)) {
1✔
249
                if (comment.contains(MergeConstants.DO_NOT_DELETE_DURING_MERGE)) {
1✔
250
                    return GeneratedType.GENERATED_KEEP;
1✔
251
                } else {
252
                    return GeneratedType.GENERATED_REMOVE;
1✔
253
                }
254
            }
255
        }
256
        return GeneratedType.NOT_GENERATED;
1✔
257
    }
258

259
    private static TypeDeclaration<?> findMainTypeDeclaration(CompilationUnit compilationUnit,
260
                                                              MergeFileType mergeFileType) throws MergeException {
261
        // Return the first public type declaration, or the first type declaration if no public one exists
262
        TypeDeclaration<?> firstType = null;
1✔
263
        for (TypeDeclaration<?> typeDeclaration : compilationUnit.getTypes()) {
1✔
264
            if (firstType == null) {
1!
265
                firstType = typeDeclaration;
1✔
266
            }
267
            if (typeDeclaration.isPublic()) {
1!
268
                return typeDeclaration;
1✔
269
            }
270
        }
×
271
        if (firstType == null) {
1!
272
            throw new MergeException(getString("RuntimeError.29", mergeFileType.toString())); //$NON-NLS-1$
1✔
273
        }
274
        return firstType;
×
275
    }
276

277
    public static ParseResults parseAndFindMainTypeDeclaration(JavaParser javaParser, String source,
278
                                                               MergeFileType mergeFileType) throws MergeException {
279
        ParseResult<CompilationUnit> parseResult = javaParser.parse(source);
1✔
280

281
        // little hack to pull the result out of the lambda. This allows us to avoid "orElseThrow()" later on
282
        @Nullable CompilationUnit[] compilationUnits = new CompilationUnit [1];
1✔
283
        parseResult.ifSuccessful(cu -> compilationUnits[0] = cu);
1✔
284

285
        if (compilationUnits[0] == null) {
1✔
286
            List<String> details = parseResult.getProblems().stream()
1✔
287
                    .map(Problem::toString)
1✔
288
                    .toList();
1✔
289
            throw new MergeException(getString("RuntimeError.28", mergeFileType.toString()), details); //$NON-NLS-1$
1✔
290
        }
291

292
        return new ParseResults(compilationUnits[0], findMainTypeDeclaration(compilationUnits[0], mergeFileType));
1✔
293
    }
294

295
    public static void deleteDuplicateMemberIfExists(TypeDeclaration<?> newTypeDeclaration, BodyDeclaration<?> member) {
296
        newTypeDeclaration.getMembers().stream()
1✔
297
                .filter(td -> membersMatch(td, member))
1✔
298
                .findFirst()
1✔
299
                .ifPresent(newTypeDeclaration::remove);
1✔
300
    }
1✔
301
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc