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
This commit is contained in:
Takase 2021-06-08 04:44:35 +08:00 committed by GitHub
parent 2170ab9649
commit 130b29438a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 2 deletions

View File

@ -1,12 +1,39 @@
local core = require "core" local core = require "core"
local command = require "core.command" 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, { command.add(nil, {
["files:create-directory"] = function() ["files:create-directory"] = function()
core.command_view:enter("New directory name", function(text) 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 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) end)
end, end,