feat: add @Tag reporting and CSV/plain output

- Default CSV output with header; -plain enables labeled text format
- Extract repeated @Tag and @Tags container values
- Configure JavaParser language level for modern syntax (records)
- Add fixture-based JUnit tests and README usage/examples
This commit is contained in:
2026-02-11 02:10:48 +01:00
parent 968558aed1
commit 63f6b8c803
19 changed files with 1382 additions and 73 deletions

26
.classpath Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/resources">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-21/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

12
.gitattributes vendored Normal file
View File

@@ -0,0 +1,12 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf
# Binary files should be left untouched
*.jar binary

49
.gitignore vendored
View File

@@ -1,4 +1,31 @@
# ---> Eclipse
##---------------------------------------------------------------------------------------- Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
##---------------------------------------------------------------------------------------- Eclipse
.metadata
bin/
tmp/
@@ -60,3 +87,23 @@ local.properties
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project
# PMD plugin conf
.pmd
##---------------------------------------------------------------------------------------- Gradle
.gradle
**/build/
!src/**/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# Ignore Gradle build output directory
build

23
.project Normal file
View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>methodatlas</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

60
LICENSE
View File

@@ -1,63 +1,3 @@
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 2026 Egothor
Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,13 +1,73 @@
# MethodAtlas
# MethodAtlasApp
MethodAtlas is a static analysis tool for Java projects.
`MethodAtlasApp` is a small standalone CLI that scans Java source trees for JUnit test methods and prints per-method
statistics:
It scans Java source code and JUnit tests to extract structured information such as:
- fully-qualified class and method names
- test method discovery (JUnit 4/5)
- lines of code (LOC)
- structural and complexity metrics (planned)
- code relationships and statistics
- **FQCN** (fully-qualified class name)
- **method name**
- **LOC** (lines of code, based on the AST source range)
- **@Tag values** attached to the method (supports repeated `@Tag` and `@Tags({...})`)
The goal of MethodAtlas is to provide a lightweight, extensible code intelligence engine
that helps developers understand, measure, and evolve Java codebases.
It supports two output modes:
- **CSV** (default)
- **Plain text** (`-plain` as the first CLI argument)
## Build & run
Assuming you have a runnable JAR (e.g. `methodatlas.jar`):
```bash
java -jar methodatlas.jar [ -plain ] <path1> [<path2> ...]
````
* If **no paths** are provided, the current directory (i.e., `.`) is scanned.
* Multiple root paths are supported.
## Output modes
### CSV (default)
* Prints a **header line**
* Each record contains **values only**
* Tags are **semicolon-separated** in the `tags` column (empty if no tags)
Example:
```text
Feb 11, 2026 1:33:35 AM org.egothor.methodatlas.MethodAtlasApp scanRoot
INFO: Scanning /tmp/junit-15560885133010516491 for JUnit files
fqcn,method,loc,tags
com.acme.tests.SampleOneTest,alpha,8,fast;crypto
com.acme.tests.SampleOneTest,beta,6,param
com.acme.tests.SampleOneTest,gamma,4,nested1;nested2
com.acme.other.AnotherTest,delta,3,
```
### Plain text (`-plain`)
* Prints one line per detected method:
* `FQCN, method, LOC=<n>, TAGS=<tag1;tag2;...>`
* If a method has **no tags**, it prints `TAGS=-`
Example:
```text
Feb 11, 2026 1:33:35 AM org.egothor.methodatlas.MethodAtlasApp scanRoot
INFO: Scanning /tmp/junit-12139245189413750595 for JUnit files
com.acme.tests.SampleOneTest, alpha, LOC=8, TAGS=fast;crypto
com.acme.tests.SampleOneTest, beta, LOC=6, TAGS=param
com.acme.tests.SampleOneTest, gamma, LOC=4, TAGS=nested1;nested2
com.acme.other.AnotherTest, delta, LOC=3, TAGS=-
```
## Notes
* The scanner looks for files ending with `*Test.java`.
* JUnit methods are detected by annotations such as:
* `@Test`
* `@ParameterizedTest`
* `@RepeatedTest`
* Tag extraction supports:
* `@Tag("x")` (including repeated `@Tag`)
* `@Tags({ @Tag("x"), @Tag("y") })`

68
build.gradle Normal file
View File

@@ -0,0 +1,68 @@
plugins {
id 'java'
id 'application'
}
group = 'org.egothor.methodatlas'
version = '0.1.0-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.github.javaparser:javaparser-core:3.28.0'
testImplementation(platform("org.junit:junit-bom:5.14.2"))
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
application {
mainClass = 'org.egothor.methodatlas.MethodAtlasApp'
}
tasks.test {
useJUnitPlatform()
}
jar {
manifest {
attributes(
'Main-Class': application.mainClass,
'Implementation-Title': rootProject.name,
'Implementation-Version': "${version}"
)
}
from sourceSets.main.output
dependsOn configurations.runtimeClasspath
// Include each JAR dependency
configurations.runtimeClasspath.findAll { it.exists() && it.name.endsWith('.jar') }.each { jarFile ->
def jarName = jarFile.name.replaceAll(/\.jar$/, '')
from(zipTree(jarFile)) {
// Exclude signature-related files
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA'
// Rename license/notice files to avoid conflicts
eachFile { file ->
if (file.path ==~ /META-INF\/(LICENSE|NOTICE)(\..*)?/) {
file.path = "META-INF/licenses-from-${jarName}/${file.name}"
}
}
includeEmptyDirs = false
}
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

12
gradle/libs.versions.toml Normal file
View File

@@ -0,0 +1,12 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format
[versions]
commons-math3 = "3.6.1"
guava = "33.1.0-jre"
junit-jupiter = "5.10.2"
[libraries]
commons-math3 = { module = "org.apache.commons:commons-math3", version.ref = "commons-math3" }
guava = { module = "com.google.guava:guava", version.ref = "guava" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" }

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

252
gradlew vendored Executable file
View File

@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

23
lib/.project Normal file
View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MethodAtlas-lib</name>
<comment>Project MethodAtlas-lib created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

1
settings.gradle Normal file
View File

@@ -0,0 +1 @@
rootProject.name = 'methodatlas'

View File

@@ -0,0 +1,443 @@
package org.egothor.methodatlas;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ParserConfiguration.LanguageLevel;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.ArrayInitializerExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.MemberValuePair;
/**
* Command-line utility that scans Java source trees for JUnit test methods and
* reports per-method statistics.
*
* <p>
* The tool walks one or more root directories, parses {@code *Test.java} files
* using JavaParser, and emits a record for each method annotated with one of
* the supported JUnit Jupiter test annotations.
* </p>
*
* <h2>Detection</h2>
* <ul>
* <li>Test methods are detected by annotations {@code @Test},
* {@code @ParameterizedTest}, and {@code @RepeatedTest} (simple name
* match).</li>
* <li>{@code @Tag} values are collected from repeated {@code @Tag("...")}
* annotations and from {@code @Tags({ @Tag("..."), ... })} containers.</li>
* <li>Lines of code (LOC) is computed from the AST source range:
* {@code endLine - beginLine + 1}. If the range is unavailable, LOC is
* {@code 0}.</li>
* </ul>
*
* <h2>Output</h2>
* <p>
* By default, the tool prints CSV with a header line:
* {@code fqcn,method,loc,tags}. The {@code tags} field is a semicolon-separated
* list.
* </p>
*
* <p>
* If {@code -plain} is provided as the first argument, the tool prints a plain
* text format:
* </p>
* <pre>
* fqcn, method, LOC=&lt;n&gt;, TAGS=&lt;tag1;tag2&gt;
* </pre>
* <p>
* If no tags are present, {@code TAGS=-} is printed.
* </p>
*
* <h2>Examples</h2> <pre>
* java -jar methodatlas.jar /path/to/repo
* java -jar methodatlas.jar -plain /path/to/repo /another/repo
* </pre>
*/
public class MethodAtlasApp {
/**
* Logging facility for scan progress and parse failures.
*/
private static final Logger LOG = Logger.getLogger(MethodAtlasApp.class.getName());
/**
* Output formats supported by the application.
*/
private enum OutputMode {
/**
* Comma-separated values with a header line and raw numeric LOC.
*/
CSV,
/**
* Plain text lines including {@code LOC=} and {@code TAGS=} labels.
*/
PLAIN
}
/**
* Program entry point.
*
* <p>
* Usage:
* </p>
* <pre>
* java -jar methodatlas.jar [ -plain ] &lt;path1&gt; [ &lt;path2&gt; ... ]
* </pre>
*
* <ul>
* <li>If {@code -plain} is provided as the first argument, the tool uses the
* plain-text output mode; otherwise CSV output is used.</li>
* <li>If no paths are provided, the current directory {@code "."} is
* scanned.</li>
* </ul>
*
* <p>
* The JavaParser language level is configured before parsing to support modern
* Java syntax (for example, {@code record} declarations).
* </p>
*
* @param args command-line arguments; see usage above
* @throws IOException if directory traversal fails while scanning input paths
*/
public static void main(String[] args) throws IOException {
ParserConfiguration pc = new ParserConfiguration();
pc.setLanguageLevel(LanguageLevel.JAVA_21); // or JAVA_17, etc.
StaticJavaParser.setConfiguration(pc);
OutputMode mode = OutputMode.CSV;
int firstPathIndex = 0;
if (args.length > 0 && "-plain".equals(args[0])) {
mode = OutputMode.PLAIN;
firstPathIndex = 1;
}
if (mode == OutputMode.CSV) {
System.out.println("fqcn,method,loc,tags");
}
if (args.length <= firstPathIndex) {
scanRoot(Paths.get("."), mode);
return;
}
for (int i = firstPathIndex; i < args.length; i++) {
scanRoot(Paths.get(args[i]), mode);
}
}
/**
* Recursively scans the supplied root directory for Java test files and
* processes them.
*
* <p>
* The current implementation matches files by suffix {@code "Test.java"}.
* </p>
*
* @param root root directory to scan
* @param mode output mode to use for emitted records
* @throws IOException if the file tree walk fails
*/
private static void scanRoot(Path root, OutputMode mode) throws IOException {
LOG.log(Level.INFO, "Scanning {0} for JUnit files", root);
Files.walk(root).filter(p -> p.toString().endsWith("Test.java")).forEach(p -> processFile(p, mode));
}
/**
* Parses a single Java source file and emits records for all detected JUnit
* test methods.
*
* <p>
* Parse errors are logged. Files that cannot be parsed are skipped.
* </p>
*
* @param path Java source file to parse
* @param mode output mode to use for emitted records
*/
private static void processFile(Path path, OutputMode mode) {
try {
CompilationUnit cu = StaticJavaParser.parse(path);
String pkg = cu.getPackageDeclaration().map(p -> p.getNameAsString()).orElse("");
cu.findAll(ClassOrInterfaceDeclaration.class).forEach(clazz -> {
String className = clazz.getNameAsString();
String fqcn = pkg.isEmpty() ? className : pkg + "." + className;
clazz.findAll(MethodDeclaration.class).forEach(method -> {
if (isJUnitTest(method)) {
int loc = countLOC(method);
List<String> tags = getTagValues(method);
emit(mode, fqcn, method.getNameAsString(), loc, tags);
}
});
});
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to parse: {0}", path);
e.printStackTrace();
}
}
/**
* Emits a single output record representing one test method.
*
* <p>
* For CSV output, values are printed as {@code fqcn,method,loc,tags} with CSV
* escaping applied to text fields. The {@code tags} field is a
* semicolon-separated list, or an empty field if no tags exist.
* </p>
*
* <p>
* For plain output, labels {@code LOC=} and {@code TAGS=} are included. If no
* tags exist, {@code TAGS=-} is printed.
* </p>
*
* @param mode output mode to use
* @param fqcn fully-qualified class name
* @param method method name
* @param loc lines of code for the method declaration (inclusive range)
* @param tags list of tag values; may be empty
*/
private static void emit(OutputMode mode, String fqcn, String method, int loc, List<String> tags) {
if (mode == OutputMode.PLAIN) {
String tagText = tags.isEmpty() ? "-" : String.join(";", tags);
System.out.println(fqcn + ", " + method + ", LOC=" + loc + ", TAGS=" + tagText);
return;
}
String tagText = tags.isEmpty() ? "" : String.join(";", tags);
System.out.println(csvEscape(fqcn) + "," + csvEscape(method) + "," + loc + "," + csvEscape(tagText));
}
/**
* Escapes a value for safe inclusion in a CSV field.
*
* <p>
* If the value contains a comma, quote, or line break, the value is quoted and
* internal quotes are doubled, per common CSV conventions.
* </p>
*
* @param value input value; may be {@code null}
* @return escaped CSV field value (never {@code null})
*/
private static String csvEscape(String value) {
if (value == null) {
return "";
}
boolean mustQuote = value.indexOf(',') >= 0 || value.indexOf('"') >= 0 || value.indexOf('\n') >= 0
|| value.indexOf('\r') >= 0;
if (!mustQuote) {
return value;
}
return "\"" + value.replace("\"", "\"\"") + "\"";
}
/**
* Determines whether the given method declaration represents a JUnit Jupiter
* test method.
*
* <p>
* The method is considered a test if it is annotated with one of the supported
* test annotations by simple name: {@code Test}, {@code ParameterizedTest}, or
* {@code RepeatedTest}.
* </p>
*
* @param method method declaration to inspect
* @return {@code true} if the method is considered a test method; {@code false}
* otherwise
*/
private static boolean isJUnitTest(MethodDeclaration method) {
for (AnnotationExpr ann : method.getAnnotations()) {
String name = ann.getNameAsString();
if ("Test".equals(name) || "ParameterizedTest".equals(name) || "RepeatedTest".equals(name)) {
return true;
}
}
return false;
}
/**
* Collects all {@code @Tag} values declared directly on a method.
*
* <p>
* Supported forms:
* </p>
* <ul>
* <li>Repeated {@code @Tag("...")} annotations</li>
* <li>{@code @Tags({ @Tag("..."), @Tag("...") })} container annotation</li>
* </ul>
*
* @param method method declaration to inspect
* @return list of tag values in encounter order; never {@code null}
*/
private static List<String> getTagValues(MethodDeclaration method) {
List<String> tags = new ArrayList<>();
for (AnnotationExpr ann : method.getAnnotations()) {
String name = ann.getNameAsString();
if (isTagAnnotationName(name)) {
extractTagValue(ann).ifPresent(tags::add);
} else if (isTagsContainerAnnotationName(name)) {
tags.addAll(extractTagValuesFromContainer(ann));
}
}
return tags;
}
/**
* Checks whether an annotation name represents {@code @Tag}.
*
* @param name annotation name (simple or qualified)
* @return {@code true} if it matches {@code Tag}; {@code false} otherwise
*/
private static boolean isTagAnnotationName(String name) {
return "Tag".equals(name) || name.endsWith(".Tag");
}
/**
* Checks whether an annotation name represents {@code @Tags} (the container for
* {@code @Tag}).
*
* @param name annotation name (simple or qualified)
* @return {@code true} if it matches {@code Tags}; {@code false} otherwise
*/
private static boolean isTagsContainerAnnotationName(String name) {
return "Tags".equals(name) || name.endsWith(".Tags");
}
/**
* Extracts the tag value from a {@code @Tag} annotation expression.
*
* <p>
* Both single-member and normal annotation syntaxes are supported:
* </p>
* <ul>
* <li>{@code @Tag("fast")}</li>
* <li>{@code @Tag(value = "fast")}</li>
* </ul>
*
* @param ann annotation expression representing {@code @Tag}
* @return extracted tag value, or empty if it cannot be determined
*/
private static Optional<String> extractTagValue(AnnotationExpr ann) {
if (ann.isSingleMemberAnnotationExpr()) {
return Optional.of(expressionToTagText(ann.asSingleMemberAnnotationExpr().getMemberValue()));
}
if (ann.isNormalAnnotationExpr()) {
for (MemberValuePair pair : ann.asNormalAnnotationExpr().getPairs()) {
if ("value".equals(pair.getNameAsString())) {
return Optional.of(expressionToTagText(pair.getValue()));
}
}
}
return Optional.empty();
}
/**
* Extracts all contained {@code @Tag} values from a {@code @Tags} container
* annotation.
*
* <p>
* Handles array initializers such as:
* </p>
* <pre>
* &#64;Tags({ @Tag("a"), @Tag("b") })
* </pre>
*
* @param ann annotation expression representing {@code @Tags}
* @return list of extracted tag values; never {@code null}
*/
private static List<String> extractTagValuesFromContainer(AnnotationExpr ann) {
List<String> tags = new ArrayList<>();
Optional<Expression> maybeValue = Optional.empty();
if (ann.isSingleMemberAnnotationExpr()) {
maybeValue = Optional.of(ann.asSingleMemberAnnotationExpr().getMemberValue());
} else if (ann.isNormalAnnotationExpr()) {
for (MemberValuePair pair : ann.asNormalAnnotationExpr().getPairs()) {
if ("value".equals(pair.getNameAsString())) {
maybeValue = Optional.of(pair.getValue());
break;
}
}
}
if (maybeValue.isEmpty()) {
return tags;
}
Expression value = maybeValue.get();
if (value.isArrayInitializerExpr()) {
ArrayInitializerExpr array = value.asArrayInitializerExpr();
for (Expression element : array.getValues()) {
if (element.isAnnotationExpr()) {
AnnotationExpr inner = element.asAnnotationExpr();
if (isTagAnnotationName(inner.getNameAsString())) {
extractTagValue(inner).ifPresent(tags::add);
}
}
}
} else if (value.isAnnotationExpr()) {
AnnotationExpr inner = value.asAnnotationExpr();
if (isTagAnnotationName(inner.getNameAsString())) {
extractTagValue(inner).ifPresent(tags::add);
}
}
return tags;
}
/**
* Converts an annotation value expression to tag text.
*
* <p>
* String literals are returned as their unescaped string value. Other
* expressions are returned using {@link Expression#toString()}.
* </p>
*
* @param expr expression to convert; may be {@code null}
* @return converted tag text (never {@code null})
*/
private static String expressionToTagText(Expression expr) {
if (expr == null) {
return "";
}
if (expr.isStringLiteralExpr()) {
return expr.asStringLiteralExpr().asString();
}
return expr.toString();
}
/**
* Computes the lines of code (LOC) for a method declaration using its source
* range.
*
* @param method method declaration
* @return inclusive LOC computed from the source range; {@code 0} if range is
* not available
*/
private static int countLOC(MethodDeclaration method) {
if (method.getRange().isPresent()) {
return method.getRange().get().end.line - method.getRange().get().begin.line + 1;
}
return 0;
}
}

View File

@@ -0,0 +1,18 @@
/**
* Provides the {@code MethodAtlasApp} command-line utility for scanning Java
* source trees for JUnit test methods and emitting per-method statistics.
*
* <p>
* The primary entry point is {@link org.egothor.methodatlas.MethodAtlasApp}.
* </p>
*
* <p>
* Output modes:
* </p>
* <ul>
* <li>CSV (default): {@code fqcn,method,loc,tags}</li>
* <li>Plain text: enabled by {@code -plain} as the first command-line
* argument</li>
* </ul>
*/
package org.egothor.methodatlas;

View File

@@ -0,0 +1,242 @@
package org.egothor.methodatlas;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* End-to-end tests for {@link MethodAtlasApp} output formats (CSV default,
* -plain).
*
* These tests copy predefined Java fixture files from
* src/test/resources/fixtures into a temporary directory and run
* MethodAtlasApp.main(...) against that directory, asserting the detected
* methods, LOC, and extracted @Tag values.
*/
public class MethodAtlasAppTest {
@Test
public void csvMode_detectsMethodsLocAndTags(@TempDir Path tempDir) throws Exception {
copyFixture(tempDir, "SampleOneTest.java");
copyFixture(tempDir, "AnotherTest.java");
String output = runAppCapturingStdout(new String[] { tempDir.toString() });
List<String> lines = nonEmptyLines(output);
assertTrue(lines.size() >= 3, "Expected header + at least 2 records, got: " + lines.size());
assertEquals("fqcn,method,loc,tags", lines.get(0));
Map<String, CsvRow> rows = new HashMap<>();
for (int i = 1; i < lines.size(); i++) {
CsvRow row = parseCsvRow(lines.get(i));
rows.put(row.fqcn + "#" + row.method, row);
}
assertCsvRow(rows, "com.acme.tests.SampleOneTest", "alpha", 8, List.of("fast", "crypto"));
assertCsvRow(rows, "com.acme.tests.SampleOneTest", "beta", 6, List.of("param"));
assertCsvRow(rows, "com.acme.tests.SampleOneTest", "gamma", 4, List.of("nested1", "nested2"));
assertCsvRow(rows, "com.acme.other.AnotherTest", "delta", 3, List.of());
}
@Test
public void plainMode_detectsMethodsLocAndTags(@TempDir Path tempDir) throws Exception {
copyFixture(tempDir, "SampleOneTest.java");
copyFixture(tempDir, "AnotherTest.java");
String output = runAppCapturingStdout(new String[] { "-plain", tempDir.toString() });
List<String> lines = nonEmptyLines(output);
assertTrue(lines.size() >= 4, "Expected at least 4 method lines, got: " + lines.size());
Map<String, PlainRow> rows = new HashMap<>();
for (String line : lines) {
PlainRow row = parsePlainRow(line);
rows.put(row.fqcn + "#" + row.method, row);
}
assertPlainRow(rows, "com.acme.tests.SampleOneTest", "alpha", 8, "fast;crypto");
assertPlainRow(rows, "com.acme.tests.SampleOneTest", "beta", 6, "param");
assertPlainRow(rows, "com.acme.tests.SampleOneTest", "gamma", 4, "nested1;nested2");
assertPlainRow(rows, "com.acme.other.AnotherTest", "delta", 3, "-");
}
private static void assertCsvRow(Map<String, CsvRow> rows, String fqcn, String method, int expectedLoc,
List<String> expectedTags) {
CsvRow row = rows.get(fqcn + "#" + method);
assertNotNull(row, "Missing row for " + fqcn + "#" + method);
assertEquals(expectedLoc, row.loc, "LOC mismatch for " + fqcn + "#" + method);
assertEquals(expectedTags, row.tags, "Tags mismatch for " + fqcn + "#" + method);
}
private static void assertPlainRow(Map<String, PlainRow> rows, String fqcn, String method, int expectedLoc,
String expectedTagsText) {
PlainRow row = rows.get(fqcn + "#" + method);
assertNotNull(row, "Missing row for " + fqcn + "#" + method);
assertEquals(expectedLoc, row.loc, "LOC mismatch for " + fqcn + "#" + method);
assertEquals(expectedTagsText, row.tagsText, "Tags mismatch for " + fqcn + "#" + method);
}
private static void copyFixture(Path destDir, String fixtureFileName) throws IOException {
String resourcePath = "/fixtures/" + fixtureFileName + ".txt";
try (InputStream in = MethodAtlasAppTest.class.getResourceAsStream(resourcePath)) {
assertNotNull(in, "Missing test resource: " + resourcePath);
Path out = destDir.resolve(fixtureFileName);
Files.copy(in, out);
}
}
private static String runAppCapturingStdout(String[] args) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream previous = System.out;
try (PrintStream ps = new PrintStream(baos, true, StandardCharsets.UTF_8)) {
System.setOut(ps);
MethodAtlasApp.main(args);
} finally {
System.setOut(previous);
}
return baos.toString(StandardCharsets.UTF_8);
}
private static List<String> nonEmptyLines(String text) {
String[] parts = text.split("\\R");
List<String> lines = new ArrayList<>();
for (String p : parts) {
String trimmed = p.trim();
if (!trimmed.isEmpty()) {
lines.add(trimmed);
}
}
return lines;
}
private static CsvRow parseCsvRow(String line) {
List<String> fields = parseCsvFields(line);
assertEquals(4, fields.size(), "Expected 4 CSV fields, got " + fields.size() + " from: " + line);
CsvRow row = new CsvRow();
row.fqcn = fields.get(0);
row.method = fields.get(1);
row.loc = Integer.parseInt(fields.get(2));
String tagsText = fields.get(3);
row.tags = splitTags(tagsText);
return row;
}
private static List<String> splitTags(String tagsText) {
List<String> tags = new ArrayList<>();
if (tagsText == null || tagsText.isEmpty()) {
return tags;
}
String[] parts = tagsText.split(";");
for (String p : parts) {
String t = p.trim();
if (!t.isEmpty()) {
tags.add(t);
}
}
return tags;
}
/**
* Minimal CSV parser that supports commas and quotes.
*/
private static List<String> parseCsvFields(String line) {
List<String> out = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean inQuotes = false;
int i = 0;
while (i < line.length()) {
char ch = line.charAt(i);
if (inQuotes) {
if (ch == '\"') {
if (i + 1 < line.length() && line.charAt(i + 1) == '\"') {
current.append('\"');
i += 2;
continue;
}
inQuotes = false;
i++;
continue;
}
current.append(ch);
i++;
continue;
}
if (ch == '\"') {
inQuotes = true;
i++;
continue;
}
if (ch == ',') {
out.add(current.toString());
current.setLength(0);
i++;
continue;
}
current.append(ch);
i++;
}
out.add(current.toString());
return out;
}
private static PlainRow parsePlainRow(String line) {
Pattern p = Pattern.compile("^(.*),\\s+(.*),\\s+LOC=(\\d+),\\s+TAGS=(.*)$");
Matcher m = p.matcher(line);
assertTrue(m.matches(), "Unexpected plain output line: " + line);
PlainRow row = new PlainRow();
row.fqcn = m.group(1).trim();
row.method = m.group(2).trim();
row.loc = Integer.parseInt(m.group(3));
row.tagsText = m.group(4).trim();
return row;
}
private static final class CsvRow {
private String fqcn;
private String method;
private int loc;
private List<String> tags;
}
private static final class PlainRow {
private String fqcn;
private String method;
private int loc;
private String tagsText;
}
}

View File

@@ -0,0 +1,10 @@
package com.acme.other;
import org.junit.jupiter.api.RepeatedTest;
public class AnotherTest {
@RepeatedTest(2)
void delta() {
}
}

View File

@@ -0,0 +1,31 @@
package com.acme.tests;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Tags;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class SampleOneTest {
@Test
@Tag("fast")
@Tag("crypto")
void alpha() {
int a = 1;
int b = 2;
int c = a + b;
}
@ParameterizedTest
@ValueSource(ints = { 1, 2 })
@Tag("param")
void beta(int x) {
// single line
}
@Test
@Tags({ @Tag("nested1"), @Tag("nested2") })
void gamma() {
}
}