Skip to content

Commit 24ba06b

Browse files
ctruedenclaude
andcommitted
scijava-common3: add FilePaths, from SciJava Common's FileUtils
FileUtils splits cleanly along a line drawn by java.nio.file: its filesystem half is now standard library, while its filename logic -- notably versioned JAR names, which Fiji's updater depends on -- has no replacement anywhere. FilePaths therefore carries normalizeSeparators (was getPath), extension, stripVersion, allVersions, matchVersionedFilename, and deleteRecursively, which java.nio.file still lacks. It is named FilePaths rather than Files because any implementation would import java.nio.file.Files, and a clashing simple name in a foundational utility module is a lasting annoyance. Dropped, with replacements recorded in docs/migration.md: readFile, writeFile, createTemporaryDirectory and getModifiedTime, all covered by java.nio.file.Files; and shortenPath and limitPath, whose only usages anywhere are inside SciJava Common itself. findResources is left for scijava-index, which needs classpath resource scanning anyway. Two deliberate behavioral changes: - deleteRecursively now deletes a plain file passed to it. SciJava Common returned true without deleting anything, since listFiles() returns null for a non-directory. - It is implemented with Files.walk in reverse order rather than recursion, so it no longer recurses into symlinked directories. Tests are ported from SciJava Common, keeping the full versioned-filename corpus (jogamp, jinput and ffmpeg native-binary naming), which is where the real complexity lives. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent 9a5b15e commit 24ba06b

3 files changed

Lines changed: 353 additions & 1 deletion

File tree

‎docs/migration.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ A **dropped** row is a successful outcome, not a gap.
3232
| `DebugUtils` | `org.scijava.common3.Threads` | ported |
3333
| `DefaultTreeNode`, `TreeNode` | on hold — only `imagej-common` uses it; may move there | open |
3434
| `DigestUtils` | `org.scijava.common3.Digests`. `digest` now throws `IllegalArgumentException` for an unknown algorithm rather than returning `null`; `best*` is SHA-1, since every Java platform guarantees it | ported |
35-
| `FileUtils` | `org.scijava.common3` (non-URL parts, Phase 1); URL parts in `common3.URLs` | planned |
35+
| `FileUtils` | split: filename logic → `org.scijava.common3.FilePaths` (`getPath` → `normalizeSeparators`, `getExtension` → `extension`, `stripFilenameVersion` → `stripVersion`, `getAllVersions` → `allVersions`, `matchVersionedFilename`, `deleteRecursively`); `urlToFile`/`listContents`/`appendContents` → `common3.URLs`; `findResources` → `scijava-index` (Phase 1) | ported |
36+
| `FileUtils` (dropped parts) | `readFile`/`writeFile` → `java.nio.file.Files.readAllBytes`/`write`; `createTemporaryDirectory` → `Files.createTempDirectory`; `getModifiedTime` → `Files.getLastModifiedTime`; `shortenPath`/`limitPath` → no replacement, used only inside SJC itself | dropped |
3637
| `GenericUtils` | `org.scijava.common3.Types` (already deprecated in SJC) | ported |
3738
| `IntCoords`, `IntRect`, `RealCoords`, `RealRect` | UI layer (Phase 4) | open |
3839
| `IteratorPlus` | none — use the standard `Iterator`/`Iterable` API | dropped |
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/*
2+
* #%L
3+
* Common functionality widely used across SciJava modules.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.common3;
31+
32+
import java.io.File;
33+
import java.io.IOException;
34+
import java.nio.file.Files;
35+
import java.nio.file.Path;
36+
import java.util.Comparator;
37+
import java.util.regex.Matcher;
38+
import java.util.regex.Pattern;
39+
import java.util.stream.Stream;
40+
41+
/**
42+
* Useful methods for working with file names and paths.
43+
* <p>
44+
* Most of SciJava Common's {@code FileUtils} is not here, because
45+
* {@link java.nio.file.Files} and {@link java.nio.file.Path} now cover it:
46+
* reading and writing a file, temporary directories, and modification times.
47+
* What remains is the filename logic the standard library has no answer for -
48+
* notably versioned JAR names - plus recursive deletion, which
49+
* {@link java.nio.file.Files} still lacks.
50+
* </p>
51+
*
52+
* @author Johannes Schindelin
53+
* @author Curtis Rueden
54+
*/
55+
public final class FilePaths {
56+
57+
private static final Pattern VERSION_PATTERN = buildVersionPattern();
58+
59+
private FilePaths() {
60+
// NB: prevent instantiation of utility class.
61+
}
62+
63+
/**
64+
* Gets the file's absolute path with separators normalized to {@code /}, so
65+
* that paths compare equal across platforms.
66+
*/
67+
public static String normalizeSeparators(final File file) {
68+
return normalizeSeparators(file.getAbsolutePath(), File.separator);
69+
}
70+
71+
/** Replaces the given separator with {@code /} throughout the path. */
72+
public static String normalizeSeparators(final String path,
73+
final String separator)
74+
{
75+
return path.replaceAll(Pattern.quote(separator), "/");
76+
}
77+
78+
/**
79+
* Gets the file's extension: the part after the last dot of its name, with
80+
* no leading dot, or the empty string if it has none.
81+
*/
82+
public static String extension(final File file) {
83+
final String name = file.getName();
84+
final int dot = name.lastIndexOf('.');
85+
return dot < 0 ? "" : name.substring(dot + 1);
86+
}
87+
88+
/** Gets the extension of the file at the given path. */
89+
public static String extension(final String path) {
90+
return extension(new File(path));
91+
}
92+
93+
/**
94+
* Strips the version from a versioned file name - for example,
95+
* {@code foo-1.2.3.jar} becomes {@code foo.jar}.
96+
*
97+
* @param filename the file name
98+
* @return the file name without its version, or the file name unchanged if
99+
* it is not versioned
100+
*/
101+
public static String stripVersion(final String filename) {
102+
final Matcher matcher = VERSION_PATTERN.matcher(filename);
103+
if (!matcher.matches()) return filename;
104+
return matcher.group(1) + matcher.group(5);
105+
}
106+
107+
/**
108+
* Finds every version of the given file in the given directory - for
109+
* example, given {@code foo-1.2.3.jar}, finds {@code foo-1.2.4.jar} too.
110+
* Only versions with a matching classifier are returned.
111+
*
112+
* @param directory the directory to search
113+
* @param filename the versioned file name
114+
* @return the matching files, or {@code null} if the directory cannot be
115+
* listed, or the file name is unversioned and does not exist
116+
*/
117+
public static File[] allVersions(final File directory,
118+
final String filename)
119+
{
120+
final Matcher matcher = VERSION_PATTERN.matcher(filename);
121+
if (!matcher.matches()) {
122+
final File file = new File(directory, filename);
123+
return file.exists() ? new File[] { file } : null;
124+
}
125+
final String baseName = matcher.group(1);
126+
final String classifier = matcher.group(6);
127+
return directory.listFiles((dir, name) -> {
128+
if (!name.startsWith(baseName)) return false;
129+
final Matcher m = VERSION_PATTERN.matcher(name);
130+
if (!m.matches() || !baseName.equals(m.group(1))) return false;
131+
final String c = m.group(6);
132+
return classifier == null ? c == null : classifier.equals(c);
133+
});
134+
}
135+
136+
/**
137+
* Matches the given file name against the versioned file name pattern, so
138+
* that callers can pick apart its base name, version and classifier.
139+
*/
140+
public static Matcher matchVersionedFilename(final String filename) {
141+
return VERSION_PATTERN.matcher(filename);
142+
}
143+
144+
/**
145+
* Deletes the given directory and everything in it.
146+
*
147+
* @param directory the directory to delete; {@code null} is a no-op
148+
* @return true if the directory is gone afterward
149+
*/
150+
public static boolean deleteRecursively(final File directory) {
151+
if (directory == null) return true;
152+
final Path path = directory.toPath();
153+
if (!Files.exists(path)) return true;
154+
try (final Stream<Path> paths = Files.walk(path)) {
155+
// NB: deepest first, so that each directory is empty when deleted.
156+
return paths.sorted(Comparator.reverseOrder()) //
157+
.map(Path::toFile) //
158+
.allMatch(File::delete);
159+
}
160+
catch (final IOException exc) {
161+
return false;
162+
}
163+
}
164+
165+
private static Pattern buildVersionPattern() {
166+
final String version =
167+
"\\d+(\\.\\d+|\\d{7})+[a-z]?\\d?(-[A-Za-z0-9.]+?|\\.GA)*?";
168+
final String suffix = "\\.jar(-[a-z]*)?";
169+
return Pattern.compile("(.+?)(-" + version + ")?((-(" + classifiers() +
170+
"))?(" + suffix + "))");
171+
}
172+
173+
/** Helper method of {@link #buildVersionPattern()}. */
174+
private static String classifiers() {
175+
final String[] classifiers = { //
176+
"swing", //
177+
"swt", //
178+
"shaded", //
179+
"sources", //
180+
"javadoc", //
181+
"natives?-?\\w*", //
182+
"(natives-)?(android|linux|macosx|macos|solaris|windows)-" +
183+
"(aarch64|amd64|arm64|armv6hf|armv6|arm|" +
184+
"i386|i486|i586|i686|universal|x86[_-]32|x86[_-]64|x86)" //
185+
};
186+
return "(" + String.join("|", classifiers) + ")";
187+
}
188+
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
/*-
2+
* #%L
3+
* Common functionality widely used across SciJava modules.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.common3;
31+
32+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
33+
import static org.junit.jupiter.api.Assertions.assertEquals;
34+
import static org.junit.jupiter.api.Assertions.assertFalse;
35+
import static org.junit.jupiter.api.Assertions.assertTrue;
36+
37+
import java.io.File;
38+
import java.io.IOException;
39+
import java.nio.file.Files;
40+
41+
import org.junit.jupiter.api.Test;
42+
43+
/**
44+
* Tests {@link FilePaths}.
45+
*
46+
* @author Johannes Schindelin
47+
* @author Curtis Rueden
48+
*/
49+
public class FilePathsTest {
50+
51+
@Test
52+
public void testNormalizeSeparators() {
53+
// Windows-style paths get standardized.
54+
assertEquals("C:/path/to/my-windows-file", //
55+
FilePaths.normalizeSeparators("C:\\path\\to\\my-windows-file", "\\"));
56+
// *nix-style paths are unchanged.
57+
assertEquals("/path/to/my-nix-file", //
58+
FilePaths.normalizeSeparators("/path/to/my-nix-file", "/"));
59+
// An already-standardized path stays good on Windows.
60+
assertEquals("/path/to/my-nix-file", //
61+
FilePaths.normalizeSeparators("/path/to/my-nix-file", "\\"));
62+
}
63+
64+
@Test
65+
public void testExtension() {
66+
assertEquals("ext", FilePaths.extension("/path/to/file.ext"));
67+
assertEquals("", FilePaths.extension("/path/to/file"));
68+
assertEquals("a", FilePaths.extension("/etc/init.d/xyz/file.a"));
69+
assertEquals("", FilePaths.extension("/etc/init.d/xyz/file"));
70+
}
71+
72+
@Test
73+
public void testStripVersion() {
74+
assertEquals("jars/bio-formats.jar", //
75+
FilePaths.stripVersion("jars/bio-formats-4.4-imagej-2.0.0-beta1.jar"));
76+
assertEquals(FilePaths.stripVersion("jars/ij-data-2.0.0.1-beta1.jar"), //
77+
FilePaths.stripVersion("jars/ij-data-2.0.0.1-SNAPSHOT.jar"));
78+
assertEquals(FilePaths.stripVersion("jars/ij-1.44.jar"), //
79+
FilePaths.stripVersion("jars/ij-1.46b.jar"));
80+
assertEquals(FilePaths.stripVersion("jars/javassist.jar"), //
81+
FilePaths.stripVersion("jars/javassist-3.9.0.GA.jar"));
82+
assertEquals(FilePaths.stripVersion("jars/javassist.jar"), //
83+
FilePaths.stripVersion("jars/javassist-3.16.1-GA.jar"));
84+
assertEquals(FilePaths.stripVersion("jars/bsh.jar"), //
85+
FilePaths.stripVersion("jars/bsh-2.0b4.jar"));
86+
assertEquals(FilePaths.stripVersion("jars/mpicbg.jar"), //
87+
FilePaths.stripVersion("jars/mpicbg-20111128.jar"));
88+
assertEquals(FilePaths.stripVersion("jars/miglayout-swing.jar"), //
89+
FilePaths.stripVersion("jars/miglayout-3.7.3.1-swing.jar"));
90+
}
91+
92+
/** Native binary JARs must not clash with their partner hook JAR. */
93+
@Test
94+
public void testStripVersionNativeBinaries() {
95+
assertEquals("jars/ffmpeg-windows-x86.jar", //
96+
FilePaths.stripVersion("jars/ffmpeg-2.6.1-0.11-windows-x86.jar"));
97+
assertEquals("jars/ffmpeg-windows-x86_64.jar", //
98+
FilePaths.stripVersion("jars/ffmpeg-2.6.1-0.11-windows-x86_64.jar"));
99+
assertEquals("jars/ffmpeg-macosx-x86_64.jar", //
100+
FilePaths.stripVersion("jars/ffmpeg-2.6.1-0.11-macosx-x86_64.jar"));
101+
assertEquals("jars/ffmpeg-linux-x86_64.jar", //
102+
FilePaths.stripVersion("jars/ffmpeg-2.6.1-0.11-linux-x86_64.jar"));
103+
assertEquals("jars/ffmpeg-android-arm.jar", //
104+
FilePaths.stripVersion("jars/ffmpeg-2.6.1-0.11-android-arm.jar"));
105+
}
106+
107+
/** The jogamp style of native binary JARs. */
108+
@Test
109+
public void testStripVersionJogamp() {
110+
assertEquals("jars/jogl-all-natives-android-aarch64.jar", FilePaths
111+
.stripVersion("jars/jogl-all-2.3.0-natives-android-aarch64.jar"));
112+
assertEquals("jars/jogl-all-natives-linux-armv6hf.jar", FilePaths
113+
.stripVersion("jars/jogl-all-2.3.0-natives-linux-armv6hf.jar"));
114+
assertEquals("jars/jogl-all-natives-macosx-universal.jar", FilePaths
115+
.stripVersion("jars/jogl-all-2.3.0-natives-macosx-universal.jar"));
116+
assertEquals("jars/jogl-all-natives-windows-i586.jar", FilePaths
117+
.stripVersion("jars/jogl-all-2.3.0-natives-windows-i586.jar"));
118+
// The jinput style.
119+
assertEquals("jars/jinput-natives-all.jar", //
120+
FilePaths.stripVersion("jars/jinput-2.0.9-natives-all.jar"));
121+
// native-lib-loader must not be mistaken for a native classifier.
122+
assertEquals("jars/native-lib-loader.jar", //
123+
FilePaths.stripVersion("jars/native-lib-loader-2.3.2.jar"));
124+
}
125+
126+
@Test
127+
public void testAllVersions() throws IOException {
128+
final String withClassifier = "miglayout-3.7.3.1-swing.jar";
129+
final String withoutClassifier = "miglayout-3.7.3.1.jar";
130+
final File tmp = Files.createTempDirectory("all-versions-").toFile();
131+
try {
132+
assertTrue(new File(tmp, withClassifier).createNewFile());
133+
assertTrue(new File(tmp, withoutClassifier).createNewFile());
134+
135+
// A classifier matches only files with that same classifier.
136+
assertArrayEquals(new File[] { new File(tmp, withClassifier) }, //
137+
FilePaths.allVersions(tmp, withClassifier));
138+
assertArrayEquals(new File[] { new File(tmp, withoutClassifier) }, //
139+
FilePaths.allVersions(tmp, withoutClassifier));
140+
}
141+
finally {
142+
FilePaths.deleteRecursively(tmp);
143+
}
144+
}
145+
146+
@Test
147+
public void testDeleteRecursively() throws IOException {
148+
final File tmp = Files.createTempDirectory("delete-recursively-").toFile();
149+
final File nested = new File(new File(tmp, "a"), "b");
150+
assertTrue(nested.mkdirs());
151+
assertTrue(new File(nested, "file.txt").createNewFile());
152+
assertTrue(new File(tmp, "top.txt").createNewFile());
153+
154+
assertTrue(FilePaths.deleteRecursively(tmp));
155+
assertFalse(tmp.exists());
156+
}
157+
158+
@Test
159+
public void testDeleteRecursivelyNullOrMissing() {
160+
assertTrue(FilePaths.deleteRecursively(null));
161+
assertTrue(FilePaths.deleteRecursively(new File("no-such-directory-xyz")));
162+
}
163+
}

0 commit comments

Comments
 (0)