diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 8306bb2..0000000 --- a/build.gradle +++ /dev/null @@ -1,154 +0,0 @@ -plugins { - id 'java' - id 'application' - id 'jacoco' - id "com.github.breadmoirai.github-release" version "2.2.12" - id "com.github.jarmstrong.buildconfig" version "1.9.0" - id "com.github.hierynomus.license" version "0.15.0" -} - -group 'com.clouds42' -version '2.7.3' - -sourceCompatibility = 11 - -repositories { - mavenCentral() - maven { url 'https://jitpack.io' } - maven { url 'https://repo1.maven.org/maven2/' } -} - - -configurations { - providedCompile -} - -dependencies { - def output = new ByteArrayOutputStream() - def edtLocation = System.getenv('EDT_LOCATION') - if (edtLocation == null) { - def ringExecutable = 'ring.sh' - if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) { - ringExecutable = 'ring.cmd' - } - exec { - commandLine ringExecutable, 'edt@2021.1.5', 'locations', 'list' - standardOutput = output - } - edtLocation = output.toString().trim().split("\n")[0].trim() + '/plugins/' - } - println 'EDT location: ' + edtLocation - - compile group: 'info.picocli', name: 'picocli', version: '4.6.3' - annotationProcessor 'info.picocli:picocli-codegen:4.6.3' - - compile group: 'org.slf4j', name: 'slf4j-api', version: '2.0.3' - compile group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.3' - - compile group: 'org.scala-sbt.ipcsocket', name: 'ipcsocket', version: '1.5.0' - - compile group: 'org.eclipse.emf', name: 'org.eclipse.emf.common', version: '2.25.0' - compile group: 'org.eclipse.emf', name: 'org.eclipse.emf.ecore.xmi', version: '2.16.0' - compile group: 'org.eclipse.emf', name: 'org.eclipse.emf.ecore.xcore.lib', version: '1.6.0' - - compile group: 'org.eclipse.platform', name: 'org.eclipse.osgi', version: '3.17.200' - - compile group: 'org.eclipse.platform', name: 'org.eclipse.core.runtime', version: '3.24.100' - compile group: 'org.eclipse.platform', name: 'org.eclipse.osgi.services', version: '3.10.200' - compile group: 'org.eclipse.platform', name: 'org.eclipse.equinox.common', version: '3.16.0' - - - compile group: 'org.eclipse.jetty', name: 'jetty-client', version: '11.0.12' - - compile group: 'com.google.guava', name: 'guava', version: '31.1-jre' - - compile group: 'com.google.inject', name: 'guice', version: '5.1.0' - - compile group: 'de.vandermeer', name:'asciitable', version: '0.3.2' - - implementation 'com.github.1c-syntax:mdclasses:0.10.3' - compile group: 'io.github.1c-syntax', name: 'bsl-common-library', version: '0.3.0' - - implementation('com.github.1c-syntax:bsl-parser:0.21.0') { - exclude group: "com.tunnelvisionlabs", module: "antlr4-annotations" - exclude group: "com.ibm.icu", module: "*" - exclude group: "org.antlr", module: "ST4" - exclude group: "org.abego.treelayout", module: "org.abego.treelayout.core" - exclude group: "org.antlr", module: "antlr-runtime" - exclude group: "org.glassfish", module: "javax.json" - } - - providedCompile fileTree(edtLocation) { include 'com._1c.g5.v8.dt.debug.*.jar' } - - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0' - testCompile 'org.xmlunit:xmlunit-core:2.9.0' - testCompile 'org.xmlunit:xmlunit-matchers:2.9.0' - testCompile 'com.fasterxml.jackson.core:jackson-core:2.13.4' - testCompile 'com.fasterxml.jackson.core:jackson-databind:2.13.4' -} - -tasks.withType(JavaCompile) { - sourceSets.main.compileClasspath += configurations.providedCompile - options.compilerArgs += ["-Aproject=${project.group}/${project.name}"] - options.encoding = 'UTF-8' -} - -run { - classpath += configurations.providedCompile -} - -test { - finalizedBy jacocoTestReport - classpath += configurations.providedCompile - useJUnitPlatform() - testLogging.showStandardStreams = true -} - -startScripts { - unixStartScriptGenerator.template = resources.text.fromFile(project.getRootDir().getAbsolutePath() + '/scripts/unixStartScript.txt') - windowsStartScriptGenerator.template = resources.text.fromFile(project.getRootDir().getAbsolutePath() + '/scripts/windowsStartScript.txt') -} - -application { - mainClassName = 'com.clouds42.Coverage41C' -} - -jacocoTestReport { - dependsOn test -} - -buildConfig { - className("BuildConfig") - packageName("com.clouds42") - buildConfigField("String", "APP_VERSION", "\"${project.version}\"") - buildConfigField("long", "BUILD_TIME", "${System.currentTimeMillis()}L") -} - -githubRelease { - token findProperty('github.token')?: "" - owner "proDOOMman" - repo "Coverage41C" - targetCommitish "master" - releaseAssets.from(distZip.archiveFile) - dryRun false -} - -license { - header = rootProject.file("HEADER.txt") - - ext["year"] = "2020-" + Calendar.getInstance().get(Calendar.YEAR) - ext["name"] = "Kosolapov Stanislav aka proDOOMman " - ext["project"] = "Coverage41C" - exclude("**/*.properties") - exclude("**/*.xml") - exclude("**/*.json") - exclude("**/*.bsl") - exclude("**/*.os") - exclude("**/*.txt") - exclude("**/*.java.orig") - exclude("**/*.impl") - exclude("**/BuildConfig.java") - strictCheck = true - mapping("java", "SLASHSTAR_STYLE") -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..b1fc9ea --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,173 @@ +import java.util.* + +plugins { + java + application + jacoco + id("com.github.breadmoirai.github-release") version "2.5.2" + id("com.github.jarmstrong.buildconfig") version "1.9.0" + id("cloud.rio.license") version "0.18.0" +} + +val edtLocation = file(project.properties["EDT_LOCATION"] as String) +println("EDT location: $edtLocation") + +repositories { + mavenCentral() + maven("https://jitpack.io") + + flatDir { + dirs(edtLocation) + } +} + +group = "com.clouds42" +version = "2.7.4" + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +application { + mainClass = "com.clouds42.Coverage41C" +} + +dependencies { + + compileOnly( + fileTree(edtLocation) { + include("com._1c.g5.v8.dt.debug.*.jar") + } + ) + + implementation("info.picocli:picocli:4.7.7") + + implementation("org.slf4j:slf4j-api:2.0.17") + implementation("org.slf4j:slf4j-simple:2.0.17") + + implementation("org.scala-sbt.ipcsocket:ipcsocket:1.6.3") + + implementation("org.eclipse.emf:org.eclipse.emf.common:2.44.0") + implementation("org.eclipse.emf:org.eclipse.emf.ecore.xmi:2.39.0") + implementation("org.eclipse.emf:org.eclipse.emf.ecore.xcore.lib:1.7.1") + + implementation("org.eclipse.platform:org.eclipse.osgi:3.24.0") + implementation("org.eclipse.platform:org.eclipse.core.runtime:3.34.100") + implementation("org.eclipse.platform:org.eclipse.osgi.services:3.12.300") + implementation("org.eclipse.platform:org.eclipse.equinox.common:3.20.300") + + implementation("org.eclipse.jetty:jetty-client:11.0.26") + + implementation("com.google.guava:guava:33.5.0-jre") + implementation("com.google.inject:guice:7.0.0") + + implementation("de.vandermeer:asciitable:0.3.2") { + exclude("org.apache.commons:commons-lang3") + } + + implementation("io.github.1c-syntax:bsl-common-library:0.9.0") + implementation("io.github.1c-syntax:utils:0.6.6") + + implementation("io.github.1c-syntax:mdclasses:0.17.0") + implementation("io.github.1c-syntax:bsl-parser:0.29.0") { + exclude("com.ibm.icu", "*") + exclude("org.antlr", "ST4") + exclude("org.antlr", "antlr-runtime") + } + + annotationProcessor("info.picocli:picocli-codegen:4.7.7") + + testImplementation("org.xmlunit:xmlunit-core:2.11.0") + testImplementation("org.xmlunit:xmlunit-matchers:2.11.0") + testImplementation("com.fasterxml.jackson.core:jackson-core:2.20.1") + testImplementation("com.fasterxml.jackson.core:jackson-databind:2.20.1") + + testImplementation("org.junit.jupiter:junit-jupiter-api:5.11.4") + testImplementation("org.junit.jupiter:junit-jupiter-engine:5.11.4") +} + +buildConfig { + className("BuildConfig") + packageName("com.clouds42") + buildConfigField("String", "APP_VERSION", "\"${project.version}\"") + buildConfigField("long", "BUILD_TIME", "${System.currentTimeMillis()}L") +} + +tasks.generateBuildConfig { + dependsOn(tasks.licenseMain) +} + +tasks.named("startScripts", CreateStartScripts::class) { + (unixStartScriptGenerator as TemplateBasedScriptGenerator).template = + resources.text.fromFile(file("${project.rootDir.absolutePath}/scripts/unixStartScript.txt")) + + (windowsStartScriptGenerator as TemplateBasedScriptGenerator).template = + resources.text.fromFile(file("${project.rootDir.absolutePath}/scripts/windowsStartScript.txt")) +} + +tasks.withType { + options.encoding = "UTF-8" + options.compilerArgs.add("-Aproject=${project.group}/${project.name}") + classpath += configurations.compileClasspath.get() +} + +tasks.test { + classpath += configurations.compileClasspath.get() + useJUnitPlatform() + + testLogging { + events("passed", "skipped", "failed", "standard_error") + } + + reports { + html.required.set(true) + } + + testLogging.showStandardStreams = true +} + +tasks.check { + dependsOn(tasks.jacocoTestReport) +} + +tasks.jacocoTestReport { + reports { + xml.required.set(true) + xml.outputLocation.set(File("${layout.buildDirectory.get()}/reports/jacoco/test/jacoco.xml")) + } +} + +license { + header = rootProject.file("HEADER.txt") + skipExistingHeaders = false + strictCheck = true + mapping("java", "SLASHSTAR_STYLE") + + ext["year"] = "2020-" + Calendar.getInstance().get(Calendar.YEAR) + ext["name"] = "Kosolapov Stanislav aka proDOOMman " + ext["project"] = "Coverage41C" + exclude("**/*.properties") + exclude("**/*.xml") + exclude("**/*.json") + exclude("**/*.bsl") + exclude("**/*.os") + exclude("**/*.txt") + exclude("**/*.java.orig") + exclude("**/*.impl") + exclude("**/BuildConfig.java") + exclude("**/test/resources/**/*") +} + +tasks.named("run", JavaExec::class) { + classpath += configurations.compileClasspath.get() +} + +githubRelease { + token(project.findProperty("github.token")?.toString() ?: "") + owner = "proDOOMman" + repo = "Coverage41C" + targetCommitish = "master" + releaseAssets(tasks.named("distZip")) + dryRun = false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7860b81 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.parallel=true +org.gradle.jvmargs=-Xmx1024m -XX:MaxMetaspaceSize=512m + +EDT_LOCATION=/opt/1C/1CE/components/1c-edt-2024.2.6+7-x86_64/plugins diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 87b738c..1b33c55 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5af0a9a..d4081da 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Tue Mar 17 22:47:19 MSK 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index af6708f..23d15a9 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,129 @@ -#!/usr/bin/env sh +#!/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 UN*X -## +# +# 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 -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# 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"' +# 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\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +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 - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +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 +CLASSPATH="\\\"\\\"" + # 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" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,92 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -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" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + 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 - i=$((i+1)) + # 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 - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# 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, 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat index 6d57edc..5eed7ee 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,84 +1,94 @@ -@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=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@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" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -: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 %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@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= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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 diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index cbce5dc..0000000 --- a/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'Coverage41C' - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..1d7e0d3 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "Coverage41C" diff --git a/src/main/java/com/clouds42/AbstractDebugClient.java b/src/main/java/com/clouds42/AbstractDebugClient.java index 0c8b209..a41c3a0 100644 --- a/src/main/java/com/clouds42/AbstractDebugClient.java +++ b/src/main/java/com/clouds42/AbstractDebugClient.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/CommandLineOptions/ConnectionOptions.java b/src/main/java/com/clouds42/CommandLineOptions/ConnectionOptions.java index a480b39..4c8fc84 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/ConnectionOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/ConnectionOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/CommandLineOptions/ConvertOptions.java b/src/main/java/com/clouds42/CommandLineOptions/ConvertOptions.java index 6f9be4c..5f9a072 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/ConvertOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/ConvertOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/CommandLineOptions/DebuggerOptions.java b/src/main/java/com/clouds42/CommandLineOptions/DebuggerOptions.java index 3462c5a..1ede586 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/DebuggerOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/DebuggerOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -93,7 +93,7 @@ public void setAutoconnectTargets(List autoconnectTargets) { public List getAutoconnectTargets() { if (autoconnectTargets == null || autoconnectTargets.isEmpty()) { - autoconnectTargets = new LinkedList(); + autoconnectTargets = new LinkedList<>(); autoconnectTargets.addAll(DebugTargetType.VALUES); autoconnectTargets.remove(DebugTargetType.UNKNOWN); diff --git a/src/main/java/com/clouds42/CommandLineOptions/FilterOptions.java b/src/main/java/com/clouds42/CommandLineOptions/FilterOptions.java index 66cbc82..b2d4196 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/FilterOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/FilterOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/CommandLineOptions/LoggingOptions.java b/src/main/java/com/clouds42/CommandLineOptions/LoggingOptions.java index 00d0cc2..38a53ad 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/LoggingOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/LoggingOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -35,7 +35,7 @@ public class LoggingOptions { private Boolean verbose; public Boolean isVerbose() { - return verbose.booleanValue(); + return verbose; } public void setVerbose(Boolean verbose) { diff --git a/src/main/java/com/clouds42/CommandLineOptions/MetadataOptions.java b/src/main/java/com/clouds42/CommandLineOptions/MetadataOptions.java index 0157429..e8ca34b 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/MetadataOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/MetadataOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/CommandLineOptions/OutputOptions.java b/src/main/java/com/clouds42/CommandLineOptions/OutputOptions.java index b4ee5a6..b3f4bdb 100644 --- a/src/main/java/com/clouds42/CommandLineOptions/OutputOptions.java +++ b/src/main/java/com/clouds42/CommandLineOptions/OutputOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/ConvertCommand.java b/src/main/java/com/clouds42/Commands/ConvertCommand.java index c65016c..d1158cf 100644 --- a/src/main/java/com/clouds42/Commands/ConvertCommand.java +++ b/src/main/java/com/clouds42/Commands/ConvertCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/CoverServer.java b/src/main/java/com/clouds42/Commands/CoverServer.java index fc05921..5be5c18 100644 --- a/src/main/java/com/clouds42/Commands/CoverServer.java +++ b/src/main/java/com/clouds42/Commands/CoverServer.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/CoverageCommand.java b/src/main/java/com/clouds42/Commands/CoverageCommand.java index 5265a75..7bd255d 100644 --- a/src/main/java/com/clouds42/Commands/CoverageCommand.java +++ b/src/main/java/com/clouds42/Commands/CoverageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -259,10 +259,7 @@ private void measureResultProcessing(Map uriListByKey, Set try { Stream all_lines = Files.lines(Paths.get(uri)); Optional first = all_lines.skip(lineNo.longValue() - 1).findFirst(); - if (first.isPresent()) { - String specific_line_n = first.get(); - logger.info(">>> {}", specific_line_n); - } + first.ifPresent(specific_line_n -> logger.info(">>> {}", specific_line_n)); } catch (Exception e) { logger.error(e.getLocalizedMessage()); } diff --git a/src/main/java/com/clouds42/Commands/SendCheckMessageCommand.java b/src/main/java/com/clouds42/Commands/SendCheckMessageCommand.java index 3091a25..1e6fca6 100644 --- a/src/main/java/com/clouds42/Commands/SendCheckMessageCommand.java +++ b/src/main/java/com/clouds42/Commands/SendCheckMessageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/SendCleanMessageCommand.java b/src/main/java/com/clouds42/Commands/SendCleanMessageCommand.java index 4375314..f0c777f 100644 --- a/src/main/java/com/clouds42/Commands/SendCleanMessageCommand.java +++ b/src/main/java/com/clouds42/Commands/SendCleanMessageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/SendDumpMessageCommand.java b/src/main/java/com/clouds42/Commands/SendDumpMessageCommand.java index 0f8f966..7472d44 100644 --- a/src/main/java/com/clouds42/Commands/SendDumpMessageCommand.java +++ b/src/main/java/com/clouds42/Commands/SendDumpMessageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/SendMessageCommand.java b/src/main/java/com/clouds42/Commands/SendMessageCommand.java index 197806b..bafa572 100644 --- a/src/main/java/com/clouds42/Commands/SendMessageCommand.java +++ b/src/main/java/com/clouds42/Commands/SendMessageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/SendStatsMessageCommand.java b/src/main/java/com/clouds42/Commands/SendStatsMessageCommand.java index 4ae34ed..6ef2c50 100644 --- a/src/main/java/com/clouds42/Commands/SendStatsMessageCommand.java +++ b/src/main/java/com/clouds42/Commands/SendStatsMessageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Commands/SendStopMessageCommand.java b/src/main/java/com/clouds42/Commands/SendStopMessageCommand.java index 4958b40..be950ad 100644 --- a/src/main/java/com/clouds42/Commands/SendStopMessageCommand.java +++ b/src/main/java/com/clouds42/Commands/SendStopMessageCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Coverage41C.java b/src/main/java/com/clouds42/Coverage41C.java index e23ba81..4a48d7d 100644 --- a/src/main/java/com/clouds42/Coverage41C.java +++ b/src/main/java/com/clouds42/Coverage41C.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/DebugClient.java b/src/main/java/com/clouds42/DebugClient.java index 3388bb7..0f54885 100644 --- a/src/main/java/com/clouds42/DebugClient.java +++ b/src/main/java/com/clouds42/DebugClient.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/GlobalCallsFilter.java b/src/main/java/com/clouds42/GlobalCallsFilter.java index a9568b1..86073ad 100644 --- a/src/main/java/com/clouds42/GlobalCallsFilter.java +++ b/src/main/java/com/clouds42/GlobalCallsFilter.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/LinesToCoverage.java b/src/main/java/com/clouds42/LinesToCoverage.java index 9d21115..326677b 100644 --- a/src/main/java/com/clouds42/LinesToCoverage.java +++ b/src/main/java/com/clouds42/LinesToCoverage.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,6 @@ import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; -import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; @@ -33,102 +32,102 @@ public class LinesToCoverage { - private static final Set> contexts = Set.of( - BSLParser.AssignmentContext.class, - BSLParser.CallStatementContext.class, - BSLParser.GotoStatementContext.class, - BSLParser.ReturnStatementContext.class, - BSLParser.BreakStatementContext.class, - BSLParser.ContinueStatementContext.class, - BSLParser.IfStatementContext.class, - BSLParser.ElsifBranchContext.class, - BSLParser.RaiseStatementContext.class, - BSLParser.ForEachStatementContext.class, - BSLParser.ForStatementContext.class, - BSLParser.WhileStatementContext.class, - BSLParser.GlobalMethodCallContext.class, - BSLParser.MethodCallContext.class, - BSLParser.ExecuteStatementContext.class, - BSLParser.AddHandlerStatementContext.class, - BSLParser.RemoveHandlerStatementContext.class - ); - - private static final Set tokenTypes = Set.of( - BSLLexer.ENDDO_KEYWORD, - BSLLexer.ENDFUNCTION_KEYWORD, - BSLLexer.ENDPROCEDURE_KEYWORD, - BSLLexer.ENDTRY_KEYWORD, - BSLLexer.ENDIF_KEYWORD, - BSLLexer.DO_KEYWORD - ); - - static int[] getLines(BSLParserRuleContext ast) { - - return Trees.getDescendants(ast).stream() - .filter(LinesToCoverage::mustCovered) - .filter(GlobalCallsFilter::filterByName) - .mapToInt(LinesToCoverage::getLine) - .filter(lineNumber -> lineNumber != 0) - .distinct().toArray(); + private static final Set> contexts = Set.of( + BSLParser.AssignmentContext.class, + BSLParser.CallStatementContext.class, + BSLParser.GotoStatementContext.class, + BSLParser.ReturnStatementContext.class, + BSLParser.BreakStatementContext.class, + BSLParser.ContinueStatementContext.class, + BSLParser.IfStatementContext.class, + BSLParser.ElsifBranchContext.class, + BSLParser.RaiseStatementContext.class, + BSLParser.ForEachStatementContext.class, + BSLParser.ForStatementContext.class, + BSLParser.WhileStatementContext.class, + BSLParser.GlobalMethodCallContext.class, + BSLParser.MethodCallContext.class, + BSLParser.ExecuteStatementContext.class, + BSLParser.AddHandlerStatementContext.class, + BSLParser.RemoveHandlerStatementContext.class + ); + + private static final Set tokenTypes = Set.of( + BSLLexer.ENDDO_KEYWORD, + BSLLexer.ENDFUNCTION_KEYWORD, + BSLLexer.ENDPROCEDURE_KEYWORD, + BSLLexer.ENDTRY_KEYWORD, + BSLLexer.ENDIF_KEYWORD, + BSLLexer.DO_KEYWORD + ); + + static int[] getLines(ParserRuleContext ast) { + + return Trees.getDescendants(ast).stream() + .filter(LinesToCoverage::mustCovered) + .filter(GlobalCallsFilter::filterByName) + .mapToInt(LinesToCoverage::getLine) + .filter(lineNumber -> lineNumber != 0) + .distinct().toArray(); + } + + static boolean mustCovered(ParseTree node) { + + if (node instanceof ParserRuleContext) { + return contexts.contains(node.getClass()); + } else if (node instanceof TerminalNode) { + return tokenTypes.contains( + ((TerminalNode) node).getSymbol().getType() + ); } - static boolean mustCovered(ParseTree node) { - - if (node instanceof ParserRuleContext) { - return contexts.contains(node.getClass()); - } else if (node instanceof TerminalNode) { - return tokenTypes.contains( - ((TerminalNode) node).getSymbol().getType() - ); - } - - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); + } + + private static int getLine(ParseTree node) { + + if (node instanceof ParserRuleContext) { + if (!(node instanceof BSLParser.MethodCallContext)) { + return ((ParserRuleContext) node).getStart().getLine(); + } + var methodCall = getRootParent((ParserRuleContext) node, BSLParser.RULE_complexIdentifier); + if (methodCall != null) { + return methodCall.getStart().getLine(); + } + } else if (node instanceof TerminalNode) { + return ((TerminalNode) node).getSymbol().getLine(); } - private static int getLine(ParseTree node) { - - if (node instanceof ParserRuleContext) { - if (!(node instanceof BSLParser.MethodCallContext)) { - return ((ParserRuleContext) node).getStart().getLine(); - } - var methodCall = getRootParent((BSLParserRuleContext) node, BSLParser.RULE_complexIdentifier); - if (methodCall != null) { - return methodCall.getStart().getLine(); - } - } else if (node instanceof TerminalNode) { - return ((TerminalNode) node).getSymbol().getLine(); - } - - return 0; + return 0; + } + + // Удалить после переноса хелпера в парсер + + /** + * Рекурсивно находит самого верхнего родителя текущей ноды нужного типа + * + * @param tnc - нода, для которой ищем родителя + * @param ruleindex - BSLParser.RULE_* + * @return tnc - если родитель не найден, вернет null + */ + public static ParserRuleContext getRootParent(ParserRuleContext tnc, int ruleindex) { + final var parent = tnc.getParent(); + if (parent == null) { + return null; } - // Удалить после переноса хелпера в парсер - - /** - * Рекурсивно находит самого верхнего родителя текущей ноды нужного типа - * - * @param tnc - нода, для которой ищем родителя - * @param ruleindex - BSLParser.RULE_* - * @return tnc - если родитель не найден, вернет null - */ - public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, int ruleindex) { - final var parent = tnc.getParent(); - if (parent == null) { - return null; - } - - if (getRuleIndex(parent) == ruleindex) { - return (BSLParserRuleContext) parent; - } else { - return getRootParent((BSLParserRuleContext) parent, ruleindex); - } + if (getRuleIndex(parent) == ruleindex) { + return parent; + } else { + return getRootParent(parent, ruleindex); } + } - private static int getRuleIndex(ParseTree node) { - if (node instanceof TerminalNode) { - return ((TerminalNode) node).getSymbol().getType(); - } else { - return ((BSLParserRuleContext) node).getRuleIndex(); - } + private static int getRuleIndex(ParseTree node) { + if (node instanceof TerminalNode terminalNode) { + return terminalNode.getSymbol().getType(); + } else { + return ((ParserRuleContext) node).getRuleIndex(); } + } } diff --git a/src/main/java/com/clouds42/MyRuntimeDebugModelXmlSerializer.java b/src/main/java/com/clouds42/MyRuntimeDebugModelXmlSerializer.java index c433faa..a3b955d 100644 --- a/src/main/java/com/clouds42/MyRuntimeDebugModelXmlSerializer.java +++ b/src/main/java/com/clouds42/MyRuntimeDebugModelXmlSerializer.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/PipeMessages.java b/src/main/java/com/clouds42/PipeMessages.java index 5e83300..4870652 100644 --- a/src/main/java/com/clouds42/PipeMessages.java +++ b/src/main/java/com/clouds42/PipeMessages.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/clouds42/Utils.java b/src/main/java/com/clouds42/Utils.java index 4506c22..eb0c651 100644 --- a/src/main/java/com/clouds42/Utils.java +++ b/src/main/java/com/clouds42/Utils.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,17 +24,15 @@ import com.clouds42.CommandLineOptions.ConnectionOptions; import com.clouds42.CommandLineOptions.MetadataOptions; import com.clouds42.CommandLineOptions.OutputOptions; -import com.github._1c_syntax.bsl.mdo.ModuleOwner; +import com.github._1c_syntax.bsl.mdclasses.CF; +import com.github._1c_syntax.bsl.mdclasses.MDClasses; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.SettingsStorage; import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLTokenizer; -import com.github._1c_syntax.bsl.parser.Tokenizer; -import com.github._1c_syntax.mdclasses.Configuration; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBSL; -//import com.github._1c_syntax.mdclasses.mdo.MDOHasModule; -import com.github._1c_syntax.mdclasses.mdo.MDSettingsStorage; -import com.github._1c_syntax.mdclasses.mdo.support.MDOModule; -import com.github._1c_syntax.bsl.types.ModuleType; import com.github._1c_syntax.bsl.support.SupportVariant; +import com.github._1c_syntax.bsl.types.ModuleType; +import com.github._1c_syntax.utils.CaseInsensitivePattern; import de.vandermeer.asciitable.AsciiTable; import de.vandermeer.asciitable.CWC_LongestLine; import org.antlr.v4.runtime.Token; @@ -56,7 +54,14 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; import java.lang.invoke.MethodHandles; import java.math.BigDecimal; import java.net.URI; @@ -65,640 +70,618 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; public class Utils { - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - - public static String getModuleTypeUuid(ModuleType moduleType, ModuleOwner mdObject) { - if (moduleType == ModuleType.CommandModule) { - return "078a6af8-d22c-4248-9c33-7e90075a3d2c"; - } else if (moduleType == ModuleType.ObjectModule) { - return "a637f77f-3840-441d-a1c3-699c8c5cb7e0"; - } else if (moduleType == ModuleType.ManagerModule) { - if (mdObject instanceof MDSettingsStorage) { - return "0c8cad23-bf8c-468e-b49e-12f1927c048b"; - } else { - return "d1b64a2c-8078-4982-8190-8f81aefda192"; - } - } else if (moduleType == ModuleType.FormModule) { - return "32e087ab-1491-49b6-aba7-43571b41ac2b"; - } else if (moduleType == ModuleType.RecordSetModule) { - return "9f36fd70-4bf4-47f6-b235-935f73aab43f"; - } else if (moduleType == ModuleType.ValueManagerModule) { - return "3e58c91f-9aaa-4f42-8999-4baf33907b75"; - } else if (moduleType == ModuleType.ManagedApplicationModule) { - return "d22e852a-cf8a-4f77-8ccb-3548e7792bea"; - } else if (moduleType == ModuleType.SessionModule) { - return "9b7bbbae-9771-46f2-9e4d-2489e0ffc702"; - } else if (moduleType == ModuleType.ExternalConnectionModule) { - return "a4a9c1e2-1e54-4c7f-af06-4ca341198fac"; - } else if (moduleType == ModuleType.OrdinaryApplicationModule) { - return "a78d9ce3-4e0c-48d5-9863-ae7342eedf94"; - } else if (moduleType == ModuleType.HTTPServiceModule - || moduleType == ModuleType.WEBServiceModule - || moduleType == ModuleType.CommonModule) { - return "d5963243-262e-4398-b4d7-fb16d06484f6"; - } else if (moduleType == ModuleType.ApplicationModule - || moduleType == ModuleType.UNKNOWN) { - logger.info("Couldn't find UUID for module type: {} for object {}", moduleType, mdObject.getName()); + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + + private static final Pattern COVER_ON = CaseInsensitivePattern.compile("Cover:(?:вкл|on)"); + + private static final Pattern COVER_OFF = CaseInsensitivePattern.compile("Cover:(?:выкл|off)"); + + private static final Pattern COVER_AUTO = CaseInsensitivePattern.compile("Cover:(?:авто|auto)"); + + public static String getModuleTypeUuid(ModuleType moduleType, MD mdObject) { + String result = ""; + switch (moduleType) { + case CommandModule -> result = "078a6af8-d22c-4248-9c33-7e90075a3d2c"; + case ObjectModule -> result = "a637f77f-3840-441d-a1c3-699c8c5cb7e0"; + case ManagerModule -> { + if (mdObject instanceof SettingsStorage) { + result = "0c8cad23-bf8c-468e-b49e-12f1927c048b"; + } else { + result = "d1b64a2c-8078-4982-8190-8f81aefda192"; } - return "UNKNOWN"; + } + case FormModule -> result = "32e087ab-1491-49b6-aba7-43571b41ac2b"; + case RecordSetModule -> result = "9f36fd70-4bf4-47f6-b235-935f73aab43f"; + case ValueManagerModule -> result = "3e58c91f-9aaa-4f42-8999-4baf33907b75"; + case ManagedApplicationModule -> result = "d22e852a-cf8a-4f77-8ccb-3548e7792bea"; + case SessionModule -> result = "9b7bbbae-9771-46f2-9e4d-2489e0ffc702"; + case ExternalConnectionModule -> result = "a4a9c1e2-1e54-4c7f-af06-4ca341198fac"; + case OrdinaryApplicationModule -> result = "a78d9ce3-4e0c-48d5-9863-ae7342eedf94"; + case HTTPServiceModule, WEBServiceModule, CommonModule -> result = "d5963243-262e-4398-b4d7-fb16d06484f6"; + case ApplicationModule, UNKNOWN -> + logger.info("Couldn't find UUID for module type: {} for object {}", moduleType, mdObject.getName()); + default -> result = "UNKNOWN"; } + return result; + } + + private static String getUriKey(String mdObjUuid, ModuleType moduleType, MD mdObj) { + return mdObjUuid + "/" + getModuleTypeUuid(moduleType, mdObj); + } + + public static String getUriKey(String objectId, String propertyId) { + return objectId + "/" + propertyId; + } + + private static void addCoverageData(Map> coverageData, URI uri) { + BSLTokenizer tokenizer; + try { + tokenizer = new BSLTokenizer(Files.readString(Path.of(uri))); + } catch (IOException e) { + logger.error(e.getLocalizedMessage()); + return; + } + + int[] linesToCover = LinesToCoverage.getLines(tokenizer.getAst()); - private static String getUriKey(String mdObjUuid, ModuleType moduleType, ModuleOwner mdObj) { - return mdObjUuid + "/" + getModuleTypeUuid(moduleType, mdObj); + List> coverageIgnorance = new ArrayList<>(); + Stack coverageIgnoranceStartStack = new Stack<>(); + List> coverageAutoIgnorance = new ArrayList<>(); + Stack coverageAutoIgnoranceStartStack = new Stack<>(); + + if (linesToCover.length > 0) { + + List allTokens = tokenizer.getTokens(); + List comments = allTokens.stream() + .filter(token -> token.getType() == BSLLexer.LINE_COMMENT) + .toList(); + + for (Token comment : comments) { + int commentLine = comment.getLine(); + Matcher offMatcher = COVER_OFF.matcher(comment.getText()); + if (offMatcher.find()) { + coverageIgnoranceStartStack.push(commentLine); + } else { + Matcher autoMatcher = COVER_AUTO.matcher(comment.getText()); + if (autoMatcher.find()) { + coverageAutoIgnoranceStartStack.push(commentLine); + } else { + Matcher onMatcher = COVER_ON.matcher(comment.getText()); + if (onMatcher.find()) { + while (!coverageIgnoranceStartStack.empty()) { + coverageIgnorance.add(Range.between(coverageIgnoranceStartStack.pop(), commentLine)); + } + while (!coverageAutoIgnoranceStartStack.empty()) { + coverageAutoIgnorance.add(Range.between(coverageAutoIgnoranceStartStack.pop(), commentLine)); + } + } + } + } + } + while (!coverageIgnoranceStartStack.empty()) { + coverageIgnorance.add( + Range.between(coverageIgnoranceStartStack.pop(), linesToCover[linesToCover.length - 1])); + } + while (!coverageAutoIgnoranceStartStack.empty()) { + coverageAutoIgnorance.add( + Range.between(coverageAutoIgnoranceStartStack.pop(), linesToCover[linesToCover.length - 1])); + } + + linesToCover = Arrays.stream(linesToCover).filter(i -> + coverageIgnorance.stream().noneMatch(integerRange -> integerRange.contains(i))).toArray(); } - public static String getUriKey(String objectId, String propertyId) { - return objectId + "/" + propertyId; + Map coverMap = new HashMap<>(); + for (int lineNumber : linesToCover) { + int countValue = 0; + if (coverageAutoIgnorance.stream().anyMatch(integerRange -> integerRange.contains(lineNumber))) { + countValue = -1; + } + coverMap.put(new BigDecimal(lineNumber), countValue); + } + coverageData.put(uri, coverMap); + } + + public static Map readMetadata(MetadataOptions metadataOptions, + Map> coverageData) throws Exception { + + boolean rawMode = false; + if (metadataOptions.isRawMode()) { + logger.info("Sources directory not set. Enabling RAW mode"); + rawMode = true; + } else { + logger.info("Project directory: {}", metadataOptions.getProjectDirName()); } + Map uriListByKey = new HashMap<>(); - private static final Pattern COVER_ON = Pattern.compile( - "Cover:(?:вкл|on)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + if (!rawMode) { - private static final Pattern COVER_OFF = Pattern.compile( - "Cover:(?:выкл|off)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + Path rootPath = Path.of(metadataOptions.getProjectDirName()) + .resolve(metadataOptions.getSrcDirName()); + logger.info("Reading configuration sources from root path: {}", rootPath.toAbsolutePath()); - private static final Pattern COVER_AUTO = Pattern.compile( - "Cover:(?:авто|auto)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + if (Files.isDirectory(rootPath)) { - private static void addCoverageData(Map> coverageData, URI uri) { - Tokenizer tokenizer; - try { - tokenizer = new BSLTokenizer(Files.readString(Path.of(uri))); - } catch (IOException e) { - logger.error(e.getLocalizedMessage()); - return; - } + var conf = (CF) MDClasses.createConfiguration(rootPath); + for (var module : conf.getAllModules()) { + var mdObj = conf.getModulesByObject().getOrDefault(module.getUri(), conf); + String mdObjUuid = mdObj.getUuid(); + uriListByKey.put(getUriKey(mdObjUuid, module.getModuleType(), mdObj), module.getUri()); - int[] linesToCover = LinesToCoverage.getLines(tokenizer.getAst()); - - List> coverageIgnorance = new ArrayList<>(); - Stack coverageIgnoranceStartStack = new Stack(); - List> coverageAutoIgnorance = new ArrayList<>(); - Stack coverageAutoIgnoranceStartStack = new Stack(); - - if (linesToCover.length > 0) { - - List allTokens = tokenizer.getTokens(); - List comments = allTokens.stream() - .filter(token -> token.getType() == BSLLexer.LINE_COMMENT) - .collect(Collectors.toList()); - - for (Token comment : comments) { - int commentLine = comment.getLine(); - Matcher offMatcher = COVER_OFF.matcher(comment.getText()); - if (offMatcher.find()) { - coverageIgnoranceStartStack.push(commentLine); - } else { - Matcher autoMatcher = COVER_AUTO.matcher(comment.getText()); - if (autoMatcher.find()) { - coverageAutoIgnoranceStartStack.push(commentLine); - } else { - Matcher onMatcher = COVER_ON.matcher(comment.getText()); - if (onMatcher.find()) { - while (!coverageIgnoranceStartStack.empty()) { - coverageIgnorance.add(Range.between(coverageIgnoranceStartStack.pop(), commentLine)); - } - while (!coverageAutoIgnoranceStartStack.empty()) { - coverageAutoIgnorance.add(Range.between(coverageAutoIgnoranceStartStack.pop(), commentLine)); - } - } - } - } - } - while (!coverageIgnoranceStartStack.empty()) { - coverageIgnorance.add( - Range.between(coverageIgnoranceStartStack.pop(), linesToCover[linesToCover.length - 1])); - } - while (!coverageAutoIgnoranceStartStack.empty()) { - coverageAutoIgnorance.add( - Range.between(coverageAutoIgnoranceStartStack.pop(), linesToCover[linesToCover.length - 1])); + if (metadataOptions.getRemoveSupport() != SupportVariant.NONE) { + SupportVariant moduleSupportVariant = module.getSupportVariant(); + if (moduleSupportVariant.compareTo(metadataOptions.getRemoveSupport()) <= 0) { + coverageData.put(module.getUri(), new HashMap<>()); + continue; } + } - linesToCover = Arrays.stream(linesToCover).filter(i -> - coverageIgnorance.stream().noneMatch(integerRange -> integerRange.contains(i))).toArray(); + addCoverageData(coverageData, module.getUri()); } + } else { + File externalDataprocessorRootXmlFile = rootPath.toFile(); + + XPath xPath = XPathFactory.newInstance().newXPath(); + FileInputStream fileIS = new FileInputStream(externalDataprocessorRootXmlFile); + DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = builderFactory.newDocumentBuilder(); + Document xmlDocument = builder.parse(fileIS); + String documentRootTagName = xmlDocument.getDocumentElement().getTagName(); + if (documentRootTagName.equals("MetaDataObject")) { + // CONFIGURATOR + String uuidExpression = "/MetaDataObject/ExternalDataProcessor/@uuid"; + String externalDataProcessorName = com.google.common.io.Files.getNameWithoutExtension(rootPath.toString()); + String externalDataProcessorUuid = (String) xPath.compile(uuidExpression).evaluate(xmlDocument, + XPathConstants.STRING); + uriListByKey.put(getUriKey(externalDataProcessorUuid, ModuleType.ObjectModule, null), + Paths.get(externalDataprocessorRootXmlFile.getParent(), + externalDataProcessorName, "Ext", "ObjectModule.bsl").toUri()); + + var externalDataProcessorPath = Paths.get( + externalDataprocessorRootXmlFile.getParent(), + externalDataProcessorName, "Forms"); + try (Stream walk = Files.list(externalDataProcessorPath)) { + + List result = walk.map(Path::toString) + .filter(f -> f.endsWith(".xml")).toList(); + + XPath formXPath = XPathFactory.newInstance().newXPath(); + String formUuidExpression = "/MetaDataObject/Form/@uuid"; + String formNameExpression = "/MetaDataObject/Form/Properties/Name/text()"; + + result.forEach(formXmlFileName -> { + try { + FileInputStream formFileIS = new FileInputStream(formXmlFileName); + Document formXmlDocument = builder.parse(formFileIS); + String formUuid = (String) formXPath.compile(formUuidExpression).evaluate(formXmlDocument, + XPathConstants.STRING); + String formName = (String) formXPath.compile(formNameExpression).evaluate(formXmlDocument, + XPathConstants.STRING); + uriListByKey.put(getUriKey(formUuid, ModuleType.FormModule, null), + Paths.get(externalDataProcessorPath.toString(), + formName, "Ext", "Form", "Module.bsl").toUri()); + } catch (Exception e) { + logger.error("Can't read form xml: {}", e.getLocalizedMessage()); + } + }); - Map coverMap = new HashMap<>(); - for (int lineNumber : linesToCover) { - int countValue = 0; - if (coverageAutoIgnorance.stream().anyMatch(integerRange -> integerRange.contains(lineNumber))) { - countValue = -1; - } - coverMap.put(new BigDecimal(lineNumber), countValue); - } - coverageData.put(uri, coverMap); - } - - public static Map readMetadata(MetadataOptions metadataOptions, - Map> coverageData) throws Exception { - boolean rawMode = false; - if (metadataOptions.isRawMode()) { - logger.info("Sources directory not set. Enabling RAW mode"); - rawMode = true; + } catch (IOException e) { + e.printStackTrace(); + } + } else if (documentRootTagName.equals("mdclass:ExternalDataProcessor")) { + // EDT + var externalDataProcessorPath = Paths.get( + externalDataprocessorRootXmlFile.getParent(), + "Forms"); + String uuidExpression = "/ExternalDataProcessor/@uuid"; + String externalDataProcessorUuid = (String) xPath.compile(uuidExpression).evaluate(xmlDocument, + XPathConstants.STRING); + uriListByKey.put(getUriKey(externalDataProcessorUuid, ModuleType.ObjectModule, null), + Paths.get(externalDataprocessorRootXmlFile.getParent(), + "ObjectModule.bsl").toUri()); + String formUuidExpression = "/ExternalDataProcessor/forms"; + NodeList externalDataProcessorFormsNodeList = (NodeList) xPath.compile(formUuidExpression).evaluate(xmlDocument, + XPathConstants.NODESET); + for (int nodeNumber = 0; nodeNumber < externalDataProcessorFormsNodeList.getLength(); nodeNumber++) { + Node externalDataProcessorFormsNode = externalDataProcessorFormsNodeList.item(nodeNumber); + String formUuid = externalDataProcessorFormsNode.getAttributes().getNamedItem("uuid").getTextContent(); + String formName = ""; + NodeList childNodes = externalDataProcessorFormsNode.getChildNodes(); + for (int childNodeNumber = 0; childNodeNumber < childNodes.getLength(); childNodeNumber++) { + Node childNode = childNodes.item(childNodeNumber); + if (childNode.getNodeName().equals("name")) { + formName = childNode.getTextContent(); + break; + } + } + if (formName.isEmpty()) { + logger.error("Can't find form name: {}", formUuid); + continue; + } + uriListByKey.put(getUriKey(formUuid, ModuleType.FormModule, null), + Paths.get(externalDataProcessorPath.toString(), + formName, "Module.bsl").toUri()); + } } else { - logger.info("Project directory: {}", metadataOptions.getProjectDirName()); + throw new Exception("Unknown source format"); } - Map uriListByKey = new HashMap<>(); - - if (!rawMode) { - - Path rootPath = Path.of(metadataOptions.getProjectDirName()) - .resolve(metadataOptions.getSrcDirName()); - logger.info("Reading configuration sources from root path: {}", rootPath.toAbsolutePath()); - - if (Files.isDirectory(rootPath)) { - - Configuration conf = Configuration.create(rootPath); - - for (MDOModule module : conf.getModules()) { - ModuleOwner mdObj = module.getOwner(); - - String mdObjUuid = mdObj.getUuid(); - - uriListByKey.put(getUriKey(mdObjUuid, module.getModuleType(), mdObj), module.getUri()); - - if (metadataOptions.getRemoveSupport() != SupportVariant.NONE) { - SupportVariant moduleSupportVariant = conf.getModuleSupport(module.getUri()).values().stream() - .min(Comparator.naturalOrder()) - .orElse(SupportVariant.NONE); - if (moduleSupportVariant.compareTo(metadataOptions.getRemoveSupport()) <= 0) { - coverageData.put(module.getUri(), new HashMap<>()); - continue; - } - } - - addCoverageData(coverageData, module.getUri()); - - } - - } else { - - File externalDataprocessorRootXmlFile = rootPath.toFile(); - - XPath xPath = XPathFactory.newInstance().newXPath(); - FileInputStream fileIS = new FileInputStream(externalDataprocessorRootXmlFile); - DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = builderFactory.newDocumentBuilder(); - Document xmlDocument = builder.parse(fileIS); - String documentRootTagName = xmlDocument.getDocumentElement().getTagName(); - if (documentRootTagName.equals("MetaDataObject")) { - // CONFIGURATOR - String uuidExpression = "/MetaDataObject/ExternalDataProcessor/@uuid"; - String externalDataProcessorName = com.google.common.io.Files.getNameWithoutExtension(rootPath.toString()); - String externalDataProcessorUuid = (String) xPath.compile(uuidExpression).evaluate(xmlDocument, - XPathConstants.STRING); - uriListByKey.put(getUriKey(externalDataProcessorUuid, ModuleType.ObjectModule, null), - Paths.get(externalDataprocessorRootXmlFile.getParent(), - externalDataProcessorName, "Ext", "ObjectModule.bsl").toUri()); - - var externalDataProcessorPath = Paths.get( - externalDataprocessorRootXmlFile.getParent(), - externalDataProcessorName, "Forms"); - try (Stream walk = Files.list(externalDataProcessorPath)) { - - List result = walk.map(Path::toString) - .filter(f -> f.endsWith(".xml")).collect(Collectors.toList()); - - XPath formXPath = XPathFactory.newInstance().newXPath(); - String formUuidExpression = "/MetaDataObject/Form/@uuid"; - String formNameExpression = "/MetaDataObject/Form/Properties/Name/text()"; - - result.forEach(formXmlFileName -> { - try { - FileInputStream formFileIS = new FileInputStream(formXmlFileName); - Document formXmlDocument = builder.parse(formFileIS); - String formUuid = (String) formXPath.compile(formUuidExpression).evaluate(formXmlDocument, - XPathConstants.STRING); - String formName = (String) formXPath.compile(formNameExpression).evaluate(formXmlDocument, - XPathConstants.STRING); - uriListByKey.put(getUriKey(formUuid, ModuleType.FormModule, null), - Paths.get(externalDataProcessorPath.toString(), - formName, "Ext", "Form", "Module.bsl").toUri()); - } catch (Exception e) { - logger.error("Can't read form xml: {}", e.getLocalizedMessage()); - } - }); - - - } catch (IOException e) { - e.printStackTrace(); - } - } else if (documentRootTagName.equals("mdclass:ExternalDataProcessor")) { - // EDT - var externalDataProcessorPath = Paths.get( - externalDataprocessorRootXmlFile.getParent(), - "Forms"); - String uuidExpression = "/ExternalDataProcessor/@uuid"; - String externalDataProcessorUuid = (String) xPath.compile(uuidExpression).evaluate(xmlDocument, - XPathConstants.STRING); - uriListByKey.put(getUriKey(externalDataProcessorUuid, ModuleType.ObjectModule, null), - Paths.get(externalDataprocessorRootXmlFile.getParent(), - "ObjectModule.bsl").toUri()); - String formUuidExpression = "/ExternalDataProcessor/forms"; - NodeList externalDataProcessorFormsNodeList = (NodeList) xPath.compile(formUuidExpression).evaluate(xmlDocument, - XPathConstants.NODESET); - for (int nodeNumber = 0; nodeNumber < externalDataProcessorFormsNodeList.getLength(); nodeNumber++) { - Node externalDataProcessorFormsNode = externalDataProcessorFormsNodeList.item(nodeNumber); - String formUuid = externalDataProcessorFormsNode.getAttributes().getNamedItem("uuid").getTextContent(); - String formName = ""; - NodeList childNodes = externalDataProcessorFormsNode.getChildNodes(); - for (int childNodeNumber = 0; childNodeNumber < childNodes.getLength(); childNodeNumber++) { - Node childNode = childNodes.item(childNodeNumber); - if (childNode.getNodeName().equals("name")) { - formName = childNode.getTextContent(); - break; - } - } - if (formName.isEmpty()) { - logger.error("Can't find form name: {}", formUuid); - continue; - } - uriListByKey.put(getUriKey(formUuid, ModuleType.FormModule, null), - Paths.get(externalDataProcessorPath.toString(), - formName, "Module.bsl").toUri()); - } - } else { - throw new Exception("Unknown source format"); - } - - uriListByKey.forEach((s, uri) -> addCoverageData(coverageData, uri)); + uriListByKey.forEach((s, uri) -> addCoverageData(coverageData, uri)); + } - } - - logger.info("Configuration sources reading DONE"); - } + logger.info("Configuration sources reading DONE"); + } - return uriListByKey; + return uriListByKey; + } + + public static void dumpCoverageFile(Map> coverageData, + MetadataOptions metadataOptions, + OutputOptions outputOptions) { + switch (outputOptions.getOutputFormat()) { + case GENERIC_COVERAGE -> dumpGenericCoverageFile(coverageData, metadataOptions, outputOptions); + case LCOV -> dumpLcovFile(coverageData, metadataOptions, outputOptions); + case COBERTURA -> dumpCoberturaFile(coverageData, metadataOptions, outputOptions); + default -> logger.info("Unknown format"); } + } - public static void dumpCoverageFile(Map> coverageData, + private static void dumpCoberturaFile(Map> coverageData, MetadataOptions metadataOptions, OutputOptions outputOptions) { - if (outputOptions.getOutputFormat() == OutputOptions.OutputFormat.GENERIC_COVERAGE) { - dumpGenericCoverageFile(coverageData, metadataOptions, outputOptions); - } else if (outputOptions.getOutputFormat() == OutputOptions.OutputFormat.LCOV) { - dumpLcovFile(coverageData, metadataOptions, outputOptions); - } else if (outputOptions.getOutputFormat() == OutputOptions.OutputFormat.COBERTURA) { - dumpCoberturaFile(coverageData, metadataOptions, outputOptions); - } else { - logger.info("Unknown format"); + DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder icBuilder; + try { + long linesToCover = 0; + long coveredLinesCount = 0; + for (Map bigDecimalMap : coverageData.values()) { + linesToCover += bigDecimalMap.values().stream().filter(value -> value >= 0).count(); + coveredLinesCount += bigDecimalMap.values().stream().filter(value -> value > 0).count(); + } + logger.info("Lines to cover: {}", linesToCover); + logger.info("Covered lines: {}", coveredLinesCount); + if (linesToCover > 0) { + logger.info("Coverage: {}%", Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.); + } + + URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); + icBuilder = icFactory.newDocumentBuilder(); + Document doc = icBuilder.newDocument(); + Element mainRootElement = doc.createElement("coverage"); + String lineRate = "0.0"; + if (linesToCover > 0) { + lineRate = String.valueOf(Math.floorDiv(coveredLinesCount * 100, linesToCover) / 100.); + } + mainRootElement.setAttribute("line-rate", lineRate); + mainRootElement.setAttribute("branch-rate", "0.0"); + mainRootElement.setAttribute("lines-covered", String.valueOf(coveredLinesCount)); + mainRootElement.setAttribute("lines-valid", String.valueOf(linesToCover)); + mainRootElement.setAttribute("branches-covered", "0"); + mainRootElement.setAttribute("branches-valid", "0"); + mainRootElement.setAttribute("complexity", "0"); + mainRootElement.setAttribute("version", "0"); + mainRootElement.setAttribute("timestamp", String.valueOf(Instant.now().getEpochSecond())); + doc.appendChild(mainRootElement); + + Element sourcesElement = doc.createElement("sources"); + mainRootElement.appendChild(sourcesElement); + + Element sourceElement = doc.createElement("source"); + String[] projectDirArray = projectUri.getPath().split("/"); + if (projectDirArray.length > 2) { + sourceElement.setTextContent("/builds/" + projectDirArray[projectDirArray.length - 2] + "/" + projectDirArray[projectDirArray.length - 1] + "/"); + } else { + sourcesElement.setTextContent(projectUri.getPath()); + } + sourcesElement.appendChild(sourceElement); + + Element packagesElement = doc.createElement("packages"); + mainRootElement.appendChild(packagesElement); + + Element packageElement = doc.createElement("package"); + packageElement.setAttribute("name", "Main"); + packageElement.setAttribute("line-rate", lineRate); + packageElement.setAttribute("branch-rate", "0.0"); + packageElement.setAttribute("complexity", "0"); + packagesElement.appendChild(packageElement); + + Element classesElement = doc.createElement("classes"); + packageElement.appendChild(classesElement); + + coverageData.forEach((uri, bigDecimalsMap) -> { + if (bigDecimalsMap.isEmpty()) { + return; } - } - private static void dumpCoberturaFile(Map> coverageData, - MetadataOptions metadataOptions, - OutputOptions outputOptions) { - DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder icBuilder; - try { - long linesToCover = 0; - long coveredLinesCount = 0; - for (Map bigDecimalMap : coverageData.values()) { - linesToCover += bigDecimalMap.values().stream().filter(value -> value >= 0).count(); - coveredLinesCount += bigDecimalMap.values().stream().filter(value -> value > 0).count(); - } - logger.info("Lines to cover: {}", linesToCover); - logger.info("Covered lines: {}", coveredLinesCount); - if (linesToCover > 0) { - logger.info("Coverage: {}%", Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.); - } + long fileLinesToCover = bigDecimalsMap.values().stream().filter(value -> value >= 0).count(); + long fileCoveredLinesCount = bigDecimalsMap.values().stream().filter(value -> value > 0).count(); + String fileLineRate = "0.0"; + if (fileLinesToCover > 0) { + fileLineRate = String.valueOf(Math.floorDiv(fileCoveredLinesCount * 100, fileLinesToCover) / 100.); + } - URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); - icBuilder = icFactory.newDocumentBuilder(); - Document doc = icBuilder.newDocument(); - Element mainRootElement = doc.createElement("coverage"); - String lineRate = "0.0"; - if (linesToCover > 0) { - lineRate = String.valueOf(Math.floorDiv(coveredLinesCount * 100, linesToCover) / 100.); - } - mainRootElement.setAttribute("line-rate", lineRate); - mainRootElement.setAttribute("branch-rate", "0.0"); - mainRootElement.setAttribute("lines-covered", String.valueOf(coveredLinesCount)); - mainRootElement.setAttribute("lines-valid", String.valueOf(linesToCover)); - mainRootElement.setAttribute("branches-covered", "0"); - mainRootElement.setAttribute("branches-valid", "0"); - mainRootElement.setAttribute("complexity", "0"); - mainRootElement.setAttribute("version", "0"); - mainRootElement.setAttribute("timestamp", String.valueOf(Instant.now().getEpochSecond())); - doc.appendChild(mainRootElement); - - Element sourcesElement = doc.createElement("sources"); - mainRootElement.appendChild(sourcesElement); - - Element sourceElement = doc.createElement("source"); - String[] projectDirArray = projectUri.getPath().split("/"); - if (projectDirArray.length > 2) { - sourceElement.setTextContent("/builds/" + projectDirArray[projectDirArray.length - 2] + "/" + projectDirArray[projectDirArray.length - 1] + "/"); - } else { - sourcesElement.setTextContent(projectUri.getPath()); - } - sourcesElement.appendChild(sourceElement); - - Element packagesElement = doc.createElement("packages"); - mainRootElement.appendChild(packagesElement); - - Element packageElement = doc.createElement("package"); - packageElement.setAttribute("name", "Main"); - packageElement.setAttribute("line-rate", lineRate); - packageElement.setAttribute("branch-rate", "0.0"); - packageElement.setAttribute("complexity", "0"); - packagesElement.appendChild(packageElement); - - Element classesElement = doc.createElement("classes"); - packageElement.appendChild(classesElement); - - coverageData.forEach((uri, bigDecimalsMap) -> { - if (bigDecimalsMap.isEmpty()) { - return; - } - - long fileLinesToCover = bigDecimalsMap.values().stream().filter(value -> value >= 0).count(); - long fileCoveredLinesCount = bigDecimalsMap.values().stream().filter(value -> value > 0).count(); - String fileLineRate = "0.0"; - if (fileLinesToCover > 0) { - fileLineRate = String.valueOf(Math.floorDiv(fileCoveredLinesCount * 100, fileLinesToCover) / 100.); - } - - Element classElement = doc.createElement("class"); - classElement.setAttribute("name", projectUri.relativize(uri).getPath()); - classElement.setAttribute("line-rate", fileLineRate); - classElement.setAttribute("branch-rate", "0.0"); - classElement.setAttribute("complexity", "0"); - classElement.setAttribute("filename", projectUri.relativize(uri).getPath()); - classesElement.appendChild(classElement); - - Element methodsElement = doc.createElement("methods"); - classElement.appendChild(methodsElement); - - bigDecimalsMap.forEach((bigDecimal, hits) -> { - if (hits >= 0) { - Element lineElement = doc.createElement("line"); - lineElement.setAttribute("hits", String.valueOf(hits)); - lineElement.setAttribute("number", bigDecimal.toString()); - lineElement.setAttribute("branch", "false"); - classElement.appendChild(lineElement); - } - }); - }); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - DOMSource source = new DOMSource(doc); - StreamResult outputStream; - if (outputOptions.getOutputFile() == null) { - outputStream = new StreamResult(System.out); - } else { - outputStream = new StreamResult(new FileOutputStream(outputOptions.getOutputFile())); - } - transformer.transform(source, outputStream); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); + Element classElement = doc.createElement("class"); + classElement.setAttribute("name", projectUri.relativize(uri).getPath()); + classElement.setAttribute("line-rate", fileLineRate); + classElement.setAttribute("branch-rate", "0.0"); + classElement.setAttribute("complexity", "0"); + classElement.setAttribute("filename", projectUri.relativize(uri).getPath()); + classesElement.appendChild(classElement); + + Element methodsElement = doc.createElement("methods"); + classElement.appendChild(methodsElement); + + bigDecimalsMap.forEach((bigDecimal, hits) -> { + if (hits >= 0) { + Element lineElement = doc.createElement("line"); + lineElement.setAttribute("hits", String.valueOf(hits)); + lineElement.setAttribute("number", bigDecimal.toString()); + lineElement.setAttribute("branch", "false"); + classElement.appendChild(lineElement); + } + }); + }); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + DOMSource source = new DOMSource(doc); + StreamResult outputStream; + if (outputOptions.getOutputFile() == null) { + outputStream = new StreamResult(System.out); + } else { + outputStream = new StreamResult(new FileOutputStream(outputOptions.getOutputFile())); + } + transformer.transform(source, outputStream); + } catch (Exception e) { + logger.error(e.getLocalizedMessage()); + } + } + + private static void dumpGenericCoverageFile(Map> coverageData, + MetadataOptions metadataOptions, + OutputOptions outputOptions) { + DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder icBuilder; + try { + + URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); + icBuilder = icFactory.newDocumentBuilder(); + Document doc = icBuilder.newDocument(); + Element mainRootElement = doc.createElement("coverage"); + mainRootElement.setAttribute("version", "1"); + doc.appendChild(mainRootElement); + coverageData.forEach((uri, bigDecimalsMap) -> { + if (bigDecimalsMap.isEmpty()) { + return; } + Element fileElement = doc.createElement("file"); + fileElement.setAttribute("path", projectUri.relativize(uri).getPath()); + bigDecimalsMap.forEach((bigDecimal, integer) -> { + if (integer >= 0) { + Element lineElement = doc.createElement("lineToCover"); + lineElement.setAttribute("covered", Boolean.toString(integer > 0)); + lineElement.setAttribute("lineNumber", bigDecimal.toString()); + fileElement.appendChild(lineElement); + } + }); + mainRootElement.appendChild(fileElement); + }); + long linesToCover = 0; + long coveredLinesCount = 0; + for (Map bigDecimalMap : coverageData.values()) { + linesToCover += bigDecimalMap.values().stream().filter(value -> value >= 0).count(); + coveredLinesCount += bigDecimalMap.values().stream().filter(value -> value > 0).count(); + } + logger.info("Lines to cover: {}", linesToCover); + logger.info("Covered lines: {}", coveredLinesCount); + if (linesToCover > 0) { + logger.info("Coverage: {}%", Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.); + } + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + DOMSource source = new DOMSource(doc); + StreamResult outputStream; + if (outputOptions.getOutputFile() == null) { + outputStream = new StreamResult(System.out); + } else { + outputStream = new StreamResult(new FileOutputStream(outputOptions.getOutputFile())); + } + transformer.transform(source, outputStream); + } catch (Exception e) { + logger.error(e.getLocalizedMessage()); } + } - private static void dumpGenericCoverageFile(Map> coverageData, - MetadataOptions metadataOptions, - OutputOptions outputOptions) { - DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder icBuilder; - try { - - URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); - icBuilder = icFactory.newDocumentBuilder(); - Document doc = icBuilder.newDocument(); - Element mainRootElement = doc.createElement("coverage"); - mainRootElement.setAttribute("version", "1"); - doc.appendChild(mainRootElement); - coverageData.forEach((uri, bigDecimalsMap) -> { - if (bigDecimalsMap.isEmpty()) { - return; - } - Element fileElement = doc.createElement("file"); - fileElement.setAttribute("path", projectUri.relativize(uri).getPath()); - bigDecimalsMap.forEach((bigDecimal, integer) -> { - if (integer >= 0) { - Element lineElement = doc.createElement("lineToCover"); - lineElement.setAttribute("covered", Boolean.toString(integer > 0)); - lineElement.setAttribute("lineNumber", bigDecimal.toString()); - fileElement.appendChild(lineElement); - } - }); - mainRootElement.appendChild(fileElement); - }); - long linesToCover = 0; - long coveredLinesCount = 0; - for (Map bigDecimalMap : coverageData.values()) { - linesToCover += bigDecimalMap.values().stream().filter(value -> value >= 0).count(); - coveredLinesCount += bigDecimalMap.values().stream().filter(value -> value > 0).count(); - } - logger.info("Lines to cover: {}", linesToCover); - logger.info("Covered lines: {}", coveredLinesCount); - if (linesToCover > 0) { - logger.info("Coverage: {}%", Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.); - } - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - DOMSource source = new DOMSource(doc); - StreamResult outputStream; - if (outputOptions.getOutputFile() == null) { - outputStream = new StreamResult(System.out); - } else { - outputStream = new StreamResult(new FileOutputStream(outputOptions.getOutputFile())); - } - transformer.transform(source, outputStream); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } + public static String normalizeXml(String xmlString) { + String result = ""; + if (!xmlString.startsWith("<")) { + return xmlString; + } + Pattern p = Pattern.compile("<\\w\\S*"); + Matcher m = p.matcher(xmlString); + String replaceFromTag = ""; + if (m.find()) { + replaceFromTag = xmlString.substring(m.start() + 1, m.end()); + } + if (replaceFromTag.isEmpty()) { + return result; + } + result = xmlString; + String tag = ""; + int indx = xmlString.indexOf(tag); + if (indx != -1) { + result = result.substring(0, indx + tag.length()); } - public static String normalizeXml(String xmlString) { - String result = ""; - if (!xmlString.startsWith("<")) { - return xmlString; - } - Pattern p = Pattern.compile("<\\w\\S*"); - Matcher m = p.matcher(xmlString); - String replaceFromTag = ""; - if (m.find()) { - replaceFromTag = xmlString.substring(m.start() + 1, m.end()); - } - if (replaceFromTag.isEmpty()) { - return result; - } - result = xmlString; - String tag = ""; - int indx = xmlString.indexOf(tag); - if (indx != -1) { - result = result.substring(0, indx + tag.length()); - } + indx = result.indexOf("/>"); + if (indx != -1) { + String candidate = result.substring(0, indx + 2); + m = p.matcher(candidate); + String candidateTag = ""; + while (m.find()) { + candidateTag = result.substring(m.start() + 1, m.end()); + } - indx = result.indexOf("/>"); - if (indx != -1) { - String candidate = result.substring(0, indx + 2); - m = p.matcher(candidate); - String candidateTag = ""; - while (m.find()) { - candidateTag = result.substring(m.start() + 1, m.end()); - } + if (replaceFromTag.equalsIgnoreCase(candidateTag)) { + result = candidate; + } - if (replaceFromTag.equalsIgnoreCase(candidateTag)) { - result = candidate; - } + } - } + return result; + } - return result; - } + private static void dumpLcovFile(Map> coverageData, + MetadataOptions metadataOptions, + OutputOptions outputOptions) { - private static void dumpLcovFile(Map> coverageData, - MetadataOptions metadataOptions, - OutputOptions outputOptions) { + try { + OutputStreamWriter outputStream; + if (outputOptions.getOutputFile() == null) { + outputStream = new OutputStreamWriter(System.out); + } else { + outputStream = new OutputStreamWriter(new FileOutputStream(outputOptions.getOutputFile()), StandardCharsets.UTF_8); + } + PrintWriter writer = new PrintWriter(outputStream); - try { - OutputStreamWriter outputStream; - if (outputOptions.getOutputFile() == null) { - outputStream = new OutputStreamWriter(System.out); - } else { - outputStream = new OutputStreamWriter(new FileOutputStream(outputOptions.getOutputFile()), StandardCharsets.UTF_8); - } - PrintWriter writer = new PrintWriter(outputStream); - - URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); - - coverageData.forEach((uri, bigDecimalsMap) -> { - if (bigDecimalsMap.isEmpty()) { - return; - } - writer.println("TN:"); - writer.printf("SF:%s\n", projectUri.relativize(uri).getPath()); - bigDecimalsMap.forEach((bigDecimal, integer) -> { - if (integer >= 0) { - writer.printf("DA:%s,%d\n", bigDecimal.toString(), integer); - } - }); - writer.printf("LH:%d\n", bigDecimalsMap.values().stream().filter(aInteger -> aInteger > 0).count()); - writer.printf("LF:%d\n", bigDecimalsMap.size()); - writer.println("end_of_record"); - }); - long linesToCover = 0; - long coveredLinesCount = 0; - for (Map bigDecimalMap : coverageData.values()) { - linesToCover += bigDecimalMap.values().stream().filter(value -> value >= 0).count(); - coveredLinesCount += bigDecimalMap.values().stream().filter(value -> value > 0).count(); - } - logger.info("Lines to cover: {}", linesToCover); - logger.info("Covered lines: {}", coveredLinesCount); - if (linesToCover > 0) { - logger.info("Coverage: {}%", Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.); - } + URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); - writer.close(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); + coverageData.forEach((uri, bigDecimalsMap) -> { + if (bigDecimalsMap.isEmpty()) { + return; } - } - - public static void printCoverageStats(Map> coverageData, - MetadataOptions metadataOptions) { - List dataList = new LinkedList<>(); - URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); - coverageData.forEach((uri, bigDecimalsMap) -> { - if (bigDecimalsMap.isEmpty()) { - return; - } - String path = projectUri.relativize(uri).getPath(); - long linesToCover = bigDecimalsMap.values().stream().filter(aInteger -> aInteger >= 0).count(); - long coveredLinesCount = bigDecimalsMap.values().stream().filter(aInteger -> aInteger > 0).count(); - double coverage = Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.; - Object[] dataRow = { - path, - linesToCover, - coveredLinesCount, - coverage}; - dataList.add(dataRow); - }); - dataList.sort(Comparator.comparing(objects -> ((Double) objects[3]))); - AsciiTable at = new AsciiTable(); - at.addRule(); - at.addRow("Path", "Lines to cover", "Covered lines", "Coverage, %"); - at.addRule(); - dataList.forEach(objects -> { - at.addRow(objects); - at.addRule(); + writer.println("TN:"); + writer.printf("SF:%s\n", projectUri.relativize(uri).getPath()); + bigDecimalsMap.forEach((bigDecimal, integer) -> { + if (integer >= 0) { + writer.printf("DA:%s,%d\n", bigDecimal.toString(), integer); + } }); - CWC_LongestLine cwc = new CWC_LongestLine(); - at.getRenderer().setCWC(cwc); - String rend = at.render(); - System.out.println(rend); + writer.printf("LH:%d\n", bigDecimalsMap.values().stream().filter(aInteger -> aInteger > 0).count()); + writer.printf("LF:%d\n", bigDecimalsMap.size()); + writer.println("end_of_record"); + }); + long linesToCover = 0; + long coveredLinesCount = 0; + for (Map bigDecimalMap : coverageData.values()) { + linesToCover += bigDecimalMap.values().stream().filter(value -> value >= 0).count(); + coveredLinesCount += bigDecimalMap.values().stream().filter(value -> value > 0).count(); + } + logger.info("Lines to cover: {}", linesToCover); + logger.info("Covered lines: {}", coveredLinesCount); + if (linesToCover > 0) { + logger.info("Coverage: {}%", Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.); + } + + writer.close(); + } catch (Exception e) { + logger.error(e.getLocalizedMessage()); } - - public static String getPipeName(ConnectionOptions connectionOptions) throws IOException { - boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win"); - - URI debugUri = URI.create(connectionOptions.getDebugServerUrl()); - String pipeName; - if (isWindows) { - pipeName = String.format("\\\\.\\pipe\\COVER_%s_%s", connectionOptions.getInfobaseAlias(), - debugUri.toString().replaceAll("[^a-zA-Z0-9-_.]", "_")); - } else { - File tempDirFile = new File("/tmp/coverage41c/"); - tempDirFile.mkdirs(); - Path tempDir = tempDirFile.toPath(); - Path sock = tempDir.resolve(String.format("%s_%s.sock", connectionOptions.getInfobaseAlias(), - debugUri.toString().replaceAll("[^a-zA-Z0-9-_.]", "_"))); - pipeName = sock.toString(); - } - return pipeName; + } + + public static void printCoverageStats(Map> coverageData, + MetadataOptions metadataOptions) { + List dataList = new LinkedList<>(); + URI projectUri = Path.of(metadataOptions.getProjectDirName()).toUri(); + coverageData.forEach((uri, bigDecimalsMap) -> { + if (bigDecimalsMap.isEmpty()) { + return; + } + String path = projectUri.relativize(uri).getPath(); + long linesToCover = bigDecimalsMap.values().stream().filter(aInteger -> aInteger >= 0).count(); + long coveredLinesCount = bigDecimalsMap.values().stream().filter(aInteger -> aInteger > 0).count(); + double coverage = Math.floorDiv(coveredLinesCount * 10000, linesToCover) / 100.; + Object[] dataRow = { + path, + linesToCover, + coveredLinesCount, + coverage}; + dataList.add(dataRow); + }); + dataList.sort(Comparator.comparing(objects -> ((Double) objects[3]))); + AsciiTable at = new AsciiTable(); + at.addRule(); + at.addRow("Path", "Lines to cover", "Covered lines", "Coverage, %"); + at.addRule(); + dataList.forEach(objects -> { + at.addRow(objects); + at.addRule(); + }); + CWC_LongestLine cwc = new CWC_LongestLine(); + at.getRenderer().setCWC(cwc); + String rend = at.render(); + System.out.println(rend); + } + + public static String getPipeName(ConnectionOptions connectionOptions) throws IOException { + boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win"); + + URI debugUri = URI.create(connectionOptions.getDebugServerUrl()); + String pipeName; + if (isWindows) { + pipeName = String.format("\\\\.\\pipe\\COVER_%s_%s", connectionOptions.getInfobaseAlias(), + debugUri.toString().replaceAll("[^a-zA-Z0-9-_.]", "_")); + } else { + File tempDirFile = new File("/tmp/coverage41c/"); + tempDirFile.mkdirs(); + Path tempDir = tempDirFile.toPath(); + Path sock = tempDir.resolve(String.format("%s_%s.sock", connectionOptions.getInfobaseAlias(), + debugUri.toString().replaceAll("[^a-zA-Z0-9-_.]", "_"))); + pipeName = sock.toString(); } - - public static boolean isProcessStillAlive(Integer pid) { - String OS = System.getProperty("os.name").toLowerCase(); - String command; - if (OS.contains("win")) { - logger.debug("Check alive Windows mode. Pid: [{}]", pid); - command = "cmd /c tasklist /FI \"PID eq " + pid + "\""; - } else if (OS.contains("nix") || OS.contains("nux")) { - logger.debug("Check alive Linux/Unix mode. Pid: [{}]", pid); - command = "ps -p " + pid; - } else { - logger.warn("Unsuported OS: Check alive for Pid: [{}] return false", pid); - return false; - } - return isProcessIdRunning(String.valueOf(pid), command); + return pipeName; + } + + public static boolean isProcessStillAlive(Integer pid) { + String OS = System.getProperty("os.name").toLowerCase(); + String command; + if (OS.contains("win")) { + logger.debug("Check alive Windows mode. Pid: [{}]", pid); + command = "cmd /c tasklist /FI \"PID eq " + pid + "\""; + } else if (OS.contains("nix") || OS.contains("nux")) { + logger.debug("Check alive Linux/Unix mode. Pid: [{}]", pid); + command = "ps -p " + pid; + } else { + logger.warn("Unsuported OS: Check alive for Pid: [{}] return false", pid); + return false; } - - private static boolean isProcessIdRunning(String pid, String command) { - logger.debug("Command [{}]", command); - try { - Runtime rt = Runtime.getRuntime(); - Process pr = rt.exec(command); - - InputStreamReader isReader = new InputStreamReader(pr.getInputStream()); - BufferedReader bReader = new BufferedReader(isReader); - String strLine; - while ((strLine = bReader.readLine()) != null) { - if (strLine.contains(" " + pid + " ")) { - return true; - } - } - - return false; - } catch (Exception ex) { - logger.warn("Got exception using system command [{}].", command, ex); - return true; + return isProcessIdRunning(String.valueOf(pid), command); + } + + private static boolean isProcessIdRunning(String pid, String command) { + logger.debug("Command [{}]", command); + try { + Runtime rt = Runtime.getRuntime(); + Process pr = rt.exec(command); + + InputStreamReader isReader = new InputStreamReader(pr.getInputStream()); + BufferedReader bReader = new BufferedReader(isReader); + String strLine; + while ((strLine = bReader.readLine()) != null) { + if (strLine.contains(" " + pid + " ")) { + return true; } + } + + return false; + } catch (Exception ex) { + logger.warn("Got exception using system command [{}].", command, ex); + return true; } + } } diff --git a/src/test/java/com/clouds42/ConvertTest.java b/src/test/java/com/clouds42/ConvertTest.java index ed337e8..7dddc21 100644 --- a/src/test/java/com/clouds42/ConvertTest.java +++ b/src/test/java/com/clouds42/ConvertTest.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/clouds42/CoverageTest.java b/src/test/java/com/clouds42/CoverageTest.java index 6d5d567..4bd6166 100644 --- a/src/test/java/com/clouds42/CoverageTest.java +++ b/src/test/java/com/clouds42/CoverageTest.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -39,6 +40,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Disabled class CoverageTest { final boolean isWindows = System.getProperty ("os.name").toLowerCase().contains("win"); diff --git a/src/test/java/com/clouds42/LinesToCoverageTest.java b/src/test/java/com/clouds42/LinesToCoverageTest.java index 75ce113..5665ece 100644 --- a/src/test/java/com/clouds42/LinesToCoverageTest.java +++ b/src/test/java/com/clouds42/LinesToCoverageTest.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/clouds42/TestUtils.java b/src/test/java/com/clouds42/TestUtils.java index ca0e467..1aba264 100644 --- a/src/test/java/com/clouds42/TestUtils.java +++ b/src/test/java/com/clouds42/TestUtils.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/clouds42/UtilsTest.java b/src/test/java/com/clouds42/UtilsTest.java index 186e879..0e7aa28 100644 --- a/src/test/java/com/clouds42/UtilsTest.java +++ b/src/test/java/com/clouds42/UtilsTest.java @@ -1,7 +1,7 @@ /* * This file is a part of Coverage41C. * - * Copyright (c) 2020-2024 + * Copyright (c) 2020-2025 * Kosolapov Stanislav aka proDOOMman and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/resources/coverage/configuration.xml b/src/test/resources/coverage/configuration.xml index b06e109..83805ec 100644 --- a/src/test/resources/coverage/configuration.xml +++ b/src/test/resources/coverage/configuration.xml @@ -105,6 +105,10 @@ + + + + diff --git a/src/test/resources/coverage/edt.xml b/src/test/resources/coverage/edt.xml index 9867eaf..ca0abe9 100644 --- a/src/test/resources/coverage/edt.xml +++ b/src/test/resources/coverage/edt.xml @@ -250,6 +250,10 @@ + + + +