8373097: Save command should create missing parent directories

Reviewed-by: jlahoda
This commit is contained in:
Christian Stein 2025-12-17 07:18:26 +00:00
parent e635330ae1
commit e9b4696acc
2 changed files with 17 additions and 2 deletions

View File

@ -3362,7 +3362,19 @@ public class JShellTool implements MessageHandler {
// error occurred, already reported
return false;
}
try (BufferedWriter writer = Files.newBufferedWriter(toPathResolvingUserHome(filename),
// Create missing parent directories before writing to target file
Path target;
try {
target = toPathResolvingUserHome(filename);
Path parent = target.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
} catch (Exception e) {
errormsg("jshell.err.file.exception", "/save", filename, e);
return false;
}
try (BufferedWriter writer = Files.newBufferedWriter(target,
Charset.defaultCharset(),
CREATE, TRUNCATE_EXISTING, WRITE)) {
if (at.hasOption("-history")) {

View File

@ -585,6 +585,7 @@ public class ToolBasicTest extends ReplToolTesting {
Compiler compiler = new Compiler();
Path path = compiler.getPath("testSave.repl");
{
Path pathWithDirectories = compiler.getPath("what/ever/testSave.repl");
List<String> list = Arrays.asList(
"int a;",
"class A { public String toString() { return \"A\"; } }"
@ -593,9 +594,11 @@ public class ToolBasicTest extends ReplToolTesting {
(a) -> assertVariable(a, "int", "a"),
(a) -> assertCommand(a, "()", null, null, null, "", ""),
(a) -> assertClass(a, "class A { public String toString() { return \"A\"; } }", "class", "A"),
(a) -> assertCommand(a, "/save " + path.toString(), "")
(a) -> assertCommand(a, "/save " + path.toString(), ""),
(a) -> assertCommand(a, "/save " + pathWithDirectories.toString(), "")
);
assertEquals(list, Files.readAllLines(path));
assertEquals(list, Files.readAllLines(pathWithDirectories));
}
{
List<String> output = new ArrayList<>();