From 130b29438afab472103abcb9715045955e9908b3 Mon Sep 17 00:00:00 2001 From: Takase <20792268+takase1121@users.noreply.github.com> Date: Tue, 8 Jun 2021 04:44:35 +0800 Subject: [PATCH] Allow creation of nested directories (#254) * allow nested directories to be created * fix / be turned into // * refactor error handling * refactor path splitting and mkdir calls If a path exists it will now return immediately. * fix typo * remove possible trailing empty string * fix bugs with path check --- data/core/commands/files.lua | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/data/core/commands/files.lua b/data/core/commands/files.lua index a0106f47..a366d43e 100644 --- a/data/core/commands/files.lua +++ b/data/core/commands/files.lua @@ -1,12 +1,39 @@ local core = require "core" local command = require "core.command" +local function mkdirp(path) + local segments = {} + local pos = 1 + while true do + local s, e = string.find(path, "[/\\]+", pos) + if not s then break end + table.insert(segments, string.sub(str, pos, s - 1)) + pos = e + 1 + end + table.insert(segments, string.sub(str, pos)) + if segments[#segments] == '' then + table.remove(segments) + end + + for i = 1, #segments do + local p = table.concat(segments, PATHSEP, 1, i) + local stat = system.get_file_info(p) + if stat and stat.type == "file" then + return nil, "path exists", p + end + local success, err = system.mkdir(p) + if not success then + return nil, err, p + end + end +end + command.add(nil, { ["files:create-directory"] = function() core.command_view:enter("New directory name", function(text) - local success, err = system.mkdir(text) + local success, err, path = mkdirp(text) if not success then - core.error("cannot create directory %q: %s", text, err) + core.error("cannot create directory %q: %s", path, err) end end) end,