36 changed files with 993 additions and 552 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.
+130 -53
View File
@@ -1,19 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
<project xmlns="http://maven.apache.org/POM/4.1.0"
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">
<modelVersion>4.0.0</modelVersion>
xsi:schemaLocation="http://maven.apache.org/POM/4.1.0 https://maven.apache.org/xsd/maven-4.1.0.xsd">
<modelVersion>4.1.0</modelVersion>
<groupId>com.inteligr8</groupId>
<artifactId>regex-maven-plugin</artifactId>
<version>1.0.0</version>
<version>2.0-SNAPSHOT</version>
<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>
<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>
<organization>
<name>Inteligr8</name>
@@ -24,71 +35,110 @@
<id>brian.long</id>
<name>Brian Long</name>
<email>brian@inteligr8.com</email>
<url>https://twitter.com/brianmlong</url>
<url>https://x.com/brianmlong</url>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.version>3.6.3</maven.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.release>17</maven.compiler.release>
<maven.version>4.0.0-rc-5</maven.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>file-management</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-api-core</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-api-annotations</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>6.0.3</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>file-management</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>${maven.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.6.0</version>
<artifactId>maven-api-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>${maven.version}</version>
<artifactId>maven-api-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>3.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>${maven.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.15.2</version>
</plugin>
<plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>3.10.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<goalPrefix>regex</goalPrefix>
</configuration>
@@ -107,10 +157,10 @@
</execution>
</executions>
</plugin>
<!--
<plugin>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-metadata</artifactId>
<version>2.0.0</version>
<executions>
<execution>
<goals>
@@ -119,9 +169,9 @@
</execution>
</executions>
</plugin>
-->
<plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<projectsDirectory>${basedir}/src/it</projectsDirectory>
<cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
@@ -142,19 +192,6 @@
</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>
</plugins>
</build>
@@ -170,7 +207,6 @@
<plugins>
<plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>3.2.2</version>
<executions>
<execution>
<id>run-its</id>
@@ -189,14 +225,55 @@
</plugins>
</build>
</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>
<distributionManagement>
<repository>
<id>inteligr8-releases</id>
<name>Inteligr8 Releases</name>
<url>http://repos.inteligr8.com/nexus/repository/inteligr8-public</url>
</repository>
</distributionManagement>
</project>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<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.
sometimes this doesn՚t work with unicode characters.
good luck!
+87 -14
View File
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
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">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>
<groupId>com.inteligr8</groupId>
@@ -11,7 +11,7 @@
<packaging>pom</packaging>
<name>Replace File Plugin Tests</name>
<build>
<plugins>
<plugin>
@@ -62,7 +62,7 @@
<excludes>
<exclude>pom.xml</exclude>
<exclude>*.log</exclude>
<exclude>target</exclude>
<exclude>target/**/*</exclude>
</excludes>
<outputDirectory>${project.build.directory}/noreplace-one</outputDirectory>
</fileset>
@@ -75,31 +75,104 @@
</regexes>
</configuration>
</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>
</plugin>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<version>3.0.0-M3</version>
<executions>
<execution>
<id>assert</id>
<goals><goal>enforce</goal></goals>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<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>
<files>
<file>${project.build.directory}/replace-one/folder1/file11.txt</file>
<file>${project.build.directory}/replace-one/folder1/file12.txt</file>
</files>
</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>
</configuration>
</execution>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
+1 -1
View File
@@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>com.inteligr8</groupId>
@@ -1,27 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.maven;
import java.util.Properties;
public interface ProjectPropertyResolver {
Properties resolveScope(String propertyName);
String resolve(String propertyName);
String resolve(String propertyName, String defaultValue);
}
@@ -1,86 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.maven;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Profile;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
@Component(role = ProjectPropertyResolver.class)
public class StandardProjectPropertyResolver implements ProjectPropertyResolver {
@Requirement
private MavenSession session;
@Requirement
private MavenProject project;
@Override
public String resolve(String propertyName) {
Properties props = this.findPropertiesObject(propertyName);
return props == null ? null : props.getProperty(propertyName);
}
@Override
public String resolve(String propertyName, String defaultValue) {
Properties props = this.findPropertiesObject(propertyName);
return props == null ? null : props.getProperty(propertyName, defaultValue);
}
@Override
public Properties resolveScope(String propertyName) {
return this.findPropertiesObject(propertyName);
}
private Properties findPropertiesObject(String key) {
// search the user/cli properties first
Properties props = this.session.getUserProperties();
if (props.containsKey(key))
return props;
// 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;
}
// now look at the project props
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) {
props = ancestor.getProperties();
if (props.containsKey(key))
return props;
ancestor = ancestor.getParent();
}
// search the system properties last (FIXME is this right?)
props = this.session.getSystemProperties();
if (props.containsKey(key))
return props;
return null;
}
}
@@ -14,7 +14,6 @@
*/
package com.inteligr8.maven.regex;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
@@ -22,29 +21,31 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Parameter;
public abstract class AbstractFileMojo extends AbstractReplaceMojo {
@Inject
private Log logger;
@Parameter( property = "sourceDirectory", required = false )
protected File sourceDirectory;
protected Path sourceDirectory;
@Parameter( property = "targetDirectory", required = false )
protected File targetDirectory;
protected Path targetDirectory;
@Parameter( property = "overwrite", required = true, defaultValue = "true" )
protected boolean overwrite = true;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing file regex");
public void go() throws MojoException {
this.logger.debug("Executing file regex");
final Path sourcePath = this.sourceDirectory.toPath();
final Path targetPath = this.targetDirectory.toPath();
try {
Files.walkFileTree(sourcePath, new FileVisitor<Path>() {
Files.walkFileTree(this.sourceDirectory, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
@@ -61,12 +62,12 @@ public abstract class AbstractFileMojo extends AbstractReplaceMojo {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
String relativePath = sourcePath.relativize(file).toString();
String relativePath = sourceDirectory.relativize(file).toString();
String replacedRelativePath = replaceFirst(relativePath);
if (!relativePath.equals(replacedRelativePath)) {
Path newFile = targetPath.resolve(replacedRelativePath);
Path newFile = targetDirectory.resolve(replacedRelativePath);
if (file.equals(newFile)) {
AbstractFileMojo.this.getLog().error("Relative paths are different, but the resultant paths are the same??");
AbstractFileMojo.this.logger.error("Relative paths are different, but the resultant paths are the same??");
throw new RuntimeException("This should never happen");
}
@@ -83,14 +84,14 @@ public abstract class AbstractFileMojo extends AbstractReplaceMojo {
}
});
} catch (IOException ie) {
throw new MojoExecutionException(ie.getMessage(), ie);
throw new MojoException(ie.getMessage(), ie);
}
}
protected abstract void executeOnFile(Path sourcePath, Path targetPath) throws IOException;
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
if (this.sourceDirectory == null)
@@ -22,32 +22,42 @@ import java.nio.file.StandardOpenOption;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Parameter;
import com.inteligr8.nio.DelimitedReadableByteChannel;
import com.inteligr8.maven.regex.nio.DelimitedReadableByteChannel;
public abstract class AbstractMatchMojo extends AbstractRegexMojo {
@Inject
private Log logger;
@Parameter( property = "allowPartialMatch", required = true, defaultValue = "true" )
protected boolean allowPartialMatch = true;
@Parameter( property = "patterns", required = true )
protected List<String> patterns;
@Parameter( property = "negate", required = true, defaultValue = "false" )
protected boolean negate = false;
private List<Pattern> compiledPatterns;
@Override
protected void executeOnText(Properties props, String text, String newPropertyName) {
protected void executeOnText(String text, String newPropertyName) {
boolean matches = this.matches(text);
if (matches)
this.getLog().debug("Matches!");
props.setProperty(newPropertyName, String.valueOf(matches));
if (this.verbose)
this.logger.info("Setting property: " + newPropertyName + ": " + matches);
else if (matches)
this.logger.info("Matches!");
this.manager.setProperty(this.project, newPropertyName, String.valueOf(matches));
}
protected boolean matches(Path file, int chunkSize) throws IOException {
@@ -79,42 +89,46 @@ public abstract class AbstractMatchMojo extends AbstractRegexMojo {
if (this.allowMultiLineMatch)
return this.matches(strbuilder.toString());
return false;
return this.negate;
}
protected boolean matches(String text) {
if (text == null)
text = "";
for (Pattern pattern : this.compiledPatterns) {
this.getLog().debug("Applying regex pattern: " + pattern);
if (text == null) {
// TODO we want to capture this somehow
this.logger.debug("Applying regex pattern: " + pattern);
this.logger.debug("Operating on value: " + text);
Matcher matcher = pattern.matcher(text);
if (this.allowPartialMatch) {
if (matcher.find()) {
if (this.verbose)
this.logger.info("Pattern '" + pattern + "' matches text: " + text);
return !this.negate;
}
} else {
this.getLog().debug("Operating on value: " + text);
Matcher matcher = pattern.matcher(text);
if (this.allowPartialMatch) {
if (matcher.find())
return true;
} else {
if (matcher.matches())
return true;
}
if (matcher.matches()) {
if (this.verbose)
this.logger.info("Pattern '" + pattern + "' matches text: " + text);
return !this.negate;
}
}
}
return false;
return this.negate;
}
@Override
protected void validateParamsPreNormalization() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.patterns == null)
throw new MojoFailureException("A 'patterns' element is required");
throw new MojoException("A 'patterns' element is required");
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
ListIterator<String> p = this.patterns.listIterator();
@@ -127,19 +141,19 @@ public abstract class AbstractMatchMojo extends AbstractRegexMojo {
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.patterns.isEmpty())
throw new MojoFailureException("At least one 'patterns' element is required");
throw new MojoException("At least one 'patterns' element is required");
this.compiledPatterns = new LinkedList<>();
for (String pattern : this.patterns) {
this.getLog().debug("Compiling regex pattern: " + pattern);
this.logger.debug("Compiling regex pattern: " + pattern);
try {
this.compiledPatterns.add(Pattern.compile(pattern));
} catch (PatternSyntaxException pse) {
throw new MojoFailureException("'" + pattern + "' is not a valid regular expression: " + pse.getMessage());
throw new MojoException("'" + pattern + "' is not a valid regular expression: " + pse.getMessage());
}
}
}
@@ -14,30 +14,30 @@
*/
package com.inteligr8.maven.regex;
import java.util.Properties;
import java.util.Map;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import org.apache.maven.api.Project;
import org.apache.maven.api.Session;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.Mojo;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Parameter;
import org.apache.maven.api.services.ProjectManager;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.annotations.Requirement;
import com.inteligr8.maven.ProjectPropertyResolver;
public abstract class AbstractRegexMojo extends AbstractMojo {
public abstract class AbstractRegexMojo implements Mojo {
@Inject
private Log logger;
@Parameter( defaultValue = "${project}", readonly = true )
protected MavenProject project;
@Inject
protected Project project;
@Parameter( defaultValue = "${session}", readonly = true )
protected MavenSession session;
@Requirement
private ProjectPropertyResolver propResolver;
@Inject
protected Session session;
@Inject
protected ProjectManager manager;
@Parameter( property = "allowMultiLineMatch", required = true, defaultValue = "false" )
protected boolean allowMultiLineMatch = false;
@@ -47,10 +47,13 @@ public abstract class AbstractRegexMojo extends AbstractMojo {
@Parameter( property = "skip", required = true, defaultValue = "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 MojoException {
if (this.skip) {
this.getLog().debug("Skipped execution");
this.logger.debug("Skipped execution");
return;
}
@@ -61,36 +64,33 @@ public abstract class AbstractRegexMojo extends AbstractMojo {
this.go();
}
protected abstract void go() throws MojoExecutionException, MojoFailureException;
protected abstract void go() throws MojoException;
@OverridingMethodsMustInvokeSuper
protected void validateParamsPreNormalization() throws MojoFailureException {
this.getLog().debug("Validating parameters before their normalization");
protected void validateParamsPreNormalization() throws MojoException {
this.logger.debug("Validating parameters before their normalization");
}
@OverridingMethodsMustInvokeSuper
protected void normalizeParameters() throws MojoFailureException {
this.getLog().debug("Normalizing parameters");
protected void normalizeParameters() throws MojoException {
this.logger.debug("Normalizing parameters");
}
@OverridingMethodsMustInvokeSuper
protected void validateParamsPostNormalization() throws MojoFailureException {
this.getLog().debug("Validating parameters after their normalization");
protected void validateParamsPostNormalization() throws MojoException {
this.logger.debug("Validating parameters after their normalization");
}
protected final void executeOnProperty(String propertyName, String newPropertyName) {
this.getLog().debug("Finding property: " + propertyName);
this.logger.debug("Finding property: " + propertyName);
Properties props = this.propResolver.resolveScope(propertyName);
if (props == null) {
this.getLog().info("Property not found: " + propertyName);
return;
}
// FIXME getEffectiveProperties() is not cached and could be expensive if called a lot
// maybe create a session scoped service that handles that part
Map<String, String> props = this.session.getEffectiveProperties(this.project);
String existingPropertyValue = props.get(propertyName);
if (existingPropertyValue == null)
this.logger.debug("Property not found: " + propertyName);
String propertyValue = props.getProperty(propertyName);
this.executeOnText(props, propertyValue, newPropertyName);
this.executeOnText(existingPropertyValue, newPropertyName);
}
protected abstract void executeOnText(Properties props, String text, String newPropertyName);
protected abstract void executeOnText(String text, String newPropertyName);
}
@@ -14,48 +14,62 @@
*/
package com.inteligr8.maven.regex;
import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Parameter;
import com.inteligr8.maven.model.Regex;
import com.inteligr8.nio.DelimitedReadableByteChannel;
import com.inteligr8.maven.regex.model.Regex;
import com.inteligr8.maven.regex.nio.DelimitedReadableByteChannel;
public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
@Inject
private Log logger;
@Parameter( property = "regexes", required = true )
protected List<Regex> regexes;
protected Regex[] regexes;
// Pattern does not implement hashCode, so not using a Map
private List<Pair<Pattern, String>> compiledRegexes;
private List<Triple<Pattern, String, Pattern>> compiledRegexes;
@Override
protected void executeOnText(Properties props, String text, String newPropertyName) {
protected void executeOnText(String text, String newPropertyName) {
if (text == null)
text = "";
String originalText = text;
text = this.replaceAll(text);
if (!text.equals(originalText)) {
if (this.verbose)
this.logger.info("Setting property: " + newPropertyName + ": " + text);
else if (this.logger.isDebugEnabled())
this.logger.debug("Manipulated value: " + text);
}
if (this.getLog().isDebugEnabled() && !text.equals(originalText))
this.getLog().debug("Manipulated value: " + text);
props.setProperty(newPropertyName, text);
this.manager.setProperty(this.project, newPropertyName, text);
}
protected boolean replaceFirst(Path file, Path tofile, int chunkSize) throws IOException {
if (this.getLog().isDebugEnabled())
this.getLog().debug("replace first: " + file + " => " + tofile);
if (this.logger.isDebugEnabled())
this.logger.debug("replace first: " + file + " => " + tofile);
boolean didReplace = false;
Charset charset = Charset.forName(this.charsetName);
@@ -106,19 +120,24 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
}
protected String replaceFirst(String text) {
if (this.getLog().isDebugEnabled())
this.getLog().debug("replace first: " + text.length());
if (text == null)
text = "";
if (this.logger.isDebugEnabled())
this.logger.debug("replace first: " + text.length());
for (Pair<Pattern, String> regex : this.compiledRegexes) {
this.getLog().debug("Applying regex pattern: " + regex.getLeft());
if (text == null) {
// TODO we want to capture this somehow
} else {
this.getLog().debug("Operating on value: " + text);
Matcher matcher = regex.getLeft().matcher(text);
text = matcher.replaceFirst(regex.getRight());
for (Triple<Pattern, String, Pattern> regex : this.compiledRegexes) {
this.logger.debug("Applying regex pattern: " + regex.getLeft());
this.logger.debug("Operating on value: " + text);
Matcher matcher = regex.getLeft().matcher(text);
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());
}
}
@@ -126,13 +145,19 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
}
protected boolean replaceAll(Path file, Path tofile, int chunkSize) throws IOException {
if (this.getLog().isDebugEnabled())
this.getLog().debug("replace all: " + file + " => " + tofile);
if (this.logger.isDebugEnabled())
this.logger.debug("replace all: " + file + " => " + tofile);
boolean overwrite = file.equals(tofile);
boolean didReplace = false;
Charset charset = Charset.forName(this.charsetName);
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);
try {
FileChannel sourceChannel = FileChannel.open(file, StandardOpenOption.READ);
@@ -147,10 +172,10 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
strbuilder.append(rbchannel.getLastDelimiterRead());
} else {
String line = strbuilder.toString();
this.getLog().debug("line: " + line);
this.logger.debug("line: " + line);
String processedLine = this.replaceAll(line);
if (!didReplace || (this.getLog().isDebugEnabled() && !line.equals(processedLine))) {
this.getLog().debug("replaced line: " + processedLine);
if (!didReplace || (this.logger.isDebugEnabled() && !line.equals(processedLine))) {
this.logger.debug("replaced line: " + processedLine);
didReplace = true;
}
@@ -176,67 +201,92 @@ public abstract class AbstractReplaceMojo extends AbstractRegexMojo {
targetChannel.close();
}
if (overwrite) {
Files.move(tofile, file, StandardCopyOption.REPLACE_EXISTING);
}
return didReplace;
}
protected String replaceAll(String text) {
if (this.getLog().isDebugEnabled())
this.getLog().debug("replace all: " + text.length());
if (text == null)
text = "";
for (Pair<Pattern, String> regex : this.compiledRegexes) {
this.getLog().debug("Applying regex pattern: " + regex.getLeft());
if (text == null) {
// TODO we want to capture this somehow
} else {
this.getLog().debug("Operating on value: " + text);
Matcher matcher = regex.getLeft().matcher(text);
text = matcher.replaceAll(regex.getRight());
}
for (Triple<Pattern, String, Pattern> regex : this.compiledRegexes) {
this.logger.debug("Applying regex pattern: " + regex.getLeft());
this.logger.debug("Operating on value: " + text);
Matcher matcher = regex.getLeft().matcher(text);
if (regex.getRight() == null) {
String newtext = matcher.replaceAll(regex.getMiddle());
if (this.verbose)
this.logger.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.logger.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.logger.info("Pattern '" + regex.getLeft() + "' matches text: " + text + "; replaced with: " + newtext);
text = newtext;
}
}
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
protected void validateParamsPreNormalization() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.regexes == null)
throw new MojoFailureException("A 'regexes' element is required");
if (this.regexes == null || this.regexes.length == 0)
throw new MojoException("A 'regexes' element is required");
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
ListIterator<Regex> r = this.regexes.listIterator();
while (r.hasNext()) {
Regex regex = r.next();
if (regex == null) {
r.remove();
} else {
regex.normalize();
}
}
for (Regex regex : this.regexes)
regex.normalize();
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.regexes.isEmpty())
throw new MojoFailureException("At least one 'regexes' element is required");
if (this.regexes == null || this.regexes.length == 0)
throw new MojoException("At least one 'regexes' element is required");
this.compiledRegexes = new LinkedList<>();
for (Regex regex : this.regexes) {
this.getLog().debug("Compiling regex pattern: " + regex.getPattern());
this.logger.debug("Compiling regex pattern: " + regex.getPattern());
try {
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) {
throw new MojoFailureException("'" + regex.getPattern() + "' is not a valid regular expression: " + pse.getMessage());
throw new MojoException("'" + regex.getPattern() + "' is not a valid regular expression: " + pse.getMessage());
}
}
}
@@ -19,12 +19,15 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.maven.plugins.annotations.Mojo;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.annotations.Mojo;
@Mojo( name = "copy-file", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "copy-file")
public class CopyFileMojo extends AbstractFileMojo {
@Inject
private Log logger;
@Override
protected void executeOnFile(Path sourcePath, Path targetPath) throws IOException {
@@ -33,6 +36,12 @@ public class CopyFileMojo extends AbstractFileMojo {
} else {
Files.copy(sourcePath, targetPath);
}
if (this.verbose) {
this.logger.info("Copied " + sourcePath + " to " + targetPath);
} else {
this.logger.info("Copied " + sourcePath.getFileName() + " to " + targetPath);
}
}
}
@@ -14,23 +14,26 @@
*/
package com.inteligr8.maven.regex;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
import org.apache.maven.shared.model.fileset.FileSet;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.codehaus.plexus.component.annotations.Component;
@Mojo( name = "match-file", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "match-file")
public class MatchFileContentMojo extends AbstractMatchMojo {
@Inject
private Log logger;
@Parameter( property = "chunkSize", required = true, defaultValue = "1024" )
protected int chunkSize = 1024;
@@ -42,51 +45,83 @@ public class MatchFileContentMojo extends AbstractMatchMojo {
protected String newProperty;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing file regex match");
public void go() throws MojoException {
this.logger.debug("Executing file regex match");
boolean matches = this.matchesContentInFileSet();
if (matches)
this.getLog().info("Matches!");
this.project.getProperties().setProperty(this.newProperty, String.valueOf(matches));
if (this.verbose)
this.logger.info("Setting property: " + this.newProperty + ": " + matches);
else if (matches)
this.logger.info("Matches!");
this.manager.setProperty(this.project, this.newProperty, String.valueOf(matches));
}
private boolean matchesContentInFileSet() throws MojoExecutionException {
FileSetManager fsman = new FileSetManager(this.getLog());
Path basepath = this.project.getBasedir().toPath();
private boolean matchesContentInFileSet() throws MojoException {
FileSetManager fsman = new FileSetManager();
Path basepath = this.project.getBasedir();
try {
for (FileSet fileSet : this.filesets) {
Path baseInputPath = this.resolveDirectory(basepath, fileSet.getDirectory(), "fileset input");
String[] filePathsAndNames = fsman.getIncludedFiles(fileSet);
for (String filePathAndName : filePathsAndNames) {
Path file = basepath.resolve(filePathAndName);
Path file = baseInputPath.resolve(filePathAndName);
if (!Files.isDirectory(file))
if (this.matches(file, this.chunkSize))
if (this.matches(file, this.chunkSize)) {
if (this.verbose)
this.logger.info("A pattern matches file: " + file);
return true;
}
}
}
} catch (IOException ie) {
throw new MojoExecutionException("Execution failed due to an I/O related issue", ie);
throw new MojoException("Execution failed due to an I/O related issue", ie);
}
return false;
return this.negate;
}
private Path resolveDirectory(Path basepath, String directory, String errorName) throws IOException, MojoException {
Path path = new File(directory).toPath();
if (!path.isAbsolute())
path = basepath.resolve(path);
if (!Files.exists(path))
throw new MojoException("A " + errorName + " directory does not exist: " + directory);
if (!Files.isDirectory(path))
throw new MojoException("A " + errorName + " does reference a directory: " + directory);
return path;
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.filesets == null || this.filesets.isEmpty())
throw new MojoException("At least one 'fileset' is required");
}
@Override
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
for (FileSet fileset : this.filesets) {
if (fileset.getDirectory() == null)
fileset.setDirectory(this.project.getBasedir().toAbsolutePath().toString());
}
this.newProperty = StringUtils.trimToNull(this.newProperty);
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.filesets == null || this.filesets.isEmpty())
throw new MojoFailureException("At least one 'fileset' is required");
if (this.newProperty == null)
throw new MojoFailureException("The 'newProperty' element is required");
throw new MojoException("The 'newProperty' element is required");
}
}
@@ -14,7 +14,6 @@
*/
package com.inteligr8.maven.regex;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
@@ -24,31 +23,32 @@ import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "match-filename", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "match-filename")
public class MatchFilenameMojo extends AbstractMatchMojo {
@Inject
private Log logger;
@Parameter( property = "sourceDirectory", required = false )
protected File sourceDirectory;
protected Path sourceDirectory;
@Parameter( property = "newProperty", required = true )
protected String newProperty;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing file regex match");
public void go() throws MojoException {
this.logger.debug("Executing file regex match");
final MutableBoolean matches = new MutableBoolean(false);
final Path basepath = this.sourceDirectory.toPath();
try {
Files.walkFileTree(basepath, new FileVisitor<Path>() {
Files.walkFileTree(this.sourceDirectory, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
@@ -65,10 +65,13 @@ public class MatchFilenameMojo extends AbstractMatchMojo {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
getLog().debug("Visiting file: " + file);
logger.debug("Visiting file: " + file);
if (matches(basepath.relativize(file).toString()))
if (matches(sourceDirectory.relativize(file).toString())) {
if (MatchFilenameMojo.this.verbose)
MatchFilenameMojo.this.logger.info("A pattern matches filename: " + file);
matches.setTrue();
}
}
return matches.isTrue() ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
}
@@ -79,16 +82,18 @@ public class MatchFilenameMojo extends AbstractMatchMojo {
}
});
} catch (IOException ie) {
throw new MojoExecutionException(ie.getMessage(), ie);
throw new MojoException(ie.getMessage(), ie);
}
if (matches.booleanValue())
this.getLog().info("Matches!");
this.project.getProperties().setProperty(this.newProperty, matches.toString());
if (this.verbose)
this.logger.info("Setting property: " + this.newProperty + ": " + matches);
else if (matches.booleanValue())
this.logger.info("Matches!");
this.manager.setProperty(this.project, this.newProperty, matches.toString());
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
if (this.sourceDirectory == null)
@@ -97,11 +102,11 @@ public class MatchFilenameMojo extends AbstractMatchMojo {
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.newProperty == null)
throw new MojoFailureException("The 'newProperty' element is required");
throw new MojoException("The 'newProperty' element is required");
}
}
@@ -18,15 +18,17 @@ import java.util.List;
import java.util.ListIterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "match-properties", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "match-properties")
public class MatchPropertiesMojo extends AbstractMatchMojo {
@Inject
private Log logger;
@Parameter( property = "properties", required = true )
protected List<String> properties;
@@ -35,8 +37,8 @@ public class MatchPropertiesMojo extends AbstractMatchMojo {
protected String propertySuffix;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing properties regex match");
public void go() throws MojoException {
this.logger.debug("Executing properties regex match");
for (String propertyName : this.properties) {
this.executeOnProperty(propertyName, propertyName + this.propertySuffix);
@@ -44,15 +46,15 @@ public class MatchPropertiesMojo extends AbstractMatchMojo {
}
@Override
protected void validateParamsPreNormalization() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.properties == null)
throw new MojoFailureException("A 'properties' element is required");
throw new MojoException("A 'properties' element is required");
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
// make sure we have a list and it is nice and neat
@@ -74,13 +76,13 @@ public class MatchPropertiesMojo extends AbstractMatchMojo {
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.propertySuffix == null)
throw new MojoFailureException("The 'propertySuffix' element is required");
throw new MojoException("The 'propertySuffix' element is required");
if (this.properties.isEmpty())
throw new MojoFailureException("At least one 'property' element is required");
throw new MojoException("At least one 'property' element is required");
}
}
@@ -15,15 +15,17 @@
package com.inteligr8.maven.regex;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "match-property", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "match-property")
public class MatchPropertyMojo extends AbstractMatchMojo {
@Inject
private Log logger;
@Parameter( property = "property", required = true )
protected String property;
@@ -32,14 +34,14 @@ public class MatchPropertyMojo extends AbstractMatchMojo {
protected String newProperty;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing property regex match");
public void go() throws MojoException {
this.logger.debug("Executing property regex match");
this.executeOnProperty(this.property, this.newProperty);
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
this.property = StringUtils.trimToNull(this.property);
@@ -49,11 +51,11 @@ public class MatchPropertyMojo extends AbstractMatchMojo {
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.property == null)
throw new MojoFailureException("The 'property' element is required");
throw new MojoException("The 'property' element is required");
}
}
@@ -15,15 +15,17 @@
package com.inteligr8.maven.regex;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "match-text", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "match-text")
public class MatchTextMojo extends AbstractMatchMojo {
@Inject
private Log logger;
@Parameter( property = "text", required = true )
protected String text;
@@ -32,33 +34,33 @@ public class MatchTextMojo extends AbstractMatchMojo {
protected String newProperty;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing property regex match");
public void go() throws MojoException {
this.logger.debug("Executing property regex match");
this.executeOnText(this.project.getProperties(), this.text, this.newProperty);
this.executeOnText(this.text, this.newProperty);
}
@Override
protected void validateParamsPreNormalization() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.text == null)
throw new MojoFailureException("The 'text' element is required");
throw new MojoException("The 'text' element is required");
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
this.newProperty = StringUtils.trimToNull(this.newProperty);
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.newProperty == null)
throw new MojoFailureException("The 'newProperty' element is required");
throw new MojoException("The 'newProperty' element is required");
}
}
@@ -19,12 +19,15 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.maven.plugins.annotations.Mojo;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.annotations.Mojo;
@Mojo( name = "move-file", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "move-file")
public class MoveFileMojo extends AbstractFileMojo {
@Inject
private Log logger;
@Override
protected void executeOnFile(Path sourcePath, Path targetPath) throws IOException {
@@ -33,6 +36,12 @@ public class MoveFileMojo extends AbstractFileMojo {
} else {
Files.move(sourcePath, targetPath);
}
if (this.verbose) {
this.logger.info("Moved " + sourcePath + " to " + targetPath);
} else {
this.logger.info("Moved " + sourcePath.getFileName() + " to " + targetPath);
}
}
}
@@ -20,17 +20,19 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
import org.apache.maven.shared.model.fileset.FileSet;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.codehaus.plexus.component.annotations.Component;
@Mojo( name = "replace-file", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "replace-file")
public class ReplaceFileContentMojo extends AbstractReplaceMojo {
@Inject
private Log logger;
@Parameter( property = "chunkSize", required = true, defaultValue = "1024" )
protected int chunkSize = 1024;
@@ -39,58 +41,85 @@ public class ReplaceFileContentMojo extends AbstractReplaceMojo {
protected List<FileSet> filesets;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing file regex replace");
public void go() throws MojoException {
this.logger.debug("Executing file regex replace");
this.replaceContentInFileSet();
}
private boolean replaceContentInFileSet() throws MojoExecutionException {
private boolean replaceContentInFileSet() throws MojoException {
boolean didReplace = false;
FileSetManager fsman = new FileSetManager(this.getLog());
Path basepath = this.project.getBasedir().toPath();
FileSetManager fsman = new FileSetManager();
Path basepath = this.project.getBasedir();
try {
for (FileSet fileSet : this.filesets) {
String outputDir = fileSet.getOutputDirectory();
Path baseOutputPath = new File(outputDir).toPath();
if (!Files.exists(baseOutputPath))
Files.createDirectories(baseOutputPath);
if (!Files.isDirectory(baseOutputPath))
throw new MojoExecutionException("A fileset output directory does not reference a directory: " + outputDir);
Path baseInputPath = this.resolveDirectory(basepath, fileSet.getDirectory(), false, "fileset input");
Path baseOutputPath = this.resolveDirectory(basepath, fileSet.getOutputDirectory(), true, "fileset output");
String[] filePathsAndNames = fsman.getIncludedFiles(fileSet);
for (String filePathAndName : filePathsAndNames) {
Path file = basepath.resolve(filePathAndName);
Path file = baseInputPath.resolve(filePathAndName);
Path tofile = baseOutputPath.resolve(filePathAndName);
if (!Files.exists(tofile.getParent()))
Files.createDirectories(tofile.getParent());
if (!Files.isDirectory(file))
didReplace = this.replaceAll(file, tofile, this.chunkSize) || didReplace;
if (!Files.isDirectory(file)) {
if (this.replaceAll(file, tofile, this.chunkSize)) {
if (this.verbose)
this.logger.info("A pattern replaced in file: " + file + " => " + tofile);
didReplace = true;
}
}
}
}
} catch (IOException ie) {
throw new MojoExecutionException("Execution failed due to an I/O related issue", ie);
throw new MojoException("Execution failed due to an I/O related issue", ie);
}
return didReplace;
}
@Override
protected void normalizeParameters() throws MojoFailureException {
super.normalizeParameters();
private Path resolveDirectory(Path basepath, String directory, boolean createIfMissing, String errorName) throws IOException, MojoException {
if (directory == null)
return this.project.getBasedir();
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 MojoException("A " + errorName + " directory does not exist: " + directory);
}
}
if (!Files.isDirectory(path))
throw new MojoException("A " + errorName + " does reference a directory: " + directory);
return path;
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
super.validateParamsPostNormalization();
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.filesets == null || this.filesets.isEmpty())
throw new MojoFailureException("At least one 'fileset' is required");
for (FileSet fileset : this.filesets)
throw new MojoException("At least one 'fileset' is required");
}
@Override
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
for (FileSet fileset : this.filesets) {
if (fileset.getDirectory() == null)
fileset.setDirectory(this.project.getBasedir().toAbsolutePath().toString());
if (fileset.getOutputDirectory() == null)
throw new MojoFailureException("All 'fileset' must have an 'outputDirectory'");
fileset.setOutputDirectory(fileset.getDirectory());
}
}
}
@@ -18,15 +18,18 @@ import java.util.List;
import java.util.ListIterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.di.MojoExecutionScoped;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "replace-properties", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "replace-properties")
public class ReplacePropertiesMojo extends AbstractReplaceMojo {
@Inject
private Log logger;
@Parameter( property = "properties", required = true )
protected List<String> properties;
@@ -35,8 +38,8 @@ public class ReplacePropertiesMojo extends AbstractReplaceMojo {
protected String propertySuffix;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing properties regex replacement");
public void go() throws MojoException {
this.logger.debug("Executing properties regex replacement");
for (String propertyName : this.properties) {
this.executeOnProperty(propertyName, propertyName + this.propertySuffix);
@@ -44,15 +47,15 @@ public class ReplacePropertiesMojo extends AbstractReplaceMojo {
}
@Override
protected void validateParamsPreNormalization() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.properties == null)
throw new MojoFailureException("A 'properties' element is required");
throw new MojoException("A 'properties' element is required");
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
// make sure we have a list and it is nice and neat
@@ -74,13 +77,13 @@ public class ReplacePropertiesMojo extends AbstractReplaceMojo {
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.propertySuffix == null)
throw new MojoFailureException("The 'propertySuffix' element is required");
throw new MojoException("The 'propertySuffix' element is required");
if (this.properties.isEmpty())
throw new MojoFailureException("At least one 'property' element is required");
throw new MojoException("At least one 'property' element is required");
}
}
@@ -15,15 +15,17 @@
package com.inteligr8.maven.regex;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "replace-property", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "replace-property")
public class ReplacePropertyMojo extends AbstractReplaceMojo {
@Inject
private Log logger;
@Parameter( property = "property", required = true )
protected String property;
@@ -32,14 +34,14 @@ public class ReplacePropertyMojo extends AbstractReplaceMojo {
protected String newProperty;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing property regex replacement");
public void go() throws MojoException {
this.logger.debug("Executing property regex replacement");
this.executeOnProperty(this.property, this.newProperty);
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
this.property = StringUtils.trimToNull(this.property);
@@ -49,11 +51,11 @@ public class ReplacePropertyMojo extends AbstractReplaceMojo {
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.property == null)
throw new MojoFailureException("The 'property' element is required");
throw new MojoException("The 'property' element is required");
}
}
@@ -15,50 +15,52 @@
package com.inteligr8.maven.regex;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.component.annotations.Component;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.plugin.annotations.Parameter;
@Mojo( name = "replace-text", threadSafe = true )
@Component( role = org.apache.maven.plugin.Mojo.class )
@Mojo(name = "replace-text")
public class ReplaceTextMojo extends AbstractReplaceMojo {
@Inject
private Log logger;
@Parameter( property = "text", required = true )
protected String text;
@Parameter( property = "newProperty", required = false )
@Parameter( property = "newProperty", required = true )
protected String newProperty;
@Override
public void go() throws MojoExecutionException {
this.getLog().debug("Executing property regex replacement");
public void go() throws MojoException {
this.logger.debug("Executing property regex replacement");
this.executeOnText(this.project.getProperties(), this.text, this.newProperty);
this.executeOnText(this.text, this.newProperty);
}
@Override
protected void validateParamsPreNormalization() throws MojoFailureException {
protected void validateParamsPreNormalization() throws MojoException {
super.validateParamsPreNormalization();
if (this.text == null)
throw new MojoFailureException("The 'text' element is required");
throw new MojoException("The 'text' element is required");
}
@Override
protected void normalizeParameters() throws MojoFailureException {
protected void normalizeParameters() throws MojoException {
super.normalizeParameters();
this.newProperty = StringUtils.trimToNull(this.newProperty);
}
@Override
protected void validateParamsPostNormalization() throws MojoFailureException {
protected void validateParamsPostNormalization() throws MojoException {
super.validateParamsPostNormalization();
if (this.newProperty == null)
throw new MojoFailureException("The 'newProperty' element is required");
throw new MojoException("The 'newProperty' element is required");
}
}
@@ -12,7 +12,7 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.maven.model;
package com.inteligr8.maven.regex.model;
public interface Normalizable {
@@ -12,14 +12,13 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.maven.model;
import org.apache.commons.lang3.StringUtils;
package com.inteligr8.maven.regex.model;
public class Regex implements Normalizable {
private String pattern;
private String replacement;
private String previousPattern;
public String getPattern() {
return this.pattern;
@@ -29,6 +28,10 @@ public class Regex implements Normalizable {
return this.replacement;
}
public String getPreviousPattern() {
return previousPattern;
}
public Regex setPattern(String pattern) {
this.pattern = pattern;
return this;
@@ -39,10 +42,15 @@ public class Regex implements Normalizable {
return this;
}
public Regex setPreviousPattern(String previousPattern) {
this.previousPattern = previousPattern;
return this;
}
@Override
public void normalize() {
this.pattern = StringUtils.trimToNull(this.pattern);
this.replacement = StringUtils.trimToNull(this.replacement);
if (this.replacement == null)
this.replacement = "";
}
}
@@ -12,7 +12,7 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.nio;
package com.inteligr8.maven.regex.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -23,8 +23,6 @@ import java.nio.charset.CharsetDecoder;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.OverridingMethodsMustInvokeSuper;
public class DelimitedReadableByteChannel implements ReadableByteChannel {
private final CharBuffer buffer;
@@ -50,7 +48,6 @@ public class DelimitedReadableByteChannel implements ReadableByteChannel {
}
@Override
@OverridingMethodsMustInvokeSuper
public void close() throws IOException {
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.jupiter.api.Assertions;
import org.junit.jupiter.api.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)));
Assertions.assertTrue(files.size() > 15);
System.err.println(files);
Assertions.assertTrue(files.contains("com"+fs+"inteligr8"+fs+"maven"+fs+"regex"+fs+"AbstractFileMojo.java"));
}
}
@@ -1,4 +1,4 @@
package com.inteligr8.nio;
package com.inteligr8.maven.regex.nio;
import java.io.File;
import java.io.IOException;
@@ -10,8 +10,8 @@ import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class DelimitedReadableByteChannelUnitTest {
@@ -24,9 +24,9 @@ public class DelimitedReadableByteChannelUnitTest {
DelimitedReadableByteChannel drbchannel = new DelimitedReadableByteChannel(fchannel, Charset.defaultCharset(), "\n");
try {
StringBuilder strbuilder = new StringBuilder();
Assert.assertEquals(-1L, drbchannel.read(strbuilder));
Assert.assertEquals(0, strbuilder.length());
Assert.assertNull(drbchannel.getLastDelimiterRead());
Assertions.assertEquals(-1L, drbchannel.read(strbuilder));
Assertions.assertEquals(0, strbuilder.length());
Assertions.assertNull(drbchannel.getLastDelimiterRead());
} finally {
drbchannel.close();
}
@@ -44,18 +44,18 @@ public class DelimitedReadableByteChannelUnitTest {
DelimitedReadableByteChannel drbchannel = new DelimitedReadableByteChannel(fchannel, Charset.defaultCharset(), "\r\n", "\n");
try {
StringWriter writer = new StringWriter(1024);
Assert.assertNotEquals(-1L, drbchannel.read(writer));
Assert.assertEquals("", writer.toString());
Assert.assertNotNull(drbchannel.getLastDelimiterRead());
Assertions.assertNotEquals(-1L, drbchannel.read(writer));
Assertions.assertEquals("", writer.toString());
Assertions.assertNotNull(drbchannel.getLastDelimiterRead());
writer = new StringWriter(1024);
Assert.assertNotEquals(-1L, drbchannel.read(writer));
Assert.assertEquals("here is a line", writer.toString());
Assert.assertNotNull(drbchannel.getLastDelimiterRead());
Assertions.assertNotEquals(-1L, drbchannel.read(writer));
Assertions.assertEquals("here is a line", writer.toString());
Assertions.assertNotNull(drbchannel.getLastDelimiterRead());
writer = new StringWriter(1024);
Assert.assertEquals(-1L, drbchannel.read(writer));
Assert.assertNull(drbchannel.getLastDelimiterRead());
Assertions.assertEquals(-1L, drbchannel.read(writer));
Assertions.assertNull(drbchannel.getLastDelimiterRead());
} finally {
drbchannel.close();
}
@@ -73,18 +73,18 @@ public class DelimitedReadableByteChannelUnitTest {
DelimitedReadableByteChannel drbchannel = new DelimitedReadableByteChannel(fchannel, Charset.defaultCharset(), "\r\n", "\n");
try {
StringWriter writer = new StringWriter(1024);
Assert.assertNotEquals(-1L, drbchannel.read(writer));
Assert.assertEquals("the first line", writer.toString());
Assert.assertNotNull(drbchannel.getLastDelimiterRead());
Assertions.assertNotEquals(-1L, drbchannel.read(writer));
Assertions.assertEquals("the first line", writer.toString());
Assertions.assertNotNull(drbchannel.getLastDelimiterRead());
writer = new StringWriter(1024);
Assert.assertNotEquals(-1L, drbchannel.read(writer));
Assert.assertEquals("the last line", writer.toString());
Assert.assertNull(drbchannel.getLastDelimiterRead());
Assertions.assertNotEquals(-1L, drbchannel.read(writer));
Assertions.assertEquals("the last line", writer.toString());
Assertions.assertNull(drbchannel.getLastDelimiterRead());
writer = new StringWriter(1024);
Assert.assertEquals(-1L, drbchannel.read(writer));
Assert.assertNull(drbchannel.getLastDelimiterRead());
Assertions.assertEquals(-1L, drbchannel.read(writer));
Assertions.assertNull(drbchannel.getLastDelimiterRead());
} finally {
drbchannel.close();
}
@@ -111,14 +111,14 @@ public class DelimitedReadableByteChannelUnitTest {
DelimitedReadableByteChannel drbchannel = new DelimitedReadableByteChannel(chunkSize, fchannel, Charset.defaultCharset(), "\n");
try {
StringWriter writer = new StringWriter(1024);
Assert.assertNotEquals(-1L, drbchannel.read(writer));
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", writer.toString());
Assert.assertEquals("\n", drbchannel.getLastDelimiterRead());
Assertions.assertNotEquals(-1L, drbchannel.read(writer));
Assertions.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", writer.toString());
Assertions.assertEquals("\n", drbchannel.getLastDelimiterRead());
writer = new StringWriter(1024);
Assert.assertEquals(1, drbchannel.read(writer));
Assert.assertEquals("", writer.toString());
Assert.assertEquals("\n", drbchannel.getLastDelimiterRead());
Assertions.assertEquals(1, drbchannel.read(writer));
Assertions.assertEquals("", writer.toString());
Assertions.assertEquals("\n", drbchannel.getLastDelimiterRead());
} finally {
drbchannel.close();
}