update to Java named module, Gradle 6.4.1, rewrite of gradle plugin, many API simplifications, more tests

This commit is contained in:
Jörg Prante 2020-06-03 16:50:54 +02:00
parent 19e2530a5e
commit b6ecde250f
154 changed files with 3444 additions and 8774 deletions

View file

@ -1,95 +1,33 @@
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
plugins {
id "org.sonarqube" version "2.6.2"
id "io.codearte.nexus-staging" version "0.11.0"
id "de.marcphilipp.nexus-publish" version "0.4.0"
id "io.codearte.nexus-staging" version "0.21.1"
}
printf "Date: %s\nHost: %s\nOS: %s %s %s\nJava: %s %s %s %s\nGradle: %s Groovy: %s Java: %s\n" +
"Build: group: ${project.group} name: ${project.name} version: ${project.version}\n",
ZonedDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
InetAddress.getLocalHost(),
System.getProperty("os.name"),
System.getProperty("os.arch"),
System.getProperty("os.version"),
System.getProperty("java.version"),
System.getProperty("java.vm.version"),
System.getProperty("java.vm.vendor"),
System.getProperty("java.vm.name"),
gradle.gradleVersion, GroovySystem.getVersion(), JavaVersion.current()
wrapper {
gradleVersion = "${project.property('gradle.wrapper.version')}"
distributionType = Wrapper.DistributionType.ALL
}
ext {
user = 'xbib'
projectName = 'rpm'
projectDescription = 'Java 8 RPM implementation with plugins for Ant, Maven, Gradle'
scmUrl = 'https://github.com/xbib/rpm'
scmConnection = 'scm:git:git://github.com/xbib/rpm.git'
scmDeveloperConnection = 'scm:git:git://github.com/xbib/rpm.git'
name = 'rpm'
description = 'RPM implementation in Java with plugins for Ant, Maven, Gradle'
inceptionYear = '2016'
url = 'https://github.com/' + user + '/' + name
scmUrl = 'https://github.com/' + user + '/' + name
scmConnection = 'scm:git:git://github.com/' + user + '/' + name + '.git'
scmDeveloperConnection = 'scm:git:ssh://git@github.com:' + user + '/' + name + '.git'
issueManagementSystem = 'Github'
issueManagementUrl = ext.scmUrl + '/issues'
licenseName = 'The Apache License, Version 2.0'
licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
subprojects {
apply plugin: 'java'
apply plugin: 'maven'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
testCompile "junit:junit:${project.property('junit.version')}"
}
compileJava {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
compileTestJava {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:all" << "-profile" << "compact1"
}
test {
testLogging {
showStandardStreams = false
exceptionFormat = 'full'
}
}
clean {
delete 'out'
}
sonarqube {
properties {
property "sonar.projectName", "xbib RPM"
property "sonar.sourceEncoding", "UTF-8"
property "sonar.tests", "src/test/java"
property "sonar.scm.provider", "git"
property "sonar.junit.reportsPath", "build/test-results/test/"
}
}
task sourcesJar(type: Jar) {
classifier 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar) {
classifier 'javadoc'
}
artifacts {
archives sourcesJar, javadocJar
}
apply from: "${rootProject.projectDir}/gradle/publish.gradle"
apply plugin: 'java-library'
apply from: rootProject.file('gradle/ide/idea.gradle')
apply from: rootProject.file('gradle/compile/java.gradle')
apply from: rootProject.file('gradle/test/junit5.gradle')
apply from: rootProject.file('gradle/publishing/publication.gradle')
}
apply from: rootProject.file('gradle/publishing/sonatype.gradle')

View file

@ -1,323 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!-- This is a checkstyle configuration file. For descriptions of
what the following rules do, please see the checkstyle configuration
page at http://checkstyle.sourceforge.net/config.html -->
<module name="Checker">
<module name="FileTabCharacter">
<!-- Checks that there are no tab characters in the file.
-->
</module>
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf"/>
</module>
<module name="RegexpSingleline">
<!-- Checks that FIXME is not used in comments. TODO is preferred.
-->
<property name="format" value="((//.*)|(\*.*))FIXME" />
<property name="message" value='TODO is preferred to FIXME. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="RegexpSingleline">
<!-- Checks that TODOs are named. (Actually, just that they are followed
by an open paren.)
-->
<property name="format" value="((//.*)|(\*.*))TODO[^(]" />
<property name="message" value='All TODOs should be named. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="JavadocPackage">
<!-- Checks that each Java package has a Javadoc file used for commenting.
Only allows a package-info.java, not package.html. -->
</module>
<!-- All Java AST specific tests live under TreeWalker module. -->
<module name="TreeWalker">
<!--
IMPORT CHECKS
-->
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<module name="ImportOrder">
<!-- Checks for out of order import statements. -->
<property name="severity" value="warning"/>
<property name="groups" value="com.google,android,junit,net,org,java,javax"/>
<!-- This ensures that static imports go first. -->
<property name="option" value="top"/>
<property name="tokens" value="STATIC_IMPORT, IMPORT"/>
</module>
<!--
JAVADOC CHECKS
-->
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
<module name="JavadocMethod">
<property name="scope" value="protected"/>
<property name="severity" value="warning"/>
<property name="allowMissingJavadoc" value="true"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowUndeclaredRTE" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="protected"/>
<property name="severity" value="error"/>
</module>
<module name="JavadocStyle">
<property name="severity" value="warning"/>
</module>
<!--
NAMING CHECKS
-->
<!-- Item 38 - Adhere to generally accepted naming conventions -->
<module name="PackageName">
<!-- Validates identifiers for package names against the
supplied expression. -->
<!-- Here the default checkstyle rule restricts package name parts to
seven characters, this is not in line with common practice at Google.
-->
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]{1,})*$"/>
<property name="severity" value="warning"/>
</module>
<module name="TypeNameCheck">
<!-- Validates static, final fields against the
expression "^[A-Z][a-zA-Z0-9]*$". -->
<metadata name="altname" value="TypeName"/>
<property name="severity" value="warning"/>
</module>
<module name="ConstantNameCheck">
<!-- Validates non-private, static, final fields against the supplied
public/package final fields "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$". -->
<metadata name="altname" value="ConstantName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="false"/>
<property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|FLAG_.*)$"/>
<message key="name.invalidPattern"
value="Variable ''{0}'' should be in ALL_CAPS (if it is a constant) or be private (otherwise)."/>
<property name="severity" value="warning"/>
</module>
<module name="StaticVariableNameCheck">
<!-- Validates static, non-final fields against the supplied
expression "^[a-z][a-zA-Z0-9]*_?$". -->
<metadata name="altname" value="StaticVariableName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
<property name="severity" value="warning"/>
</module>
<module name="MemberNameCheck">
<!-- Validates non-static members against the supplied expression. -->
<metadata name="altname" value="MemberName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
<property name="severity" value="warning"/>
</module>
<module name="MethodNameCheck">
<!-- Validates identifiers for method names. -->
<metadata name="altname" value="MethodName"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$"/>
<property name="severity" value="warning"/>
</module>
<module name="ParameterName">
<!-- Validates identifiers for method parameters against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalFinalVariableName">
<!-- Validates identifiers for local final variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalVariableName">
<!-- Validates identifiers for local variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<!--
LENGTH and CODING CHECKS
-->
<module name="LineLength">
<!-- Checks if a line is too long. -->
<property name="max" value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.max}" default="128"/>
<property name="severity" value="error"/>
<!--
The default ignore pattern exempts the following elements:
- import statements
- long URLs inside comments
-->
<property name="ignorePattern"
value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.ignorePattern}"
default="^(package .*;\s*)|(import .*;\s*)|( *(\*|//).*https?://.*)$"/>
</module>
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
<module name="RightCurly">
<!-- Checks right curlies on CATCH, ELSE, and TRY blocks are on
the same line. e.g., the following example is fine:
<pre>
if {
...
} else
</pre>
-->
<!-- This next example is not fine:
<pre>
if {
...
}
else
</pre>
-->
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
<!-- Checks for braces around if and else blocks -->
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"/>
</module>
<module name="UpperEll">
<!-- Checks that long constants are defined with an upper ell.-->
<property name="severity" value="error"/>
</module>
<module name="FallThrough">
<!-- Warn about falling through to the next case statement. Similar to
javac -Xlint:fallthrough, but the check is suppressed if a single-line comment
on the last non-blank line preceding the fallen-into case contains 'fall through' (or
some other variants which we don't publicized to promote consistency).
-->
<property name="reliefPattern"
value="fall through|Fall through|fallthru|Fallthru|falls through|Falls through|fallthrough|Fallthrough|No break|NO break|no break|continue on"/>
<property name="severity" value="error"/>
</module>
<!--
MODIFIERS CHECKS
-->
<module name="ModifierOrder">
<!-- Warn if modifier order is inconsistent with JLS3 8.1.1, 8.3.1, and
8.4.3. The prescribed order is:
public, protected, private, abstract, static, final, transient, volatile,
synchronized, native, strictfp
-->
</module>
<!--
WHITESPACE CHECKS
-->
<module name="WhitespaceAround">
<!-- Checks that various tokens are surrounded by whitespace.
This includes most binary operators and keywords followed
by regular or curly braces.
-->
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR,
BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN,
EQUAL, GE, GT, LAND, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE,
LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN,
LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS,
MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION,
SL, SL_ASSIGN, SR_ASSIGN, STAR, STAR_ASSIGN"/>
<property name="severity" value="error"/>
</module>
<module name="WhitespaceAfter">
<!-- Checks that commas, semicolons and typecasts are followed by
whitespace.
-->
<property name="tokens" value="COMMA, SEMI, TYPECAST"/>
</module>
<module name="NoWhitespaceAfter">
<!-- Checks that there is no whitespace after various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS,
UNARY_PLUS"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="NoWhitespaceBefore">
<!-- Checks that there is no whitespace before various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="SEMI, DOT, POST_DEC, POST_INC"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="ParenPad">
<!-- Checks that there is no whitespace before close parens or after
open parens.
-->
<property name="severity" value="warning"/>
</module>
</module>
</module>

View file

@ -1,5 +0,0 @@
This is a derived work of
https://github.com/nebula-plugins/gradle-ospackage-plugin
licensed under Apache Software License 2.0.

View file

@ -1,37 +1,41 @@
plugins {
id 'java-gradle-plugin'
id 'com.gradle.plugin-publish' version '0.10.0'
id 'com.gradle.plugin-publish' version '0.11.0'
}
group = 'org.xbib.gradle.plugin'
apply plugin: 'groovy'
apply plugin: 'maven'
apply plugin: 'signing'
apply plugin: 'java-gradle-plugin'
apply plugin: 'com.gradle.plugin-publish'
dependencies {
compile gradleApi()
compile project(':rpm-core')
compileOnly "org.codehaus.groovy:groovy:${project.property('groovy.version')}"
testCompile "junit:junit:${project.property('junit.version')}"
testCompile("org.spockframework:spock-core:${project.property('spock-core.version')}") {
exclude module: 'groovy'
exclude module: 'junit'
}
testCompile "org.xbib:guice:${project.property('xbib-guice.version')}"
api gradleApi()
api project(':rpm-core')
testImplementation gradleTestKit()
}
compileGroovy {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
test {
testLogging {
showStandardStreams = true
exceptionFormat = 'full'
compileTestGroovy {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
validatePlugins {
// disable warning as failures because gradle plugin does not recognize @Delegate tag
failOnWarning = false
}
gradlePlugin {
plugins {
rpmPlugin {
id = 'org.xbib.gradle.plugin.rpm'
implementationClass = 'org.xbib.gradle.plugin.RpmPlugin'
}
}
}
@ -43,8 +47,8 @@ if (project.hasProperty('gradle.publish.key')) {
rpmPlugin {
id = 'org.xbib.gradle.plugin.rpm'
version = project.version
description = projectDescription
displayName = projectDescription
description = rootProject.ext.description
displayName = rootProject.ext.description
tags = ['gradle', 'plugin', 'rpm']
}
}

View file

@ -1,323 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!-- This is a checkstyle configuration file. For descriptions of
what the following rules do, please see the checkstyle configuration
page at http://checkstyle.sourceforge.net/config.html -->
<module name="Checker">
<module name="FileTabCharacter">
<!-- Checks that there are no tab characters in the file.
-->
</module>
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf"/>
</module>
<module name="RegexpSingleline">
<!-- Checks that FIXME is not used in comments. TODO is preferred.
-->
<property name="format" value="((//.*)|(\*.*))FIXME" />
<property name="message" value='TODO is preferred to FIXME. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="RegexpSingleline">
<!-- Checks that TODOs are named. (Actually, just that they are followed
by an open paren.)
-->
<property name="format" value="((//.*)|(\*.*))TODO[^(]" />
<property name="message" value='All TODOs should be named. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="JavadocPackage">
<!-- Checks that each Java package has a Javadoc file used for commenting.
Only allows a package-info.java, not package.html. -->
</module>
<!-- All Java AST specific tests live under TreeWalker module. -->
<module name="TreeWalker">
<!--
IMPORT CHECKS
-->
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<module name="ImportOrder">
<!-- Checks for out of order import statements. -->
<property name="severity" value="warning"/>
<property name="groups" value="com.google,android,junit,net,org,java,javax"/>
<!-- This ensures that static imports go first. -->
<property name="option" value="top"/>
<property name="tokens" value="STATIC_IMPORT, IMPORT"/>
</module>
<!--
JAVADOC CHECKS
-->
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
<module name="JavadocMethod">
<property name="scope" value="protected"/>
<property name="severity" value="warning"/>
<property name="allowMissingJavadoc" value="true"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowUndeclaredRTE" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="protected"/>
<property name="severity" value="error"/>
</module>
<module name="JavadocStyle">
<property name="severity" value="warning"/>
</module>
<!--
NAMING CHECKS
-->
<!-- Item 38 - Adhere to generally accepted naming conventions -->
<module name="PackageName">
<!-- Validates identifiers for package names against the
supplied expression. -->
<!-- Here the default checkstyle rule restricts package name parts to
seven characters, this is not in line with common practice at Google.
-->
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]{1,})*$"/>
<property name="severity" value="warning"/>
</module>
<module name="TypeNameCheck">
<!-- Validates static, final fields against the
expression "^[A-Z][a-zA-Z0-9]*$". -->
<metadata name="altname" value="TypeName"/>
<property name="severity" value="warning"/>
</module>
<module name="ConstantNameCheck">
<!-- Validates non-private, static, final fields against the supplied
public/package final fields "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$". -->
<metadata name="altname" value="ConstantName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="false"/>
<property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|FLAG_.*)$"/>
<message key="name.invalidPattern"
value="Variable ''{0}'' should be in ALL_CAPS (if it is a constant) or be private (otherwise)."/>
<property name="severity" value="warning"/>
</module>
<module name="StaticVariableNameCheck">
<!-- Validates static, non-final fields against the supplied
expression "^[a-z][a-zA-Z0-9]*_?$". -->
<metadata name="altname" value="StaticVariableName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
<property name="severity" value="warning"/>
</module>
<module name="MemberNameCheck">
<!-- Validates non-static members against the supplied expression. -->
<metadata name="altname" value="MemberName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
<property name="severity" value="warning"/>
</module>
<module name="MethodNameCheck">
<!-- Validates identifiers for method names. -->
<metadata name="altname" value="MethodName"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$"/>
<property name="severity" value="warning"/>
</module>
<module name="ParameterName">
<!-- Validates identifiers for method parameters against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalFinalVariableName">
<!-- Validates identifiers for local final variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalVariableName">
<!-- Validates identifiers for local variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<!--
LENGTH and CODING CHECKS
-->
<module name="LineLength">
<!-- Checks if a line is too long. -->
<property name="max" value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.max}" default="128"/>
<property name="severity" value="error"/>
<!--
The default ignore pattern exempts the following elements:
- import statements
- long URLs inside comments
-->
<property name="ignorePattern"
value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.ignorePattern}"
default="^(package .*;\s*)|(import .*;\s*)|( *(\*|//).*https?://.*)$"/>
</module>
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
<module name="RightCurly">
<!-- Checks right curlies on CATCH, ELSE, and TRY blocks are on
the same line. e.g., the following example is fine:
<pre>
if {
...
} else
</pre>
-->
<!-- This next example is not fine:
<pre>
if {
...
}
else
</pre>
-->
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
<!-- Checks for braces around if and else blocks -->
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"/>
</module>
<module name="UpperEll">
<!-- Checks that long constants are defined with an upper ell.-->
<property name="severity" value="error"/>
</module>
<module name="FallThrough">
<!-- Warn about falling through to the next case statement. Similar to
javac -Xlint:fallthrough, but the check is suppressed if a single-line comment
on the last non-blank line preceding the fallen-into case contains 'fall through' (or
some other variants which we don't publicized to promote consistency).
-->
<property name="reliefPattern"
value="fall through|Fall through|fallthru|Fallthru|falls through|Falls through|fallthrough|Fallthrough|No break|NO break|no break|continue on"/>
<property name="severity" value="error"/>
</module>
<!--
MODIFIERS CHECKS
-->
<module name="ModifierOrder">
<!-- Warn if modifier order is inconsistent with JLS3 8.1.1, 8.3.1, and
8.4.3. The prescribed order is:
public, protected, private, abstract, static, final, transient, volatile,
synchronized, native, strictfp
-->
</module>
<!--
WHITESPACE CHECKS
-->
<module name="WhitespaceAround">
<!-- Checks that various tokens are surrounded by whitespace.
This includes most binary operators and keywords followed
by regular or curly braces.
-->
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR,
BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN,
EQUAL, GE, GT, LAND, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE,
LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN,
LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS,
MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION,
SL, SL_ASSIGN, SR_ASSIGN, STAR, STAR_ASSIGN"/>
<property name="severity" value="error"/>
</module>
<module name="WhitespaceAfter">
<!-- Checks that commas, semicolons and typecasts are followed by
whitespace.
-->
<property name="tokens" value="COMMA, SEMI, TYPECAST"/>
</module>
<module name="NoWhitespaceAfter">
<!-- Checks that there is no whitespace after various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS,
UNARY_PLUS"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="NoWhitespaceBefore">
<!-- Checks that there is no whitespace before various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="SEMI, DOT, POST_DEC, POST_INC"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="ParenPad">
<!-- Checks that there is no whitespace before close parens or after
open parens.
-->
<property name="severity" value="warning"/>
</module>
</module>
</module>

View file

@ -0,0 +1,51 @@
package org.xbib.gradle.plugin
import org.gradle.api.internal.file.copy.CopyAction
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import java.util.concurrent.Callable
class Rpm extends AbstractArchiveTask {
@Delegate
@Nested
RpmExtension rpmExtension
Rpm() {
rpmExtension = project.extensions.findByName('rpm') as RpmExtension
getArchiveExtension().set("rpm")
Callable<String> archiveFileNameProvider = new Callable<String>() {
@Override
String call() throws Exception {
constructArchiveFileName()
}
}
archiveFileName.set(project.provider(archiveFileNameProvider))
}
@Override
protected CopyAction createCopyAction() {
new RpmCopyAction(project, rpmExtension, this)
}
private String constructArchiveFileName() {
StringBuilder sb = new StringBuilder()
if (packageName) {
sb.append(packageName)
}
if (packageVersion) {
sb.append('-').append(packageVersion)
}
if (packageRelease) {
sb.append('-').append(packageRelease)
}
if (arch) {
sb.append('.').append(arch.name().toLowerCase(Locale.ROOT))
}
if (archiveExtension) {
sb.append('.').append(archiveExtension.get())
}
sb.toString()
}
}

View file

@ -0,0 +1,212 @@
package org.xbib.gradle.plugin
import org.gradle.api.Project
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.FileCopyDetails
import org.gradle.api.internal.file.CopyActionProcessingStreamAction
import org.gradle.api.internal.file.copy.CopyAction
import org.gradle.api.internal.file.copy.CopyActionProcessingStream
import org.gradle.api.internal.file.copy.FileCopyDetailsInternal
import org.gradle.api.tasks.WorkResult
import org.gradle.api.tasks.WorkResults
import org.xbib.rpm.Dependency
import org.xbib.rpm.Directory
import org.xbib.rpm.Link
import org.xbib.rpm.RpmBuilder
import org.xbib.rpm.payload.Directive
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
class RpmCopyAction implements CopyAction {
Project project
Rpm task
RpmExtension ext
RpmBuilder builder
Path tempDir
RpmCopyAction(Project project, RpmExtension rpmExtension, Rpm task) {
this.project = project
this.task = task
this.ext = rpmExtension
}
@Override
WorkResult execute(CopyActionProcessingStream copyActionProcessingStream) {
if (ext.enabled) {
task.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
tempDir = task.getTemporaryDir().toPath()
this.builder = createRpm()
copyActionProcessingStream.process(new StreamAction())
addOther()
buildRpm()
}
WorkResults.didWork(true)
}
RpmBuilder createRpm() {
RpmBuilder builder = new RpmBuilder()
builder.setPackage ext.packageName, ext.packageVersion, ext.packageRelease, ext.epoch
builder.setType ext.packageType
builder.setPlatform ext.arch, ext.os
builder.setGroup ext.packageGroup
builder.setBuildHost ext.buildHost
builder.setSummary ext.summary
builder.setDescription ext.packageDescription
builder.setLicense ext.license
builder.setPackager ext.packager
builder.setDistribution ext.distribution
builder.setVendor ext.vendor
builder.setUrl ext.url
builder.setPrefixes task.prefixes
builder.setPrivateKeyId task.getSigningKeyId()
builder.setPrivateKeyPassphrase task.getSigningKeyPassphrase()
builder.setPrivateKeyRing task.getSigningKeyRing()
builder.setPrivateKeyHashAlgo task.getSigningKeyHashAlgo()
builder.setSourceRpm(task.sourcePackage)
builder.setPreInstall task.preInstallFile?.text ?: task.preInstall
builder.setPostInstall task.postInstallFile?.text ?: task.postInstall
builder.setPreUninstall task.preUninstallFile?.text ?: task.preUninstall
builder.setPostUninstall task.postUninstallFile?.text ?: task.postUninstall
builder.setPreTrans task.preTransFile?.text ?: task.preTrans
builder.setPostTrans task.postTransFile?.text ?: task.postTrans
builder.setPreInstall prepareScripts(task, task.preInstallCommands)
builder.setPostInstall prepareScripts(task, task.postInstallCommands)
builder.setPreUninstall prepareScripts(task, task.preUninstallCommands)
builder.setPostUninstall prepareScripts(task, task.postUninstallCommands)
builder.setPreTrans prepareScripts(task, task.preTransCommands)
builder.setPostTrans prepareScripts(task, task.postTransCommands)
if (task.changeLogFile) {
builder.addChangelog task.changeLogFile?.toPath()
}
if (task.changeLog) {
builder.addChangelog(task.changeLog)
}
builder
}
void addOther() {
for (Link link : task.links) {
builder.addLink(link.path, link.target, link.permissions)
}
for (Dependency dep : task.dependencies) {
builder.addDependency(dep.packageName, dep.flags, dep.version)
}
for (Dependency obsolete: task.obsoletes) {
builder.addObsoletes(obsolete.packageName, obsolete.flags, obsolete.version)
}
for (Dependency conflict : task.conflicts) {
builder.addConflicts(conflict.packageName, conflict.flags, conflict.version)
}
for (Dependency provides : task.provides) {
builder.addProvides(provides.packageName, provides.flags, provides.version)
}
for (Directory directory : task.directories) {
String user = directory.user ? directory.user : task.user
String group = directory.group ? directory.group : task.group
builder.addDirectory(directory.path, directory.permissions, null, user, group, directory.addParents)
}
}
void buildRpm() {
Path path = task.archiveFile.get().asFile.toPath()
Files.createDirectories(path.parent)
Files.newByteChannel(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING).withCloseable { ch ->
builder.build(ch)
}
}
private class StreamAction implements CopyActionProcessingStreamAction {
@Override
void processFile(FileCopyDetailsInternal fileCopyDetailsInternal) {
boolean addParents = ext.addParentDirs != null ? ext.addParentDirs : task.addParentDirs
Path path = extractPath(tempDir, fileCopyDetailsInternal)
String p = "/${fileCopyDetailsInternal.path}"
if (Files.isSymbolicLink(path)) {
builder.addLink(p, Files.readSymbolicLink(path).toFile().path, -1)
} else if (!fileCopyDetailsInternal.isDirectory()) {
int mode = fileCopyDetailsInternal.mode
int dirmode = -1
EnumSet<Directive> directive = makeDirective(ext.fileType)
String user = ext.user ?: task.user
String group = ext.group ?: task.group
builder.addFile(p, path, mode, dirmode, directive, user, group, addParents)
}
}
}
private static Path extractPath(Path tempDir, FileCopyDetails fileDetails) {
Path path
try {
path = fileDetails.file.toPath()
} catch (UnsupportedOperationException e) {
path = tempDir.resolve(fileDetails.path)
fileDetails.copyTo(path.toFile())
}
path
}
private static EnumSet<Directive> makeDirective(List<String> strings) {
EnumSet<Directive> set = EnumSet.of(Directive.NONE)
for (String string : strings) {
set.add(Directive.valueOf(string.toUpperCase(Locale.ROOT)))
}
set
}
private static String prepareScripts(Rpm task, List<Object> scripts) {
if (scripts != null && !scripts.isEmpty()) {
List<Object> list = []
def stdDefines = standardScriptDefines(task)
if (stdDefines) {
list.add(stdDefines)
}
if (task.commonCommands) {
list.addAll(task.commonCommands)
}
list.addAll(scripts)
return concatAndRemoveShebangLines(list)
} else {
return null
}
}
private static String standardScriptDefines(Rpm task) {
String.format(" RPM_ARCH=%s \n RPM_OS=%s \n RPM_PACKAGE_NAME=%s \n RPM_PACKAGE_VERSION=%s \n RPM_PACKAGE_RELEASE=%s \n\n",
task.arch?.toString()?.toLowerCase()?:'',
task.os?.toString()?.toLowerCase()?: '',
task.packageName,
task.packageVersion,
task.packageRelease)
}
private static String concatAndRemoveShebangLines(Collection<Object> scripts) {
String shebang
StringBuilder result = new StringBuilder()
scripts.each { script ->
script?.eachLine { line ->
if (line.matches('^#!.*$')) {
if (!shebang) {
shebang = line
} else if (line != shebang) {
throw new IllegalArgumentException("mismatching #! script lines")
}
} else {
result.append line
result.append "\n"
}
}
}
if (shebang) {
result.insert(0, shebang + "\n")
}
result.toString()
}
}

View file

@ -0,0 +1,409 @@
package org.xbib.gradle.plugin
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.xbib.rpm.Dependency
import org.xbib.rpm.Directory
import org.xbib.rpm.Link
import org.xbib.rpm.lead.Architecture
import org.xbib.rpm.lead.Os
import org.xbib.rpm.lead.PackageType
class RpmExtension {
@Optional
@Input
boolean enabled = true
@Optional
@Input
String packageName
@Optional
@Input
String packageVersion
@Optional
@Input
String packageRelease
@Optional
@Input
Integer epoch = 0
@Optional
@Input
String signingKeyPassphrase
@Optional
@Input
String signingKeyRing
@Optional
@Input
String signingKeyId
@Optional
@Input
String signingKeyHashAlgo
@Optional
@Input
String user
@Optional
@Input
String group
@Optional
@Input
String buildHost
@Optional
@Input
String packageGroup
@Optional
@Input
String packageDescription = ''
@Optional
@Input
String summary
@Optional
@Input
String license
@Optional
@Input
String packager
@Optional
@Input
String distribution
@Optional
@Input
String vendor
@Optional
@Input
String url
@Optional
@Input
String sourcePackage
@Optional
@Input
List<String> fileType
@Optional
@Input
Boolean addParentDirs = false
@Optional
@Input
Architecture arch = Architecture.X86_64
@Optional
@Input
Os os = Os.LINUX
@Optional
@Input
PackageType packageType = PackageType.BINARY
@Input
List<String> prefixes = new ArrayList<String>()
@Optional
@Input
Integer uid
@Optional
@Input
Integer gid
@Optional
@Input
String maintainer
@Optional
@Input
String uploaders
@Optional
@Input
String priority
@Optional
@Input
String preInstall
@Optional
@Input
File preInstallFile
@Input
List<Object> preInstallCommands = []
@Optional
@Input
String postInstall
@Optional
@Input
File postInstallFile
@Input
List<Object> postInstallCommands = []
@Optional
@Input
String preUninstall
@Optional
@Input
File preUninstallFile
@Input
List<Object> preUninstallCommands = []
@Optional
@Input
String postUninstall
@Optional
@Input
File postUninstallFile
@Input
List<Object> postUninstallCommands = []
@Optional
@Input
String preTrans
@Optional
@Input
File preTransFile
@Input
List<Object> preTransCommands = []
@Optional
@Input
String postTrans
@Optional
@Input
File postTransFile
@Input
List<Object> postTransCommands = []
@Input
List<Object> commonCommands = []
@Input
List<Link> links = []
Link link(String path, String target) {
link(path, target, -1)
}
Link link(String path, String target, int permissions) {
Link link = new Link(path, target, permissions)
links.add(link)
link
}
@Input
List<Dependency> dependencies = []
@Input
List<Dependency> obsoletes = []
@Input
List<Dependency> conflicts = []
@Input
List<Dependency> recommends = []
@Input
List<Dependency> suggests = []
@Input
List<Dependency> enhances = []
@Input
List<Dependency> preDepends = []
@Input
List<Dependency> breaks = []
@Input
List<Dependency> replaces = []
@Input
List<Dependency> provides = []
Dependency requires(String packageName) {
requires(packageName, '')
}
Dependency requires(String packageName, String version){
requires(packageName, version, 0)
}
Dependency requires(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
dependencies.add(dep)
dep
}
Dependency obsoletes(String packageName) {
obsoletes(packageName, '')
}
Dependency obsoletes(String packageName, String version) {
obsoletes(packageName, version, 0)
}
Dependency obsoletes(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
obsoletes.add(dep)
dep
}
Dependency conflicts(String packageName) {
conflicts(packageName, '')
}
Dependency conflicts(String packageName, String version) {
conflicts(packageName, version, 0)
}
Dependency conflicts(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
conflicts.add(dep)
dep
}
Dependency recommends(String packageName) {
recommends(packageName, '')
}
Dependency recommends(String packageName, String version) {
recommends(packageName, version, 0)
}
Dependency recommends(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
recommends.add(dep)
dep
}
Dependency suggests(String packageName) {
suggests(packageName, '')
}
Dependency suggests(String packageName, String version) {
suggests(packageName, version, 0)
}
Dependency suggests(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
suggests.add(dep)
dep
}
Dependency enhances(String packageName) {
enhances(packageName, '')
}
Dependency enhances(String packageName, String version) {
enhances(packageName, version, 0)
}
Dependency enhances(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
enhances.add(dep)
dep
}
Dependency preDepends(String packageName) {
preDepends(packageName, '')
}
Dependency preDepends(String packageName, String version) {
preDepends(packageName, version, 0)
}
Dependency preDepends(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
preDepends.add(dep)
dep
}
Dependency breaks(String packageName) {
breaks(packageName, '')
}
Dependency breaks(String packageName, String version) {
breaks(packageName, version, 0)
}
Dependency breaks(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
breaks.add(dep)
dep
}
Dependency replaces(String packageName) {
replaces(packageName, '')
}
Dependency replaces(String packageName, String version) {
replaces(packageName, version, 0)
}
Dependency replaces(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
replaces.add(dep)
dep
}
Dependency provides(String packageName) {
provides(packageName, '')
}
Dependency provides(String packageName, String version) {
provides(packageName, version, 0)
}
Dependency provides(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
provides.add(dep)
dep
}
@Input
List<Directory> directories = []
Directory directory(String path) {
Directory directory = new Directory(path: path)
directories << directory
directory
}
@Optional
@Input
File changeLogFile
@Optional
@Input
String changeLog
}

View file

@ -0,0 +1,43 @@
package org.xbib.gradle.plugin
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.tasks.TaskProvider
import org.gradle.util.GradleVersion
class RpmPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
checkVersion()
project.plugins.apply(BasePlugin)
project.ext.Rpm = Rpm.class
project.with {
createExtension(project)
}
/*project.afterEvaluate {
addTasks(project)
}*/
}
private static void checkVersion() {
String version = '6.4'
if (GradleVersion.current() < GradleVersion.version(version)) {
throw new GradleException("need Gradle ${version} or higher")
}
}
private static void createExtension(Project project) {
project.extensions.create('rpm', RpmExtension)
}
/*private static void addTasks(Project project) {
TaskProvider<Rpm> taskProvider = project.tasks.register('buildRpm', Rpm) {
group = 'rpm'
description = 'Generate RPM archive'
}
project.tasks.findByName('build').dependsOn taskProvider
}*/
}

View file

@ -1,77 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.file.CopySpec
import org.gradle.api.internal.file.copy.CopySpecWrapper
import org.gradle.internal.impldep.org.apache.commons.lang.reflect.FieldUtils
/**
*
*/
@Category(CopySpec)
class CopySpecEnhancement {
static void appendFieldToCopySpec(CopySpec spec, String fieldName, Object value) {
def directSpec = spec
if (spec instanceof CopySpecWrapper) {
def delegateField = FieldUtils.getField(CopySpecWrapper, 'delegate', true)
directSpec = delegateField.get(spec)
}
directSpec.metaClass["get${fieldName.capitalize()}"] = { value }
}
static void user(CopySpec spec, String user) {
appendFieldToCopySpec(spec, 'user', user)
}
static void setUser(CopySpec spec, String userArg) {
user(spec, userArg)
}
static void permissionGroup(CopySpec spec, String permissionGroup) {
appendFieldToCopySpec(spec, 'permissionGroup', permissionGroup)
}
static void setPermissionGroup(CopySpec spec, String permissionGroupArg) {
permissionGroup(spec, permissionGroupArg)
}
static void setFileType(CopySpec spec, List<String> fileTypeArg) {
fileType(spec, fileTypeArg)
}
static void fileType(CopySpec spec, List<String> fileType) {
appendFieldToCopySpec(spec, 'fileType', fileType)
}
static void addParentDirs(CopySpec spec, boolean addParentDirs) {
appendFieldToCopySpec(spec, 'addParentDirs', addParentDirs)
}
static void setAddParentDirs(CopySpec spec, boolean addParentDirsArg) {
addParentDirs(spec, addParentDirsArg)
}
static void createDirectoryEntry(CopySpec spec, boolean createDirectoryEntry) {
appendFieldToCopySpec(spec, 'createDirectoryEntry', createDirectoryEntry)
}
static void setCreateDirectoryEntry(CopySpec spec, boolean createDirectoryEntryArg) {
createDirectoryEntry(spec, createDirectoryEntryArg)
}
static void uid(CopySpec spec, int uid) {
appendFieldToCopySpec(spec, 'uid', uid)
}
static void setUid(CopySpec spec, int uidArg) {
uid(spec, uidArg)
}
static void gid(CopySpec spec, int gid) {
appendFieldToCopySpec(spec, 'gid', gid)
}
static void setGid(CopySpec spec, int gidArg) {
gid(spec, gidArg)
}
}

View file

@ -1,55 +0,0 @@
package org.xbib.gradle.plugin.rpm
import groovy.transform.EqualsAndHashCode
import org.xbib.rpm.format.Flags
@EqualsAndHashCode
class Dependency implements Serializable {
String packageName
String version
int flag = 0
Dependency alternative = null
Dependency(String packageName, String version, int flag=0) {
if (packageName.contains(',')) {
throw new IllegalArgumentException('package name can not contain comma')
}
this.packageName = packageName
this.version = version
this.flag = flag
}
Dependency or(String packageName, String version='', int flag=0) {
alternative = new Dependency(packageName, version, flag)
alternative
}
String toDebString() {
def signMap = [
(Flags.GREATER|Flags.EQUAL): '>=',
(Flags.LESS|Flags.EQUAL): '<=',
(Flags.EQUAL): '=',
(Flags.GREATER): '>>',
(Flags.LESS): '<<'
]
def depStr = this.packageName
if (this.flag && this.version) {
def sign = signMap[this.flag]
if (sign==null) {
throw new IllegalArgumentException()
}
depStr += " (${sign} ${this.version})"
} else if (this.version) {
depStr += " (${this.version})"
}
if (alternative) {
depStr += " | " + alternative.toDebString()
}
depStr
}
}

View file

@ -1,14 +0,0 @@
package org.xbib.gradle.plugin.rpm
class Directory {
String path
int permissions = -1
String user = null
String permissionGroup = null
boolean addParents = false
}

View file

@ -1,21 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.file.FileCopyDetails
import org.gradle.api.tasks.AbstractCopyTask
import java.nio.file.Files
class FromConfigurationFactory {
static Closure<AbstractCopyTask> preserveSymlinks(delegate) {
return {
delegate.eachFile { FileCopyDetails details ->
if (Files.isSymbolicLink(details.file.toPath())) {
details.exclude()
def toFile = Files.readSymbolicLink(details.file.toPath()).toFile()
delegate.link(details.relativePath.toString(), toFile.toString())
}
}
}
}
}

View file

@ -1,13 +0,0 @@
package org.xbib.gradle.plugin.rpm
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode
class Link implements Serializable {
String path
String target
int permissions = -1
}

View file

@ -1,257 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.file.CopyProcessingSpec
import org.gradle.api.file.CopySpec
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.FileCopyDetails
import org.gradle.api.file.FileTree
import org.gradle.api.file.FileTreeElement
import org.gradle.api.file.RelativePath
import org.gradle.api.internal.file.FileResolver
import org.gradle.api.internal.file.copy.CopySpecInternal
import org.gradle.api.internal.file.copy.DefaultCopySpec
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.specs.Spec
import org.gradle.internal.reflect.Instantiator
import java.util.regex.Pattern
/**
* An extension which can be attached to the project.
* This is a superset of SystemPackagingExtension because we don't
* want the @Delegate to inherit the copy spec parts.
*
* We can't extends DefaultCopySpec, since it's @NotExtensible, meaning that we won't get any convention
* mappings. If we extend DelegatingCopySpec we get groovy compilation errors around the return types between
* CopySourceSpec's methods and the ones overriden in DelegatingCopySpec, even though that's perfectly valid
* Java code. The theory is that it's some bug in groovyc.
*/
class ProjectPackagingExtension extends SystemPackagingExtension {
CopySpecInternal delegateCopySpec
ProjectPackagingExtension(Project project) {
FileResolver resolver = ((ProjectInternal) project).getFileResolver()
Instantiator instantiator = ((ProjectInternal) project).getServices().get(Instantiator)
delegateCopySpec = new DefaultCopySpec(resolver, instantiator)
}
/*
* Special Use cases that involve Closure's which we want to wrap.
*/
CopySpec from(Object sourcePath, Closure c) {
def preserveSymlinks = FromConfigurationFactory.preserveSymlinks(this)
use(CopySpecEnhancement) {
return getDelegateCopySpec().from(sourcePath, c << preserveSymlinks)
}
}
CopySpec from(Object... sourcePaths) {
def spec = null
for (Object sourcePath : sourcePaths) {
spec = from(sourcePath, {})
}
spec
}
CopySpec into(Object destPath, Closure configureClosure) {
use(CopySpecEnhancement) {
return getDelegateCopySpec().into(destPath, configureClosure)
}
}
CopySpec include(Closure includeSpec) {
use(CopySpecEnhancement) {
return getDelegateCopySpec().include(includeSpec)
}
}
CopySpec exclude(Closure excludeSpec) {
use(CopySpecEnhancement) {
return getDelegateCopySpec().exclude(excludeSpec)
}
}
CopySpec filter(Closure closure) {
use(CopySpecEnhancement) {
return getDelegateCopySpec().filter(closure)
}
}
CopySpec rename(Closure closure) {
use(CopySpecEnhancement) {
return getDelegateCopySpec().rename(closure)
}
}
CopySpec eachFile(Closure closure) {
use(CopySpecEnhancement) {
return getDelegateCopySpec().eachFile(closure)
}
}
/*
* Copy and Paste from org.gradle.api.internal.file.copy.DelegatingCopySpec, since extending it causes
* compilation problems. The methods above are special cases and are commented out below.
*/
RelativePath getDestPath() {
getDelegateCopySpec().getDestPath()
}
FileTree getSource() {
getDelegateCopySpec().getSource()
}
boolean hasSource() {
getDelegateCopySpec().hasSource()
}
Collection<? extends Action<? super FileCopyDetails>> getAllCopyActions() {
getDelegateCopySpec().getAllCopyActions()
}
boolean isCaseSensitive() {
getDelegateCopySpec().isCaseSensitive()
}
void setCaseSensitive(boolean caseSensitive) {
getDelegateCopySpec().setCaseSensitive(caseSensitive)
}
boolean getIncludeEmptyDirs() {
getDelegateCopySpec().getIncludeEmptyDirs()
}
void setIncludeEmptyDirs(boolean includeEmptyDirs) {
getDelegateCopySpec().setIncludeEmptyDirs(includeEmptyDirs)
}
DuplicatesStrategy getDuplicatesStrategy() {
getDelegateCopySpec().getDuplicatesStrategy()
}
void setDuplicatesStrategy(DuplicatesStrategy strategy) {
getDelegateCopySpec().setDuplicatesStrategy(strategy)
}
CopySpec filesMatching(String pattern, Action<? super FileCopyDetails> action) {
getDelegateCopySpec().filesMatching(pattern, action)
}
CopySpec filesNotMatching(String pattern, Action<? super FileCopyDetails> action) {
getDelegateCopySpec().filesNotMatching(pattern, action)
}
CopySpec with(CopySpec... sourceSpecs) {
getDelegateCopySpec().with(sourceSpecs)
}
CopySpec setIncludes(Iterable<String> includes) {
getDelegateCopySpec().setIncludes(includes)
}
CopySpec setExcludes(Iterable<String> excludes) {
getDelegateCopySpec().setExcludes(excludes)
}
CopySpec include(String... includes) {
getDelegateCopySpec().include(includes)
}
CopySpec include(Iterable<String> includes) {
getDelegateCopySpec().include(includes)
}
CopySpec include(Spec<FileTreeElement> includeSpec) {
getDelegateCopySpec().include(includeSpec)
}
CopySpec exclude(String... excludes) {
getDelegateCopySpec().exclude(excludes)
}
CopySpec exclude(Iterable<String> excludes) {
getDelegateCopySpec().exclude(excludes)
}
CopySpec exclude(Spec<FileTreeElement> excludeSpec) {
getDelegateCopySpec().exclude(excludeSpec)
}
CopySpec into(Object destPath) {
getDelegateCopySpec().into(destPath)
}
CopySpec rename(String sourceRegEx, String replaceWith) {
getDelegateCopySpec().rename(sourceRegEx, replaceWith)
}
CopyProcessingSpec rename(Pattern sourceRegEx, String replaceWith) {
getDelegateCopySpec().rename(sourceRegEx, replaceWith)
}
CopySpec filter(Map<String, ?> properties, Class<? extends FilterReader> filterType) {
getDelegateCopySpec().filter(properties, filterType)
}
CopySpec filter(Class<? extends FilterReader> filterType) {
getDelegateCopySpec().filter(filterType)
}
CopySpec expand(Map<String, ?> properties) {
getDelegateCopySpec().expand(properties)
}
CopySpec eachFile(Action<? super FileCopyDetails> action) {
getDelegateCopySpec().eachFile(action)
}
Integer getFileMode() {
getDelegateCopySpec().getFileMode()
}
CopyProcessingSpec setFileMode(Integer mode) {
getDelegateCopySpec().setFileMode(mode)
}
Integer getDirMode() {
getDelegateCopySpec().getDirMode()
}
CopyProcessingSpec setDirMode(Integer mode) {
getDelegateCopySpec().setDirMode(mode)
}
Set<String> getIncludes() {
getDelegateCopySpec().getIncludes()
}
Set<String> getExcludes() {
getDelegateCopySpec().getExcludes()
}
Iterable<CopySpecInternal> getChildren() {
getDelegateCopySpec().getChildren()
}
FileTree getAllSource() {
getDelegateCopySpec().getAllSource()
}
DefaultCopySpec addChild() {
getDelegateCopySpec().addChild()
}
DefaultCopySpec addFirst() {
getDelegateCopySpec().addFirst()
}
void walk(Action<? super CopySpecInternal> action) {
action.execute(this)
for (CopySpecInternal child : getChildren()) {
child.walk(action)
}
}
}

View file

@ -1,448 +0,0 @@
package org.xbib.gradle.plugin.rpm
import groovy.util.logging.Log4j
import org.gradle.api.file.FileCollection
import org.gradle.api.file.RegularFile
import org.gradle.api.internal.ConventionMapping
import org.gradle.api.internal.IConventionAware
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.SkipWhenEmpty
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.util.GUtil
import org.xbib.rpm.lead.Architecture
import org.xbib.rpm.lead.Os
import org.xbib.rpm.lead.PackageType
import javax.annotation.Nullable
import java.nio.file.Path
import java.util.concurrent.Callable
/**
*
*/
@Log4j
class Rpm extends AbstractArchiveTask {
final ObjectFactory objectFactory
@Input
@Optional
Path changeLogFile
@Delegate
@Nested
SystemPackagingExtension systemPackagingExtension
ProjectPackagingExtension projectPackagingExtension
Rpm() {
super()
objectFactory = project.objects
systemPackagingExtension = new SystemPackagingExtension()
projectPackagingExtension = project.extensions.findByType(ProjectPackagingExtension)
if (projectPackagingExtension) {
getRootSpec().with(projectPackagingExtension.delegateCopySpec)
}
archiveExtension.set('rpm')
// override archive file name provider in Gradle 5
Callable<String> archiveFileNameProvider = new Callable<String>() {
@Override
String call() throws Exception {
constructArchiveFile()
}
}
getArchiveFileName().set(getProject().provider(archiveFileNameProvider))
}
@Override
RpmCopyAction createCopyAction() {
new RpmCopyAction(this)
}
@Override
@TaskAction
protected void copy() {
use(CopySpecEnhancement) {
super.copy()
}
}
@Override
Rpm from(Object... sourcePaths) {
for (Object sourcePath : sourcePaths) {
from(sourcePath, {})
}
this
}
@Override
Rpm from(Object sourcePath, Closure c) {
def preserveSymlinks = FromConfigurationFactory.preserveSymlinks(this)
use(CopySpecEnhancement) {
getMainSpec().from(sourcePath, c << preserveSymlinks)
}
this
}
@Override
Rpm into(Object destPath, Closure configureClosure) {
use(CopySpecEnhancement) {
getMainSpec().into(destPath, configureClosure)
}
this
}
@Override
Rpm exclude(Closure excludeSpec) {
use(CopySpecEnhancement) {
getMainSpec().exclude(excludeSpec)
}
this
}
@Override
Rpm filter(Closure closure) {
use(CopySpecEnhancement) {
getMainSpec().filter(closure)
}
this
}
@Override
Rpm rename(Closure closure) {
use(CopySpecEnhancement) {
getMainSpec().rename(closure)
}
this
}
@Input
@Optional
List<Object> getAllConfigurationPaths() {
getConfigurationPaths() + (projectPackagingExtension?.getConfigurationPaths()?: [])
}
@Input
@Optional
List<Object> getAllPreInstallCommands() {
getPreInstallCommands() + (projectPackagingExtension?.getPreInstallCommands() ?: [])
}
@Input
@Optional
List<Object> getAllPostInstallCommands() {
getPostInstallCommands() + (projectPackagingExtension?.getPostInstallCommands() ?: [])
}
@Input
@Optional
List<Object> getAllPreUninstallCommands() {
getPreUninstallCommands() + (projectPackagingExtension?.getPreUninstallCommands() ?: [])
}
@Input
@Optional
List<Object> getAllPostUninstallCommands() {
getPostUninstallCommands() + (projectPackagingExtension?.getPostUninstallCommands() ?: [])
}
@Input
@Optional
List<Object> getAllPreTransCommands() {
getPreTransCommands() + projectPackagingExtension?.getPreTransCommands()
}
@Input
@Optional
List<Object> getAllPostTransCommands() {
getPostTransCommands() + projectPackagingExtension?.getPostTransCommands()
}
@Input
@Optional
List<Object> getAllCommonCommands() {
getCommonCommands() + projectPackagingExtension?.getCommonCommands()
}
@Input
@Optional
List<Object> getAllSupplementaryControlFiles() {
getSupplementaryControlFiles() + (projectPackagingExtension?.getSupplementaryControlFiles() ?: [])
}
@Input
@Optional
List<Link> getAllLinks() {
if (projectPackagingExtension) {
return getLinks() + projectPackagingExtension.getLinks()
} else {
return getLinks()
}
}
@Input
@Optional
List<Dependency> getAllDependencies() {
if (projectPackagingExtension) {
return getDependencies() + projectPackagingExtension.getDependencies()
} else {
return getDependencies()
}
}
@Input
@Optional
def getAllPrefixes() {
if (projectPackagingExtension) {
return (getPrefixes() + projectPackagingExtension.getPrefixes()).unique()
} else {
return getPrefixes()
}
}
@Input
@Optional
List<Dependency> getAllProvides() {
if (projectPackagingExtension) {
return projectPackagingExtension.getProvides() + getProvides()
} else {
return getProvides()
}
}
@Input
@Optional
List<Dependency> getAllObsoletes() {
if (projectPackagingExtension) {
return getObsoletes() + projectPackagingExtension.getObsoletes()
} else {
return getObsoletes()
}
}
@Input
@Optional
List<Dependency> getAllConflicts() {
if (projectPackagingExtension) {
return getConflicts() + projectPackagingExtension.getConflicts()
} else {
return getConflicts()
}
}
/**
* Defines input files annotation with @SkipWhenEmpty as a workaround to force building the archive even if no
* from clause is declared. Without this method the task would be marked UP-TO-DATE - the actual archive creation
* would be skipped.
*
* The provided file collection is not supposed to be used or modified anywhere else in the task.
*
* @return Collection of files
*/
@InputFiles
@SkipWhenEmpty
private final FileCollection getFakeFiles() {
project.files('fake')
}
void applyConventions() {
ConventionMapping mapping = ((IConventionAware) this).getConventionMapping()
mapping.map('packageName', {
projectPackagingExtension?.getPackageName()?:getArchiveBaseName().getOrNull()?:'test'
})
mapping.map('version', {
sanitizeVersion(projectPackagingExtension?.getVersion()?:project.getVersion().toString())
})
mapping.map('release', {
projectPackagingExtension?.getRelease()?:''
})
mapping.map('epoch', {
projectPackagingExtension?.getEpoch()?:0
})
mapping.map('signingKeyId', {
projectPackagingExtension?.getSigningKeyId()
})
mapping.map('signingKeyPassphrase', {
projectPackagingExtension?.getSigningKeyPassphrase()
})
mapping.map('signingKeyRing', {
projectPackagingExtension?.getSigningKeyRing()
})
mapping.map('signingKeyHashAlgo', {
projectPackagingExtension?.getSigningKeyHashAlgo()
})
mapping.map('user', {
projectPackagingExtension?.getUser()?:getPackager()
})
mapping.map('maintainer', {
projectPackagingExtension?.getMaintainer()?:getPackager()
})
mapping.map('uploaders', {
projectPackagingExtension?.getUploaders()?:getPackager()
})
mapping.map('permissionGroup', {
projectPackagingExtension?.getPermissionGroup()?:''
})
mapping.map('packageGroup', {
projectPackagingExtension?.getPackageGroup()
})
mapping.map('buildHost', {
projectPackagingExtension?.getBuildHost()?: getLocalHostName()
})
mapping.map('summary', {
projectPackagingExtension?.getSummary()?:getPackageName()
})
mapping.map('packageDescription', {
String packageDescription = projectPackagingExtension?.getPackageDescription()?:project.getDescription()
packageDescription ?: ''
})
mapping.map('license', {
projectPackagingExtension?.getLicense()?:''
})
mapping.map('packager', {
projectPackagingExtension?.getPackager()?:System.getProperty('user.name', '')
})
mapping.map('distribution', {
projectPackagingExtension?.getDistribution()?:''
})
mapping.map('vendor', {
projectPackagingExtension?.getVendor()?:''
})
mapping.map('url', {
projectPackagingExtension?.getUrl()?:''
})
mapping.map('sourcePackage', {
projectPackagingExtension?.getSourcePackage()?:''
})
mapping.map('createDirectoryEntry', {
projectPackagingExtension?.getCreateDirectoryEntry()?:false
})
mapping.map('priority', {
projectPackagingExtension?.getPriority()?:'optional'
})
mapping.map('preInstall', {
projectPackagingExtension?.getPreInstall()
})
mapping.map('postInstall', {
projectPackagingExtension?.getPostInstall()
})
mapping.map('preUninstall', {
projectPackagingExtension?.getPreUninstall()
})
mapping.map('postUninstall', {
projectPackagingExtension?.getPostUninstall()
})
mapping.map('fileType', {
projectPackagingExtension?.getFileType()
})
mapping.map('addParentDirs', {
projectPackagingExtension?.getAddParentDirs()?:true
})
mapping.map('arch', {
projectPackagingExtension?.arch?:Architecture.NOARCH
})
mapping.map('os', {
projectPackagingExtension?.os?:Os.UNKNOWN
})
mapping.map('type', {
projectPackagingExtension?.type?:PackageType.BINARY
})
mapping.map('prefixes', {
projectPackagingExtension?.getPrefixes()?:[]
})
mapping.map('archiveName', {
constructArchiveFile()
})
mapping.map('archivePath', {
determineArchivePath()
})
mapping.map('archiveFile', {
determineArchiveFile()
})
}
void prefixes(String... addPrefixes) {
systemPackagingExtension.prefixes.addAll(addPrefixes)
}
List<String> getPrefixes() {
systemPackagingExtension.prefixes
}
void setChangeLogFile(Path changeLogFile) {
this.changeLogFile = changeLogFile
}
Path getChangeLogFile() {
changeLogFile
}
Provider<RegularFile> determineArchiveFile() {
Property<RegularFile> regularFile = objectFactory.fileProperty()
regularFile.set(new DestinationFile(new File(getDestinationDirectory().get().asFile.path, constructArchiveFile())))
regularFile
}
File determineArchivePath() {
determineArchiveFile().get().asFile
}
String constructArchiveFile() {
String name = GUtil.elvis(getPackageName(), "")
name += maybe(name, '-', getVersion())
name += maybe(name, '-', getRelease())
name += maybe(name, '.', getArch().name().toLowerCase())
String extension = archiveExtension.getOrNull()
name += GUtil.isTrue(extension) ? "." + extension : ""
name
}
static String sanitizeVersion(String version) {
version.replaceAll(/\+.*/, '').replaceAll(/-/, '~')
}
static String getLocalHostName() {
try {
return InetAddress.localHost.hostName
} catch (UnknownHostException ignore) {
return "unknown"
}
}
static String maybe(@Nullable String prefix, String delimiter, @Nullable String value) {
if (GUtil.isTrue(value)) {
if (GUtil.isTrue(prefix)) {
return delimiter.concat(value)
} else {
return value
}
}
""
}
static class DestinationFile implements RegularFile {
private final File file
DestinationFile(File file) {
this.file = file
}
String toString() {
return this.file.toString()
}
@Override
File getAsFile() {
return this.file
}
}
}

View file

@ -1,318 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.internal.file.CopyActionProcessingStreamAction
import org.gradle.api.internal.file.copy.CopyAction
import org.gradle.api.internal.file.copy.CopyActionProcessingStream
import org.gradle.api.internal.file.copy.CopySpecInternal
import org.gradle.api.internal.file.copy.CopySpecResolver
import org.gradle.api.internal.file.copy.DefaultCopySpec
import org.gradle.api.internal.file.copy.DefaultFileCopyDetails
import org.gradle.api.internal.file.copy.FileCopyDetailsInternal
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
import org.gradle.api.tasks.WorkResult
import org.gradle.api.tasks.WorkResults
import org.gradle.internal.UncheckedException
import org.xbib.gradle.plugin.rpm.validation.RpmTaskPropertiesValidator
import org.xbib.rpm.RpmBuilder
import org.xbib.rpm.header.HeaderTag
import org.xbib.rpm.payload.Directive
import java.lang.reflect.Field
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
/**
*
*/
class RpmCopyAction implements CopyAction {
private static final Logger logger = Logging.getLogger(RpmCopyAction.class)
Rpm task
Path tempDir
RpmBuilder builder
boolean includeStandardDefines = true
private final RpmTaskPropertiesValidator rpmTaskPropertiesValidator = new RpmTaskPropertiesValidator()
private RpmFileVisitorStrategy rpmFileVisitorStrategy
RpmCopyAction(Rpm task) {
this.task = task
rpmTaskPropertiesValidator.validate(task)
}
WorkResult execute(CopyActionProcessingStream stream) {
try {
startVisit(this)
stream.process(new StreamAction())
endVisit()
} catch (Exception e) {
UncheckedException.throwAsUncheckedException(e)
}
WorkResults.didWork(true)
}
private class StreamAction implements CopyActionProcessingStreamAction {
@Override
void processFile(FileCopyDetailsInternal details) {
def ourSpec = extractSpec(details)
if (details.isDirectory()) {
visitDir(details, ourSpec)
} else {
visitFile(details, ourSpec)
}
}
}
void endVisit() {
for (Link link : task.getAllLinks()) {
logger.debug "adding link {} -> {}", link.path, link.target
addLink link
}
for (Dependency dep : task.getAllDependencies()) {
logger.debug "adding dependency on {} {}", dep.packageName, dep.version
addDependency dep
}
for (Dependency obsolete: task.getAllObsoletes()) {
logger.debug "adding obsoletes on {} {}", obsolete.packageName, obsolete.version
addObsolete obsolete
}
for (Dependency conflict : task.getAllConflicts()) {
logger.debug "adding conflicts on {} {}", conflict.packageName, conflict.version
addConflict conflict
}
for (Dependency provides : task.getAllProvides()) {
logger.debug "adding provides on {} {}", provides.packageName, provides.version
addProvides(provides)
}
task.directories.each { directory ->
logger.debug "adding directory {}", directory.path
addDirectory(directory)
}
end()
}
static String concat(Collection<Object> scripts) {
String shebang
StringBuilder result = new StringBuilder()
scripts.each { script ->
script?.eachLine { line ->
if (line.matches('^#!.*$')) {
if (!shebang) {
shebang = line
} else if (line != shebang) {
throw new IllegalArgumentException("mismatching #! script lines")
}
} else {
result.append line
result.append "\n"
}
}
}
if (shebang) {
result.insert(0, shebang + "\n")
}
result.toString()
}
static CopySpecInternal extractSpec(FileCopyDetailsInternal fileDetails) {
if (fileDetails instanceof DefaultFileCopyDetails) {
def startingClass = fileDetails.getClass()
while( startingClass != null && startingClass != DefaultFileCopyDetails) {
startingClass = startingClass.superclass
}
Field specField = startingClass.getDeclaredField('specResolver')
specField.setAccessible(true)
CopySpecResolver specResolver = specField.get(fileDetails)
Field field = DefaultCopySpec.DefaultCopySpecResolver.class.getDeclaredField('this$0')
field.setAccessible(true)
CopySpecInternal spec = field.get(specResolver)
return spec
} else {
return null
}
}
Path extractPath(FileCopyDetailsInternal fileDetails) {
Path path
try {
path = fileDetails.getFile().toPath()
} catch (UnsupportedOperationException uoe) {
path = tempDir.resolve(fileDetails.path)
fileDetails.copyTo(path.toFile())
}
path
}
void startVisit(CopyAction action) {
tempDir = task.getTemporaryDir().toPath()
if (!task.getVersion()) {
throw new IllegalArgumentException('RPM requires a version string')
}
if ([task.preInstall, task.postInstall, task.preUninstall, task.postUninstall].any()) {
logger.warn('at least one of (preInstall|postInstall|preUninstall|postUninstall) is defined ' +
'and will be ignored for RPM builds')
}
builder = new RpmBuilder()
builder.setPackage task.packageName, task.version, task.release, task.epoch
builder.setType task.type
builder.setPlatform task.arch, task.os
builder.setGroup task.packageGroup
builder.setBuildHost task.buildHost
builder.setSummary task.summary
builder.setDescription task.packageDescription ?: ''
builder.setLicense task.license
builder.setPackager task.packager
builder.setDistribution task.distribution
builder.setVendor task.vendor
builder.setUrl task.url
if (task.allPrefixes) {
builder.setPrefixes(task.allPrefixes as String[])
}
if (task.getSigningKeyId() && task.getSigningKeyPassphrase() && task.getSigningKeyRing()) {
builder.setPrivateKeyId task.getSigningKeyId()
builder.setPrivateKeyPassphrase task.getSigningKeyPassphrase()
builder.setPrivateKeyRing task.getSigningKeyRing()
builder.setPrivateKeyHashAlgo task.getSigningKeyHashAlgo()
}
String sourcePackage = task.sourcePackage
if (!sourcePackage) {
sourcePackage = builder.defaultSourcePackage
}
builder.addHeaderEntry HeaderTag.SOURCERPM, sourcePackage
builder.setPreInstall task.getPreInstall()
builder.setPostInstall task.getPostInstall()
builder.setPreUninstall task.getPreUninstall()
builder.setPostUninstall task.getPostUninstall()
builder.setPreTrans task.getPreTrans()
builder.setPostTrans task.getPostTrans()
builder.setPreInstallValue(scriptWithUtils(task.allCommonCommands, task.allPreInstallCommands))
builder.setPostInstallValue(scriptWithUtils(task.allCommonCommands, task.allPostInstallCommands))
builder.setPreUninstallValue(scriptWithUtils(task.allCommonCommands, task.allPreUninstallCommands))
builder.setPostUninstallValue(scriptWithUtils(task.allCommonCommands, task.allPostUninstallCommands))
builder.setPreTransValue(scriptWithUtils(task.allCommonCommands, task.allPreTransCommands))
builder.setPostTransValue(scriptWithUtils(task.allCommonCommands, task.allPostTransCommands))
if (((Rpm) task).changeLogFile != null) {
builder.addChangelog(((Rpm) task).changeLogFile)
}
rpmFileVisitorStrategy = new RpmFileVisitorStrategy(builder)
}
void visitFile(FileCopyDetailsInternal fileDetails, def specToLookAt) {
logger.debug "adding file {}", fileDetails.relativePath.pathString
def inputFile = extractPath(fileDetails)
EnumSet<Directive> fileType = lookup(specToLookAt, 'fileType')
String user = lookup(specToLookAt, 'user') ?: task.user
String group = lookup(specToLookAt, 'permissionGroup') ?: task.permissionGroup
int fileMode = lookup(specToLookAt, 'fileMode') ?: fileDetails.mode
def specAddParentsDir = lookup(specToLookAt, 'addParentDirs')
boolean addParentsDir = specAddParentsDir!=null ? specAddParentsDir : task.addParentDirs
rpmFileVisitorStrategy.addFile(fileDetails, inputFile, fileMode, -1, fileType, user, group, addParentsDir)
}
void visitDir(FileCopyDetailsInternal dirDetails, def specToLookAt) {
if (specToLookAt == null) {
logger.info("Got an empty spec from ${dirDetails.class.name} for ${dirDetails.path}/${dirDetails.name}")
return
}
// Have to take booleans specially, since they would fail an elvis operator if set to false
def specCreateDirectoryEntry = lookup(specToLookAt, 'createDirectoryEntry')
boolean createDirectoryEntry = specCreateDirectoryEntry!=null ? specCreateDirectoryEntry : task.createDirectoryEntry
def specAddParentsDir = lookup(specToLookAt, 'addParentDirs')
boolean addParentsDir = specAddParentsDir != null ? specAddParentsDir : task.addParentDirs
if (createDirectoryEntry) {
logger.debug 'adding directory {}', dirDetails.relativePath.pathString
int dirMode = lookup(specToLookAt, 'dirMode') ?: dirDetails.mode
List<String> directiveList = (lookup(specToLookAt, 'fileType') ?: task.fileType) as List<String>
EnumSet<Directive> directive = makeDirective(directiveList)
String user = lookup(specToLookAt, 'user') ?: task.user
String group = lookup(specToLookAt, 'permissionGroup') ?: task.permissionGroup
rpmFileVisitorStrategy.addDirectory(dirDetails, dirMode, directive, user, group, addParentsDir)
}
}
protected void addLink(Link link) {
builder.addLink link.path, link.target, link.permissions
}
protected void addDependency(Dependency dep) {
builder.addDependency(dep.packageName, dep.flag, dep.version)
}
protected void addConflict(Dependency dep) {
builder.addConflicts(dep.packageName, dep.flag, dep.version)
}
protected void addObsolete(Dependency dep) {
builder.addObsoletes(dep.packageName, dep.flag, dep.version)
}
protected void addProvides(Dependency dep) {
builder.addProvides(dep.packageName, dep.version, dep.flag)
}
protected void addDirectory(Directory directory) {
def user = directory.user ? directory.user : task.user
def permissionGroup = directory.permissionGroup ? directory.permissionGroup : task.permissionGroup
builder.addDirectory(directory.path, directory.permissions, null, user, permissionGroup, directory.addParents)
}
protected void end() {
Path path = task.archiveFile.get().asFile.toPath()
Files.createDirectories(path.parent)
Files.newByteChannel(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING).withCloseable { ch ->
builder.build(ch)
}
logger.info 'created RPM archive {}', path
}
String standardScriptDefines() {
includeStandardDefines ?
String.format(" RPM_ARCH=%s \n RPM_OS=%s \n RPM_PACKAGE_NAME=%s \n RPM_PACKAGE_VERSION=%s \n RPM_PACKAGE_RELEASE=%s \n\n",
task.arch?.toString()?.toLowerCase()?:'',
task.os?.toString()?.toLowerCase()?: '',
task.getPackageName(),
task.getVersion(),
task.getRelease()) : null
}
String scriptWithUtils(List<Object> utils, List<Object> scripts) {
def list = []
def stdDefines = standardScriptDefines()
if (stdDefines) {
list.add(stdDefines)
}
list.addAll(utils)
list.addAll(scripts)
concat(list)
}
static <T> T lookup(def specToLookAt, String propertyName) {
if (specToLookAt?.metaClass?.hasProperty(specToLookAt, propertyName) != null) {
def prop = specToLookAt.metaClass.getProperty(specToLookAt, propertyName)
if (prop instanceof MetaBeanProperty) {
return prop?.getProperty(specToLookAt) as T
} else {
return prop as T
}
} else {
return null
}
}
static EnumSet<Directive> makeDirective(List<String> strings) {
EnumSet<Directive> set = EnumSet.of(Directive.NONE)
for (String string : strings) {
set.add(Directive.valueOf(string))
}
set
}
}

View file

@ -1,63 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.xbib.rpm.RpmBuilder
import org.xbib.rpm.payload.Directive
import org.gradle.api.file.FileCopyDetails
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class RpmFileVisitorStrategy {
protected final RpmBuilder builder
RpmFileVisitorStrategy(RpmBuilder builder) {
this.builder = builder
}
void addFile(FileCopyDetails details, Path source, int mode, int dirmode, EnumSet<Directive> directive, String uname, String gname, boolean addParents) {
try {
if (!Files.isSymbolicLink(Paths.get(details.file.parentFile.path))) {
addFileToBuilder(details, source, mode, dirmode, directive, uname, gname, addParents)
}
}
catch (UnsupportedOperationException e) {
// For file details that have filters, accessing the file throws this exception
addFileToBuilder(details, source, mode, dirmode, directive, uname, gname, addParents)
}
}
void addDirectory(FileCopyDetails details, int permissions, EnumSet<Directive> directive, String uname,
String gname, boolean addParents) {
try {
if (Files.isSymbolicLink(Paths.get(details.file.path))) {
addLinkToBuilder(details)
}
else {
addDirectoryToBuilder(details, permissions, directive, uname, gname, addParents)
}
} catch (UnsupportedOperationException e) {
// For file details that have filters, accessing the directory throws this exception
addDirectoryToBuilder(details, permissions, directive, uname, gname, addParents)
}
}
protected void addFileToBuilder(FileCopyDetails details, Path source, int mode, int dirmode, EnumSet<Directive> directive, String uname, String gname, boolean addParents) {
builder.addFile(getRootPath(details), source, mode, dirmode, directive, uname, gname, addParents)
}
protected void addDirectoryToBuilder(FileCopyDetails details, int permissions, EnumSet<Directive> directive, String uname, String gname, boolean addParents) {
builder.addDirectory(getRootPath(details), permissions, directive, uname, gname, addParents)
}
private void addLinkToBuilder(FileCopyDetails details) {
Path path = Paths.get(details.file.path)
Path target = Files.readSymbolicLink(path)
builder.addLink(getRootPath(details), target.toFile().path)
}
private static String getRootPath(FileCopyDetails details) {
"/${details.path}".toString()
}
}

View file

@ -1,65 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.plugins.BasePlugin
import org.xbib.rpm.RpmBuilder
import org.xbib.rpm.lead.Architecture
import org.xbib.rpm.format.Flags
import org.xbib.rpm.lead.Os
import org.xbib.rpm.lead.PackageType
import org.xbib.rpm.payload.Directive
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.lang.reflect.Field
import java.lang.reflect.Modifier
/**
*
*/
class RpmPlugin implements Plugin<Project> {
void apply(Project project) {
project.plugins.apply(BasePlugin)
project.ext.Rpm = Rpm.class
RpmBuilder.metaClass.getDefaultSourcePackage() {
format.getLead().getName() + ".src.rpm"
}
project.tasks.withType(Rpm) { Rpm task ->
applyAliases(task)
task.applyConventions()
}
}
def static applyAliases(def dynamicObjectAware) {
aliasEnumValues(Architecture.values(), dynamicObjectAware)
aliasEnumValues(Os.values(), dynamicObjectAware)
aliasEnumValues(PackageType.values(), dynamicObjectAware)
aliasStaticInstances(Directive.class, dynamicObjectAware)
aliasStaticInstances(Flags.class, int.class, dynamicObjectAware)
}
private static <T extends Enum<T>> void aliasEnumValues(T[] values, dynAware) {
for (T value : values) {
dynAware.metaClass."${value.name()}" = value
}
}
private static <T> void aliasStaticInstances(Class<T> forClass, dynAware) {
aliasStaticInstances(forClass, forClass, dynAware)
}
private static <T, U> void aliasStaticInstances(Class<T> forClass, Class<U> ofClass, dynAware) {
for (Field field : forClass.fields) {
if (field.type == ofClass && hasModifier(field, Modifier.STATIC)) {
dynAware.metaClass."${field.name}" = field.get(null)
}
}
}
private static boolean hasModifier(Field field, int modifier) {
(field.modifiers & modifier) == modifier
}
}

View file

@ -1,494 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.xbib.rpm.lead.Architecture
import org.xbib.rpm.lead.Os
import org.xbib.rpm.lead.PackageType
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* Extension that can be used to configure RPM.
*/
class SystemPackagingExtension {
@Input @Optional
String packageName
@Input @Optional
String release
@Input @Optional
String version
@Input @Optional
Integer epoch
@Input @Optional
String signingKeyPassphrase
@Input @Optional
String signingKeyRing
@Input @Optional
String signingKeyId
@Input @Optional
String signingKeyHashAlgo
@Input @Optional
String user
@Input @Optional
String permissionGroup
@Input @Optional
String packageGroup
@Input @Optional
String buildHost
@Input @Optional
String summary
@Input @Optional
String packageDescription
@Input @Optional
String license
@Input @Optional
String packager
@Input @Optional
String distribution
@Input @Optional
String vendor
@Input @Optional
String url
@Input @Optional
String sourcePackage
@Input @Optional
List<String> fileType
@Input @Optional
Boolean createDirectoryEntry
@Input @Optional
Boolean addParentDirs
//String archStr
@Input @Optional
Architecture arch
//void setArch(Object arch) {
// archStr = (arch instanceof Architecture) ? arch.name() : arch.toString()
//}
@Input @Optional
Os os
@Input @Optional
PackageType type
List<String> prefixes = new ArrayList<String>()
def prefix(String prefixStr) {
prefixes << prefixStr
return this
}
@Input @Optional
Integer uid
@Input @Optional
Integer gid
@Input @Optional
String maintainer
@Input @Optional
String uploaders
@Input @Optional
String priority
@Input @Optional
final List<Object> supplementaryControlFiles = []
def supplementaryControl(Object file) {
supplementaryControlFiles << file
return this
}
@Input @Optional
String preInstall
@Input @Optional
String postInstall
@Input @Optional
String preUninstall
@Input @Optional
String postUninstall
@Input @Optional
String preTrans
@Input @Optional
String postTrans
final List<Object> configurationPaths = []
final List<Object> preInstallCommands = []
final List<Object> postInstallCommands = []
final List<Object> preUninstallCommands = []
final List<Object> postUninstallCommands = []
final List<Object> preTransCommands = []
final List<Object> postTransCommands = []
final List<Object> commonCommands = []
def setInstallUtils(Path script) {
installUtils(script)
}
def installUtils(String script) {
commonCommands << script
return this
}
def installUtils(Path script) {
commonCommands << script
return this
}
def setConfigurationPath(String script) {
configurationPath(script)
}
def configurationPath(String path) {
configurationPaths << path
this
}
def setPreInstall(String script) {
preInstall(script)
}
def setPreInstall(Path script) {
preInstall(script)
}
def preInstall(String script) {
preInstall(Paths.get(script))
}
def preInstall(Path script) {
if (Files.exists(script)) {
preInstallValue(script.text)
}
this
}
def preInstallValue(String content) {
preInstallCommands << content
this
}
def setPostInstall(String script) {
postInstall(script)
}
def setPostInstall(Path script) {
postInstall(script)
}
def postInstall(String script) {
postInstall(Paths.get(script))
}
def postInstall(Path script) {
if (Files.exists(script)) {
postInstallValue(script.text)
}
this
}
def postInstallValue(String content) {
postInstallCommands << content
this
}
def setPreUninstall(String script) {
preUninstall(script)
}
def setPreUninstall(Path script) {
preUninstall(script)
}
def preUninstall(String script) {
preUninstall(Paths.get(script))
}
def preUninstall(Path script) {
if (Files.exists(script)) {
preUninstallValue(script.text)
}
this
}
def preUninstallValue(String script) {
preUninstallCommands << script
this
}
def setPostUninstall(String script) {
postUninstall(script)
}
def setPostUninstall(Path script) {
postUninstall(script)
}
def postUninstall(String script) {
postUninstall(Paths.get(script))
}
def postUninstall(Path script) {
if (Files.exists(script)) {
postUninstallValue(script.text)
}
this
}
def postUninstallValue(String content) {
postUninstallCommands << content
this
}
def setPreTrans(String script) {
preTrans(script)
}
def setPreTrans(Path script) {
preTrans(script)
}
def preTrans(String script) {
preTrans(Paths.get(script))
}
def preTrans(Path script) {
if (Files.exists(script)) {
preTransValue(script.text)
}
this
}
def preTransValue(String script) {
preTransCommands << script
this
}
def setPostTrans(String script) {
postTrans(script)
}
def setPostTrans(Path script) {
postTrans(script)
}
def postTrans(String script) {
postTrans(Paths.get(script))
}
def postTrans(Path script) {
if (Files.exists(script)) {
postTransValue(script.text)
}
return this
}
def postTransValue(String script) {
postTransCommands << script
return this
}
List<Link> links = []
Link link(String path, String target) {
link(path, target, -1)
}
Link link(String path, String target, int permissions) {
Link link = new Link()
link.path = path
link.target = target
link.permissions = permissions
links.add(link)
link
}
List<Dependency> dependencies = []
List<Dependency> obsoletes = []
List<Dependency> conflicts = []
List<Dependency> recommends = []
List<Dependency> suggests = []
List<Dependency> enhances = []
List<Dependency> preDepends = []
List<Dependency> breaks = []
List<Dependency> replaces = []
List<Dependency> provides = []
Dependency requires(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
dependencies.add(dep)
dep
}
Dependency requires(String packageName, String version){
requires(packageName, version, 0)
}
Dependency requires(String packageName) {
requires(packageName, '', 0)
}
Dependency obsoletes(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
obsoletes.add(dep)
dep
}
Dependency obsoletes(String packageName) {
obsoletes(packageName, '', 0)
}
Dependency conflicts(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
conflicts.add(dep)
dep
}
Dependency conflicts(String packageName) {
conflicts(packageName, '', 0)
}
Dependency recommends(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
recommends.add(dep)
dep
}
Dependency recommends(String packageName) {
recommends(packageName, '', 0)
}
Dependency suggests(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
suggests.add(dep)
dep
}
Dependency suggests(String packageName) {
suggests(packageName, '', 0)
}
Dependency enhances(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
enhances.add(dep)
dep
}
Dependency enhances(String packageName) {
enhances(packageName, '', 0)
}
Dependency preDepends(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
preDepends.add(dep)
dep
}
Dependency preDepends(String packageName) {
preDepends(packageName, '', 0)
}
Dependency breaks(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
breaks.add(dep)
dep
}
Dependency breaks(String packageName) {
breaks(packageName, '', 0)
}
Dependency replaces(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
replaces.add(dep)
dep
}
Dependency replaces(String packageName) {
replaces(packageName, '', 0)
}
Dependency provides(String packageName, String version, int flag) {
def dep = new Dependency(packageName, version, flag)
provides.add(dep)
dep
}
Dependency provides(String packageName) {
provides(packageName, '', 0)
}
List<Directory> directories = []
Directory directory(String path) {
Directory directory = directory(path, -1)
directories << directory
directory
}
Directory directory(String path, boolean addParents) {
Directory directory = new Directory(path: path, addParents: addParents)
directories << directory
directory
}
Directory directory(String path, int permissions) {
Directory directory = new Directory(path: path, permissions: permissions)
directories << directory
directory
}
Directory directory(String path, int permissions, boolean addParents) {
Directory directory = new Directory(path: path, permissions: permissions, addParents: addParents)
directories << directory
directory
}
Directory directory(String path, int permissions, String user, String permissionGroup) {
Directory directory = new Directory(path: path, permissions: permissions, user: user,
permissionGroup: permissionGroup)
directories << directory
directory
}
Directory directory(String path, int permissions, String user, String permissionGroup, boolean addParents) {
Directory directory = new Directory(path: path, permissions: permissions, user: user,
permissionGroup: permissionGroup, addParents: addParents)
directories << directory
directory
}
private static IllegalStateException multipleFilesDefined(String fileName) {
new IllegalStateException("Cannot specify more than one $fileName File")
}
private static IllegalStateException conflictingDefinitions(String type) {
new IllegalStateException("Cannot specify $type File and $type Commands")
}
}

View file

@ -1,18 +0,0 @@
package org.xbib.gradle.plugin.rpm.validation
class RpmPackageNameAttributeValidator implements SystemPackagingAttributeValidator {
@Override
boolean validate(String packageName) {
matchesExpectedCharacters(packageName)
}
private static boolean matchesExpectedCharacters(String packageName) {
packageName ==~ /[a-zA-Z0-9-._+]+/
}
@Override
String getErrorMessage(String attribute) {
"Invalid package name '$attribute' - a valid package name must only contain [a-zA-Z0-9-._+]"
}
}

View file

@ -1,16 +0,0 @@
package org.xbib.gradle.plugin.rpm.validation
import org.xbib.gradle.plugin.rpm.Rpm
import org.gradle.api.InvalidUserDataException
class RpmTaskPropertiesValidator implements SystemPackagingTaskPropertiesValidator<Rpm> {
private final SystemPackagingAttributeValidator packageNameValidator = new RpmPackageNameAttributeValidator()
@Override
void validate(Rpm task) {
if (!packageNameValidator.validate(task.getPackageName())) {
throw new InvalidUserDataException(packageNameValidator.getErrorMessage(task.getPackageName()))
}
}
}

View file

@ -1,8 +0,0 @@
package org.xbib.gradle.plugin.rpm.validation
interface SystemPackagingAttributeValidator {
boolean validate(String attribute)
String getErrorMessage(String attribute)
}

View file

@ -1,8 +0,0 @@
package org.xbib.gradle.plugin.rpm.validation
import org.gradle.api.Task
interface SystemPackagingTaskPropertiesValidator<T extends Task> {
void validate(T task)
}

View file

@ -1 +0,0 @@
implementation-class=org.xbib.gradle.plugin.rpm.RpmPlugin

View file

@ -0,0 +1,336 @@
package org.xbib.gradle.plugin
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.xbib.rpm.RpmReader
import org.xbib.rpm.RpmReaderResult
import org.xbib.rpm.format.Format
import org.xbib.rpm.header.IntegerList
import org.xbib.rpm.header.StringList
import java.nio.charset.StandardCharsets
import java.nio.file.Paths
import static org.hamcrest.CoreMatchers.is
import static org.hamcrest.MatcherAssert.assertThat
import static org.junit.jupiter.api.Assertions.assertEquals
import static org.junit.jupiter.api.Assertions.assertNotNull
import static org.xbib.rpm.format.Flags.EQUAL
import static org.xbib.rpm.format.Flags.GREATER
import static org.xbib.rpm.format.Flags.LESS
import static org.xbib.rpm.header.HeaderTag.CONFLICTFLAGS
import static org.xbib.rpm.header.HeaderTag.CONFLICTNAME
import static org.xbib.rpm.header.HeaderTag.CONFLICTVERSION
import static org.xbib.rpm.header.HeaderTag.DISTRIBUTION
import static org.xbib.rpm.header.HeaderTag.FILEGROUPNAME
import static org.xbib.rpm.header.HeaderTag.FILEMODES
import static org.xbib.rpm.header.HeaderTag.FILEUSERNAME
import static org.xbib.rpm.header.HeaderTag.OBSOLETEFLAGS
import static org.xbib.rpm.header.HeaderTag.OBSOLETENAME
import static org.xbib.rpm.header.HeaderTag.OBSOLETEVERSION
import static org.xbib.rpm.header.HeaderTag.PREFIXES
import static org.xbib.rpm.lead.Architecture.I386
import static org.xbib.rpm.lead.Os.LINUX
import static org.xbib.rpm.lead.PackageType.BINARY
import static org.xbib.rpm.payload.CpioHeader.DIR
import static org.xbib.rpm.payload.CpioHeader.FILE
class RpmFullTest {
File projectDir
@BeforeEach
void setup() {
projectDir = new File("build/testrpm")
projectDir.mkdirs()
}
@Test
void testCopySpec() {
File bananaFile = new File(projectDir, 'test/banana')
bananaFile.parentFile.mkdirs()
bananaFile.withWriter {
out -> out.write('banana')
}
File srcDir = new File(projectDir, 'src')
srcDir.mkdirs()
String fruit = 'apple'
File appleFile = new File(srcDir, fruit)
appleFile.withWriter {
out -> out.write(fruit)
}
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'test'
packageVersion = '1.0.0'
packageRelease = '1'
addParentDirs = true
from(bananaFile.absoluteFile.parent) {
into '/usr/share/myproduct/etc'
}
from(appleFile.absoluteFile.parent) {
into '/usr/local/myproduct/bin'
}
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertEquals([
'./usr/local/myproduct',
'./usr/local/myproduct/bin',
'./usr/local/myproduct/bin/apple',
'./usr/share/myproduct',
'./usr/share/myproduct/etc',
'./usr/share/myproduct/etc/banana'], result.files*.name)
assertEquals([DIR, DIR, FILE, DIR, DIR, FILE], result.files*.type)
}
@Test
void testExplicitDirectory() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'test'
packageVersion = '1.0.0'
packageRelease = '1'
directory '/lib'
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertNotNull(result.files.find { it.name == './lib' })
}
@Test
void testFilter() {
File appleFile = new File(projectDir, 'src/apple')
appleFile.mkdirs()
appleFile.withWriter {
out -> out.write('{{BASE}}/apple')
}
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'test'
packageVersion = '1.0.0'
packageRelease = '1'
from(appleFile.absoluteFile.parent) {
into '/usr/local/myproduct/bin'
filter({ line ->
return line.replaceAll(/\{\{BASE\}\}/, '/usr/local/myproduct')
})
}
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
def scannerApple = result.files.find { it.name == './usr/local/myproduct/bin/apple' }
assertEquals(StandardCharsets.UTF_8.decode(scannerApple.contents).toString(), '/usr/local/myproduct/apple')
}
@Test
void testCustomCopySpec() {
File srcDir = new File(projectDir, 'src')
srcDir.mkdirs()
String fruit = 'apple'
File appleFile = new File(srcDir, fruit)
appleFile.withWriter {
out -> out.write(fruit)
}
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
def customCopySpec = project.copySpec {
into('lib') {
from 'src'
}
}
project.task([type: Rpm], 'buildRpm', {
packageName = 'copyspec'
packageVersion = '1.0.0'
packageRelease = '1'
with customCopySpec
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertThat(result.files*.name, is(['./lib/apple']))
}
@Test
void testFileMode() {
File srcDir1 = new File(projectDir, 'src1')
srcDir1.mkdirs()
new File(srcDir1, 'apple').withWriter { out -> out.write('apple') }
File srcDir2 = new File(projectDir, 'src2')
srcDir2.mkdirs()
new File(srcDir2, 'banana').withWriter { out -> out.write('banana') }
File srcDir3 = new File(projectDir, 'src3')
srcDir3.mkdirs()
new File(srcDir3, 'cherry').withWriter { out -> out.write('cherry') }
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'fileMode'
packageVersion = '2.0'
packageRelease = '2'
into '/tiny'
fileMode 0555
from(srcDir1.absoluteFile) {
// should be default group
}
from(srcDir2.absoluteFile) {
fileMode 0666
}
from(srcDir3.absoluteFile) {
fileMode 0555
}
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertEquals([FILE, FILE, FILE], result.files*.type)
assertEquals(['./tiny/apple', './tiny/banana', './tiny/cherry'], result.files*.name)
assertThat([(short)0100555, (short)0100666, (short)0100555], is(result.format.header.getEntry(FILEMODES).values))
}
@Test
void testUserGroup() {
File srcDir = new File(projectDir, 'src')
srcDir.mkdirs()
new File(srcDir, 'apple').withWriter { out -> out.write('apple') }
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'userTest'
packageVersion = '2.0'
packageRelease = '2'
user = 'joerg'
group = 'users'
from srcDir.absoluteFile
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertEquals([FILE], result.files*.type)
StringList users = result.format.header.getEntry(FILEUSERNAME)?.values as StringList
assertThat(['joerg'], is(users))
StringList groups = result.format.header.getEntry(FILEGROUPNAME)?.values as StringList
assertThat(['users'], is(groups))
}
@Test
void testPrefix() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'prefixes'
packageVersion = '1.0.0'
packageRelease = '1'
prefixes = ['/opt']
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertThat(StringList.of('/opt') as StringList, is(result.format.header.getEntry(PREFIXES).values))
}
@Test
void testConflictsAndObsoletes() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
File srcDir = new File(projectDir, 'src')
srcDir.mkdirs()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'testing'
packageVersion = '1.2'
packageRelease = '3'
packageType = BINARY
arch = I386
os = LINUX
license = 'Free'
distribution = 'SuperSystem'
vendor = 'Super Associates, LLC'
url = 'http://www.example.com/'
obsoletes('blarg', '1.0', GREATER | EQUAL)
conflicts('blech')
conflicts('packageA', '1.0', LESS)
obsoletes('packageB', '2.2', GREATER)
obsoletes('packageC')
from(srcDir)
into '/opt/bleah'
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
def result = rpmReader.read(Paths.get(projectDir.toString(), 'build', 'distributions', 'testing-1.2-3.i386.rpm'))
Format format = result.format
StringList obsoletes = format.header.getEntry(OBSOLETENAME).values as StringList
StringList obsoleteVersions = format.header.getEntry(OBSOLETEVERSION).values as StringList
IntegerList obsoleteComparisons = format.header.getEntry(OBSOLETEFLAGS).values as IntegerList
StringList conflicts = format.header.getEntry(CONFLICTNAME).values as StringList
StringList conflictVersions = format.header.getEntry(CONFLICTVERSION).values as StringList
IntegerList conflictComparisons = format.header.getEntry(CONFLICTFLAGS).values as IntegerList
StringList distribution = format.header.getEntry(DISTRIBUTION).values as StringList
assertThat(StringList.of('SuperSystem') as StringList, is(distribution))
assertThat('blarg', is(obsoletes.get(0)))
assertThat(GREATER | EQUAL, is(obsoleteComparisons.get(0)))
assertThat('blech', is(conflicts.get(0)))
assertThat('', is(conflictVersions.get(0)))
assertThat(0, is(conflictComparisons.get(0)))
assertThat('packageA', is(conflicts.get(1)))
assertThat('1.0', is(conflictVersions.get(1)))
assertThat(LESS, is(conflictComparisons.get(1)))
assertThat('packageB', is(obsoletes.get(1)))
assertThat('2.2', is(obsoleteVersions.get(1)))
assertThat(GREATER, is(obsoleteComparisons.get(1)))
assertThat('packageC', is(obsoletes.get(2)))
}
@Test
void testFilesFromConfiguration() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.repositories {
mavenCentral()
}
project.configurations {
myconf
}
project.dependencies {
myconf "junit:junit:4.12"
}
project.task([type: Rpm], 'buildRpm', {
packageName = 'fromconfiguration'
packageVersion = '1.0.0'
packageRelease = '1'
into('/tmp') {
from project.configurations.myconf
}
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
assertThat(['./tmp/hamcrest-core-1.3.jar', './tmp/junit-4.12.jar'], is(result.files*.name))
}
}

View file

@ -0,0 +1,57 @@
package org.xbib.gradle.plugin
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import static org.junit.jupiter.api.Assertions.assertEquals
class RpmPluginIntegrationTest {
private File projectDir
private File settingsFile
private File buildFile
@BeforeEach
void setup(@TempDir File testProjectDir) throws IOException {
this.projectDir = testProjectDir
this.settingsFile = new File(testProjectDir, "settings.gradle")
this.buildFile = new File(testProjectDir, "build.gradle")
}
@Test
void testPlugin() {
String settingsFileContent = '''
rootProject.name = 'rpm-test'
'''
settingsFile.write(settingsFileContent)
String buildFileContent = '''
plugins {
id 'org.xbib.gradle.plugin.rpm'
}
rpm {
enabled = true
}
task myRpm(type: Rpm) {
packageName = 'rpmIsUpToDate'
arch = org.xbib.rpm.lead.Architecture.NOARCH
os = org.xbib.rpm.lead.Os.LINUX
}
'''
buildFile.write(buildFileContent)
BuildResult result = GradleRunner.create()
.withProjectDir(projectDir)
.withArguments(":build", "--info")
.withPluginClasspath()
.forwardOutput()
.build()
assertEquals(TaskOutcome.UP_TO_DATE, result.task(":build").getOutcome())
}
}

View file

@ -0,0 +1,156 @@
package org.xbib.gradle.plugin
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.xbib.rpm.RpmReader
import org.xbib.rpm.changelog.ChangelogParser
import org.xbib.rpm.format.Format
import org.xbib.rpm.header.EntryType
import org.xbib.rpm.header.IntegerList
import org.xbib.rpm.header.StringList
import org.xbib.rpm.header.entry.SpecEntry
import java.time.LocalDateTime
import java.time.ZoneOffset
import static org.hamcrest.MatcherAssert.assertThat
import static org.hamcrest.CoreMatchers.*
import static org.junit.jupiter.api.Assertions.assertEquals
import static org.junit.jupiter.api.Assertions.assertNotNull
import static org.xbib.rpm.header.HeaderTag.POSTINSCRIPT
import static org.xbib.rpm.header.HeaderTag.POSTTRANSSCRIPT
import static org.xbib.rpm.header.HeaderTag.POSTUNSCRIPT
import static org.xbib.rpm.header.HeaderTag.PREINSCRIPT
import static org.xbib.rpm.header.HeaderTag.PRETRANSSCRIPT
import static org.xbib.rpm.header.HeaderTag.PREUNSCRIPT
import static org.xbib.rpm.header.HeaderTag.CHANGELOGNAME
import static org.xbib.rpm.header.HeaderTag.CHANGELOGTEXT
import static org.xbib.rpm.header.HeaderTag.CHANGELOGTIME
class RpmScriptTest {
File projectDir
@BeforeEach
void setup() {
projectDir = new File("build/testrpm")
projectDir.mkdirs()
}
@Test
void testInstallScripts() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'installscripts'
packageVersion = '1.0'
packageRelease = '1'
preInstall = "echo 'Hello Pre World'"
postInstall = "echo 'Hello Post World'"
preUninstall = "echo 'Hello PreUn World'"
postUninstall = "echo 'Hello PostUn World'"
preTrans = "echo 'Hello PreTrans World'"
postTrans = "echo 'Hello PostTrans World'"
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
def result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
Format format = result.format
assertThat(["echo 'Hello Pre World'"], is(format.header.getEntry(PREINSCRIPT)?.values))
assertThat(["echo 'Hello Post World'"], is(format.header.getEntry(POSTINSCRIPT)?.values))
assertThat(["echo 'Hello PreUn World'"], is(format.header.getEntry(PREUNSCRIPT)?.values))
assertThat(["echo 'Hello PostUn World'"], is(format.header.getEntry(POSTUNSCRIPT)?.values))
assertThat(["echo 'Hello PreTrans World'"], is(format.header.getEntry(PRETRANSSCRIPT)?.values))
assertThat(["echo 'Hello PostTrans World'"], is(format.header.getEntry(POSTTRANSSCRIPT)?.values))
}
@Test
void testInstallScriptFiles() {
String preinstall = getClass().getResource('preinstall.sh').text
File scriptDir = new File(projectDir, 'scripts')
scriptDir.mkdirs()
new File(scriptDir, 'preinstall.sh').withWriter { out -> out.write(preinstall) }
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'installscripts'
packageVersion = '1.0'
packageRelease = '1'
preInstallFile = project.file('scripts/preinstall.sh')
postInstall = "echo 'Hello Post World'"
preUninstall = "echo 'Hello PreUn World'"
postUninstall = "echo 'Hello PostUn World'"
preTrans = "echo 'Hello PreTrans World'"
postTrans = "echo 'Hello PostTrans World'"
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
def result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
Format format = result.format
assertThat(["#!/usr/bin/env bash\necho 'Hello from file'\n"], is(format.header.getEntry(PREINSCRIPT)?.values))
assertThat(["echo 'Hello Post World'"], is(format.header.getEntry(POSTINSCRIPT)?.values))
assertThat(["echo 'Hello PreUn World'"], is(format.header.getEntry(PREUNSCRIPT)?.values))
assertThat(["echo 'Hello PostUn World'"], is(format.header.getEntry(POSTUNSCRIPT)?.values))
assertThat(["echo 'Hello PreTrans World'"], is(format.header.getEntry(PRETRANSSCRIPT)?.values))
assertThat(["echo 'Hello PostTrans World'"], is(format.header.getEntry(POSTTRANSSCRIPT)?.values))
}
@Test
void testChangeLog() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
String changelog = getClass().getResource('changelog').text
File changelogDir = new File(projectDir, 'changelog')
changelogDir.mkdirs()
new File(changelogDir, 'changelog').withWriter { out -> out.write(changelog) }
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'changelog'
packageVersion = '1.0'
packageRelease = '1'
changeLogFile = project.file('changelog/changelog')
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
def result = rpmReader.read(project.tasks.buildRpm.outputs.files.first().toPath())
Format format = result.format
assertDateEntryHeaderEqualsAt("Tue Feb 24 2015", format,
CHANGELOGTIME, 10, 0)
assertHeaderEqualsAt("Thomas Jefferson", format,
CHANGELOGNAME, 10, 4)
assertHeaderEqualsAt("- Initial rpm for this package", format,
CHANGELOGTEXT, 10, 9)
assertHeaderEqualsAt("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod \n" +
"tempor incididunt ut labore et dolore magna aliqua", format,
CHANGELOGTEXT, 10, 0)
}
private static void assertDateEntryHeaderEqualsAt(String expected, Format format, EntryType entryType, int size, int pos) {
assertNotNull(format, "null format")
SpecEntry<?> entry = format.getHeader().getEntry(entryType)
assertNotNull(entry, "Entry not found : " + entryType.getName())
assertEquals(4, entry.getType(), "Entry type : " + entryType.getName())
IntegerList values = (IntegerList) entry.getValues()
assertNotNull(values, "null values")
assertEquals(size, values.size(), "Entry size : " + entryType.getName())
LocalDateTime localDate = LocalDateTime.ofEpochSecond(values.get(pos), 0, ZoneOffset.UTC)
assertEquals(expected, ChangelogParser.CHANGELOG_FORMAT.format(localDate), "Entry value : " + entryType.getName())
}
private static void assertHeaderEqualsAt(String expected, Format format, EntryType entryType, int size, int pos) {
assertNotNull(format, "null format")
SpecEntry<?> entry = format.getHeader().getEntry(entryType)
assertNotNull(entry, "Entry not found : " + entryType.getName())
assertEquals(8, entry.getType(), "Entry type : " + entryType.getName())
StringList values = (StringList) entry.getValues()
assertNotNull(values, "null values")
assertEquals(size, values.size(), "Entry size : " + entryType.getName())
assertEquals(expected, values.get(pos), "Entry value : " + entryType.getName())
}
}

View file

@ -0,0 +1,62 @@
package org.xbib.gradle.plugin
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.xbib.rpm.RpmReader
import org.xbib.rpm.signature.SignatureTag
import java.nio.file.Paths
import static org.junit.jupiter.api.Assertions.assertNotNull
import static org.junit.jupiter.api.Assertions.assertNull
import static org.xbib.rpm.lead.Architecture.I386
class RpmSignTest {
File projectDir
@BeforeEach
void setup() {
projectDir = new File("build/testrpm")
projectDir.mkdirs()
}
@Test
void testUnsigned() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'bleah'
packageVersion = '1.0'
packageRelease = '1'
arch = I386
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
def res = rpmReader.read(Paths.get(projectDir.toString(), 'build', 'distributions', 'bleah-1.0-1.i386.rpm'))
assertNull(res.format.signatureHeader.getEntry(SignatureTag.LEGACY_PGP))
}
@Test
void testSign() {
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'bleah'
packageVersion = '1.0'
packageRelease = '1'
arch = I386
signingKeyId = 'F02C6D2C'
signingKeyPassphrase = 'test'
signingKeyRing = 'src/test/resources/test-secring.gpg'
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
def res = rpmReader.read(Paths.get(projectDir.toString(), 'build', 'distributions', 'bleah-1.0-1.i386.rpm'))
assertNotNull(res.format.signatureHeader.getEntry(SignatureTag.LEGACY_PGP))
}
}

View file

@ -0,0 +1,104 @@
package org.xbib.gradle.plugin
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.xbib.rpm.RpmReaderResult
import org.xbib.rpm.RpmReader
import org.xbib.rpm.format.Format
import java.nio.file.Paths
import static org.hamcrest.MatcherAssert.assertThat
import static org.hamcrest.CoreMatchers.*
import static org.junit.jupiter.api.Assertions.assertTrue
import static org.xbib.rpm.format.Flags.EQUAL
import static org.xbib.rpm.format.Flags.GREATER
import static org.xbib.rpm.header.HeaderTag.ARCH
import static org.xbib.rpm.header.HeaderTag.DISTRIBUTION
import static org.xbib.rpm.header.HeaderTag.EPOCH
import static org.xbib.rpm.header.HeaderTag.NAME
import static org.xbib.rpm.header.HeaderTag.OS
import static org.xbib.rpm.header.HeaderTag.RELEASE
import static org.xbib.rpm.header.HeaderTag.VERSION
import static org.xbib.rpm.lead.Architecture.I386
import static org.xbib.rpm.lead.Os.LINUX
import static org.xbib.rpm.lead.PackageType.BINARY
class RpmSimpleTest {
File projectDir
@BeforeEach
void setup() {
projectDir = new File("build/testrpm")
projectDir.mkdirs()
}
@Test
void simpleRpm() {
File srcDir = new File(projectDir, 'src')
srcDir.mkdirs()
new File(srcDir, 'apple').withWriter { out ->
out.write('apple')
}
File noParentsDir = new File(projectDir, 'noParentsDir')
noParentsDir.mkdirs()
new File(noParentsDir, 'alone').withWriter { out ->
out.write('alone')
}
Project project = ProjectBuilder.builder()
.withProjectDir(projectDir)
.build()
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
project.task([type: Rpm], 'buildRpm', {
packageName = 'bleah'
packageVersion = '1.0'
packageRelease = '1'
packageType = BINARY
arch = I386
os = LINUX
packageGroup = 'Development/Libraries'
packageDescription = 'Not a very interesting library.'
summary = 'Bleah blarg'
license = 'Free'
distribution = 'SuperSystem'
vendor = 'Super Associates, LLC'
url = 'http://www.example.com/'
requires('blarg', '1.0', GREATER | EQUAL)
requires('blech')
into '/opt/bleah'
from('src') {
fileType = ['config', 'noreplace']
}
from('noParentsDir') {
into '/a/path/not/to/create'
}
link('/opt/bleah/banana', '/opt/bleah/apple')
})
project.tasks.buildRpm.copy()
RpmReader rpmReader = new RpmReader()
RpmReaderResult result = rpmReader.read(Paths.get(projectDir.toString(), 'build', 'distributions', 'bleah-1.0-1.i386.rpm'))
Format format = result.format
assertThat(['bleah'], is(format.header.getEntry(NAME)?.values))
assertThat(['1.0'], is(format.header.getEntry(VERSION)?.values))
assertThat(['1'], is(format.header.getEntry(RELEASE)?.values))
assertThat([0], is(format.header.getEntry(EPOCH)?.values))
assertThat(['i386'], is(format.header.getEntry(ARCH)?.values))
assertThat(['linux'], is(format.header.getEntry(OS)?.values))
assertThat(['SuperSystem'], is(format.header.getEntry(DISTRIBUTION)?.values))
assertTrue(result.files*.name.every { fileName ->
['./a/path/not/to/create/alone',
'./opt/bleah',
'./opt/bleah/apple',
'./opt/bleah/banana'
].any { path ->
path.startsWith(fileName)
}
})
assertTrue(result.files*.name.every { fileName ->
['./a/path/not/to/create'].every { path ->
!path.startsWith(fileName)
}
})
}
}

View file

@ -1,107 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.gradle.api.internal.file.DefaultFileLookup
import org.gradle.api.internal.file.FileResolver
import org.gradle.api.internal.file.copy.DefaultCopySpec
import org.gradle.api.tasks.util.PatternSet
import org.gradle.api.tasks.util.internal.PatternSets
import org.gradle.internal.Factory
import org.gradle.internal.nativeintegration.filesystem.FileSystem
import org.gradle.internal.nativeintegration.services.NativeServices
import org.gradle.internal.reflect.DirectInstantiator
import org.gradle.internal.reflect.Instantiator
import org.junit.Test
import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertNull
class CopySpecEnhancementTest {
private final FileResolver fileResolver = [resolve: { it as File }, getPatternSetFactory: {
TestFiles.getPatternSetFactory()
}] as FileResolver
private final Instantiator instantiator = DirectInstantiator.INSTANCE
def spec = new DefaultCopySpec(fileResolver, instantiator)
@Test
public void addUser() {
assertNull(spec.metaClass.hasProperty('user'))
CopySpecEnhancement.user(spec, 'USER')
assertEquals('USER', spec.user)
}
@Test
public void addAddParentDirs() {
CopySpecEnhancement.setAddParentDirs(spec, true)
assertEquals(true, spec.addParentDirs)
}
@Test
public void addCreateDirectoryEntry() {
use(CopySpecEnhancement) {
spec.createDirectoryEntry false
}
assertEquals(false, spec.createDirectoryEntry)
use(CopySpecEnhancement) {
spec.createDirectoryEntry true
}
assertEquals(true, spec.createDirectoryEntry)
use(CopySpecEnhancement) {
spec.setCreateDirectoryEntry(false)
}
assertEquals(false, spec.createDirectoryEntry)
use(CopySpecEnhancement) {
spec.setCreateDirectoryEntry(true)
}
assertEquals(true, spec.createDirectoryEntry)
}
}
// Copied from Gradle core as DefaultCopySpec can no longer have null arguments
class TestFiles {
private static final FileSystem FILE_SYSTEM = NativeServicesTestFixture.getInstance().get(FileSystem.class);
private static final DefaultFileLookup FILE_LOOKUP = new DefaultFileLookup(FILE_SYSTEM, PatternSets.getNonCachingPatternSetFactory());
/**
* Returns a resolver with no base directory.
*/
static FileResolver resolver() {
return FILE_LOOKUP.getFileResolver()
}
static Factory<PatternSet> getPatternSetFactory() {
return resolver().getPatternSetFactory()
}
}
class NativeServicesTestFixture {
static NativeServices nativeServices
static boolean initialized
static void initialize() {
if (!initialized) {
File nativeDir = new File("build/native-libs")
NativeServices.initialize(nativeDir)
initialized = true
}
}
static synchronized NativeServices getInstance() {
if (nativeServices == null) {
initialize()
nativeServices = NativeServices.getInstance()
}
nativeServices
}
}

View file

@ -1,51 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.junit.Before
import org.junit.Test
import org.xbib.gradle.plugin.test.ProjectSpec
import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertTrue
class RpmCopySpecVisitorTest extends ProjectSpec {
RpmCopyAction visitor
@Before
void setup() {
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
Rpm rpmTask = project.task('buildRpm', type: Rpm) {
packageName = 'can-execute-rpm-task-with-valid-version'
}
visitor = new RpmCopyAction(rpmTask)
}
@Test
void withoutUtils() {
visitor.includeStandardDefines = false
File script = resourceFile("script.sh")
Object result = visitor.scriptWithUtils([], [script])
assertTrue result instanceof String
assertEquals(
"#!/bin/bash\n" +
"hello\n", result)
}
@Test
void withUtils() {
visitor.includeStandardDefines = false
Object result = visitor.scriptWithUtils([resourceFile("utils.sh")], [resourceFile("script.sh")])
assertTrue result instanceof String
assertEquals(
"#!/bin/bash\n" +
"function hello() {\n" +
" echo 'Hello, world.'\n" +
"}\n" +
"hello\n", result)
}
File resourceFile(String name) {
new File(getClass().getResource(name).getPath())
}
}

View file

@ -1,28 +0,0 @@
package org.xbib.gradle.plugin.rpm
import org.xbib.gradle.plugin.test.IntegrationSpec
class RpmPluginIntegrationTest extends IntegrationSpec {
def "rpm task is marked up-to-date when setting arch or os property"() {
given:
buildFile << '''
apply plugin: 'org.xbib.gradle.plugin.rpm'
task buildRpm(type: Rpm) {
packageName = 'rpmIsUpToDate'
arch = org.xbib.rpm.lead.Architecture.NOARCH
os = org.xbib.rpm.lead.Os.LINUX
}
'''
when:
runTasksSuccessfully('buildRpm')
and:
def result = runTasksSuccessfully('buildRpm')
then:
result.wasUpToDate('buildRpm')
}
}

View file

@ -1,131 +0,0 @@
package org.xbib.gradle.plugin.rpm
import groovy.transform.Canonical
import org.xbib.io.compress.bzip2.Bzip2InputStream
import org.xbib.io.compress.xz.XZInputStream
import org.xbib.rpm.header.Header
import org.xbib.rpm.header.HeaderTag
import org.xbib.rpm.header.entry.SpecEntry
import org.xbib.rpm.io.ChannelWrapper
import org.xbib.rpm.io.ReadableChannelWrapper
import org.xbib.rpm.format.Format
import org.xbib.rpm.payload.CompressionType
import org.xbib.rpm.payload.CpioHeader
import org.spockframework.util.Nullable
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.channels.Channels
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.file.Path
import java.util.zip.GZIPInputStream
import static org.xbib.rpm.header.HeaderTag.HEADERIMMUTABLE
import static org.xbib.rpm.signature.SignatureTag.SIGNATURES
import static org.junit.Assert.assertEquals
/**
*
*/
class RpmReader {
@Canonical
static class ReaderResult {
Format format
List<ReaderFile> files
}
@Canonical
static class ReaderFile {
@Delegate
CpioHeader header
@Nullable
ByteBuffer contents
String asString() {
if (contents == null ) {
return null
}
Charset charset = StandardCharsets.UTF_8
CharBuffer buffer = charset.decode(contents)
return buffer.toString()
}
}
static ReaderResult read(Path path) throws Exception {
ReaderResult readerResult = null
path.withInputStream { InputStream inputStream ->
readerResult = read(inputStream)
}
readerResult
}
static ReaderResult read(InputStream inputStream, boolean includeContents = true) {
ReadableChannelWrapper wrapper = new ReadableChannelWrapper(Channels.newChannel(inputStream))
Format format = readHeader(wrapper)
InputStream uncompressed = createUncompressedStream(format.getHeader(), inputStream)
wrapper = new ReadableChannelWrapper(Channels.newChannel(uncompressed))
CpioHeader header = null
def files = []
int total = 0
while (header == null || !header.isLast()) {
header = new CpioHeader()
total = header.read(wrapper, total)
final int fileSize = header.getFileSize()
boolean includingContents = includeContents && header.type == CpioHeader.FILE
if (!header.isLast()) {
ByteBuffer descriptor = includingContents ? ChannelWrapper.fill(wrapper, fileSize) : null
files += new ReaderFile(header, descriptor)
}
if (!includingContents) {
assertEquals(fileSize, uncompressed.skip(fileSize))
}
total += fileSize
}
return new ReaderResult(format,files)
}
static InputStream createUncompressedStream(Header header, InputStream inputStream) {
InputStream compressedInput = inputStream
SpecEntry<?> pcEntry = header.getEntry(HeaderTag.PAYLOADCOMPRESSOR)
String[] pc = (String[]) pcEntry.getValues()
CompressionType compressionType = CompressionType.valueOf(pc[0].toUpperCase())
switch (compressionType) {
case CompressionType.NONE:
break
case CompressionType.GZIP:
compressedInput = new GZIPInputStream(inputStream)
break
case CompressionType.BZIP2:
compressedInput = new Bzip2InputStream(inputStream)
break
case CompressionType.XZ:
compressedInput = new XZInputStream(inputStream)
break
}
compressedInput
}
static Format readHeader(ReadableChannelWrapper wrapper) throws Exception {
Format format = new Format()
format.getLead().read(wrapper)
int count = format.signatureHeader.read(wrapper)
int expected = ByteBuffer.wrap(format.signatureHeader.getEntry(SIGNATURES).values, 8, 4).getInt() / -16
assertEquals(expected, count)
count = format.getHeader().read(wrapper)
expected = ByteBuffer.wrap(format.getHeader().getEntry(HEADERIMMUTABLE).values, 8, 4).getInt() / -16
assertEquals(expected, count)
return format
}
def static getHeaderEntry(ReaderResult res, tag) {
def header = res.format.header
header.getEntry(tag.code)
}
def static getHeaderEntryString(ReaderResult res, tag) {
getHeaderEntry(res, tag)?.values?.join('')
}
}

View file

@ -1,75 +0,0 @@
package org.xbib.gradle.plugin.rpm
import spock.lang.Specification
class SystemPackagingExtensionTest extends Specification {
SystemPackagingExtension extension = new SystemPackagingExtension()
def "Can define required package name without version and flag"() {
given:
String packageName = 'myPackage'
when:
extension.requires(packageName)
then:
extension.dependencies.size() == 1
Dependency dep = extension.dependencies[0]
dep.packageName == packageName
dep.version == ''
dep.flag == 0
}
def "Can define required package name with version and without flag"(){
given:
String packageName = 'myPackage'
when:
extension.requires(packageName, '1.0.0')
then:
extension.dependencies.size() == 1
Dependency dep = extension.dependencies[0]
dep.packageName == packageName
dep.version == '1.0.0'
dep.flag == 0
}
def "Can define required package name with version and flag"() {
given:
String packageName = 'myPackage'
when:
extension.requires(packageName, '1.0.0', 5)
then:
extension.dependencies.size() == 1
Dependency dep = extension.dependencies[0]
dep.packageName == packageName
dep.version == '1.0.0'
dep.flag == 5
}
def "Cannot define required package name containing comma without version and flag"() {
given:
String packageName = 'myPackage,something'
when:
extension.requires(packageName)
then:
Throwable t = thrown(IllegalArgumentException)
}
def "Cannot define required package name containing comma with version and flag"() {
given:
String packageName = 'myPackage,something'
when:
extension.requires(packageName, '1.0.0', 5)
then:
Throwable t = thrown(IllegalArgumentException)
}
}

View file

@ -1,35 +0,0 @@
package org.xbib.gradle.plugin.rpm.validation
import spock.lang.Specification
import spock.lang.Unroll
class RpmPackageNameAttributeValidatorTest extends Specification {
RpmPackageNameAttributeValidator validator = new RpmPackageNameAttributeValidator()
@Unroll
def "verifies #description: '#attribute'"() {
when:
boolean valid = validator.validate(attribute)
then:
valid == result
where:
attribute | result | description
'a25b' | true | 'valid package name with mixed alphanumeric characters'
'my.awesome.package' | true | 'package with dot characters'
'my-awesome-package' | true | 'package with dash characters'
'my_awesome_package' | true | 'package with underscore characters'
'My-Awesome-Package' | true | 'package with upper case characters'
'abc^' | false | 'package name with an invalid character'
}
def "provide error message"() {
when:
String errorMessage = validator.getErrorMessage('abc^')
then:
errorMessage == "Invalid package name 'abc^' - a valid package name must only contain [a-zA-Z0-9-._+]"
}
}

View file

@ -1,41 +0,0 @@
package org.xbib.gradle.plugin.rpm.validation
import org.gradle.api.InvalidUserDataException
import org.xbib.gradle.plugin.test.ProjectSpec
import org.xbib.gradle.plugin.rpm.Rpm
class RpmTaskPropertiesValidatorIntegrationTest extends ProjectSpec {
RpmTaskPropertiesValidator validator = new RpmTaskPropertiesValidator()
def setup() {
project.apply plugin: 'org.xbib.gradle.plugin.rpm'
}
def 'can execute Rpm task with valid version and package name'() {
given:
Rpm rpmTask = project.task('buildRpm', type: Rpm) {
packageName = 'can-execute-rpm-task-with-valid-version'
}
when:
validator.validate(rpmTask)
then:
noExceptionThrown()
}
def 'executing a Rpm task with invalid package name throws exception'() {
given:
Rpm rpmTask = project.task('buildRpm', type: Rpm) {
packageName = 'abc^'
}
when:
validator.validate(rpmTask)
then:
Throwable t = thrown(InvalidUserDataException)
t.message == "Invalid package name 'abc^' - a valid package name must only contain [a-zA-Z0-9-._+]"
}
}

View file

@ -1,52 +0,0 @@
package org.xbib.gradle.plugin.test
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Rule
import org.junit.rules.TestName
import spock.lang.Specification
abstract class AbstractProjectSpec extends Specification {
static final String CLEAN_PROJECT_DIR_SYS_PROP = 'cleanProjectDir'
File ourProjectDir
@Rule TestName testName = new TestName()
String canonicalName
Project project
MultiProjectHelper helper
void setup() {
ourProjectDir = new File("build/xbibtest/${this.class.canonicalName}/${testName.methodName.replaceAll(/\W+/, '-')}").absoluteFile
if (ourProjectDir.exists()) {
ourProjectDir.deleteDir()
}
ourProjectDir.mkdirs()
canonicalName = testName.getMethodName().replaceAll(' ', '-')
project = ProjectBuilder.builder().withName(canonicalName).withProjectDir(ourProjectDir).build()
helper = new MultiProjectHelper(project)
}
void cleanup() {
if (deleteProjectDir()) {
ourProjectDir.deleteDir()
}
}
boolean deleteProjectDir() {
String cleanProjectDirSystemProperty = System.getProperty(CLEAN_PROJECT_DIR_SYS_PROP)
cleanProjectDirSystemProperty ? cleanProjectDirSystemProperty.toBoolean() : true
}
Project addSubproject(String subprojectName) {
helper.addSubproject(subprojectName)
}
Project addSubprojectWithDirectory(String subprojectName) {
helper.addSubprojectWithDirectory(subprojectName)
}
}

View file

@ -1,192 +0,0 @@
package org.xbib.gradle.plugin.test
import groovy.transform.CompileStatic
import groovy.transform.TypeCheckingMode
import org.gradle.api.logging.LogLevel
import org.junit.Rule
import org.junit.rules.TestName
import spock.lang.Specification
abstract class BaseIntegrationSpec extends Specification {
@Rule
TestName testName = new TestName()
File projectDir
protected String moduleName
protected LogLevel logLevel = LogLevel.LIFECYCLE
protected List<File> initScripts = []
private static final LOGGING_LEVEL_ENV_VARIABLE = "TEST_LOGGING_LEVEL"
def setup() {
projectDir = new File("build/xbibtest/${this.class.canonicalName}/${testName.methodName.replaceAll(/\W+/, '-')}").absoluteFile
if (projectDir.exists()) {
projectDir.deleteDir()
}
projectDir.mkdirs()
moduleName = findModuleName()
}
/**
* Override to alter its value
* @return
*/
protected LogLevel getLogLevel() {
String levelFromEnv = System.getenv(LOGGING_LEVEL_ENV_VARIABLE)
if(!levelFromEnv) {
return logLevel
}
return LogLevel.valueOf(levelFromEnv.toUpperCase())
}
/* Setup */
protected File directory(String path, File baseDir = getProjectDir()) {
new File(baseDir, path).with {
mkdirs()
it
}
}
protected File file(String path, File baseDir = getProjectDir()) {
def splitted = path.split('/')
def directory = splitted.size() > 1 ? directory(splitted[0..-2].join('/'), baseDir) : baseDir
def file = new File(directory, splitted[-1])
file.createNewFile()
file
}
@CompileStatic(TypeCheckingMode.SKIP)
protected File createFile(String path, File baseDir = getProjectDir()) {
File file = file(path, baseDir)
if (!file.exists()) {
assert file.parentFile.mkdirs() || file.parentFile.exists()
file.createNewFile()
}
file
}
protected static void checkForDeprecations(String output) {
def deprecations = output.readLines().findAll {
it.contains("has been deprecated and is scheduled to be removed in Gradle") ||
it.contains("Deprecated Gradle features were used in this build") ||
it.contains("has been deprecated. This is scheduled to be removed in Gradle") ||
it.contains("This behaviour has been deprecated and is scheduled to be removed in Gradle")
}
// temporary for known issue with overwriting task
// overridden task expected to not be needed in future version
if (deprecations.size() == 1 && deprecations.first().contains("Creating a custom task named 'dependencyInsight' has been deprecated and is scheduled to be removed in Gradle 5.0.")) {
return
}
if (!System.getProperty("ignoreDeprecations") && !deprecations.isEmpty()) {
throw new IllegalArgumentException("Deprecation warnings were found (Set the ignoreDeprecations system property during the test to ignore):\n" + deprecations.collect {
" - $it"
}.join("\n"))
}
}
protected static void checkForMutableProjectState(String output) {
def mutableProjectStateWarnings = output.readLines().findAll {
it.contains("was resolved without accessing the project in a safe manner") ||
it.contains("This may happen when a configuration is resolved from a thread not managed by Gradle or from a different project")
}
if (!System.getProperty("ignoreMutableProjectStateWarnings") && !mutableProjectStateWarnings.isEmpty()) {
throw new IllegalArgumentException("Mutable Project State warnings were found (Set the ignoreMutableProjectStateWarnings system property during the test to ignore):\n" + mutableProjectStateWarnings.collect {
" - $it"
}.join("\n"))
}
}
protected void writeHelloWorld(String packageDotted, File baseDir = getProjectDir()) {
def path = 'src/main/java/' + packageDotted.replace('.', '/') + '/HelloWorld.java'
def javaFile = createFile(path, baseDir)
javaFile << """\
package ${packageDotted};
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello Integration Test");
}
}
""".stripIndent()
}
/**
* Creates a unit test for testing your plugin.
* @param failTest true if you want the test to fail, false if the test should pass
* @param baseDir the directory to begin creation from, defaults to projectDir
*/
protected void writeUnitTest(boolean failTest, File baseDir = getProjectDir()) {
writeTest('src/test/java/', 'xbib', failTest, baseDir)
}
/**
*
* Creates a unit test for testing your plugin.
* @param srcDir the directory in the project where the source file should be created.
* @param packageDotted the package for the unit test class, written in dot notation
* @param failTest true if you want the test to fail, false if the test should pass
* @param baseDir the directory to begin creation from, defaults to projectDir
*/
protected void writeTest(String srcDir, String packageDotted, boolean failTest, File baseDir = getProjectDir()) {
def path = srcDir + packageDotted.replace('.', '/') + '/HelloWorldTest.java'
def javaFile = createFile(path, baseDir)
javaFile << """\
package ${packageDotted};
import org.junit.Test;
import static org.junit.Assert.assertFalse;
public class HelloWorldTest {
@Test public void doesSomething() {
assertFalse( $failTest );
}
}
""".stripIndent()
}
/**
* Creates a properties file to included as project resource.
* @param srcDir the directory in the project where the source file should be created.
* @param fileName to be used for the file, sans extension. The .properties extension will be added to the name.
* @param baseDir the directory to begin creation from, defaults to projectDir
*/
protected void writeResource(String srcDir, String fileName, File baseDir = getProjectDir()) {
def path = "$srcDir/${fileName}.properties"
def resourceFile = createFile(path, baseDir)
resourceFile.text = "firstProperty=foo.bar"
}
protected void addResource(String srcDir, String filename, String contents, File baseDir = getProjectDir()) {
def resourceFile = createFile("${srcDir}/${filename}", baseDir)
resourceFile.text = contents
}
protected String findModuleName() {
getProjectDir().getName().replaceAll(/_\d+/, '')
}
protected List<String> calculateArguments(String... args) {
List<String> arguments = []
// Gradle will use these files name from the PWD, instead of the project directory. It's easier to just leave
// them out and let the default find them, since we're not changing their default names.
//arguments += '--build-file'
//arguments += (buildFile.canonicalPath - projectDir.canonicalPath).substring(1)
//arguments += '--settings-file'
//arguments += (settingsFile.canonicalPath - projectDir.canonicalPath).substring(1)
//arguments += '--no-daemon'
switch (getLogLevel()) {
case LogLevel.INFO:
arguments += '--info'
break
case LogLevel.DEBUG:
arguments += '--debug'
break
}
arguments += '--stacktrace'
arguments += '-Dorg.gradle.warning.mode=all'
arguments.addAll(args)
arguments.addAll(initScripts.collect { file -> '-I' + file.absolutePath })
arguments
}
}

View file

@ -1,96 +0,0 @@
package org.xbib.gradle.plugin.test
import org.gradle.tooling.BuildException
import org.gradle.tooling.BuildLauncher
import org.gradle.tooling.ProgressEvent
import org.gradle.tooling.ProgressListener
class BuildLauncherBackedGradleHandle implements GradleHandle {
final private ByteArrayOutputStream standardOutput = new ByteArrayOutputStream()
final private ByteArrayOutputStream standardError = new ByteArrayOutputStream()
final private BuildLauncher launcher
final private boolean forkedProcess
final private List<String> tasksExecuted
public static final String PROGRESS_TASK_PREFIX = "Task :"
private GradleHandleBuildListener buildListener
BuildLauncherBackedGradleHandle(BuildLauncher launcher, boolean forkedProcess) {
this.forkedProcess = forkedProcess
launcher.setStandardOutput(standardOutput)
launcher.setStandardError(standardError)
tasksExecuted = new ArrayList<String>()
launcher.addProgressListener(new ProgressListener() {
@Override
void statusChanged(ProgressEvent event) {
// These are free form strings, :-(
if (event.description.startsWith(PROGRESS_TASK_PREFIX)) { // E.g. "Task :echo"
String taskName = event.description.substring(PROGRESS_TASK_PREFIX.length() - 1)
tasksExecuted.add(taskName)
}
}
})
this.launcher = launcher
}
@Override
void registerBuildListener(GradleHandleBuildListener buildListener) {
this.buildListener = buildListener
}
@Override
boolean isForkedProcess() {
forkedProcess
}
private String getStandardOutput() {
return standardOutput.toString()
}
private String getStandardError() {
return standardError.toString()
}
@Override
ExecutionResult run() {
Throwable failure = null
try {
buildListener?.buildStarted()
launcher.run()
} catch(BuildException e) {
failure = e.getCause()
} catch(Exception e) {
failure = e
}
finally {
buildListener?.buildFinished()
}
String stdout = getStandardOutput()
List<MinimalExecutedTask> tasks = new ArrayList<>()
for (String taskName: tasksExecuted) {
boolean upToDate = isTaskUpToDate(stdout, taskName)
boolean skipped = isTaskSkipped(stdout, taskName)
tasks.add(new MinimalExecutedTask(taskName, upToDate, skipped))
}
boolean success = failure == null
new ToolingExecutionResult(success, stdout, getStandardError(), tasks, failure)
}
private isTaskUpToDate(String stdout, String taskName) {
containsOutput(stdout, taskName, 'UP-TO-DATE')
}
private isTaskSkipped(String stdout, String taskName) {
containsOutput(stdout, taskName, 'SKIPPED')
}
private boolean containsOutput(String stdout, String taskName, String stateIdentifier) {
stdout.contains("$taskName $stateIdentifier".toString())
}
}

View file

@ -1,58 +0,0 @@
package org.xbib.gradle.plugin.test
import com.google.common.base.Function
import com.google.common.base.Predicate
import com.google.common.collect.FluentIterable
import org.gradle.internal.ErroringAction
import org.gradle.internal.IoActions
import org.gradle.internal.classloader.ClasspathUtil
import org.gradle.internal.classpath.ClassPath
import org.gradle.util.TextUtil
class ClasspathAddingInitScriptBuilder {
private ClasspathAddingInitScriptBuilder() {
}
static void build(File initScriptFile, final ClassLoader classLoader, Predicate<URL> classpathFilter) {
build(initScriptFile, getClasspathAsFiles(classLoader, classpathFilter))
}
static void build(File initScriptFile, final List<File> classpath) {
IoActions.writeTextFile(initScriptFile, new ErroringAction<Writer>() {
@Override
protected void doExecute(Writer writer) throws Exception {
writer.write("allprojects {\n")
writer.write(" buildscript {\n")
writer.write(" dependencies {\n")
for (File file : classpath) {
writer.write(String.format(" classpath files('%s')\n", TextUtil.escapeString(file.getAbsolutePath())))
}
writer.write(" }\n")
writer.write(" }\n")
writer.write("}\n")
}
})
}
static List<File> getClasspathAsFiles(ClassLoader classLoader, Predicate<URL> classpathFilter) {
List<URL> classpathUrls = getClasspathUrls(classLoader)
return FluentIterable.from(classpathUrls).filter(classpathFilter).transform(new Function<URL, File>() {
@Override
File apply(URL url) {
return new File(url.toURI())
}
}).toList()
}
private static List<URL> getClasspathUrls(ClassLoader classLoader) {
Object cp = ClasspathUtil.getClasspath(classLoader)
if (cp instanceof List<URL>) {
return (List<URL>) cp
}
if (cp instanceof ClassPath) {
return ((ClassPath) cp).asURLs
}
throw new IllegalStateException("Unable to extract classpath urls from type ${cp.class.canonicalName}")
}
}

View file

@ -1,35 +0,0 @@
package org.xbib.gradle.plugin.test;
import com.google.common.base.Predicate
import org.gradle.util.GFileUtils
class ClasspathInjectingGradleHandleFactory implements GradleHandleFactory {
private final ClassLoader classLoader
private final GradleHandleFactory delegateFactory
private Predicate<URL> classpathFilter
ClasspathInjectingGradleHandleFactory(ClassLoader classLoader, GradleHandleFactory delegateFactory,
Predicate<URL> classpathFilter) {
this.classpathFilter = classpathFilter
this.classLoader = classLoader
this.delegateFactory = delegateFactory
}
@Override
GradleHandle start(File projectDir, List<String> arguments, List<String> jvmArguments = []) {
File testKitDir = new File(projectDir, ".gradle-test-kit")
if (!testKitDir.exists()) {
GFileUtils.mkdirs(testKitDir)
}
File initScript = new File(testKitDir, "init.gradle");
ClasspathAddingInitScriptBuilder.build(initScript, classLoader, classpathFilter)
List<String> ammendedArguments = new ArrayList<String>(arguments.size() + 2)
ammendedArguments.add("--init-script")
ammendedArguments.add(initScript.getAbsolutePath())
ammendedArguments.addAll(arguments)
return delegateFactory.start(projectDir, ammendedArguments, jvmArguments)
}
}

View file

@ -1,18 +0,0 @@
package org.xbib.gradle.plugin.test
import groovy.transform.Immutable
@Immutable
class Coordinate {
String group
String artifact
String version
@Override
String toString() {
"${group}:${artifact}:${version}"
}
}

View file

@ -1,90 +0,0 @@
package org.xbib.gradle.plugin.test;
import org.gradle.api.GradleException
abstract class DefaultExecutionResult implements ExecutionResult {
private final Boolean success
private final String standardOutput
private final String standardError
private final List<? extends ExecutedTask> executedTasks
private final Throwable failure
DefaultExecutionResult(Boolean success, String standardOutput, String standardError,
List<? extends ExecutedTask> executedTasks, Throwable failure) {
this.success = success
this.standardOutput = standardOutput
this.standardError = standardError
this.executedTasks = executedTasks
this.failure = failure
}
@Override
Boolean getSuccess() {
success
}
@Override
String getStandardOutput() {
standardOutput
}
@Override
String getStandardError() {
standardError
}
@Override
boolean wasExecuted(String taskPath) {
executedTasks.any { ExecutedTask task ->
taskPath = normalizeTaskPath(taskPath)
def match = task.path == taskPath
return match
}
}
@Override
boolean wasUpToDate(String taskPath) {
getExecutedTaskByPath(taskPath).upToDate
}
@Override
boolean wasSkipped(String taskPath) {
getExecutedTaskByPath(taskPath).skipped
}
String normalizeTaskPath(String taskPath) {
taskPath.startsWith(':') ? taskPath : ":$taskPath"
}
private ExecutedTask getExecutedTaskByPath(String taskPath) {
taskPath = normalizeTaskPath(taskPath)
def task = executedTasks.find { ExecutedTask task ->
task.path == taskPath
}
if (task == null) {
throw new RuntimeException("Task with path $taskPath was not found")
}
task
}
@Override
Throwable getFailure() {
failure
}
@Override
ExecutionResult rethrowFailure() {
if (failure instanceof GradleException) {
throw (GradleException) failure
}
if (failure != null) {
throw new GradleException("Build aborted because of an internal error.", failure)
}
this
}
}

View file

@ -1,25 +0,0 @@
package org.xbib.gradle.plugin.test
class DefaultGradleRunner implements GradleRunner {
private final GradleHandleFactory handleFactory
DefaultGradleRunner(GradleHandleFactory handleFactory) {
this.handleFactory = handleFactory
}
@Override
ExecutionResult run(File projectDir, List<String> arguments, List<String> jvmArguments = [],
List<PreExecutionAction> preExecutionActions = []) {
handle(projectDir, arguments, jvmArguments, preExecutionActions).run()
}
@Override
GradleHandle handle(File projectDir, List<String> arguments, List<String> jvmArguments = [],
List<PreExecutionAction> preExecutionActions = []) {
preExecutionActions?.each {
it.execute(projectDir, arguments, jvmArguments)
}
handleFactory.start(projectDir, arguments, jvmArguments)
}
}

View file

@ -1,37 +0,0 @@
package org.xbib.gradle.plugin.test
class DependencyGraph {
Collection<DependencyGraphNode> nodes = []
DependencyGraph(List<String> graph) {
graph.each { nodes << parseNode(it) }
}
DependencyGraph(String... graph) {
this(graph as List)
}
DependencyGraph(Map tuple) {
nodes = tuple.nodes
}
private DependencyGraphNode parseNode(String s) {
// Don't use tokenize, it'll make each character a possible delimeter, e.g. \t\n would tokenize on both
// \t OR \n, not the combination of \t\n.
def parts = s.split('->')
def (group, artifact, version) = parts[0].trim().tokenize(':')
def coordinate = new Coordinate(group: group, artifact: artifact, version: version)
def dependencies = (parts.size() > 1) ? parseDependencies(parts[1]) : []
new DependencyGraphNode(coordinate: coordinate, dependencies: dependencies)
}
private List<Coordinate> parseDependencies(String s) {
List<Coordinate> dependencies = []
s.tokenize('|').each { String dependency ->
def (group, artifact, version) = dependency.trim().tokenize(':')
dependencies << new Coordinate(group: group, artifact: artifact, version: version)
}
dependencies
}
}

View file

@ -1,16 +0,0 @@
package org.xbib.gradle.plugin.test
import groovy.transform.Immutable
@Immutable
class DependencyGraphNode {
@Delegate Coordinate coordinate
List<Coordinate> dependencies = []
@Override
String toString() {
"${group}:${artifact}:${version}"
}
}

View file

@ -1,10 +0,0 @@
package org.xbib.gradle.plugin.test
interface ExecutedTask {
String getPath()
boolean isUpToDate()
boolean isSkipped()
}

View file

@ -1,20 +0,0 @@
package org.xbib.gradle.plugin.test;
interface ExecutionResult {
Boolean getSuccess()
String getStandardOutput()
String getStandardError()
boolean wasExecuted(String taskPath)
boolean wasUpToDate(String taskPath)
boolean wasSkipped(String taskPath)
Throwable getFailure()
ExecutionResult rethrowFailure()
}

View file

@ -1,104 +0,0 @@
package org.xbib.gradle.plugin.test
class GradleDependencyGenerator {
static final String STANDARD_SUBPROJECT_BLOCK = '''\
subprojects {
apply plugin: 'maven-publish'
apply plugin: 'java'
publishing {
repositories {
maven {
url "../mavenrepo"
}
}
publications {
maven(MavenPublication) {
from components.java
}
}
}
}
'''.stripIndent()
static final String BUILD_GRADLE = 'build.gradle'
private boolean generated = false
DependencyGraph graph
File gradleRoot
File mavenRepoDir
GradleDependencyGenerator(DependencyGraph graph, String directory = 'build/testrepogen') {
this.graph = graph
this.gradleRoot = new File(directory)
this.mavenRepoDir = new File(directory, 'mavenrepo')
generateGradleFiles()
}
File generateTestMavenRepo() {
runTasks('publishMavenPublicationToMavenRepository')
mavenRepoDir
}
String getMavenRepoDirPath() {
mavenRepoDir.absolutePath
}
String getMavenRepoUrl() {
mavenRepoDir.toURI().toURL()
}
String getMavenRepositoryBlock() {
"""\
maven { url '${getMavenRepoUrl()}' }
""".stripIndent()
}
private void generateGradleFiles() {
if (generated) {
return
} else {
generated = true
}
gradleRoot.mkdirs()
def rootBuildGradle = new File(gradleRoot, BUILD_GRADLE)
rootBuildGradle.text = STANDARD_SUBPROJECT_BLOCK
def includes = []
graph.nodes.each { DependencyGraphNode n ->
String subName = "${n.group}.${n.artifact}_${n.version.replaceAll(/\./, '_')}"
includes << subName
def subfolder = new File(gradleRoot, subName)
subfolder.mkdir()
def subBuildGradle = new File(subfolder, BUILD_GRADLE)
subBuildGradle.text = generateSubBuildGradle(n)
}
def settingsGradle = new File(gradleRoot, 'settings.gradle')
settingsGradle.text = 'include ' + includes.collect { "'${it}'"}.join(', ')
}
private String generateSubBuildGradle(DependencyGraphNode node) {
StringWriter block = new StringWriter()
if (node.dependencies) {
block.withPrintWriter { writer ->
writer.println 'dependencies {'
node.dependencies.each { writer.println " compile '${it}'" }
writer.println '}'
}
}
"""\
group = '${node.group}'
version = '${node.version}'
ext { artifactName = '${node.artifact}' }
""".stripIndent() + block.toString()
}
private void runTasks(String tasks) {
def runner = GradleRunnerFactory.createTooling()
runner.run(gradleRoot, tasks.tokenize()).rethrowFailure()
}
}

View file

@ -1,10 +0,0 @@
package org.xbib.gradle.plugin.test
interface GradleHandle {
ExecutionResult run()
void registerBuildListener(GradleHandleBuildListener buildListener)
boolean isForkedProcess()
}

View file

@ -1,8 +0,0 @@
package org.xbib.gradle.plugin.test
interface GradleHandleBuildListener {
void buildStarted()
void buildFinished()
}

View file

@ -1,8 +0,0 @@
package org.xbib.gradle.plugin.test
interface GradleHandleFactory {
GradleHandle start(File dir, List<String> arguments)
GradleHandle start(File dir, List<String> arguments, List<String> jvmArguments)
}

View file

@ -1,78 +0,0 @@
package org.xbib.gradle.plugin.test
import com.google.common.base.Predicate
import com.google.common.base.Predicates
import com.google.common.base.StandardSystemProperty
interface GradleRunner {
// These predicates are here, instead of on GradleRunnerFactory due to a Groovy static compiler bug
// https://issues.apache.org/jira/browse/GROOVY-7159
static final Predicate<URL> CLASSPATH_GRADLE_CACHE = new Predicate<URL>() {
@Override
boolean apply(URL url) {
return url.path.contains('/caches/modules-')
}
}
static final Predicate<URL> CLASSPATH_PROJECT_DIR = new Predicate<URL>() {
@Override
boolean apply(URL url) {
File userDir = new File(StandardSystemProperty.USER_DIR.value())
return url.path.startsWith(userDir.toURI().toURL().path)
}
}
static final Predicate<URL> CLASSPATH_PROJECT_DEPENDENCIES = new Predicate<URL>() {
@Override
boolean apply(URL url) {
return url.path.contains('/build/classes') ||
url.path.contains('/build/resources') ||
url.path.contains('/build/libs') ||
url.path.contains('/out/')
}
}
/**
* Attempts to provide a classpath that approximates the 'normal' Gradle runtime classpath. Use {@link #CLASSPATH_ALL}
* to default to pre-2.2.2 behaviour.
*/
static final Predicate<URL> CLASSPATH_DEFAULT =
Predicates.or(CLASSPATH_PROJECT_DIR, CLASSPATH_GRADLE_CACHE, CLASSPATH_PROJECT_DEPENDENCIES)
/**
* Accept all URLs. Provides pre-2.2.2 behaviour.
*/
static final Predicate<URL> CLASSPATH_ALL = new Predicate<URL>() {
@Override
boolean apply(URL url) {
return true
}
}
/**
* Create handle and run build
* @param directory
* @param args
* @return results from execution
*/
ExecutionResult run(File directory, List<String> args)
ExecutionResult run(File directory, List<String> args, List<String> jvmArgs)
ExecutionResult run(File directory, List<String> args, List<String> jvmArgs,
List<PreExecutionAction> preExecutionActions)
/**
* Handle on instance of Gradle that can be run.
* @param directory
* @param args
* @return handle
*/
GradleHandle handle(File directory, List<String> args)
GradleHandle handle(File directory, List<String> args, List<String> jvmArgs)
GradleHandle handle(File directory, List<String> args, List<String> jvmArgs,
List<PreExecutionAction> preExecutionActions)
}

View file

@ -1,26 +0,0 @@
package org.xbib.gradle.plugin.test
import com.google.common.base.Predicate
class GradleRunnerFactory {
static GradleRunner createTooling(boolean fork = false, String version = null,
Integer daemonMaxIdleTimeInSeconds = null,
Predicate<URL> classpathFilter = null) {
GradleHandleFactory toolingApiHandleFactory =
new ToolingApiGradleHandleFactory(fork, version, daemonMaxIdleTimeInSeconds)
return create(toolingApiHandleFactory, classpathFilter ?: GradleRunner.CLASSPATH_DEFAULT)
}
static GradleRunner create(GradleHandleFactory handleFactory, Predicate<URL> classpathFilter = null) {
ClassLoader sourceClassLoader = GradleRunnerFactory.class.getClassLoader()
create(handleFactory, sourceClassLoader, classpathFilter ?: GradleRunner.CLASSPATH_DEFAULT)
}
static GradleRunner create(GradleHandleFactory handleFactory, ClassLoader sourceClassLoader,
Predicate<URL> classpathFilter) {
GradleHandleFactory classpathInjectingHandleFactory =
new ClasspathInjectingGradleHandleFactory(sourceClassLoader, handleFactory, classpathFilter)
return new DefaultGradleRunner(classpathInjectingHandleFactory)
}
}

View file

@ -1,185 +0,0 @@
package org.xbib.gradle.plugin.test
import com.google.common.base.Predicate
import org.gradle.api.logging.LogLevel
abstract class IntegrationSpec extends BaseIntegrationSpec {
private static final String DEFAULT_REMOTE_DEBUG_JVM_ARGUMENTS = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"
private static final Integer DEFAULT_DAEMON_MAX_IDLE_TIME_IN_SECONDS_IN_MEMORY_SAFE_MODE = 15;
private ExecutionResult result
protected String gradleVersion
protected LogLevel logLevel = LogLevel.INFO
protected String moduleName
protected File settingsFile
protected File buildFile
protected boolean fork = false
protected boolean remoteDebug = false
protected List<String> jvmArguments = []
protected Predicate<URL> classpathFilter
protected List<File> initScripts = []
protected List<PreExecutionAction> preExecutionActions = []
//Shutdown Gradle daemon after a few seconds to release memory. Useful for testing with multiple Gradle versions on shared CI server
protected boolean memorySafeMode = false
protected Integer daemonMaxIdleTimeInSecondsInMemorySafeMode = DEFAULT_DAEMON_MAX_IDLE_TIME_IN_SECONDS_IN_MEMORY_SAFE_MODE
String findModuleName() {
getProjectDir().getName().replaceAll(/_\d+/, '')
}
def setup() {
moduleName = findModuleName()
if (!settingsFile) {
settingsFile = new File(getProjectDir(), 'settings.gradle')
settingsFile.text = "rootProject.name='${moduleName}'\n"
}
if (!buildFile) {
buildFile = new File(getProjectDir(), 'build.gradle')
}
buildFile << "// Running test for ${moduleName}\n"
}
protected GradleHandle launcher(String... args) {
List<String> arguments = calculateArguments(args)
List<String> jvmArguments = calculateJvmArguments()
Integer daemonMaxIdleTimeInSeconds = calculateMaxIdleDaemonTimeoutInSeconds()
GradleRunner runner = GradleRunnerFactory.createTooling(fork, gradleVersion, daemonMaxIdleTimeInSeconds, classpathFilter)
runner.handle(getProjectDir(), arguments, jvmArguments, preExecutionActions)
}
List<String> calculateArguments(String... args) {
List<String> arguments = []
// Gradle will use these files name from the PWD, instead of the project directory. It's easier to just leave
// them out and let the default find them, since we're not changing their default names.
//arguments += '--build-file'
//arguments += (buildFile.canonicalPath - projectDir.canonicalPath).substring(1)
//arguments += '--settings-file'
//arguments += (settingsFile.canonicalPath - projectDir.canonicalPath).substring(1)
//arguments += '--no-daemon'
switch (getLogLevel()) {
case LogLevel.INFO:
arguments += '--info'
break
case LogLevel.DEBUG:
arguments += '--debug'
break
}
arguments += '--stacktrace'
arguments.addAll(args)
arguments.addAll(initScripts.collect { file -> '-I' + file.absolutePath })
arguments
}
private List<String> calculateJvmArguments() {
return jvmArguments + (remoteDebug ? [DEFAULT_REMOTE_DEBUG_JVM_ARGUMENTS] : [] as List) as List
}
private Integer calculateMaxIdleDaemonTimeoutInSeconds() {
return memorySafeMode ? daemonMaxIdleTimeInSecondsInMemorySafeMode : null
}
protected void addInitScript(File initFile) {
initScripts.add(initFile)
}
protected void addPreExecute(PreExecutionAction preExecutionAction) {
preExecutionActions.add(preExecutionAction)
}
/**
* Override to alter its value
* @return
*/
protected LogLevel getLogLevel() {
return logLevel
}
/*protected void copyResources(String srcDir, String destination) {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(srcDir);
if (resource == null) {
throw new RuntimeException("Could not find classpath resource: $srcDir")
}
File destinationFile = file(destination)
File resourceFile = new File(resource.toURI())
if (resourceFile.file) {
FileUtils.copyFile(resourceFile, destinationFile)
} else {
FileUtils.copyDirectory(resourceFile, destinationFile)
}
}*/
protected String applyPlugin(Class pluginClass) {
"apply plugin: $pluginClass.name"
}
/* Checks */
protected boolean fileExists(String path) {
new File(projectDir, path).exists()
}
@Deprecated
protected boolean wasExecuted(String taskPath) {
result.wasExecuted(taskPath)
}
@Deprecated
protected boolean wasUpToDate(String taskPath) {
result.wasUpToDate(taskPath)
}
@Deprecated
protected String getStandardError() {
result.standardError
}
@Deprecated
protected String getStandardOutput() {
result.standardOutput
}
protected ExecutionResult runTasksSuccessfully(String... tasks) {
ExecutionResult result = runTasks(tasks)
if (result.failure) {
result.rethrowFailure()
}
result
}
protected ExecutionResult runTasksWithFailure(String... tasks) {
ExecutionResult result = runTasks(tasks)
assert result.failure
result
}
protected ExecutionResult runTasks(String... tasks) {
ExecutionResult result = launcher(tasks).run()
this.result = result
return checkForDeprecations(result)
}
protected ExecutionResult checkForDeprecations(ExecutionResult result) {
checkForDeprecations(result.standardOutput)
return result
}
File getSettingsFile() {
return settingsFile
}
}

View file

@ -1,22 +0,0 @@
package org.xbib.gradle.plugin.test
import org.xbib.gradle.plugin.test.ExecutedTask
class MinimalExecutedTask implements ExecutedTask {
String path
boolean upToDate
boolean skipped
MinimalExecutedTask(String path, boolean upToDate, boolean skipped) {
this.path = path
this.upToDate = upToDate
this.skipped = skipped
}
String toString() {
"executed $path"
}
}

View file

@ -1,43 +0,0 @@
package org.xbib.gradle.plugin.test
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
class MultiProjectHelper {
Project parent
MultiProjectHelper(Project parent) {
this.parent = parent
}
Map<String, MultiProjectInfo> create(Collection<String> projectNames) {
Map<String, MultiProjectInfo> info = [:]
projectNames.each {
def subproject = ProjectBuilder.builder().withName(it).withParent(parent).build()
info[it] = new MultiProjectInfo(name: it, project: subproject, parent: parent)
}
info
}
Map<String, MultiProjectInfo> createWithDirectories(Collection<String> projectNames) {
Map<String, MultiProjectInfo> info = [:]
projectNames.each {
def subDirectory = new File(parent.projectDir, it)
subDirectory.mkdirs()
def subproject = ProjectBuilder.builder().withName(it).withProjectDir(subDirectory).withParent(parent).build()
info[it] = new MultiProjectInfo(name: it, project: subproject, parent: parent, directory: subDirectory)
}
info
}
Project addSubproject(String name) {
ProjectBuilder.builder().withName(name).withParent(parent).build()
}
Project addSubprojectWithDirectory(String name) {
def dir = new File(parent.projectDir, name)
dir.mkdirs()
ProjectBuilder.builder().withName(name).withProjectDir(dir).withParent(parent).build()
}
}

View file

@ -1,14 +0,0 @@
package org.xbib.gradle.plugin.test
import org.gradle.api.Project
class MultiProjectInfo {
String name
Project parent
Project project
File directory
}

View file

@ -1,6 +0,0 @@
package org.xbib.gradle.plugin.test
interface PreExecutionAction {
void execute(File projectDir, List<String> arguments, List<String> jvmArguments)
}

View file

@ -1,8 +0,0 @@
package org.xbib.gradle.plugin.test
class ProjectSpec extends AbstractProjectSpec {
File getProjectDir() {
ourProjectDir
}
}

View file

@ -1,113 +0,0 @@
package org.xbib.gradle.plugin.test
import org.gradle.tooling.BuildLauncher
import org.gradle.tooling.GradleConnector
import org.gradle.tooling.ProjectConnection
import java.util.concurrent.TimeUnit
class ToolingApiGradleHandleFactory implements GradleHandleFactory {
private final boolean fork
private final String version
private final Integer daemonMaxIdleTimeInSeconds
ToolingApiGradleHandleFactory(boolean fork, String version, Integer daemonMaxIdleTimeInSeconds = null) {
this.fork = fork
this.version = version
this.daemonMaxIdleTimeInSeconds = daemonMaxIdleTimeInSeconds
}
@Override
GradleHandle start(File projectDir, List<String> arguments, List<String> jvmArguments = []) {
GradleConnector connector = createGradleConnector(projectDir)
boolean forkedProcess = isForkedProcess()
connector.embedded(!forkedProcess)
if (daemonMaxIdleTimeInSeconds != null) {
connector.daemonMaxIdleTime(daemonMaxIdleTimeInSeconds, TimeUnit.SECONDS)
}
ProjectConnection connection = connector.connect();
BuildLauncher launcher = createBuildLauncher(connection, arguments, jvmArguments)
createGradleHandle(connection, launcher, forkedProcess)
}
private GradleConnector createGradleConnector(File projectDir) {
GradleConnector connector = GradleConnector.newConnector();
connector.forProjectDirectory(projectDir);
configureGradleVersion(connector, projectDir)
connector
}
private void configureGradleVersion(GradleConnector connector, File projectDir) {
if (version != null) {
connector.useGradleVersion(version)
} else {
configureWrapperDistributionIfUsed(connector, projectDir)
}
}
private static void configureWrapperDistributionIfUsed(GradleConnector connector, File projectDir) {
File target = projectDir.absoluteFile
while (target != null) {
URI distribution = prepareDistributionURI(target)
if (distribution) {
connector.useDistribution(distribution)
return
}
target = target.parentFile
}
}
private static URI prepareDistributionURI(File target) {
File propertiesFile = new File(target, "gradle/wrapper/gradle-wrapper.properties")
if (propertiesFile.exists()) {
Properties properties = new Properties()
propertiesFile.withInputStream {
properties.load(it)
}
URI source = new URI(properties.getProperty("distributionUrl"))
return source.getScheme() == null ? (new File(propertiesFile.getParentFile(), source.getSchemeSpecificPart())).toURI() : source;
}
return null
}
private boolean isForkedProcess() {
fork
}
private static BuildLauncher createBuildLauncher(ProjectConnection connection, List<String> arguments,
List<String> jvmArguments) {
BuildLauncher launcher = connection.newBuild();
launcher.withArguments(arguments as String[]);
launcher.setJvmArguments(jvmArguments as String[])
launcher
}
private GradleHandle createGradleHandle(ProjectConnection connection, BuildLauncher launcher, boolean forkedProcess) {
GradleHandleBuildListener toolingApiBuildListener =
new ToolingApiBuildListener(connection)
BuildLauncherBackedGradleHandle buildLauncherBackedGradleHandle =
new BuildLauncherBackedGradleHandle(launcher, forkedProcess)
buildLauncherBackedGradleHandle.registerBuildListener(toolingApiBuildListener)
buildLauncherBackedGradleHandle
}
private class ToolingApiBuildListener implements GradleHandleBuildListener {
private final ProjectConnection connection
ToolingApiBuildListener(ProjectConnection connection) {
this.connection = connection
}
@Override
void buildStarted() {
}
@Override
void buildFinished() {
connection.close()
}
}
}

View file

@ -1,12 +0,0 @@
package org.xbib.gradle.plugin.test
/**
* Hold additional response data, that is only available
*/
class ToolingExecutionResult extends DefaultExecutionResult {
ToolingExecutionResult(Boolean success, String standardOutput, String standardError,
List<MinimalExecutedTask> executedTasks, Throwable failure) {
super(success, standardOutput, standardError, executedTasks, failure)
}
}

View file

@ -1,119 +0,0 @@
import org.junit.Rule
import org.junit.rules.TestName
import spock.lang.Specification
abstract class BaseIntegrationSpec extends Specification {
@Rule
TestName testName = new TestName()
File projectDir
def setup() {
projectDir = new File("build/xbibtest/${this.class.canonicalName}/${testName.methodName.replaceAll(/\W+/, '-')}").absoluteFile
if (projectDir.exists()) {
projectDir.deleteDir()
}
projectDir.mkdirs()
}
protected File directory(String path, File baseDir = getProjectDir()) {
new File(baseDir, path).with {
mkdirs()
it
}
}
protected File file(String path, File baseDir = getProjectDir()) {
def splitted = path.split('/')
def directory = splitted.size() > 1 ? directory(splitted[0..-2].join('/'), baseDir) : baseDir
def file = new File(directory, splitted[-1])
file.createNewFile()
file
}
protected File createFile(String path, File baseDir = getProjectDir()) {
File file = file(path, baseDir)
if (!file.exists()) {
assert file.parentFile.mkdirs() || file.parentFile.exists()
file.createNewFile()
}
file
}
protected static void checkForDeprecations(String output) {
def deprecations = output.readLines().findAll {
it.contains("has been deprecated and is scheduled to be removed in Gradle")
}
if (!System.getProperty("ignoreDeprecations") && !deprecations.isEmpty()) {
throw new IllegalArgumentException("Deprecation warnings were found (Set the ignoreDeprecations system property during the test to ignore):\n" + deprecations.collect {
" - $it"
}.join("\n"))
}
}
protected void writeHelloWorld(String packageDotted, File baseDir = getProjectDir()) {
def path = 'src/main/java/' + packageDotted.replace('.', '/') + '/HelloWorld.java'
def javaFile = createFile(path, baseDir)
javaFile << """\
package ${packageDotted};
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello Integration Test");
}
}
""".stripIndent()
}
/**
* Creates a unit test for testing your plugin.
* @param failTest true if you want the test to fail, false if the test should pass
* @param baseDir the directory to begin creation from, defaults to projectDir
*/
protected void writeUnitTest(boolean failTest, File baseDir = getProjectDir()) {
writeTest('src/test/java/', 'nebula', failTest, baseDir)
}
/**
*
* Creates a unit test for testing your plugin.
* @param srcDir the directory in the project where the source file should be created.
* @param packageDotted the package for the unit test class, written in dot notation (ex. - nebula.integration)
* @param failTest true if you want the test to fail, false if the test should pass
* @param baseDir the directory to begin creation from, defaults to projectDir
*/
protected void writeTest(String srcDir, String packageDotted, boolean failTest, File baseDir = getProjectDir()) {
def path = srcDir + packageDotted.replace('.', '/') + '/HelloWorldTest.java'
def javaFile = createFile(path, baseDir)
javaFile << """\
package ${packageDotted};
import org.junit.Test;
import static org.junit.Assert.assertFalse;
public class HelloWorldTest {
@Test public void doesSomething() {
assertFalse( $failTest );
}
}
""".stripIndent()
}
/**
* Creates a properties file to included as project resource.
* @param srcDir the directory in the project where the source file should be created.
* @param fileName to be used for the file, sans extension. The .properties extension will be added to the name.
* @param baseDir the directory to begin creation from, defaults to projectDir
*/
protected void writeResource(String srcDir, String fileName, File baseDir = getProjectDir()) {
def path = "$srcDir/${fileName}.properties"
def resourceFile = createFile(path, baseDir)
resourceFile.text = "firstProperty=foo.bar"
}
protected void addResource(String srcDir, String filename, String contents, File baseDir = getProjectDir()) {
def resourceFile = createFile("${srcDir}/${filename}", baseDir)
resourceFile.text = contents
}
}

View file

@ -0,0 +1,24 @@
* Tue Feb 24 2015 George Washington
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua
* Tue Feb 10 2015 George Washington
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
* Mon Nov 17 2014 George Washington
consectetur, adipisci velit, sed quia non numquam eius modi
sunt explicabo. Nemo enim ipsam voluptatem quia vol
eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat
Excepteur sint occaecat cupidatat non proident, sunt
* Fri Mar 06 2009 John Adams
- nostrum exercitationem ullam corporis suscipit
* Thu Oct 16 2008 Thomas Jefferson
- Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit,
* Thu Aug 23 2007 James Madison
eaque ipsa quae ab illo inventore veritatis et quasi architecto
* Mon Jun 04 2007 James Monroe
- adipisci velit, sed q
* Tue May 08 2007 James Madison
- dolore eu fugiat nulla pariatur
* Tue Apr 10 2007 James Monroe
-+// quis nostrum exercitationem ullam corporis
* Wed Nov 08 2006 James Madison
- Initial rpm for this package

View file

@ -0,0 +1,2 @@
#!/usr/bin/env bash
echo 'Hello from file'

View file

@ -1,21 +1,17 @@
group = org.xbib
name = rpm
version = 1.1.0
version = 2.0.0
bouncycastle.version = 1.60
xbib-archive.version = 0.0.1
ant.version = 1.10.5
log4j.version = 2.11.1
# must match groovy version in gradle
groovy.version = 2.5.4
spock-core.version = 1.2-groovy-2.5
xbib-guice.version = 4.0.4
maven.version = 3.5.0
maven-plugin-annotations.version = 3.5
maven-plugin-plugin.version = 3.5
mvel.version = 2.4.0.Final
junit.version = 4.12
wagon.version = 3.0.0
org.gradle.warning.mode=all
gradle.wrapper.version = 6.4.1
gradle.publish.plugin.version = 0.11.0
bouncycastle.version = 1.64
xbib-archive.version = 1.0.0
ant.version = 1.10.8
maven.version = 3.6.3
maven-plugin-annotations.version = 3.6.0
maven-plugin-plugin.version = 3.6.0
maven-wagon.version = 3.3.4
aether-connector-basic.version = 1.1.0
aether-transport-wagon.version = 1.1.0
slf4j.version = 1.7.25
mvel.version = 2.4.5.Final

View file

@ -0,0 +1,35 @@
apply plugin: 'java-library'
java {
modularity.inferModulePath.set(true)
}
compileJava {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
compileTestJava {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
jar {
manifest {
attributes('Implementation-Version': project.version)
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier 'javadoc'
}
artifacts {
archives sourcesJar, javadocJar
}

View file

@ -0,0 +1,55 @@
apply plugin: 'org.xbib.gradle.plugin.asciidoctor'
configurations {
asciidoclet
}
dependencies {
asciidoclet "org.asciidoctor:asciidoclet:${project.property('asciidoclet.version')}"
}
asciidoctor {
backends 'html5'
outputDir = file("${rootProject.projectDir}/docs")
separateOutputDirs = false
attributes 'source-highlighter': 'coderay',
idprefix: '',
idseparator: '-',
toc: 'left',
doctype: 'book',
icons: 'font',
encoding: 'utf-8',
sectlink: true,
sectanchors: true,
linkattrs: true,
imagesdir: 'img',
stylesheet: "${projectDir}/src/docs/asciidoc/css/foundation.css"
}
/*javadoc {
options.docletpath = configurations.asciidoclet.files.asType(List)
options.doclet = 'org.asciidoctor.Asciidoclet'
//options.overview = "src/docs/asciidoclet/overview.adoc"
options.addStringOption "-base-dir", "${projectDir}"
options.addStringOption "-attribute",
"name=${project.name},version=${project.version},title-link=https://github.com/xbib/${project.name}"
configure(options) {
noTimestamp = true
}
}*/
/*javadoc {
options.docletpath = configurations.asciidoclet.files.asType(List)
options.doclet = 'org.asciidoctor.Asciidoclet'
options.overview = "${rootProject.projectDir}/src/docs/asciidoclet/overview.adoc"
options.addStringOption "-base-dir", "${projectDir}"
options.addStringOption "-attribute",
"name=${project.name},version=${project.version},title-link=https://github.com/xbib/${project.name}"
options.destinationDirectory(file("${projectDir}/docs/javadoc"))
configure(options) {
noTimestamp = true
}
}*/

View file

13
gradle/ide/idea.gradle Normal file
View file

@ -0,0 +1,13 @@
apply plugin: 'idea'
idea {
module {
outputDir file('build/classes/java/main')
testOutputDir file('build/classes/java/test')
}
}
if (project.convention.findPlugin(JavaPluginConvention)) {
//sourceSets.main.output.classesDirs = file("build/classes/java/main")
//sourceSets.test.output.classesDirs = file("build/classes/java/test")
}

View file

@ -1,85 +0,0 @@
apply plugin: 'signing'
configurations {
wagon
}
dependencies {
wagon "org.apache.maven.wagon:wagon-ssh:${project.property('wagon.version')}"
}
if (project.hasProperty('signing.keyId')) {
signing {
sign configurations.archives
}
}
task xbibUpload(type: Upload) {
group = 'publish'
configuration = configurations.archives
uploadDescriptor = true
repositories {
if (project.hasProperty('xbibUsername')) {
mavenDeployer {
configuration = configurations.wagon
repository(url: uri('sftp://xbib.org/repository')) {
authentication(userName: xbibUsername, privateKey: xbibPrivateKey)
}
}
}
}
}
task sonatypeUpload(type: Upload) {
group = 'publish'
configuration = configurations.archives
uploadDescriptor = true
repositories {
if (project.hasProperty('ossrhUsername')) {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repository(url: uri(ossrhReleaseUrl)) {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
snapshotRepository(url: uri(ossrhSnapshotUrl)) {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
pom.project {
name projectName
description projectDescription
packaging 'jar'
inceptionYear '2017'
url scmUrl
organization {
name 'xbib'
url 'http://xbib.org'
}
developers {
developer {
id user
name 'Jörg Prante'
email 'joergprante@gmail.com'
url 'https://github.com/jprante'
}
}
scm {
url scmUrl
connection scmConnection
developerConnection scmDeveloperConnection
}
licenses {
license {
name 'The Apache License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
}
}
}
}
}
nexusStaging {
packageGroup = "org.xbib"
}

View file

@ -0,0 +1,64 @@
apply plugin: "de.marcphilipp.nexus-publish"
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
artifact sourcesJar
artifact javadocJar
pom {
name = project.name
description = rootProject.ext.description
url = rootProject.ext.url
inceptionYear = rootProject.ext.inceptionYear
packaging = 'jar'
organization {
name = 'xbib'
url = 'https://xbib.org'
}
developers {
developer {
id = 'jprante'
name = 'Jörg Prante'
email = 'joergprante@gmail.com'
url = 'https://github.com/jprante'
}
}
scm {
url = rootProject.ext.scmUrl
connection = rootProject.ext.scmConnection
developerConnection = rootProject.ext.scmDeveloperConnection
}
issueManagement {
system = rootProject.ext.issueManagementSystem
url = rootProject.ext.issueManagementUrl
}
licenses {
license {
name = rootProject.ext.licenseName
url = rootProject.ext.licenseUrl
distribution = 'repo'
}
}
}
}
}
}
if (project.hasProperty("signing.keyId")) {
apply plugin: 'signing'
signing {
sign publishing.publications.mavenJava
}
}
nexusPublishing {
repositories {
sonatype {
username = project.property('ossrhUsername')
password = project.property('ossrhPassword')
packageGroup = "org.xbib"
}
}
}

View file

@ -0,0 +1,11 @@
if (project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword')) {
apply plugin: 'io.codearte.nexus-staging'
nexusStaging {
username = project.property('ossrhUsername')
password = project.property('ossrhPassword')
packageGroup = "org.xbib"
}
}

28
gradle/test/junit5.gradle Normal file
View file

@ -0,0 +1,28 @@
def junitVersion = project.hasProperty('junit.version')?project.property('junit.version'):'5.6.2'
def hamcrestVersion = project.hasProperty('hamcrest.version')?project.property('hamcrest.version'):'2.2'
dependencies {
testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}"
testImplementation "org.junit.jupiter:junit-jupiter-params:${junitVersion}"
testImplementation "org.hamcrest:hamcrest-library:${hamcrestVersion}"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junitVersion}"
}
test {
useJUnitPlatform()
failFast = true
testLogging {
showStandardStreams = true
events 'STARTED', 'PASSED', 'FAILED', 'SKIPPED'
}
afterSuite { desc, result ->
if (!desc.parent) {
println "\nTest result: ${result.resultType}"
println "Test summary: ${result.testCount} tests, " +
"${result.successfulTestCount} succeeded, " +
"${result.failedTestCount} failed, " +
"${result.skippedTestCount} skipped"
}
}
}

Binary file not shown.

View file

@ -1,6 +1,5 @@
#Thu Jan 10 23:25:32 CET 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1-all.zip

53
gradlew vendored
View file

@ -1,5 +1,21 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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.
#
##############################################################################
##
## Gradle start up script for UN*X
@ -28,7 +44,7 @@ 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"'
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@ -66,6 +82,7 @@ esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
@ -109,10 +126,11 @@ if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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
@ -138,19 +156,19 @@ if $cygwin ; then
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
i=`expr $i + 1`
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" ;;
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
@ -159,14 +177,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
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")"
fi
exec "$JAVACMD" "$@"

22
gradlew.bat vendored
View file

@ -1,3 +1,19 @@
@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
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@ -13,8 +29,11 @@ if "%DIRNAME%" == "" set DIRNAME=.
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"
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@ -65,6 +84,7 @@ set CMD_LINE_ARGS=%*
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%

View file

@ -1,33 +1,31 @@
apply plugin: 'maven'
// for this script, see https://gist.github.com/fikovnik/ffc1fed1867bc7fa679aaf8e48f00c21
configurations {
mavenEmbedder
}
dependencies {
compile project(':rpm-core')
compile "org.mvel:mvel2:${project.property('mvel.version')}"
compile "org.apache.ant:ant:${project.property('ant.version')}"
api project(':rpm-core')
api "org.apache.ant:ant:${project.property('ant.version')}"
implementation "org.mvel:mvel2:${project.property('mvel.version')}"
compileOnly "org.apache.maven:maven-core:${project.property('maven.version')}"
compileOnly "org.apache.maven:maven-plugin-api:${project.property('maven.version')}"
compileOnly "org.apache.maven.plugin-tools:maven-plugin-annotations:${project.property('maven-plugin-annotations.version')}"
testCompile "org.apache.maven:maven-core:${project.property('maven.version')}"
testCompile "org.apache.maven:maven-plugin-api:${project.property('maven.version')}"
testCompile "org.apache.maven.plugin-tools:maven-plugin-annotations:${project.property('maven-plugin-annotations.version')}"
testImplementation "org.apache.maven:maven-core:${project.property('maven.version')}"
testImplementation "org.apache.maven:maven-plugin-api:${project.property('maven.version')}"
testImplementation "org.apache.maven.plugin-tools:maven-plugin-annotations:${project.property('maven-plugin-annotations.version')}"
mavenEmbedder "org.apache.maven:maven-embedder:${project.property('maven.version')}"
mavenEmbedder "org.slf4j:slf4j-simple:1.7.25"
mavenEmbedder "org.apache.maven.wagon:wagon-http:3.1.0:shaded"
mavenEmbedder "org.apache.maven.wagon:wagon-provider-api:3.1.0"
mavenEmbedder "org.eclipse.aether:aether-connector-basic:1.1.0"
mavenEmbedder "org.eclipse.aether:aether-transport-wagon:1.1.0"
mavenEmbedder "org.apache.maven:maven-compat:${project.property('maven.version')}"
mavenEmbedder "org.slf4j:slf4j-simple:${project.property('slf4j.version')}"
mavenEmbedder "org.apache.maven.wagon:wagon-http:${project.property('maven-wagon.version')}:shaded"
mavenEmbedder "org.apache.maven.wagon:wagon-provider-api:${project.property('maven-wagon.version')}"
mavenEmbedder "org.eclipse.aether:aether-connector-basic:${project.property('aether-connector-basic.version')}"
mavenEmbedder "org.eclipse.aether:aether-transport-wagon:${project.property('aether-transport-wagon.version')}"
}
test {
testLogging {
showStandardStreams = false
exceptionFormat = 'full'
}
systemProperty 'project.build.testOutputDirectory', project.buildDir.path + "/resources/test"
}
@ -52,7 +50,7 @@ task generatePluginDescriptor(type: JavaExec, dependsOn: compileJava) {
'--update-snapshots',
'--errors',
'--batch-mode',
'--settings', '../config/maven/repo-settings.xml',
'--settings', "${project.projectDir}/config/maven/repo-settings.xml",
'--file', "${buildDir}/pom.xml",
"org.apache.maven.plugins:maven-plugin-plugin:${project.property('maven-plugin-plugin.version')}:descriptor"
]

View file

@ -1,323 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!-- This is a checkstyle configuration file. For descriptions of
what the following rules do, please see the checkstyle configuration
page at http://checkstyle.sourceforge.net/config.html -->
<module name="Checker">
<module name="FileTabCharacter">
<!-- Checks that there are no tab characters in the file.
-->
</module>
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf"/>
</module>
<module name="RegexpSingleline">
<!-- Checks that FIXME is not used in comments. TODO is preferred.
-->
<property name="format" value="((//.*)|(\*.*))FIXME" />
<property name="message" value='TODO is preferred to FIXME. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="RegexpSingleline">
<!-- Checks that TODOs are named. (Actually, just that they are followed
by an open paren.)
-->
<property name="format" value="((//.*)|(\*.*))TODO[^(]" />
<property name="message" value='All TODOs should be named. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="JavadocPackage">
<!-- Checks that each Java package has a Javadoc file used for commenting.
Only allows a package-info.java, not package.html. -->
</module>
<!-- All Java AST specific tests live under TreeWalker module. -->
<module name="TreeWalker">
<!--
IMPORT CHECKS
-->
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<module name="ImportOrder">
<!-- Checks for out of order import statements. -->
<property name="severity" value="warning"/>
<property name="groups" value="com.google,android,junit,net,org,java,javax"/>
<!-- This ensures that static imports go first. -->
<property name="option" value="top"/>
<property name="tokens" value="STATIC_IMPORT, IMPORT"/>
</module>
<!--
JAVADOC CHECKS
-->
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
<module name="JavadocMethod">
<property name="scope" value="protected"/>
<property name="severity" value="warning"/>
<property name="allowMissingJavadoc" value="true"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowUndeclaredRTE" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="protected"/>
<property name="severity" value="error"/>
</module>
<module name="JavadocStyle">
<property name="severity" value="warning"/>
</module>
<!--
NAMING CHECKS
-->
<!-- Item 38 - Adhere to generally accepted naming conventions -->
<module name="PackageName">
<!-- Validates identifiers for package names against the
supplied expression. -->
<!-- Here the default checkstyle rule restricts package name parts to
seven characters, this is not in line with common practice at Google.
-->
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]{1,})*$"/>
<property name="severity" value="warning"/>
</module>
<module name="TypeNameCheck">
<!-- Validates static, final fields against the
expression "^[A-Z][a-zA-Z0-9]*$". -->
<metadata name="altname" value="TypeName"/>
<property name="severity" value="warning"/>
</module>
<module name="ConstantNameCheck">
<!-- Validates non-private, static, final fields against the supplied
public/package final fields "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$". -->
<metadata name="altname" value="ConstantName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="false"/>
<property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|FLAG_.*)$"/>
<message key="name.invalidPattern"
value="Variable ''{0}'' should be in ALL_CAPS (if it is a constant) or be private (otherwise)."/>
<property name="severity" value="warning"/>
</module>
<module name="StaticVariableNameCheck">
<!-- Validates static, non-final fields against the supplied
expression "^[a-z][a-zA-Z0-9]*_?$". -->
<metadata name="altname" value="StaticVariableName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
<property name="severity" value="warning"/>
</module>
<module name="MemberNameCheck">
<!-- Validates non-static members against the supplied expression. -->
<metadata name="altname" value="MemberName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
<property name="severity" value="warning"/>
</module>
<module name="MethodNameCheck">
<!-- Validates identifiers for method names. -->
<metadata name="altname" value="MethodName"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$"/>
<property name="severity" value="warning"/>
</module>
<module name="ParameterName">
<!-- Validates identifiers for method parameters against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalFinalVariableName">
<!-- Validates identifiers for local final variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalVariableName">
<!-- Validates identifiers for local variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<!--
LENGTH and CODING CHECKS
-->
<module name="LineLength">
<!-- Checks if a line is too long. -->
<property name="max" value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.max}" default="128"/>
<property name="severity" value="error"/>
<!--
The default ignore pattern exempts the following elements:
- import statements
- long URLs inside comments
-->
<property name="ignorePattern"
value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.ignorePattern}"
default="^(package .*;\s*)|(import .*;\s*)|( *(\*|//).*https?://.*)$"/>
</module>
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
<module name="RightCurly">
<!-- Checks right curlies on CATCH, ELSE, and TRY blocks are on
the same line. e.g., the following example is fine:
<pre>
if {
...
} else
</pre>
-->
<!-- This next example is not fine:
<pre>
if {
...
}
else
</pre>
-->
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
<!-- Checks for braces around if and else blocks -->
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"/>
</module>
<module name="UpperEll">
<!-- Checks that long constants are defined with an upper ell.-->
<property name="severity" value="error"/>
</module>
<module name="FallThrough">
<!-- Warn about falling through to the next case statement. Similar to
javac -Xlint:fallthrough, but the check is suppressed if a single-line comment
on the last non-blank line preceding the fallen-into case contains 'fall through' (or
some other variants which we don't publicized to promote consistency).
-->
<property name="reliefPattern"
value="fall through|Fall through|fallthru|Fallthru|falls through|Falls through|fallthrough|Fallthrough|No break|NO break|no break|continue on"/>
<property name="severity" value="error"/>
</module>
<!--
MODIFIERS CHECKS
-->
<module name="ModifierOrder">
<!-- Warn if modifier order is inconsistent with JLS3 8.1.1, 8.3.1, and
8.4.3. The prescribed order is:
public, protected, private, abstract, static, final, transient, volatile,
synchronized, native, strictfp
-->
</module>
<!--
WHITESPACE CHECKS
-->
<module name="WhitespaceAround">
<!-- Checks that various tokens are surrounded by whitespace.
This includes most binary operators and keywords followed
by regular or curly braces.
-->
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR,
BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN,
EQUAL, GE, GT, LAND, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE,
LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN,
LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS,
MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION,
SL, SL_ASSIGN, SR_ASSIGN, STAR, STAR_ASSIGN"/>
<property name="severity" value="error"/>
</module>
<module name="WhitespaceAfter">
<!-- Checks that commas, semicolons and typecasts are followed by
whitespace.
-->
<property name="tokens" value="COMMA, SEMI, TYPECAST"/>
</module>
<module name="NoWhitespaceAfter">
<!-- Checks that there is no whitespace after various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS,
UNARY_PLUS"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="NoWhitespaceBefore">
<!-- Checks that there is no whitespace before various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="SEMI, DOT, POST_DEC, POST_INC"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="ParenPad">
<!-- Checks that there is no whitespace before close parens or after
open parens.
-->
<property name="severity" value="warning"/>
</module>
</module>
</module>

View file

@ -9,7 +9,7 @@
<repositories>
<repository>
<id>xbib</id>
<url>http://xbib.org/repository</url>
<url>https://xbib.org/repository</url>
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>

View file

@ -1120,7 +1120,7 @@ public class RpmPackage {
builder.setBuildHost(getBuildHostName());
builder.setPackager(getPackager());
builder.setUrl(getUrl());
builder.setPrefixes(getPrefixes().toArray(new String[0]));
builder.setPrefixes(getPrefixes());
builder.setSourceRpm(getSourceRpm());
for (String builtin : getBuiltins()) {
builder.addBuiltinDirectory(builtin);
@ -1183,7 +1183,9 @@ public class RpmPackage {
}
for (RpmLink link : getLinks()) {
builder.addLink(link.getPath(), link.getTarget(),
link.getPermissionsOrDefault(), link.getOwnerOrDefault(), link.getGroupOrDefault());
link.getPermissionsOrDefault(),
link.getOwnerOrDefault(),
link.getGroupOrDefault());
}
getLog().debug("Setting trigger scripts");
RpmScriptTemplateRenderer scriptTemplateRenderer = getMojo().getTemplateRenderer();

View file

@ -251,8 +251,8 @@ public class RpmPackageRule extends RpmBaseObject {
getLog().debug(String.format("Adding file: %s to path %s with owner '%s', " +
"group '%s', with file mode %o.",
sourcePath, destinationPath, owner, group, fileMode));
builder.addFile(destinationPath, Paths.get(sourcePath), fileMode,
getDirectives(), owner, group);
builder.addFile(destinationPath, Paths.get(sourcePath), fileMode, -1,
getDirectives(), owner, group, true);
}
return includedFiles;
}

View file

@ -1,8 +1,7 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
*

View file

@ -4,7 +4,7 @@ import org.apache.maven.monitor.logging.DefaultLog;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.xbib.maven.plugin.rpm.mojo.PackageRpmMojo;
import java.io.File;
@ -16,7 +16,7 @@ public class RpmLinkTest extends RpmBaseObjectTest {
private RpmLink rpmLink;
@Before
@BeforeEach
public void setUp() throws Exception {
String testOutputPath = System.getProperty("project.build.testOutputDirectory");
PackageRpmMojo mojo = new PackageRpmMojo();

View file

@ -1,9 +1,9 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
*
@ -12,69 +12,69 @@ public class RpmPackageAssociationTest {
private RpmPackageAssociation association;
@Before
@BeforeEach
public void setUp() {
association = new RpmPackageAssociation();
}
@Test
public void nameAccessors() {
assertEquals(null, association.getName());
assertNull(association.getName());
association.setName("testname");
assertEquals("testname", association.getName());
}
@Test
public void unassignedVersion() {
assertEquals(null, association.getVersion());
assertEquals(null, association.getMinVersion());
assertEquals(null, association.getMaxVersion());
assertNull(association.getVersion());
assertNull(association.getMinVersion());
assertNull(association.getMaxVersion());
}
@Test
public void latestVersion() {
association.setVersion(null);
assertEquals(null, association.getVersion());
assertEquals(null, association.getMinVersion());
assertEquals(null, association.getMaxVersion());
assertNull(association.getVersion());
assertNull(association.getMinVersion());
assertNull(association.getMaxVersion());
association.setVersion("");
assertEquals(null, association.getVersion());
assertEquals(null, association.getMinVersion());
assertEquals(null, association.getMaxVersion());
assertNull(association.getVersion());
assertNull(association.getMinVersion());
assertNull(association.getMaxVersion());
association.setVersion("RELEASE");
assertEquals(null, association.getVersion());
assertEquals(null, association.getMinVersion());
assertEquals(null, association.getMaxVersion());
assertNull(association.getVersion());
assertNull(association.getMinVersion());
assertNull(association.getMaxVersion());
}
@Test
public void specificVersion() {
association.setVersion("1.2.3");
assertEquals("1.2.3", association.getVersion());
assertEquals(null, association.getMinVersion());
assertEquals(null, association.getMaxVersion());
assertNull(association.getMinVersion());
assertNull(association.getMaxVersion());
}
@Test
public void minVersionRange() {
association.setVersion("[1.2.3,)");
assertEquals(null, association.getVersion());
assertNull(association.getVersion());
assertEquals("1.2.3", association.getMinVersion());
assertEquals(null, association.getMaxVersion());
assertNull(association.getMaxVersion());
}
@Test
public void maxVersionRange() {
association.setVersion("[,1.2.3)");
assertEquals(null, association.getVersion());
assertEquals(null, association.getMinVersion());
assertNull(association.getVersion());
assertNull(association.getMinVersion());
assertEquals("1.2.3", association.getMaxVersion());
}
@Test
public void minMaxVersionRange() {
association.setVersion("[1.2.3,1.2.5)");
assertEquals(null, association.getVersion());
assertNull(association.getVersion());
assertEquals("1.2.3", association.getMinVersion());
assertEquals("1.2.5", association.getMaxVersion());
}

View file

@ -1,9 +1,8 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.xbib.rpm.exception.InvalidDirectiveException;
import org.xbib.rpm.payload.Directive;

View file

@ -1,14 +1,15 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.apache.maven.monitor.logging.DefaultLog;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.maven.plugin.rpm.mojo.PackageRpmMojo;
import org.xbib.rpm.exception.InvalidDirectiveException;
import org.xbib.rpm.exception.InvalidPathException;
@ -33,8 +34,8 @@ public class RpmPackageRuleTest extends RpmBaseObjectTest {
private RpmPackage rpmPackage;
@Before
public void setUp() throws Exception {
@BeforeEach
public void setUp() {
testOutputPath = System.getProperty("project.build.testOutputDirectory");
PackageRpmMojo mojo = new PackageRpmMojo();
mojo.setDefaultFileMode(0644);
@ -84,9 +85,9 @@ public class RpmPackageRuleTest extends RpmBaseObjectTest {
@Test
public void destinationAccessors() {
rpmFileRule.setDestination("");
assertEquals(null, rpmFileRule.getDestination());
assertNull(rpmFileRule.getDestination());
rpmFileRule.setDestination(null);
assertEquals(null, rpmFileRule.getDestination());
assertNull(rpmFileRule.getDestination());
assertEquals(String.format("%svar%swww%stest", File.separator, File.separator, File.separator),
rpmFileRule.getDestinationOrDefault());
rpmFileRule.setDestination(String.format("%sfoo", File.separator));
@ -131,10 +132,12 @@ public class RpmPackageRuleTest extends RpmBaseObjectTest {
assertEquals(62, files.length);
}
@Test(expected = PathOutsideBuildPathException.class)
@Test
public void testListFilesOutsideBuildPath() throws RpmException {
rpmFileRule.setBase(String.format("..%s", File.separator));
rpmFileRule.listFiles();
Assertions.assertThrows(PathOutsideBuildPathException.class, () -> {
rpmFileRule.setBase(String.format("..%s", File.separator));
rpmFileRule.listFiles();
});
}
@Test

View file

@ -1,21 +1,21 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.maven.model.Build;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.maven.plugin.rpm.mojo.PackageRpmMojo;
import org.xbib.rpm.exception.RpmException;
import org.xbib.rpm.exception.UnknownArchitectureException;
import org.xbib.rpm.exception.UnknownOperatingSystemException;
import org.xbib.rpm.lead.Architecture;
import org.xbib.rpm.lead.Os;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@ -34,7 +34,7 @@ public class RpmPackageTest {
private MavenProject project;
@Before
@BeforeEach
public void setUp() {
testOutputPath = System.getProperty("project.build.testOutputDirectory");
Build projectBuild = new Build();
@ -119,42 +119,42 @@ public class RpmPackageTest {
@Test
public void urlAccessors() {
assertEquals(null, rpmPackage.getUrl());
assertNull(rpmPackage.getUrl());
rpmPackage.setUrl("http://www.example.com/foo");
assertEquals("http://www.example.com/foo", rpmPackage.getUrl());
}
@Test
public void groupAccessors() {
assertEquals(null, rpmPackage.getGroup());
assertNull(rpmPackage.getGroup());
rpmPackage.setGroup("group/subgroup");
assertEquals("group/subgroup", rpmPackage.getGroup());
}
@Test
public void licenseAccessors() {
assertEquals(null, rpmPackage.getLicense());
assertNull(rpmPackage.getLicense());
rpmPackage.setLicense("license");
assertEquals("license", rpmPackage.getLicense());
}
@Test
public void summaryAccessors() {
assertEquals(null, rpmPackage.getSummary());
assertNull(rpmPackage.getSummary());
rpmPackage.setSummary("summary");
assertEquals("summary", rpmPackage.getSummary());
}
@Test
public void descriptionAccessors() {
assertEquals(null, rpmPackage.getDescription());
assertNull(rpmPackage.getDescription());
rpmPackage.setDescription("description");
assertEquals("description", rpmPackage.getDescription());
}
@Test
public void distributionAccessors() {
assertEquals(null, rpmPackage.getDistribution());
assertNull(rpmPackage.getDistribution());
rpmPackage.setDistribution("distribution");
assertEquals("distribution", rpmPackage.getDistribution());
}
@ -166,19 +166,22 @@ public class RpmPackageTest {
assertEquals(Architecture.SPARC, rpmPackage.getArchitecture());
}
@Test(expected = UnknownArchitectureException.class)
public void architectureInvalidException() throws UnknownArchitectureException {
rpmPackage.setArchitecture("NONEXISTENT");
@Test
public void architectureInvalidException() {
Assertions.assertThrows(UnknownArchitectureException.class, () ->
rpmPackage.setArchitecture("NONEXISTENT"));
}
@Test(expected = UnknownArchitectureException.class)
public void architectureBlankException() throws UnknownArchitectureException {
rpmPackage.setArchitecture("");
@Test
public void architectureBlankException() {
Assertions.assertThrows(UnknownArchitectureException.class, () ->
rpmPackage.setArchitecture(""));
}
@Test(expected = UnknownArchitectureException.class)
public void architectureNullException() throws UnknownArchitectureException {
rpmPackage.setArchitecture(null);
@Test
public void architectureNullException() {
Assertions.assertThrows(UnknownArchitectureException.class, () ->
rpmPackage.setArchitecture(null));
}
@Test
@ -188,19 +191,22 @@ public class RpmPackageTest {
assertEquals(Os.LINUX390, rpmPackage.getOperatingSystem());
}
@Test(expected = UnknownOperatingSystemException.class)
public void operatingSystemInvalidException() throws UnknownOperatingSystemException {
rpmPackage.setOperatingSystem("NONEXISTENT");
@Test
public void operatingSystemInvalidException() {
Assertions.assertThrows(UnknownOperatingSystemException.class, () ->
rpmPackage.setOperatingSystem("NONEXISTENT"));
}
@Test(expected = UnknownOperatingSystemException.class)
public void operatingSystemBlankException() throws UnknownOperatingSystemException {
rpmPackage.setOperatingSystem("");
@Test
public void operatingSystemBlankException() {
Assertions.assertThrows(UnknownOperatingSystemException.class, () ->
rpmPackage.setOperatingSystem(""));
}
@Test(expected = UnknownOperatingSystemException.class)
public void operatingSystemNullException() throws UnknownOperatingSystemException {
rpmPackage.setOperatingSystem(null);
@Test
public void operatingSystemNullException() {
Assertions.assertThrows(UnknownOperatingSystemException.class, () ->
rpmPackage.setOperatingSystem(null));
}
@Test
@ -212,21 +218,21 @@ public class RpmPackageTest {
@Test
public void packagerAccessors() {
assertEquals(null, rpmPackage.getPackager());
assertNull(rpmPackage.getPackager());
rpmPackage.setPackager("packager");
assertEquals("packager", rpmPackage.getPackager());
}
@Test
public void attachAccessors() {
assertEquals(true, rpmPackage.isAttach());
assertTrue(rpmPackage.isAttach());
rpmPackage.setAttach(false);
assertEquals(false, rpmPackage.isAttach());
assertFalse(rpmPackage.isAttach());
}
@Test
public void classifierAccessors() {
assertEquals(null, rpmPackage.getClassifier());
assertNull(rpmPackage.getClassifier());
rpmPackage.setClassifier("classifier");
assertEquals("classifier", rpmPackage.getClassifier());
}
@ -236,10 +242,8 @@ public class RpmPackageTest {
List<RpmPackageRule> rules = new ArrayList<>();
rules.add(new RpmPackageRule());
rules.add(new RpmPackageRule());
rpmPackage.setRules(rules);
assertEquals(rules, rpmPackage.getRules());
rpmPackage.setRules(null);
assertNull(rpmPackage.getRules());
}
@ -247,47 +251,40 @@ public class RpmPackageTest {
@Test
public void eventHookAccessors() {
Path scriptFile = Paths.get("samplescript.sh");
// pre transaction
assertEquals(null, rpmPackage.getPreTransactionScriptPath());
assertNull(rpmPackage.getPreTransactionScriptPath());
rpmPackage.setPreTransactionScriptPath(scriptFile);
assertEquals(scriptFile, rpmPackage.getPreTransactionScriptPath());
assertEquals(null, rpmPackage.getPreTransactionProgram());
assertNull(rpmPackage.getPreTransactionProgram());
rpmPackage.setPreTransactionProgram("/bin/sh");
assertEquals("/bin/sh", rpmPackage.getPreTransactionProgram());
// pre install
assertEquals(null, rpmPackage.getPreInstallScriptPath());
assertNull(rpmPackage.getPreInstallScriptPath());
rpmPackage.setPreInstallScriptPath(scriptFile);
assertEquals(scriptFile, rpmPackage.getPreInstallScriptPath());
assertEquals(null, rpmPackage.getPreInstallProgram());
assertNull(rpmPackage.getPreInstallProgram());
rpmPackage.setPreInstallProgram("/bin/sh");
assertEquals("/bin/sh", rpmPackage.getPreInstallProgram());
assertEquals(null, rpmPackage.getPostInstallScriptPath());
assertNull(rpmPackage.getPostInstallScriptPath());
rpmPackage.setPostInstallScriptPath(scriptFile);
assertEquals(scriptFile, rpmPackage.getPostInstallScriptPath());
assertEquals(null, rpmPackage.getPostInstallProgram());
assertNull(rpmPackage.getPostInstallProgram());
rpmPackage.setPostInstallProgram("/bin/sh");
assertEquals("/bin/sh", rpmPackage.getPostInstallProgram());
assertEquals(null, rpmPackage.getPreUninstallScriptPath());
assertNull(rpmPackage.getPreUninstallScriptPath());
rpmPackage.setPreUninstallScriptPath(scriptFile);
assertEquals(scriptFile, rpmPackage.getPreUninstallScriptPath());
assertEquals(null, rpmPackage.getPreUninstallProgram());
assertNull(rpmPackage.getPreUninstallProgram());
rpmPackage.setPreUninstallProgram("/bin/sh");
assertEquals("/bin/sh", rpmPackage.getPreUninstallProgram());
assertEquals(null, rpmPackage.getPostUninstallScriptPath());
assertNull(rpmPackage.getPostUninstallScriptPath());
rpmPackage.setPostUninstallScriptPath(scriptFile);
assertEquals(scriptFile, rpmPackage.getPostUninstallScriptPath());
assertEquals(null, rpmPackage.getPostUninstallProgram());
assertNull(rpmPackage.getPostUninstallProgram());
rpmPackage.setPostUninstallProgram("/bin/sh");
assertEquals("/bin/sh", rpmPackage.getPostUninstallProgram());
assertEquals(null, rpmPackage.getPostTransactionScriptPath());
assertNull(rpmPackage.getPostTransactionScriptPath());
rpmPackage.setPostTransactionScriptPath(scriptFile);
assertEquals(scriptFile, rpmPackage.getPostTransactionScriptPath());
assertEquals(null, rpmPackage.getPostTransactionProgram());
assertNull(rpmPackage.getPostTransactionProgram());
rpmPackage.setPostTransactionProgram("/bin/sh");
assertEquals("/bin/sh", rpmPackage.getPostTransactionProgram());
}
@ -302,13 +299,13 @@ public class RpmPackageTest {
@Test
public void signingKeyAccessors() {
assertEquals(null, rpmPackage.getSigningKey());
assertNull(rpmPackage.getSigningKey());
rpmPackage.setSigningKey("key");
assertEquals("key", rpmPackage.getSigningKey());
assertEquals(null, rpmPackage.getSigningKeyId());
assertNull(rpmPackage.getSigningKeyId());
rpmPackage.setSigningKeyId(0L);
assertEquals(new Long(0L), rpmPackage.getSigningKeyId());
assertEquals(null, rpmPackage.getSigningKeyPassPhrase());
assertEquals(Long.valueOf(0L), rpmPackage.getSigningKeyId());
assertNull(rpmPackage.getSigningKeyPassPhrase());
rpmPackage.setSigningKeyPassPhrase("passphrase");
assertEquals("passphrase", rpmPackage.getSigningKeyPassPhrase());
}
@ -371,7 +368,7 @@ public class RpmPackageTest {
rpmPackage.setPostTransactionProgram("/bin/sh");
rpmPackage.build();
String rpmFileName = String.format("%s%s%s", testOutputPath, File.separator, rpmPackage.getFinalName());
assertEquals(true, new File(rpmFileName).exists());
assertTrue(new File(rpmFileName).exists());
}
@Test
@ -379,7 +376,7 @@ public class RpmPackageTest {
rpmPackage.setName("buildSecondaryAttachment");
rpmPackage.build();
String rpmFileName = String.format("%s%s%s", testOutputPath, File.separator, rpmPackage.getFinalName());
assertEquals(true, new File(rpmFileName).exists());
assertTrue(new File(rpmFileName).exists());
}
@Test
@ -387,7 +384,7 @@ public class RpmPackageTest {
rpmPackage.setVersion("2.0");
rpmPackage.build();
String rpmFileName = String.format("%s%s%s", testOutputPath, File.separator, rpmPackage.getFinalName());
assertEquals(true, new File(rpmFileName).exists());
assertTrue(new File(rpmFileName).exists());
}
@Test
@ -396,7 +393,7 @@ public class RpmPackageTest {
rpmPackage.setVersion("2.0");
rpmPackage.build();
String rpmFileName = String.format("%s%s%s", testOutputPath, File.separator, rpmPackage.getFinalName());
assertEquals(true, new File(rpmFileName).exists());
assertTrue(new File(rpmFileName).exists());
}
@Test
@ -405,6 +402,6 @@ public class RpmPackageTest {
rpmPackage.setAttach(false);
rpmPackage.build();
String rpmFileName = String.format("%s%s%s", testOutputPath, File.separator, rpmPackage.getFinalName());
assertEquals(true, new File(rpmFileName).exists());
assertTrue(new File(rpmFileName).exists());
}
}

View file

@ -1,11 +1,9 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
@ -17,7 +15,7 @@ import java.nio.file.Paths;
public class RpmScriptTemplateRendererTest {
private String testOutputPath;
@Before
@BeforeEach
public void setUp() {
this.testOutputPath = System.getProperty("project.build.testOutputDirectory");
}

View file

@ -1,10 +1,8 @@
package org.xbib.maven.plugin.rpm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

View file

@ -1,16 +1,15 @@
package org.xbib.maven.plugin.rpm.mojo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.maven.model.Build;
import org.apache.maven.model.License;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.maven.plugin.rpm.MockMojo;
import org.xbib.maven.plugin.rpm.RpmPackage;
import org.xbib.maven.plugin.rpm.RpmScriptTemplateRenderer;
@ -36,7 +35,7 @@ public class AbstractRpmMojoTest {
private MockMojo mojo;
private MavenProject project;
@Before
@BeforeEach
public void setUp() {
testOutputPath = System.getProperty("project.build.testOutputDirectory");
Build projectBuild = new Build();

View file

@ -3,8 +3,8 @@ package org.xbib.maven.plugin.rpm.mojo;
import org.apache.maven.model.Build;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.maven.plugin.rpm.RpmPackage;
import org.xbib.maven.plugin.rpm.RpmPackageRule;
@ -21,7 +21,7 @@ public class ListFilesRpmMojoTest {
private ListFilesRpmMojo mojo;
private RpmPackageRule packageRule;
@Before
@BeforeEach
public void setUp() {
this.testOutputPath = System.getProperty("project.build.testOutputDirectory");
Build projectBuild = new Build();

View file

@ -1,16 +1,15 @@
package org.xbib.maven.plugin.rpm.mojo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.maven.model.Build;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.maven.plugin.rpm.RpmPackage;
import org.xbib.maven.plugin.rpm.RpmPackageRule;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@ -26,7 +25,7 @@ public class PackageRpmMojoTest {
private RpmPackageRule packageRule;
@Before
@BeforeEach
public void setUp() {
// Test output path
String testOutputPath = System.getProperty("project.build.testOutputDirectory");
@ -59,7 +58,7 @@ public class PackageRpmMojoTest {
includes.add("**");
packageRule.setIncludes(includes);
mojo.execute();
assertEquals(true, project.getArtifact().getFile().exists());
assertTrue(project.getArtifact().getFile().exists());
}
@Test
@ -73,12 +72,14 @@ public class PackageRpmMojoTest {
assertNull(project.getArtifact());
}
@Test(expected = MojoExecutionException.class)
@Test
public void packageRpmMissedFiles() throws MojoExecutionException {
project.setVersion("2.0-SNAPSHOT");
List<String> includes = new ArrayList<>();
packageRule.setIncludes(includes);
mojo.execute();
Assertions.assertThrows(MojoExecutionException.class, () -> {
project.setVersion("2.0-SNAPSHOT");
List<String> includes = new ArrayList<>();
packageRule.setIncludes(includes);
mojo.execute();
});
}
@Test
@ -91,13 +92,15 @@ public class PackageRpmMojoTest {
mojo.execute();
}
@Test(expected = MojoExecutionException.class)
@Test
public void packageRpmNoFilesPackaged() throws MojoExecutionException {
mojo.setPerformCheckingForExtraFiles(false);
project.setVersion("4.0-SNAPSHOT");
List<String> includes = new ArrayList<>();
packageRule.setIncludes(includes);
mojo.execute();
Assertions.assertThrows(MojoExecutionException.class, () -> {
mojo.setPerformCheckingForExtraFiles(false);
project.setVersion("4.0-SNAPSHOT");
List<String> includes = new ArrayList<>();
packageRule.setIncludes(includes);
mojo.execute();
});
}
@Test

View file

@ -1,4 +1,4 @@
dependencies {
compile project(':rpm-core')
compile "org.apache.ant:ant:${project.property('ant.version')}"
api project(':rpm-core')
implementation "org.apache.ant:ant:${project.property('ant.version')}"
}

View file

@ -1,323 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!-- This is a checkstyle configuration file. For descriptions of
what the following rules do, please see the checkstyle configuration
page at http://checkstyle.sourceforge.net/config.html -->
<module name="Checker">
<module name="FileTabCharacter">
<!-- Checks that there are no tab characters in the file.
-->
</module>
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf"/>
</module>
<module name="RegexpSingleline">
<!-- Checks that FIXME is not used in comments. TODO is preferred.
-->
<property name="format" value="((//.*)|(\*.*))FIXME" />
<property name="message" value='TODO is preferred to FIXME. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="RegexpSingleline">
<!-- Checks that TODOs are named. (Actually, just that they are followed
by an open paren.)
-->
<property name="format" value="((//.*)|(\*.*))TODO[^(]" />
<property name="message" value='All TODOs should be named. e.g. "TODO(johndoe): Refactor when v2 is released."' />
</module>
<module name="JavadocPackage">
<!-- Checks that each Java package has a Javadoc file used for commenting.
Only allows a package-info.java, not package.html. -->
</module>
<!-- All Java AST specific tests live under TreeWalker module. -->
<module name="TreeWalker">
<!--
IMPORT CHECKS
-->
<module name="RedundantImport">
<!-- Checks for redundant import statements. -->
<property name="severity" value="error"/>
</module>
<module name="ImportOrder">
<!-- Checks for out of order import statements. -->
<property name="severity" value="warning"/>
<property name="groups" value="com.google,android,junit,net,org,java,javax"/>
<!-- This ensures that static imports go first. -->
<property name="option" value="top"/>
<property name="tokens" value="STATIC_IMPORT, IMPORT"/>
</module>
<!--
JAVADOC CHECKS
-->
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
<module name="JavadocMethod">
<property name="scope" value="protected"/>
<property name="severity" value="warning"/>
<property name="allowMissingJavadoc" value="true"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowUndeclaredRTE" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="protected"/>
<property name="severity" value="error"/>
</module>
<module name="JavadocStyle">
<property name="severity" value="warning"/>
</module>
<!--
NAMING CHECKS
-->
<!-- Item 38 - Adhere to generally accepted naming conventions -->
<module name="PackageName">
<!-- Validates identifiers for package names against the
supplied expression. -->
<!-- Here the default checkstyle rule restricts package name parts to
seven characters, this is not in line with common practice at Google.
-->
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]{1,})*$"/>
<property name="severity" value="warning"/>
</module>
<module name="TypeNameCheck">
<!-- Validates static, final fields against the
expression "^[A-Z][a-zA-Z0-9]*$". -->
<metadata name="altname" value="TypeName"/>
<property name="severity" value="warning"/>
</module>
<module name="ConstantNameCheck">
<!-- Validates non-private, static, final fields against the supplied
public/package final fields "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$". -->
<metadata name="altname" value="ConstantName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="false"/>
<property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|FLAG_.*)$"/>
<message key="name.invalidPattern"
value="Variable ''{0}'' should be in ALL_CAPS (if it is a constant) or be private (otherwise)."/>
<property name="severity" value="warning"/>
</module>
<module name="StaticVariableNameCheck">
<!-- Validates static, non-final fields against the supplied
expression "^[a-z][a-zA-Z0-9]*_?$". -->
<metadata name="altname" value="StaticVariableName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
<property name="severity" value="warning"/>
</module>
<module name="MemberNameCheck">
<!-- Validates non-static members against the supplied expression. -->
<metadata name="altname" value="MemberName"/>
<property name="applyToPublic" value="true"/>
<property name="applyToProtected" value="true"/>
<property name="applyToPackage" value="true"/>
<property name="applyToPrivate" value="true"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
<property name="severity" value="warning"/>
</module>
<module name="MethodNameCheck">
<!-- Validates identifiers for method names. -->
<metadata name="altname" value="MethodName"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$"/>
<property name="severity" value="warning"/>
</module>
<module name="ParameterName">
<!-- Validates identifiers for method parameters against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalFinalVariableName">
<!-- Validates identifiers for local final variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<module name="LocalVariableName">
<!-- Validates identifiers for local variables against the
expression "^[a-z][a-zA-Z0-9]*$". -->
<property name="severity" value="warning"/>
</module>
<!--
LENGTH and CODING CHECKS
-->
<module name="LineLength">
<!-- Checks if a line is too long. -->
<property name="max" value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.max}" default="128"/>
<property name="severity" value="error"/>
<!--
The default ignore pattern exempts the following elements:
- import statements
- long URLs inside comments
-->
<property name="ignorePattern"
value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.ignorePattern}"
default="^(package .*;\s*)|(import .*;\s*)|( *(\*|//).*https?://.*)$"/>
</module>
<module name="LeftCurly">
<!-- Checks for placement of the left curly brace ('{'). -->
<property name="severity" value="warning"/>
</module>
<module name="RightCurly">
<!-- Checks right curlies on CATCH, ELSE, and TRY blocks are on
the same line. e.g., the following example is fine:
<pre>
if {
...
} else
</pre>
-->
<!-- This next example is not fine:
<pre>
if {
...
}
else
</pre>
-->
<property name="option" value="same"/>
<property name="severity" value="warning"/>
</module>
<!-- Checks for braces around if and else blocks -->
<module name="NeedBraces">
<property name="severity" value="warning"/>
<property name="tokens" value="LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"/>
</module>
<module name="UpperEll">
<!-- Checks that long constants are defined with an upper ell.-->
<property name="severity" value="error"/>
</module>
<module name="FallThrough">
<!-- Warn about falling through to the next case statement. Similar to
javac -Xlint:fallthrough, but the check is suppressed if a single-line comment
on the last non-blank line preceding the fallen-into case contains 'fall through' (or
some other variants which we don't publicized to promote consistency).
-->
<property name="reliefPattern"
value="fall through|Fall through|fallthru|Fallthru|falls through|Falls through|fallthrough|Fallthrough|No break|NO break|no break|continue on"/>
<property name="severity" value="error"/>
</module>
<!--
MODIFIERS CHECKS
-->
<module name="ModifierOrder">
<!-- Warn if modifier order is inconsistent with JLS3 8.1.1, 8.3.1, and
8.4.3. The prescribed order is:
public, protected, private, abstract, static, final, transient, volatile,
synchronized, native, strictfp
-->
</module>
<!--
WHITESPACE CHECKS
-->
<module name="WhitespaceAround">
<!-- Checks that various tokens are surrounded by whitespace.
This includes most binary operators and keywords followed
by regular or curly braces.
-->
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR,
BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN,
EQUAL, GE, GT, LAND, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE,
LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN,
LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS,
MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION,
SL, SL_ASSIGN, SR_ASSIGN, STAR, STAR_ASSIGN"/>
<property name="severity" value="error"/>
</module>
<module name="WhitespaceAfter">
<!-- Checks that commas, semicolons and typecasts are followed by
whitespace.
-->
<property name="tokens" value="COMMA, SEMI, TYPECAST"/>
</module>
<module name="NoWhitespaceAfter">
<!-- Checks that there is no whitespace after various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS,
UNARY_PLUS"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="NoWhitespaceBefore">
<!-- Checks that there is no whitespace before various unary operators.
Linebreaks are allowed.
-->
<property name="tokens" value="SEMI, DOT, POST_DEC, POST_INC"/>
<property name="allowLineBreaks" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="ParenPad">
<!-- Checks that there is no whitespace before close parens or after
open parens.
-->
<property name="severity" value="warning"/>
</module>
</module>
</module>

View file

@ -30,6 +30,7 @@ import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
@ -78,31 +79,31 @@ public class RpmTask extends Task {
private Path destination;
private List<ArchiveFileSet> filesets = new ArrayList<>();
private final List<ArchiveFileSet> filesets = new ArrayList<>();
private List<EmptyDir> emptyDirs = new ArrayList<>();
private final List<EmptyDir> emptyDirs = new ArrayList<>();
private List<Ghost> ghosts = new ArrayList<>();
private final List<Ghost> ghosts = new ArrayList<>();
private List<Link> links = new ArrayList<>();
private final List<Link> links = new ArrayList<>();
List<Depends> depends = new ArrayList<>();
private List<Provides> moreProvides = new ArrayList<>();
private final List<Provides> moreProvides = new ArrayList<>();
private List<Conflicts> conflicts = new ArrayList<>();
private final List<Conflicts> conflicts = new ArrayList<>();
private List<Obsoletes> obsoletes = new ArrayList<>();
private final List<Obsoletes> obsoletes = new ArrayList<>();
private List<TriggerPreIn> triggersPreIn = new ArrayList<>();
private final List<TriggerPreIn> triggersPreIn = new ArrayList<>();
private List<TriggerIn> triggersIn = new ArrayList<>();
private final List<TriggerIn> triggersIn = new ArrayList<>();
private List<TriggerUn> triggersUn = new ArrayList<>();
private final List<TriggerUn> triggersUn = new ArrayList<>();
private List<TriggerPostUn> triggersPostUn = new ArrayList<>();
private final List<TriggerPostUn> triggersPostUn = new ArrayList<>();
private List<BuiltIn> builtIns = new ArrayList<>();
private final List<BuiltIn> builtIns = new ArrayList<>();
private Path preTransScript;
@ -143,7 +144,7 @@ public class RpmTask extends Task {
if (group == null) {
throw new BuildException("attribute 'group' is required");
}
Integer numEpoch;
int numEpoch;
try {
numEpoch = Integer.parseInt(epoch);
} catch (Exception e) {
@ -165,7 +166,9 @@ public class RpmTask extends Task {
if (provides != null) {
rpmBuilder.setProvides(provides);
}
rpmBuilder.setPrefixes(prefixes == null ? null : prefixes.split(","));
if (prefixes != null) {
rpmBuilder.setPrefixes(Arrays.asList(prefixes.split(",")));
}
rpmBuilder.setPrivateKeyRing(privateKeyRing);
rpmBuilder.setPrivateKeyId(privateKeyId);
rpmBuilder.setPrivateKeyPassphrase(privateKeyPassphrase);
@ -212,8 +215,8 @@ public class RpmTask extends Task {
prefix += "/";
}
DirectoryScanner directoryScanner = fileset.getDirectoryScanner(getProject());
Integer filemode = fileset.getFileMode(getProject()) & 4095;
Integer dirmode = fileset.getDirMode(getProject()) & 4095;
int filemode = fileset.getFileMode(getProject()) & 4095;
int dirmode = fileset.getDirMode(getProject()) & 4095;
String username = null;
String group = null;
EnumSet<Directive> directive = null;
@ -238,13 +241,13 @@ public class RpmTask extends Task {
rpmBuilder.addURL(prefix + entry, url, filemode, dirmode, directive, username, group);
} else {
Path path = directoryScanner.getBasedir().toPath().resolve(entry);
rpmBuilder.addFile(prefix + entry, path, filemode, dirmode, directive, username, group);
rpmBuilder.addFile(prefix + entry, path, filemode, dirmode, directive, username, group, true);
}
}
}
for (Ghost ghost : ghosts) {
rpmBuilder.addFile(ghost.getPath(), null, ghost.getFilemode(), ghost.getDirmode(),
ghost.getDirectives(), ghost.getUsername(), ghost.getGroup());
ghost.getDirectives(), ghost.getUsername(), ghost.getGroup(), true);
}
for (Link link : links) {
rpmBuilder.addLink(link.getPath(), link.getTarget(), link.getPermissions());

Some files were not shown because too many files have changed in this diff Show more