javamavenrelative-pathmojo

Mojo plugin for writing to filesystem


I would like to write mojo plugin like this:

 /**
 * @goal write-to-fs
 */

public class WriteToFsMojo extends AbstractMojo
{

    public void execute() throws MojoExecutionException
    {
        String relativePathToFile = "resource/my_direcory/my_file.csv"
        // find `relativePathToFile` from where goal executes
        // write the file using goal arguments
    }
}

I would like to find in project specific file e.g. Menu.csv and insert row into this file from mvn goal argument.

For example:

mvn org.apache.maven.plugins:my-plugin:write-to-fs "-Did=100" "-Dname=New Menu Item"

What I am interesting about is this approach correct? Is it possible? Could you provide examples?


Solution

  • First of all, you are using the ancient method of annotating your classes with Javadoc doclets. That mechanism is deprecated. Ever since Maven 3, you should use annotations instead.

    Apart from that, it depends on what you are trying to do in your plugin. If you elaborate on what you are trying to do, I'll expand on my answer.

    Here's a skeleton:

    @Mojo(name = "write-csv")
    public class WriteToFsMojo extends AbstractMojo {
    
        @Parameter(defaultValue = "${project}", readonly = true)
        private MavenProject project;
    
        @Parameter(property = "outputFile", defaultValue = "someFileName.csv")
        private String filePath;
    
        public void execute() throws MojoExecutionException {
            File outputFile = new File(project.getBasedir(), filePath);
            // now do something with it
        }
    }
    

    This will get the Maven project definition injected and let the user supply the outputFile parameter, either via command line, or via plugin configuration.