15 Commits
27 changed files with 653 additions and 152 deletions
+203
View File
@@ -0,0 +1,203 @@
# Regular Expression Maven Plugin
This is a maven plugin that provides various regular expression based goals to Maven.
## Usage
```xml
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>com.inteligr8</groupId>
<artifactId>regex-maven-plugin</artifactId>
<version>...</version>
<executions>
<execution>
<id>sample-regex-test</id>
<phase>validate</phase>
<goals><goal>replace-property</goal></goals>
<configuration>
<property>a.property.to.eval</property>
<regexes>
<regex>
<pattern>\.txt<pattern>
<replacement></replacement>
</regex>
</regexes>
<newProperty>a.new.property.to.set</newProperty>
</configuration>
</execution>
</executions>
</plugin>
...
</plugins>
...
</build>
...
</project>
```
## Goals
| Goal | Description |
| -------------------- | ----------- |
| `replace-file` | Apply a regular expression pattern against the contents of a file, replacing matches with the regex-compliant replacement text. The existing file is changed. |
| `replace-properties` | Apply a regular expression pattern against a set of property values, replacing matches with the regex-compliant replacement text, and storing in new properties. |
| `replace-property` | Apply a regular expression pattern against a property value, replacing matches with the regex-compliant replacement text, and storing in a new property. |
| `replace-text` | Apply a regular expression pattern against text, replacing matches with the regex-compliant replacement text, and storing in a new property. |
| `match-file` | Evaluate a regular expression pattern against the contents of a file, storing the result in a boolean property. |
| `match-filename` | Evaluate a regular expression pattern against the name of a file, storing the result in a boolean property. |
| `match-properties` | Evaluate a regular expression pattern against a set of property values, storing the result in boolean properties. |
| `match-property` | Evaluate a regular expression pattern against a property value, storing the result in a boolean property. |
| `match-text` | Evaluate a regular expression pattern against text, storing the result in a boolean property. |
| `copy-file` | A convenience goal that copies all files/folders specified in a source path to a target path. |
| `move-file` | A convenience goal that moves all files/folders specified in a source path to a target path. |
### Common Configuration Properties
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:-----------:|:--------:| ------- | ----------- |
| `allowMultiLineMatch` | `boolean` | | `false` | A value of `true` allows for multi-line matching. This takes substantially more memory/time to process. |
| `charset` | `string` | | `utf-8` | |
| `skip` | `boolean` | | `false` | |
| `verbose` | `boolean` | | `false` | |
### Goal: `replace-file`
Manipulates all the contents in the specified files based the specified regular expression replacements.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:-----------:|:--------:| ------- | ----------- |
| `chunkSize` | `int` | | `1024` | The streaming buffer/chunk size in bytes, while evaluating the regular expressions. Adjust for classic speed/memory trade-off. Be aware that files are processed line-by-line, unless `allowMultiLineMatch` is set to `true`. |
| `filesets` | `FileSet[]` | Yes | | Executes against these files. |
| `regexes` | `Regex[]` | Yes | | Applies these regular expressions and replacement text against those files. |
### Goal: `replace-properties`
Copies and replaces the values of the specified properties based on the specified regular expression replacements; storing the changed values in new properties.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:----------:|:--------:| -------- | ----------- |
| `properties` | `String[]` | Yes | | Executes against these properties. |
| `newPropertySuffix` | `String` | | `-regex` | All evaluated properties will be copied to new properties with the same property name plus this suffix. |
| `regexes` | `Regex[]` | Yes | | Applies these regular expressions and replacement text against those files. |
### Goal: `replace-property`
Copies and replaces the value of the specified property based on the specified regular expression replacements; storing the changed value in a new property.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:----------:|:--------:| ------- | ----------- |
| `property` | `String` | Yes | | Executes against this property. |
| `newProperty` | `String` | | | The evaluated property will be copied to this property name. If not specified, it will be the same name as the `property` with a `-regex` suffix. |
| `regexes` | `Regex[]` | Yes | | Applies these regular expressions and replacement text against those files. |
### Goal: `replace-text`
Replaces the specified text based on the specified regular expression replacements; storing the result in a property.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:----------:|:--------:| ------- | ----------- |
| `text` | `String` | Yes | | Execute against this text. |
| `newProperty` | `String` | Yes | | The evaluated text will be copied to this property name. |
| `regexes` | `Regex[]` | Yes | | Applies these regular expressions and replacement text against those files. |
### Goal: `match-file`
Searches the contents of the specified files based using the specified regular expressions; storing the result of the search in a property.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:-----------:|:--------:| ------- | ----------- |
| `chunkSize` | `int` | | `1024` | The streaming buffer/chunk size in bytes, while evaluating the regular expressions. Adjust for classic speed/memory trade-off. Be aware that files are processed line-by-line, unless `allowMultiLineMatch` is set to `true`. |
| `filesets` | `FileSet[]` | Yes | | Executes against these files. |
| `newProperty` | `String` | Yes | | If a single regular expression matches the contents in a single file, then this property will be set to `true`; `false` otherwise. |
| `patterns` | `String[]` | Yes | | Evaluates these regular expressions against those files. |
| `allowPartialMatch` | `boolean` | | `true` | A value of `true` allows for partial matching, rather than exact line-by-line matching. |
| `negate` | `boolean` | | `false` | A value of `true` will reverse the `true`/`false` on the resultant property value. |
### Goal: `match-filename`
Checks the filenames of the specified files based using the specified regular expressions; storing the result in a property.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:-----------:|:--------:| ------- | ----------- |
| `sourceDirectory` | `File` | Yes | | Executes against this file. |
| `newProperty` | `String` | Yes | | If a single regular expression matches the name of the file, then this property will be set to `true`; `false` otherwise. |
| `patterns` | `String[]` | Yes | | Evaluates these regular expressions the file. |
| `allowPartialMatch` | `boolean` | | `true` | A value of `true` allows for partial matching, rather than exact filename matching. |
| `negate` | `boolean` | | `false` | A value of `true` will reverse the `true`/`false` on the resultant property value. |
### Goal: `match-properties`
Checks the values of the specified properties based on the specified regular expressions; storing the results in new properties.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:----------:|:--------:| -------- | ----------- |
| `properties` | `String[]` | Yes | | Executes against these properties. |
| `newPropertySuffix` | `String` | | `-regex` | All evaluated properties will be copied to new properties with the same property name plus this suffix. |
| `patterns` | `String[]` | Yes | | Evaluates these regular expressions against those properties' values. |
| `allowPartialMatch` | `boolean` | | `true` | A value of `true` allows for partial matching, rather than exact matching. |
| `negate` | `boolean` | | `false` | A value of `true` will reverse the `true`/`false` on the resultant property value. |
### Goal: `match-property`
Checks the value of the specified property based on the specified regular expressions; storing the result in a new property.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:----------:|:--------:| ------- | ----------- |
| `property` | `String` | Yes | | Executes against this property. |
| `newProperty` | `String` | | | The evaluated property will be copied to this property name. If not specified, it will be the same name as the `property` with a `-regex` suffix. |
| `patterns` | `String[]` | Yes | | Evaluates these regular expressions against the property value. |
| `allowPartialMatch` | `boolean` | | `true` | A value of `true` allows for partial matching, rather than exact matching. |
| `negate` | `boolean` | | `false` | A value of `true` will reverse the `true`/`false` on the resultant property value. |
### Goal: `match-text`
Checks the specified text based on the specified regular expressions; storing the result in a property.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:----------:|:--------:| ------- | ----------- |
| `text` | `String` | Yes | | Execute against this text. |
| `newProperty` | `String` | Yes | | The evaluated text will be copied to this property name. |
| `patterns` | `String[]` | Yes | | Evaluates these regular expressions against the property value. |
| `allowPartialMatch` | `boolean` | | `true` | A value of `true` allows for partial matching, rather than exact matching. |
| `negate` | `boolean` | | `false` | A value of `true` will reverse the `true`/`false` on the resultant property value. |
### Goal: `copy-file`
Copies all the files in the specified source directory while applying the specified regular expression replacements to their contents; storing the files in the specified target directory.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:---------:|:--------:| ---------- | ----------- |
| `sourceDirectory` | `File` | | ${basedir} | Copy all files from this directory. |
| `targetDirectory` | `File` | | ${basedir} | Copy all files to this directory. |
| `regexes` | `Regex[]` | Yes | | Applies these regular expressions and replacement text against those files. |
| `overwrite` | `boolean` | | `true` | |
### Goal: `move-file`
Moves all the files from the specified source directory while applying the specified regular expression replacements to their contents; storing the files in the specified target directory.
| Configuration Property | Data Type | Required | Default | Description |
| ---------------------- |:---------:|:--------:| ---------- | ----------- |
| `sourceDirectory` | `File` | | ${basedir} | Move all files from this directory. |
| `targetDirectory` | `File` | | ${basedir} | Move all files to this directory. |
| `regexes` | `Regex[]` | Yes | | Applies these regular expressions and replacement text against those files. |
| `overwrite` | `boolean` | | `true` | |
## Model
### Object Type: `Regex`
| Element | Data Type | Required | Default | Description |
| ----------------- |:---------:|:--------:| ------- | ----------- |
| `pattern` | `String` | Yes | | A regular expression pattern. |
| `replacement` | `String` | | `` | A regular expression replacement string. |
| `previousPattern` | `String` | | | A regular expression pattern to look back against, removing everything down to and including the pattern. |
The `previousPattern` allows for you to match some text and remove everything before the match, up to the `prevoiusPattern`. This is useful when matching a method and removing it and all its annotations. If the `previousPattern` has no match, it will not remove any text before the primary match.
+86 -34
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
@@ -10,10 +10,21 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<packaging>maven-plugin</packaging> <packaging>maven-plugin</packaging>
<name>A Maven plugin for regex operations</name> <name>Regular Expression Maven Plugin</name>
<description>A Maven plugin for regular expression operations</description>
<url>https://git.inteligr8.com/inteligr8/regex-maven-plugin</url>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
</license>
</licenses>
<scm> <scm>
<url>https://bitbucket.org/inteligr8/regex-maven-plugin</url> <connection>scm:git:https://git.inteligr8.com/inteligr8/regex-maven-plugin.git</connection>
<developerConnection>scm:git:git@git.inteligr8.com:inteligr8/regex-maven-plugin.git</developerConnection>
<url>https://git.inteligr8.com/inteligr8/regex-maven-plugin</url>
</scm> </scm>
<organization> <organization>
<name>Inteligr8</name> <name>Inteligr8</name>
@@ -32,19 +43,19 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<maven.version>3.6.3</maven.version> <maven.version>3.9.11</maven.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>3.4</version> <version>3.20.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven.shared</groupId> <groupId>org.apache.maven.shared</groupId>
<artifactId>file-management</artifactId> <artifactId>file-management</artifactId>
<version>3.0.0</version> <version>3.2.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven</groupId> <groupId>org.apache.maven</groupId>
@@ -55,7 +66,7 @@
<dependency> <dependency>
<groupId>org.apache.maven.plugin-tools</groupId> <groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId> <artifactId>maven-plugin-annotations</artifactId>
<version>3.6.0</version> <version>3.15.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -79,16 +90,32 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.12</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.15.2</version>
</plugin>
<plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>3.9.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-metadata</artifactId>
<version>2.2.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-plugin-plugin</artifactId> <artifactId>maven-plugin-plugin</artifactId>
<version>3.6.0</version>
<configuration> <configuration>
<goalPrefix>regex</goalPrefix> <goalPrefix>regex</goalPrefix>
</configuration> </configuration>
@@ -110,7 +137,6 @@
<plugin> <plugin>
<groupId>org.codehaus.plexus</groupId> <groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-metadata</artifactId> <artifactId>plexus-component-metadata</artifactId>
<version>2.0.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@@ -121,7 +147,6 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-invoker-plugin</artifactId> <artifactId>maven-invoker-plugin</artifactId>
<version>3.2.2</version>
<configuration> <configuration>
<projectsDirectory>${basedir}/src/it</projectsDirectory> <projectsDirectory>${basedir}/src/it</projectsDirectory>
<cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo> <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
@@ -142,19 +167,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>javadoc</id>
<phase>package</phase>
<goals><goal>jar</goal></goals>
<configuration>
<show>public</show>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
@@ -170,7 +182,6 @@
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-invoker-plugin</artifactId> <artifactId>maven-invoker-plugin</artifactId>
<version>3.2.2</version>
<executions> <executions>
<execution> <execution>
<id>run-its</id> <id>run-its</id>
@@ -189,14 +200,55 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>central-publish</id>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>source</id>
<phase>package</phase>
<goals><goal>jar-no-fork</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>javadoc</id>
<phase>package</phase>
<goals><goal>jar</goal></goals>
<configuration>
<show>public</show>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign</id>
<phase>verify</phase>
<goals><goal>sign</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.central</groupId>
<artifactId>central-publishing-maven-plugin</artifactId>
<version>0.8.0</version>
<extensions>true</extensions>
<configuration>
<publishingServerId>central</publishingServerId>
<autoPublish>true</autoPublish>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>
<distributionManagement>
<repository>
<id>inteligr8-releases</id>
<name>Inteligr8 Releases</name>
<url>http://repos.inteligr8.com/nexus/repository/inteligr8-public</url>
</repository>
</distributionManagement>
</project> </project>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
@@ -3,4 +3,6 @@ this is a multi line test file.
it is supposed to emulate larger files and multiline pattern matching. it is supposed to emulate larger files and multiline pattern matching.
sometimes this doesn՚t work with unicode characters.
good luck! good luck!
+85 -12
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
@@ -62,7 +62,7 @@
<excludes> <excludes>
<exclude>pom.xml</exclude> <exclude>pom.xml</exclude>
<exclude>*.log</exclude> <exclude>*.log</exclude>
<exclude>target</exclude> <exclude>target/**/*</exclude>
</excludes> </excludes>
<outputDirectory>${project.build.directory}/noreplace-one</outputDirectory> <outputDirectory>${project.build.directory}/noreplace-one</outputDirectory>
</fileset> </fileset>
@@ -75,31 +75,104 @@
</regexes> </regexes>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>replace-linestart</id>
<phase>validate</phase>
<goals>
<goal>replace-file</goal>
</goals>
<configuration>
<filesets>
<fileset>
<directory>${basedir}/folder1</directory>
<includes>
<include>file12.txt</include>
</includes>
<outputDirectory>${project.build.directory}/replace-linestart</outputDirectory>
</fileset>
</filesets>
<regexes>
<regex>
<pattern>^it is</pattern>
<replacement># it is</replacement>
</regex>
</regexes>
</configuration>
</execution>
<execution>
<id>inplace</id>
<phase>validate</phase>
<goals>
<goal>replace-file</goal>
</goals>
<configuration>
<filesets>
<fileset>
<includes>
<include>**/file12.txt</include>
</includes>
<excludes>
<exclude>target/**/*</exclude>
</excludes>
</fileset>
</filesets>
<regexes>
<regex>
<pattern>is supposed</pattern>
<replacement>is likely</replacement>
</regex>
</regexes>
</configuration>
</execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M3</version>
<executions> <executions>
<execution> <execution>
<id>assert</id> <id>assert</id>
<goals><goal>enforce</goal></goals> <goals>
<goal>enforce</goal>
</goals>
<configuration> <configuration>
<rules> <rules>
<requireFilesExist>
<files>
<file>${project.build.directory}/replace-one/file1.txt</file>
<file>${project.build.directory}/noreplace-one/file1.txt</file>
<file>${project.build.directory}/noreplace-one/folder1/file11.txt</file>
<file>${project.build.directory}/noreplace-one/folder1/file12.txt</file>
</files>
</requireFilesExist>
<requireFilesDontExist> <requireFilesDontExist>
<files> <files>
<file>${project.build.directory}/replace-one/folder1/file11.txt</file> <file>${project.build.directory}/replace-one/folder1/file11.txt</file>
<file>${project.build.directory}/replace-one/folder1/file12.txt</file> <file>${project.build.directory}/replace-one/folder1/file12.txt</file>
</files> </files>
</requireFilesDontExist> </requireFilesDontExist>
<requireFileChecksum>
<file>${project.build.directory}/replace-one/file1.txt</file>
<checksum>6f1ed002ab5595859014ebf0951522d9</checksum>
<type>md5</type>
</requireFileChecksum>
<requireFileChecksum>
<file>${project.build.directory}/noreplace-one/file1.txt</file>
<checksum>6f1ed002ab5595859014ebf0951522d9</checksum>
<type>md5</type>
</requireFileChecksum>
<requireFileChecksum>
<file>${project.build.directory}/noreplace-one/folder1/file11.txt</file>
<checksum>72cd622783716925706f49d392089b48</checksum>
<type>md5</type>
</requireFileChecksum>
<requireFileChecksum>
<file>${project.build.directory}/noreplace-one/folder1/file12.txt</file>
<checksum>725d3a15f631dda5b058357129fd17fd</checksum>
<type>md5</type>
</requireFileChecksum>
<requireFileChecksum>
<file>${project.build.directory}/replace-linestart/file12.txt</file>
<checksum>791882a340c18da89b524d7735cc085c</checksum>
<type>md5</type>
</requireFileChecksum>
<requireFileChecksum>
<file>${basedir}/folder1/file12.txt</file>
<checksum>6fb82d67ec64b04df220a11adfba81a3</checksum>
<type>md5</type>
</requireFileChecksum>
</rules> </rules>
</configuration> </configuration>
</execution> </execution>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId> <groupId>com.inteligr8</groupId>
@@ -21,9 +21,10 @@ import org.apache.maven.model.Profile;
import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.AbstractLogEnabled;
@Component(role = ProjectPropertyResolver.class) @Component(role = ProjectPropertyResolver.class, instantiationStrategy = "per-lookup")
public class StandardProjectPropertyResolver implements ProjectPropertyResolver { public class StandardProjectPropertyResolver extends AbstractLogEnabled implements ProjectPropertyResolver {
@Requirement @Requirement
private MavenSession session; private MavenSession session;
@@ -51,34 +52,38 @@ public class StandardProjectPropertyResolver implements ProjectPropertyResolver
private Properties findPropertiesObject(String key) { private Properties findPropertiesObject(String key) {
// search the user/cli properties first // search the user/cli properties first
Properties props = this.session.getUserProperties(); Properties props = this.session.getUserProperties();
if (props.containsKey(key)) if (props.containsKey(key)) {
return props; this.getLogger().debug("Found in session user properties: " + key);
// search the profiles next; in order (FIXME maybe we should go backwards?)
for (Profile profile : this.project.getActiveProfiles()) {
props = profile.getProperties();
if (props.containsKey(key))
return props; return props;
} }
// now look at the project props MavenProject ancestor = this.project;
props = this.project.getProperties();
if (props.containsKey(key))
return props;
// now recursively look up the parent project props
MavenProject ancestor = this.project.getParent();
while (ancestor != null) { while (ancestor != null) {
props = ancestor.getProperties(); // search the profiles next; in order (FIXME maybe we should go backwards?)
if (props.containsKey(key)) for (Profile profile : ancestor.getActiveProfiles()) {
props = profile.getProperties();
if (props.containsKey(key)) {
this.getLogger().debug("Found in project profile properties: " + ancestor.getArtifact() + ": " + profile.getId() + ": " + key);
return props; return props;
}
}
// now look at the project props
props = ancestor.getProperties();
if (props.containsKey(key)) {
this.getLogger().debug("Found in project properties: " + ancestor.getArtifact() + ": " + key);
return props;
}
ancestor = ancestor.getParent(); ancestor = ancestor.getParent();
} }
// search the system properties last (FIXME is this right?) // search the system properties last (FIXME is this right?)
props = this.session.getSystemProperties(); props = this.session.getSystemProperties();
if (props.containsKey(key)) if (props.containsKey(key)) {
this.getLogger().debug("Found in system properties: " + key);
return props; return props;
}
return null; return null;
} }
@@ -14,12 +14,11 @@
*/ */
package com.inteligr8.maven.model; package com.inteligr8.maven.model;
import org.apache.commons.lang3.StringUtils;
public class Regex implements Normalizable { public class Regex implements Normalizable {
private String pattern; private String pattern;
private String replacement; private String replacement;
private String previousPattern;
public String getPattern() { public String getPattern() {
return this.pattern; return this.pattern;
@@ -29,6 +28,10 @@ public class Regex implements Normalizable {
return this.replacement; return this.replacement;
} }
public String getPreviousPattern() {
return previousPattern;
}
public Regex setPattern(String pattern) { public Regex setPattern(String pattern) {
this.pattern = pattern; this.pattern = pattern;
return this; return this;
@@ -39,10 +42,15 @@ public class Regex implements Normalizable {
return this; return this;
} }
public Regex setPreviousPattern(String previousPattern) {
this.previousPattern = previousPattern;
return this;
}
@Override @Override
public void normalize() { public void normalize() {
this.pattern = StringUtils.trimToNull(this.pattern); if (this.replacement == null)
this.replacement = StringUtils.trimToNull(this.replacement); this.replacement = "";
} }
} }
@@ -48,8 +48,10 @@ public abstract class AbstractMatchMojo extends AbstractRegexMojo {
@Override @Override
protected void executeOnText(Properties props, String text, String newPropertyName) { protected void executeOnText(Properties props, String text, String newPropertyName) {
boolean matches = this.matches(text); boolean matches = this.matches(text);
if (matches) if (this.verbose)
this.getLog().debug("Matches!"); this.getLog().info("Setting property: " + newPropertyName + ": " + matches);
else if (matches)
this.getLog().info("Matches!");
if (props == null) if (props == null)
props = this.project.getProperties(); props = this.project.getProperties();
props.setProperty(newPropertyName, String.valueOf(matches)); props.setProperty(newPropertyName, String.valueOf(matches));
@@ -97,13 +99,19 @@ public abstract class AbstractMatchMojo extends AbstractRegexMojo {
Matcher matcher = pattern.matcher(text); Matcher matcher = pattern.matcher(text);
if (this.allowPartialMatch) { if (this.allowPartialMatch) {
if (matcher.find()) if (matcher.find()) {
if (this.verbose)
this.getLog().info("Pattern '" + pattern + "' matches text: " + text);
return !this.negate; return !this.negate;
}
} else { } else {
if (matcher.matches()) if (matcher.matches()) {
if (this.verbose)
this.getLog().info("Pattern '" + pattern + "' matches text: " + text);
return !this.negate; return !this.negate;
} }
} }
}
return this.negate; return this.negate;
} }
@@ -16,8 +16,6 @@ package com.inteligr8.maven.regex;
import java.util.Properties; import java.util.Properties;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
@@ -48,6 +46,9 @@ public abstract class AbstractRegexMojo extends AbstractMojo {
@Parameter( property = "skip", required = true, defaultValue = "false" ) @Parameter( property = "skip", required = true, defaultValue = "false" )
protected boolean skip = false; protected boolean skip = false;
@Parameter( property = "verbose", required = true, defaultValue = "false" )
protected boolean verbose = false;
public final void execute() throws MojoExecutionException, MojoFailureException { public final void execute() throws MojoExecutionException, MojoFailureException {
if (this.skip) { if (this.skip) {
this.getLog().debug("Skipped execution"); this.getLog().debug("Skipped execution");
@@ -63,17 +64,14 @@ public abstract class AbstractRegexMojo extends AbstractMojo {
protected abstract void go() throws MojoExecutionException, MojoFailureException; protected abstract void go() throws MojoExecutionException, MojoFailureException;
@OverridingMethodsMustInvokeSuper
protected void validateParamsPreNormalization() throws MojoFailureException { protected void validateParamsPreNormalization() throws MojoFailureException {
this.getLog().debug("Validating parameters before their normalization"); this.getLog().debug("Validating parameters before their normalization");
} }
@OverridingMethodsMustInvokeSuper
protected void normalizeParameters() throws MojoFailureException { protected void normalizeParameters() throws MojoFailureException {
this.getLog().debug("Normalizing parameters"); this.getLog().debug("Normalizing parameters");
} }
@OverridingMethodsMustInvokeSuper
protected void validateParamsPostNormalization() throws MojoFailureException { protected void validateParamsPostNormalization() throws MojoFailureException {
this.getLog().debug("Validating parameters after their normalization"); this.getLog().debug("Validating parameters after their normalization");
} }
@@ -14,21 +14,24 @@
*/ */
package com.inteligr8.maven.regex; package com.inteligr8.maven.regex;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator;
import java.util.Properties; import java.util.Properties;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; import java.util.regex.PatternSyntaxException;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.Parameter;
@@ -38,10 +41,10 @@ import com.inteligr8.nio.DelimitedReadableByteChannel;
public abstract class AbstractReplaceMojo extends AbstractRegexMojo { public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
@Parameter( property = "regexes", required = true ) @Parameter( property = "regexes", required = true )
protected List<Regex> regexes; protected Regex[] regexes;
// Pattern does not implement hashCode, so not using a Map // Pattern does not implement hashCode, so not using a Map
private List<Pair<Pattern, String>> compiledRegexes; private List<Triple<Pattern, String, Pattern>> compiledRegexes;
@Override @Override
protected void executeOnText(Properties props, String text, String newPropertyName) { protected void executeOnText(Properties props, String text, String newPropertyName) {
@@ -50,8 +53,12 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
String originalText = text; String originalText = text;
text = this.replaceAll(text); text = this.replaceAll(text);
if (this.getLog().isDebugEnabled() && !text.equals(originalText)) if (!text.equals(originalText)) {
if (this.verbose)
this.getLog().info("Setting property: " + newPropertyName + ": " + text);
else if (this.getLog().isDebugEnabled())
this.getLog().debug("Manipulated value: " + text); this.getLog().debug("Manipulated value: " + text);
}
if (props == null) if (props == null)
props = this.project.getProperties(); props = this.project.getProperties();
props.setProperty(newPropertyName, text); props.setProperty(newPropertyName, text);
@@ -115,12 +122,20 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
if (this.getLog().isDebugEnabled()) if (this.getLog().isDebugEnabled())
this.getLog().debug("replace first: " + text.length()); this.getLog().debug("replace first: " + text.length());
for (Pair<Pattern, String> regex : this.compiledRegexes) { for (Triple<Pattern, String, Pattern> regex : this.compiledRegexes) {
this.getLog().debug("Applying regex pattern: " + regex.getLeft()); this.getLog().debug("Applying regex pattern: " + regex.getLeft());
this.getLog().debug("Operating on value: " + text); this.getLog().debug("Operating on value: " + text);
Matcher matcher = regex.getLeft().matcher(text); Matcher matcher = regex.getLeft().matcher(text);
text = matcher.replaceFirst(regex.getRight()); if (regex.getRight() == null) {
text = matcher.replaceFirst(regex.getMiddle());
} else if (matcher.find()) {
Integer previousMatchStart = this.findLastMatchIndex(regex.getRight(), text.substring(0, matcher.start()));
text = text.substring(0, previousMatchStart) + text.substring(matcher.start());
matcher = regex.getLeft().matcher(text);
text = matcher.replaceFirst(regex.getMiddle());
}
} }
return text; return text;
@@ -130,10 +145,16 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
if (this.getLog().isDebugEnabled()) if (this.getLog().isDebugEnabled())
this.getLog().debug("replace all: " + file + " => " + tofile); this.getLog().debug("replace all: " + file + " => " + tofile);
boolean overwrite = file.equals(tofile);
boolean didReplace = false; boolean didReplace = false;
Charset charset = Charset.forName(this.charsetName); Charset charset = Charset.forName(this.charsetName);
StringBuilder strbuilder = new StringBuilder(); StringBuilder strbuilder = new StringBuilder();
if (overwrite) {
// if overwriting the existing file, use a temporary file
tofile = File.createTempFile("regexed-", ".tmp").toPath();
}
FileChannel targetChannel = FileChannel.open(tofile, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); FileChannel targetChannel = FileChannel.open(tofile, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
try { try {
FileChannel sourceChannel = FileChannel.open(file, StandardOpenOption.READ); FileChannel sourceChannel = FileChannel.open(file, StandardOpenOption.READ);
@@ -177,31 +198,64 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
targetChannel.close(); targetChannel.close();
} }
if (overwrite) {
Files.move(tofile, file, StandardCopyOption.REPLACE_EXISTING);
}
return didReplace; return didReplace;
} }
protected String replaceAll(String text) { protected String replaceAll(String text) {
if (text == null) if (text == null)
text = ""; text = "";
if (this.getLog().isDebugEnabled())
this.getLog().debug("replace all: " + text.length());
for (Pair<Pattern, String> regex : this.compiledRegexes) { for (Triple<Pattern, String, Pattern> regex : this.compiledRegexes) {
this.getLog().debug("Applying regex pattern: " + regex.getLeft()); this.getLog().debug("Applying regex pattern: " + regex.getLeft());
this.getLog().debug("Operating on value: " + text); this.getLog().debug("Operating on value: " + text);
Matcher matcher = regex.getLeft().matcher(text); Matcher matcher = regex.getLeft().matcher(text);
text = matcher.replaceAll(regex.getRight()); if (regex.getRight() == null) {
String newtext = matcher.replaceAll(regex.getMiddle());
if (this.verbose)
this.getLog().info("Pattern '" + regex.getLeft() + "' matches text: " + text + "; replaced with: " + newtext);
text = newtext;
} else while (matcher.find()) {
Integer previousMatchStart = this.findLastMatchIndex(regex.getRight(), text.substring(0, matcher.start()));
if (previousMatchStart == null) {
// the previous pattern matches nothing; ignore
} else {
String newtext = text.substring(0, previousMatchStart) + text.substring(matcher.start());
if (this.verbose)
this.getLog().info("Pattern '" + regex.getRight() + "' matches text: " + text + "; chopped until next pattern: " + text);
text = newtext;
matcher = regex.getLeft().matcher(text);
}
String newtext = matcher.replaceFirst(regex.getMiddle());
if (this.verbose)
this.getLog().info("Pattern '" + regex.getLeft() + "' matches text: " + text + "; replaced with: " + newtext);
text = newtext;
}
} }
return text; return text;
} }
private Integer findLastMatchIndex(Pattern pattern, String text) {
Matcher matcher = pattern.matcher(text);
Integer index = null;
while (matcher.find())
index = matcher.start();
return index;
}
@Override @Override
protected void validateParamsPreNormalization() throws MojoFailureException { protected void validateParamsPreNormalization() throws MojoFailureException {
super.validateParamsPreNormalization(); super.validateParamsPreNormalization();
if (this.regexes == null) if (this.regexes == null || this.regexes.length == 0)
throw new MojoFailureException("A 'regexes' element is required"); throw new MojoFailureException("A 'regexes' element is required");
} }
@@ -209,22 +263,15 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
protected void normalizeParameters() throws MojoFailureException { protected void normalizeParameters() throws MojoFailureException {
super.normalizeParameters(); super.normalizeParameters();
ListIterator<Regex> r = this.regexes.listIterator(); for (Regex regex : this.regexes)
while (r.hasNext()) {
Regex regex = r.next();
if (regex == null) {
r.remove();
} else {
regex.normalize(); regex.normalize();
} }
}
}
@Override @Override
protected void validateParamsPostNormalization() throws MojoFailureException { protected void validateParamsPostNormalization() throws MojoFailureException {
super.validateParamsPostNormalization(); super.validateParamsPostNormalization();
if (this.regexes.isEmpty()) if (this.regexes == null || this.regexes.length == 0)
throw new MojoFailureException("At least one 'regexes' element is required"); throw new MojoFailureException("At least one 'regexes' element is required");
this.compiledRegexes = new LinkedList<>(); this.compiledRegexes = new LinkedList<>();
@@ -232,7 +279,9 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
this.getLog().debug("Compiling regex pattern: " + regex.getPattern()); this.getLog().debug("Compiling regex pattern: " + regex.getPattern());
try { try {
Pattern pattern = Pattern.compile(regex.getPattern()); Pattern pattern = Pattern.compile(regex.getPattern());
this.compiledRegexes.add(new ImmutablePair<Pattern, String>(pattern, regex.getReplacement())); String previousPatternStr = StringUtils.trimToNull(regex.getPreviousPattern());
Pattern previousPattern = previousPatternStr == null ? null : Pattern.compile(previousPatternStr);
this.compiledRegexes.add(new ImmutableTriple<>(pattern, regex.getReplacement(), previousPattern));
} catch (PatternSyntaxException pse) { } catch (PatternSyntaxException pse) {
throw new MojoFailureException("'" + regex.getPattern() + "' is not a valid regular expression: " + pse.getMessage()); throw new MojoFailureException("'" + regex.getPattern() + "' is not a valid regular expression: " + pse.getMessage());
} }
@@ -33,6 +33,12 @@ public class CopyFileMojo extends AbstractFileMojo {
} else { } else {
Files.copy(sourcePath, targetPath); Files.copy(sourcePath, targetPath);
} }
if (this.verbose) {
this.getLog().info("Copied " + sourcePath + " to " + targetPath);
} else {
this.getLog().info("Copied " + sourcePath.getFileName() + " to " + targetPath);
}
} }
} }
@@ -14,6 +14,7 @@
*/ */
package com.inteligr8.maven.regex; package com.inteligr8.maven.regex;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@@ -46,25 +47,32 @@ public class MatchFileContentMojo extends AbstractMatchMojo {
this.getLog().debug("Executing file regex match"); this.getLog().debug("Executing file regex match");
boolean matches = this.matchesContentInFileSet(); boolean matches = this.matchesContentInFileSet();
if (matches) if (this.verbose)
this.getLog().info("Setting property: " + this.newProperty + ": " + matches);
else if (matches)
this.getLog().info("Matches!"); this.getLog().info("Matches!");
this.project.getProperties().setProperty(this.newProperty, String.valueOf(matches)); this.project.getProperties().setProperty(this.newProperty, String.valueOf(matches));
} }
private boolean matchesContentInFileSet() throws MojoExecutionException { private boolean matchesContentInFileSet() throws MojoExecutionException {
FileSetManager fsman = new FileSetManager(this.getLog()); FileSetManager fsman = new FileSetManager();
Path basepath = this.project.getBasedir().toPath(); Path basepath = this.project.getBasedir().toPath();
try { try {
for (FileSet fileSet : this.filesets) { for (FileSet fileSet : this.filesets) {
Path baseInputPath = this.resolveDirectory(basepath, fileSet.getDirectory(), "fileset input");
String[] filePathsAndNames = fsman.getIncludedFiles(fileSet); String[] filePathsAndNames = fsman.getIncludedFiles(fileSet);
for (String filePathAndName : filePathsAndNames) { for (String filePathAndName : filePathsAndNames) {
Path file = basepath.resolve(filePathAndName); Path file = baseInputPath.resolve(filePathAndName);
if (!Files.isDirectory(file)) if (!Files.isDirectory(file))
if (this.matches(file, this.chunkSize)) if (this.matches(file, this.chunkSize)) {
if (this.verbose)
this.getLog().info("A pattern matches file: " + file);
return true; return true;
} }
} }
}
} catch (IOException ie) { } catch (IOException ie) {
throw new MojoExecutionException("Execution failed due to an I/O related issue", ie); throw new MojoExecutionException("Execution failed due to an I/O related issue", ie);
} }
@@ -72,10 +80,37 @@ public class MatchFileContentMojo extends AbstractMatchMojo {
return this.negate; return this.negate;
} }
private Path resolveDirectory(Path basepath, String directory, String errorName) throws IOException, MojoExecutionException {
Path path = new File(directory).toPath();
if (!path.isAbsolute())
path = basepath.resolve(path);
if (!Files.exists(path))
throw new MojoExecutionException("A " + errorName + " directory does not exist: " + directory);
if (!Files.isDirectory(path))
throw new MojoExecutionException("A " + errorName + " does reference a directory: " + directory);
return path;
}
@Override
protected void validateParamsPreNormalization() throws MojoFailureException {
super.validateParamsPreNormalization();
if (this.filesets == null || this.filesets.isEmpty())
throw new MojoFailureException("At least one 'fileset' is required");
}
@Override @Override
protected void normalizeParameters() throws MojoFailureException { protected void normalizeParameters() throws MojoFailureException {
super.normalizeParameters(); super.normalizeParameters();
for (FileSet fileset : this.filesets) {
if (fileset.getDirectory() == null)
fileset.setDirectory(this.project.getBasedir().getAbsolutePath());
}
this.newProperty = StringUtils.trimToNull(this.newProperty); this.newProperty = StringUtils.trimToNull(this.newProperty);
} }
@@ -83,8 +118,6 @@ public class MatchFileContentMojo extends AbstractMatchMojo {
protected void validateParamsPostNormalization() throws MojoFailureException { protected void validateParamsPostNormalization() throws MojoFailureException {
super.validateParamsPostNormalization(); super.validateParamsPostNormalization();
if (this.filesets == null || this.filesets.isEmpty())
throw new MojoFailureException("At least one 'fileset' is required");
if (this.newProperty == null) if (this.newProperty == null)
throw new MojoFailureException("The 'newProperty' element is required"); throw new MojoFailureException("The 'newProperty' element is required");
} }
@@ -67,9 +67,12 @@ public class MatchFilenameMojo extends AbstractMatchMojo {
if (!Files.isDirectory(file)) { if (!Files.isDirectory(file)) {
getLog().debug("Visiting file: " + file); getLog().debug("Visiting file: " + file);
if (matches(basepath.relativize(file).toString())) if (matches(basepath.relativize(file).toString())) {
if (MatchFilenameMojo.this.verbose)
MatchFilenameMojo.this.getLog().info("A pattern matches filename: " + file);
matches.setTrue(); matches.setTrue();
} }
}
return matches.isTrue() ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE; return matches.isTrue() ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
} }
@@ -82,7 +85,9 @@ public class MatchFilenameMojo extends AbstractMatchMojo {
throw new MojoExecutionException(ie.getMessage(), ie); throw new MojoExecutionException(ie.getMessage(), ie);
} }
if (matches.booleanValue()) if (this.verbose)
this.getLog().info("Setting property: " + this.newProperty + ": " + matches);
else if (matches.booleanValue())
this.getLog().info("Matches!"); this.getLog().info("Matches!");
this.project.getProperties().setProperty(this.newProperty, matches.toString()); this.project.getProperties().setProperty(this.newProperty, matches.toString());
} }
@@ -33,6 +33,12 @@ public class MoveFileMojo extends AbstractFileMojo {
} else { } else {
Files.move(sourcePath, targetPath); Files.move(sourcePath, targetPath);
} }
if (this.verbose) {
this.getLog().info("Moved " + sourcePath + " to " + targetPath);
} else {
this.getLog().info("Moved " + sourcePath.getFileName() + " to " + targetPath);
}
} }
} }
@@ -47,27 +47,28 @@ public class ReplaceFileContentMojo extends AbstractReplaceMojo {
private boolean replaceContentInFileSet() throws MojoExecutionException { private boolean replaceContentInFileSet() throws MojoExecutionException {
boolean didReplace = false; boolean didReplace = false;
FileSetManager fsman = new FileSetManager(this.getLog()); FileSetManager fsman = new FileSetManager();
Path basepath = this.project.getBasedir().toPath(); Path basepath = this.project.getBasedir().toPath();
try { try {
for (FileSet fileSet : this.filesets) { for (FileSet fileSet : this.filesets) {
String outputDir = fileSet.getOutputDirectory(); Path baseInputPath = this.resolveDirectory(basepath, fileSet.getDirectory(), false, "fileset input");
Path baseOutputPath = new File(outputDir).toPath(); Path baseOutputPath = this.resolveDirectory(basepath, fileSet.getOutputDirectory(), true, "fileset output");
if (!Files.exists(baseOutputPath))
Files.createDirectories(baseOutputPath);
if (!Files.isDirectory(baseOutputPath))
throw new MojoExecutionException("A fileset output directory does not reference a directory: " + outputDir);
String[] filePathsAndNames = fsman.getIncludedFiles(fileSet); String[] filePathsAndNames = fsman.getIncludedFiles(fileSet);
for (String filePathAndName : filePathsAndNames) { for (String filePathAndName : filePathsAndNames) {
Path file = basepath.resolve(filePathAndName); Path file = baseInputPath.resolve(filePathAndName);
Path tofile = baseOutputPath.resolve(filePathAndName); Path tofile = baseOutputPath.resolve(filePathAndName);
if (!Files.exists(tofile.getParent())) if (!Files.exists(tofile.getParent()))
Files.createDirectories(tofile.getParent()); Files.createDirectories(tofile.getParent());
if (!Files.isDirectory(file)) if (!Files.isDirectory(file)) {
didReplace = this.replaceAll(file, tofile, this.chunkSize) || didReplace; if (this.replaceAll(file, tofile, this.chunkSize)) {
if (this.verbose)
this.getLog().info("A pattern replaced in file: " + file + " => " + tofile);
didReplace = true;
}
}
} }
} }
} catch (IOException ie) { } catch (IOException ie) {
@@ -77,20 +78,46 @@ public class ReplaceFileContentMojo extends AbstractReplaceMojo {
return didReplace; return didReplace;
} }
@Override private Path resolveDirectory(Path basepath, String directory, boolean createIfMissing, String errorName) throws IOException, MojoExecutionException {
protected void normalizeParameters() throws MojoFailureException { if (directory == null)
super.normalizeParameters(); return this.project.getBasedir().toPath();
Path path = new File(directory).toPath();
if (!path.isAbsolute())
path = basepath.resolve(path);
if (!Files.exists(path)) {
if (createIfMissing) {
Files.createDirectories(path);
} else {
throw new MojoExecutionException("A " + errorName + " directory does not exist: " + directory);
}
}
if (!Files.isDirectory(path))
throw new MojoExecutionException("A " + errorName + " does reference a directory: " + directory);
return path;
} }
@Override @Override
protected void validateParamsPostNormalization() throws MojoFailureException { protected void validateParamsPreNormalization() throws MojoFailureException {
super.validateParamsPostNormalization(); super.validateParamsPreNormalization();
if (this.filesets == null || this.filesets.isEmpty()) if (this.filesets == null || this.filesets.isEmpty())
throw new MojoFailureException("At least one 'fileset' is required"); throw new MojoFailureException("At least one 'fileset' is required");
for (FileSet fileset : this.filesets) }
@Override
protected void normalizeParameters() throws MojoFailureException {
super.normalizeParameters();
for (FileSet fileset : this.filesets) {
if (fileset.getDirectory() == null)
fileset.setDirectory(this.project.getBasedir().getAbsolutePath());
if (fileset.getOutputDirectory() == null) if (fileset.getOutputDirectory() == null)
throw new MojoFailureException("All 'fileset' must have an 'outputDirectory'"); fileset.setOutputDirectory(fileset.getDirectory());
}
} }
} }
@@ -28,7 +28,7 @@ public class ReplaceTextMojo extends AbstractReplaceMojo {
@Parameter( property = "text", required = true ) @Parameter( property = "text", required = true )
protected String text; protected String text;
@Parameter( property = "newProperty", required = false ) @Parameter( property = "newProperty", required = true )
protected String newProperty; protected String newProperty;
@Override @Override
@@ -23,8 +23,6 @@ import java.nio.charset.CharsetDecoder;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.annotation.OverridingMethodsMustInvokeSuper;
public class DelimitedReadableByteChannel implements ReadableByteChannel { public class DelimitedReadableByteChannel implements ReadableByteChannel {
private final CharBuffer buffer; private final CharBuffer buffer;
@@ -50,7 +48,6 @@ public class DelimitedReadableByteChannel implements ReadableByteChannel {
} }
@Override @Override
@OverridingMethodsMustInvokeSuper
public void close() throws IOException { public void close() throws IOException {
this.rbchannel.close(); this.rbchannel.close();
} }
@@ -0,0 +1,29 @@
package com.inteligr8.maven.regex;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.maven.shared.model.fileset.FileSet;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.junit.Assert;
import org.junit.Test;
public class FileSetUnitTest {
@Test
public void srcMainJava() {
FileSet fileset = new FileSet();
fileset.setDirectory("src/main/java");
fileset.setIncludes(Arrays.asList("**/*.java"));
String fs = File.separator;
FileSetManager fsman = new FileSetManager();
Set<String> files = new HashSet<>(Arrays.asList(fsman.getIncludedFiles(fileset)));
Assert.assertTrue(files.size() > 15);
System.err.println(files);
Assert.assertTrue(files.contains("com"+fs+"inteligr8"+fs+"maven"+fs+"regex"+fs+"AbstractFileMojo.java"));
}
}