View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.maven;
6   
7   import com.google.common.base.Predicates;
8   import com.google.common.collect.Collections2;
9   import com.google.common.collect.Iterables;
10  import com.jcabi.log.Logger;
11  import com.qulice.spi.Binary;
12  import java.io.File;
13  import java.net.MalformedURLException;
14  import java.net.URL;
15  import java.net.URLClassLoader;
16  import java.nio.charset.Charset;
17  import java.util.ArrayList;
18  import java.util.Collection;
19  import java.util.LinkedHashSet;
20  import java.util.List;
21  import java.util.Properties;
22  import javax.annotation.Nullable;
23  import org.apache.commons.io.FileUtils;
24  import org.apache.commons.io.FilenameUtils;
25  import org.apache.commons.io.filefilter.DirectoryFileFilter;
26  import org.apache.commons.io.filefilter.IOFileFilter;
27  import org.apache.commons.io.filefilter.WildcardFileFilter;
28  import org.apache.maven.artifact.DependencyResolutionRequiredException;
29  import org.apache.maven.model.Build;
30  import org.apache.maven.model.Resource;
31  import org.apache.maven.project.MavenProject;
32  import org.codehaus.plexus.context.Context;
33  
34  /**
35   * Environment, passed from MOJO to validators.
36   *
37   * @since 0.3
38   */
39  @SuppressWarnings("PMD.GodClass")
40  public final class DefaultMavenEnvironment implements MavenEnvironment {
41  
42      /**
43       * Maven project.
44       */
45      private MavenProject iproject;
46  
47      /**
48       * Plexus context.
49       */
50      private Context icontext;
51  
52      /**
53       * Plugin configuration.
54       */
55      private final Properties iproperties;
56  
57      /**
58       * MOJO executor.
59       */
60      private MojoExecutor exectr;
61  
62      /**
63       * Excludes, regular expressions.
64       */
65      private final Collection<String> exc;
66  
67      /**
68       * Xpath queries for pom.xml validation.
69       */
70      private final Collection<String> assertion;
71  
72      /**
73       * Source code encoding charset.
74       */
75      private String charset;
76  
77      /**
78       * Default constructor.
79       */
80      public DefaultMavenEnvironment() {
81          this.iproperties = new Properties();
82          this.exc = new ArrayList<>(0);
83          this.assertion = new ArrayList<>(0);
84          this.charset = "UTF-8";
85      }
86  
87      @Override
88      public String param(final String name, final String value) {
89          String ret = this.iproperties.getProperty(name);
90          if (ret == null && this.iproject != null) {
91              ret = this.iproject.getProperties().getProperty(name);
92          }
93          if (ret == null) {
94              ret = value;
95          }
96          return ret;
97      }
98  
99      @Override
100     public File basedir() {
101         return this.iproject.getBasedir();
102     }
103 
104     @Override
105     public File tempdir() {
106         final File dir = new File(
107             this.iproject.getBuild().getDirectory(), "tempdir"
108         );
109         if (!dir.mkdirs() && !dir.isDirectory()) {
110             throw new IllegalStateException(
111                 String.format("Cannot create tempdir at %s", dir)
112             );
113         }
114         return dir;
115     }
116 
117     @Override
118     public File outdir() {
119         return new File(this.iproject.getBuild().getOutputDirectory());
120     }
121 
122     @Override
123     public Collection<File> testdirs() {
124         final Collection<File> dirs = new ArrayList<>(0);
125         final List<String> roots = this.iproject.getTestCompileSourceRoots();
126         if (roots != null) {
127             for (final String root : roots) {
128                 dirs.add(this.resolve(root));
129             }
130         }
131         return dirs;
132     }
133 
134     @Override
135     public Collection<String> classpath() {
136         final Collection<String> paths = new ArrayList<>(0);
137         try {
138             for (final String name
139                 : this.iproject.getTestClasspathElements()) {
140                 paths.add(name.replace(File.separatorChar, '/'));
141             }
142         } catch (final DependencyResolutionRequiredException ex) {
143             throw new IllegalStateException("Failed to read classpath", ex);
144         }
145         return paths;
146     }
147 
148     @Override
149     public ClassLoader classloader() {
150         final List<URL> urls = new ArrayList<>(0);
151         for (final String path : this.classpath()) {
152             try {
153                 urls.add(new File(path).toURI().toURL());
154             } catch (final MalformedURLException ex) {
155                 throw new IllegalStateException("Failed to build URL", ex);
156             }
157         }
158         final URLClassLoader loader = new PrivilegedClassLoader(urls).run();
159         for (final URL url : loader.getURLs()) {
160             Logger.debug(this, "Classpath: %s", url);
161         }
162         return loader;
163     }
164 
165     @Override
166     public MavenProject project() {
167         return this.iproject;
168     }
169 
170     @Override
171     public Properties properties() {
172         return this.iproperties;
173     }
174 
175     @Override
176     public Context context() {
177         return this.icontext;
178     }
179 
180     @Override
181     public Properties config() {
182         return this.iproperties;
183     }
184 
185     @Override
186     public MojoExecutor executor() {
187         return this.exectr;
188     }
189 
190     @Override
191     public Collection<String> asserts() {
192         return this.assertion;
193     }
194 
195     @Override
196     public Collection<File> files(final String pattern) {
197         final Collection<File> files = new LinkedHashSet<>(0);
198         final IOFileFilter filter = WildcardFileFilter.builder().setWildcards(pattern).get();
199         for (final File sources : this.sources()) {
200             if (sources.exists()) {
201                 for (final File found : FileUtils.listFiles(
202                     sources,
203                     filter,
204                     DirectoryFileFilter.INSTANCE
205                 )) {
206                     if (new Binary(found).yes()) {
207                         Logger.debug(
208                             this,
209                             "Skipping binary file %s",
210                             found
211                         );
212                     } else {
213                         files.add(found);
214                     }
215                 }
216             }
217         }
218         return files;
219     }
220 
221     @Override
222     public boolean exclude(final String check, final String name) {
223         return Iterables.any(
224             this.excludes(check),
225             new PathPredicate(name)
226         );
227     }
228 
229     @Override
230     public Collection<String> excludes(final String checker) {
231         return Collections2.filter(
232             Collections2.transform(
233                 this.exc,
234                 new CheckerExcludes(checker)
235             ),
236             Predicates.notNull()
237         );
238     }
239 
240     /**
241      * Set Maven Project (used mostly for unit testing).
242      *
243      * @param proj The project to set
244      */
245     public void setProject(final MavenProject proj) {
246         this.iproject = proj;
247     }
248 
249     /**
250      * Set context.
251      *
252      * @param ctx The context to set
253      */
254     public void setContext(final Context ctx) {
255         this.icontext = ctx;
256     }
257 
258     /**
259      * Set executor.
260      *
261      * @param exec The executor
262      */
263     public void setMojoExecutor(final MojoExecutor exec) {
264         this.exectr = exec;
265     }
266 
267     /**
268      * Set property.
269      *
270      * @param name Its name
271      * @param value Its value
272      */
273     public void setProperty(final String name, final String value) {
274         this.iproperties.setProperty(name, value);
275     }
276 
277     /**
278      * Set list of regular expressions to exclude.
279      *
280      * @param exprs Expressions
281      */
282     public void setExcludes(final Collection<String> exprs) {
283         this.exc.clear();
284         this.exc.addAll(exprs);
285     }
286 
287     /**
288      * Set list of Xpath queries for pom.xml validation.
289      *
290      * @param ass Xpath queries
291      */
292     public void setAssertion(final Collection<String> ass) {
293         this.assertion.clear();
294         this.assertion.addAll(ass);
295     }
296 
297     /**
298      * Set the encoding of source files.
299      *
300      * @param encoding The encoding to use
301      */
302     public void setEncoding(final String encoding) {
303         this.charset = encoding;
304     }
305 
306     @Override
307     public Charset encoding() {
308         if (this.charset == null || this.charset.isEmpty()) {
309             this.charset = "UTF-8";
310         }
311         return Charset.forName(this.charset);
312     }
313 
314     private Collection<File> sources() {
315         final Collection<File> dirs = new LinkedHashSet<>(0);
316         final Build build = this.iproject.getBuild();
317         final File output = this.buildDirectory(build);
318         this.addRoots(dirs, this.iproject.getCompileSourceRoots(), output);
319         this.addRoots(dirs, this.iproject.getTestCompileSourceRoots(), output);
320         if (build != null) {
321             this.addResources(dirs, build.getResources(), output);
322             this.addResources(dirs, build.getTestResources(), output);
323         }
324         if (dirs.isEmpty()) {
325             dirs.add(new File(this.basedir(), "src"));
326         }
327         return dirs;
328     }
329 
330     @Nullable
331     private File buildDirectory(@Nullable final Build build) {
332         File dir = null;
333         if (build != null && build.getDirectory() != null) {
334             dir = this.resolve(build.getDirectory());
335         }
336         return dir;
337     }
338 
339     private void addRoots(final Collection<File> dirs,
340         final List<String> roots, @Nullable final File output) {
341         if (roots != null) {
342             for (final String root : roots) {
343                 final File resolved = this.resolve(root);
344                 if (DefaultMavenEnvironment.outside(resolved, output)) {
345                     dirs.add(resolved);
346                 } else {
347                     Logger.debug(
348                         this,
349                         "Skipping generated source root %s under %s",
350                         resolved, output
351                     );
352                 }
353             }
354         }
355     }
356 
357     private void addResources(final Collection<File> dirs,
358         final List<Resource> resources, @Nullable final File output) {
359         if (resources != null) {
360             for (final Resource res : resources) {
361                 final File resolved = this.resolve(res.getDirectory());
362                 if (DefaultMavenEnvironment.outside(resolved, output)) {
363                     dirs.add(resolved);
364                 } else {
365                     Logger.debug(
366                         this,
367                         "Skipping generated resource directory %s under %s",
368                         resolved, output
369                     );
370                 }
371             }
372         }
373     }
374 
375     private static boolean outside(final File file,
376         @Nullable final File parent) {
377         boolean answer = true;
378         if (parent != null) {
379             final String head = FilenameUtils.normalize(
380                 parent.getAbsolutePath(), true
381             );
382             final String tail = FilenameUtils.normalize(
383                 file.getAbsolutePath(), true
384             );
385             if (head != null && tail != null
386                 && (tail.equals(head) || tail.startsWith(head.concat("/")))) {
387                 answer = false;
388             }
389         }
390         return answer;
391     }
392 
393     private File resolve(final String path) {
394         final File file = new File(path);
395         final String absolute;
396         if (file.isAbsolute()) {
397             absolute = file.getAbsolutePath();
398         } else {
399             absolute = new File(this.basedir(), path).getAbsolutePath();
400         }
401         final String normalized = FilenameUtils.normalize(absolute, true);
402         final File resolved;
403         if (normalized == null) {
404             resolved = new File(absolute);
405         } else {
406             resolved = new File(normalized);
407         }
408         return resolved;
409     }
410 }