2023-12-26 03:08:29 +00:00
|
|
|
-- @module dirs
|
2022-04-23 03:56:57 +00:00
|
|
|
local fs = require 'fs'
|
|
|
|
|
|
|
|
local dirs = {}
|
|
|
|
|
|
|
|
--- Last (current working) directory. Separate from recentDirs mainly for
|
|
|
|
--- easier use.
|
|
|
|
dirs.old = ''
|
|
|
|
--- Table of recent directories. For use, look at public functions.
|
|
|
|
dirs.recentDirs = {}
|
|
|
|
--- Size of the recentDirs table.
|
|
|
|
dirs.recentSize = 10
|
|
|
|
|
|
|
|
--- Get (and remove) a `num` of entries from recent directories.
|
2023-12-26 03:08:29 +00:00
|
|
|
-- @param num number
|
|
|
|
-- @param remove boolean Whether to remove items
|
2022-04-23 03:56:57 +00:00
|
|
|
function dirRecents(num, remove)
|
|
|
|
num = num or 1
|
|
|
|
local entries = {}
|
|
|
|
|
|
|
|
if #dirs.recentDirs ~= 0 then
|
|
|
|
for i = 1, num do
|
|
|
|
local idx = remove and 1 or i
|
|
|
|
if not dirs.recentDirs[idx] then break end
|
|
|
|
table.insert(entries, dirs.recentDirs[idx])
|
|
|
|
if remove then table.remove(dirs.recentDirs, 1) end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
if #entries == 1 then
|
|
|
|
return entries[1]
|
|
|
|
end
|
|
|
|
|
|
|
|
return entries
|
|
|
|
end
|
|
|
|
|
|
|
|
--- Look at `num` amount of recent directories, starting from the latest.
|
2023-12-26 03:08:29 +00:00
|
|
|
-- @param num? number
|
2022-04-23 03:56:57 +00:00
|
|
|
function dirs.peak(num)
|
|
|
|
return dirRecents(num)
|
|
|
|
end
|
|
|
|
|
2023-12-26 03:08:29 +00:00
|
|
|
--- Add `d` to the recent directories list.
|
2022-04-23 03:56:57 +00:00
|
|
|
function dirs.push(d)
|
|
|
|
dirs.recentDirs[dirs.recentSize + 1] = nil
|
|
|
|
if dirs.recentDirs[#dirs.recentDirs - 1] ~= d then
|
|
|
|
ok, d = pcall(fs.abs, d)
|
|
|
|
assert(ok, 'could not turn "' .. d .. '"into an absolute path')
|
|
|
|
|
|
|
|
table.insert(dirs.recentDirs, 1, d)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-12-26 03:08:29 +00:00
|
|
|
--- Remove the specified amount of dirs from the recent directories list.
|
|
|
|
-- @param num number
|
2022-04-23 03:56:57 +00:00
|
|
|
function dirs.pop(num)
|
|
|
|
return dirRecents(num, true)
|
|
|
|
end
|
|
|
|
|
2023-12-26 03:08:29 +00:00
|
|
|
--- Get entry from recent directories list based on index.
|
|
|
|
-- @param idx number
|
2022-04-23 03:56:57 +00:00
|
|
|
function dirs.recent(idx)
|
|
|
|
return dirs.recentDirs[idx]
|
|
|
|
end
|
|
|
|
|
2023-12-26 03:08:29 +00:00
|
|
|
--- Sets the old directory string.
|
|
|
|
-- @param d string
|
2022-04-23 03:56:57 +00:00
|
|
|
function dirs.setOld(d)
|
|
|
|
ok, d = pcall(fs.abs, d)
|
|
|
|
assert(ok, 'could not turn "' .. d .. '"into an absolute path')
|
|
|
|
|
|
|
|
os.setenv('OLDPWD', d)
|
|
|
|
dirs.old = d
|
|
|
|
end
|
|
|
|
|
|
|
|
return dirs
|