refactor: 优化 clean 命令的逻辑,使其符合直觉
This commit is contained in:
parent
a6c251c8da
commit
3c43e31afb
@ -32,16 +32,15 @@ public final class CleanTask implements Task {
|
|||||||
public void run() throws IOException {
|
public void run() throws IOException {
|
||||||
Path build = Path.of("build");
|
Path build = Path.of("build");
|
||||||
Path dist = Path.of("dist");
|
Path dist = Path.of("dist");
|
||||||
deleteDir(build);
|
deleteDir(build, false);
|
||||||
deleteDir(dist);
|
deleteDir(dist, false);
|
||||||
Files.createDirectories(build);
|
|
||||||
Files.createDirectories(dist);
|
|
||||||
|
|
||||||
System.out.println("[clean] done.");
|
System.out.println("[clean] done.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 递归删除指定目录及其所有子文件和子目录。
|
* 递归删除指定目录下的所有子文件和子目录。
|
||||||
|
* 如需删除指定目录本身可将第二个参数 <span>containSelf</span> 设置为 true
|
||||||
* <p>
|
* <p>
|
||||||
* 若目录不存在,则直接返回。
|
* 若目录不存在,则直接返回。
|
||||||
* </p>
|
* </p>
|
||||||
@ -50,14 +49,18 @@ public final class CleanTask implements Task {
|
|||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @param dir 需要删除的目录路径
|
* @param dir 需要删除的目录路径
|
||||||
|
* @param containSelf 是否删除指定目录本身
|
||||||
* @throws IOException 删除目录或文件过程中发生 IO 错误时抛出
|
* @throws IOException 删除目录或文件过程中发生 IO 错误时抛出
|
||||||
*/
|
*/
|
||||||
private void deleteDir(Path dir) throws IOException {
|
private void deleteDir(Path dir, boolean containSelf) throws IOException {
|
||||||
if (Files.notExists(dir)) return;
|
if (Files.notExists(dir)) return;
|
||||||
try (var stream = Files.walk(dir)) {
|
try (var stream = Files.walk(dir)) {
|
||||||
stream.sorted(Comparator.reverseOrder()) // 先删子文件,后删父目录
|
stream.sorted(Comparator.reverseOrder()) // 先删子文件,后删父目录
|
||||||
.forEach(p -> {
|
.forEach(p -> {
|
||||||
try {
|
try {
|
||||||
|
if (!containSelf && p == dir) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
Files.delete(p);
|
Files.delete(p);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user