Skip to content

Commit e9b4696

Browse files
committed
8373097: Save command should create missing parent directories
Reviewed-by: jlahoda
1 parent e635330 commit e9b4696

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3362,7 +3362,19 @@ private boolean cmdSave(String rawargs) {
33623362
// error occurred, already reported
33633363
return false;
33643364
}
3365-
try (BufferedWriter writer = Files.newBufferedWriter(toPathResolvingUserHome(filename),
3365+
// Create missing parent directories before writing to target file
3366+
Path target;
3367+
try {
3368+
target = toPathResolvingUserHome(filename);
3369+
Path parent = target.getParent();
3370+
if (parent != null) {
3371+
Files.createDirectories(parent);
3372+
}
3373+
} catch (Exception e) {
3374+
errormsg("jshell.err.file.exception", "/save", filename, e);
3375+
return false;
3376+
}
3377+
try (BufferedWriter writer = Files.newBufferedWriter(target,
33663378
Charset.defaultCharset(),
33673379
CREATE, TRUNCATE_EXISTING, WRITE)) {
33683380
if (at.hasOption("-history")) {

test/langtools/jdk/jshell/ToolBasicTest.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,7 @@ public void testSave() throws IOException {
585585
Compiler compiler = new Compiler();
586586
Path path = compiler.getPath("testSave.repl");
587587
{
588+
Path pathWithDirectories = compiler.getPath("what/ever/testSave.repl");
588589
List<String> list = Arrays.asList(
589590
"int a;",
590591
"class A { public String toString() { return \"A\"; } }"
@@ -593,9 +594,11 @@ public void testSave() throws IOException {
593594
(a) -> assertVariable(a, "int", "a"),
594595
(a) -> assertCommand(a, "()", null, null, null, "", ""),
595596
(a) -> assertClass(a, "class A { public String toString() { return \"A\"; } }", "class", "A"),
596-
(a) -> assertCommand(a, "/save " + path.toString(), "")
597+
(a) -> assertCommand(a, "/save " + path.toString(), ""),
598+
(a) -> assertCommand(a, "/save " + pathWithDirectories.toString(), "")
597599
);
598600
assertEquals(list, Files.readAllLines(path));
601+
assertEquals(list, Files.readAllLines(pathWithDirectories));
599602
}
600603
{
601604
List<String> output = new ArrayList<>();

0 commit comments

Comments
 (0)