1 package com.github.mikkoi.maven.plugins.enforcer.rule.propertyusage.configuration;
2
3 import org.apache.maven.plugin.logging.Log;
4 import org.codehaus.plexus.util.DirectoryScanner;
5 import org.codehaus.plexus.util.StringUtils;
6
7 import javax.annotation.Nonnull;
8 import java.io.File;
9 import java.nio.file.Path;
10 import java.nio.file.Paths;
11 import java.util.Arrays;
12 import java.util.Collection;
13 import java.util.HashSet;
14 import java.util.stream.Collectors;
15
16
17
18
19 public class FileSpecs {
20
21 private FileSpecs() {
22
23 throw new AssertionError();
24 }
25
26 public static String absoluteCwdAndFile(@Nonnull final String filename) {
27 return Paths.get(System.getProperty("user.dir"), filename).toAbsolutePath().normalize().toString();
28 }
29
30
31
32
33
34
35
36
37
38
39 @Nonnull
40 public static Collection<String> getAbsoluteFilenames(
41 @Nonnull final Collection<String> files,
42 @Nonnull final Path basedir,
43 @Nonnull final Log log
44 ) {
45 Collection<String> allFilenames = new HashSet<>();
46 if(!files.isEmpty()) {
47
48
49
50 for (String fileSpec : files) {
51 if (StringUtils.isBlank(fileSpec)) {
52 log.error(logFileIterationMsg(fileSpec, "is blank. Error in configuration") + "!");
53 continue;
54 }
55 File file = new File(fileSpec);
56 if (file.exists() && file.isFile()) {
57 log.debug(logFileIterationMsg(fileSpec, "is a file") + ".");
58 allFilenames.add(file.getAbsolutePath());
59 } else if (file.exists() && file.isDirectory()) {
60 log.debug(logFileIterationMsg(fileSpec, "is a directory") + ".");
61 DirectoryScanner ds = initializeDS(Paths.get(fileSpec));
62 ds.scan();
63 allFilenames.addAll(Arrays.stream(ds.getIncludedFiles()).map(includedFile -> new File(includedFile).getAbsolutePath()).collect(Collectors.toSet()));
64 } else if (file.exists()) {
65 log.error(logFileIterationMsg(fileSpec, "is not a file or directory. Do not know what to do") + "!");
66 } else {
67 log.debug(logFileIterationMsg(fileSpec, "does not exist. Assume wildcards") + ".");
68 DirectoryScanner ds = initializeDS(basedir);
69 ds.setIncludes(new String[]{fileSpec});
70 ds.scan();
71 Collection<String> foundFiles = Arrays.stream(ds.getIncludedFiles()).map(includedFile -> Paths.get(basedir.toString(), includedFile).toString()).collect(Collectors.toSet());
72 log.debug(" Found files:[");
73 for (final String foundFile : foundFiles) {
74 log.debug(" " + foundFile);
75 }
76 log.debug(" ]");
77 allFilenames.addAll(foundFiles);
78 }
79 }
80 }
81 return allFilenames;
82 }
83
84 private static DirectoryScanner initializeDS(@Nonnull final Path path) {
85 DirectoryScanner ds = new DirectoryScanner();
86 ds.setCaseSensitive(true);
87 ds.setFollowSymlinks(true);
88 ds.addDefaultExcludes();
89 ds.setBasedir(path.toAbsolutePath().toString());
90 return ds;
91 }
92
93 @Nonnull
94 private static String logFileIterationMsg(@Nonnull final String filename, @Nonnull final String comment) {
95 return "File spec '" + filename + "' " + comment;
96 }
97
98
99 }