Skip to content

Commit

Permalink
[Perf] wrap platform utils and refactor the logic to get default (#126)
Browse files Browse the repository at this point in the history
save_path
  • Loading branch information
mistricky authored Jul 30, 2024
1 parent a8bba8a commit ef8c9bc
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 12 deletions.
13 changes: 1 addition & 12 deletions lua/codesnap/static.lua
Original file line number Diff line number Diff line change
@@ -1,15 +1,4 @@
local path_utils = require("codesnap.utils.path")
-- Get user os
-- If linux, use XDG_PICTURE_DIR, if mac use ~/Pictures, if windows use FOLDERID_Pictures (If support is added back)
local default_save_path = nil
local os_name = vim.loop.os_uname().sysname
if os_name == "Linux" then
default_save_path = os.getenv("XDG_PICTURES_DIR") or (os.getenv("HOME") .. "/Pictures")
elseif os_name == "Darwin" then
default_save_path = os.getenv("HOME") .. "/Pictures"
else
error("codesnap.nvim only supports Linux and MacOS")
end

return {
config = {
Expand All @@ -26,7 +15,7 @@ return {
min_width = 0,
bg_x_padding = 122,
bg_y_padding = 82,
save_path = default_save_path,
save_path = path_utils.get_default_save_path(),
},
cwd = path_utils.back(path_utils.back(debug.getinfo(1, "S").source:sub(2):match("(.*[/\\])"))),
preview_switch = true,
Expand Down
18 changes: 18 additions & 0 deletions lua/codesnap/utils/path.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
local string_utils = require("codesnap.utils.string")
local platform_utils = require("codesnap.utils.platform")
local path_utils = {}

function path_utils.get_escaped_cwd()
Expand Down Expand Up @@ -26,4 +27,21 @@ function path_utils.get_relative_path()
return full_file_path:gsub(path_utils.get_escaped_cwd(), ""):sub(2)
end

-- Get default save path by OS
-- If Linux, use XDG_PICTURE_DIR
-- if mac use ~/Pictures
-- if windows use FOLDERID_Pictures (If support is added back)
function path_utils.get_default_save_path()
local home_picture_folder = os.getenv("HOME") .. "/Pictures"

return platform_utils.match_os({
Darwin = function()
return home_picture_folder
end,
Linux = function()
return os.getenv("XDG_PICTURES_DIR") or home_picture_folder
end,
})
end

return path_utils
15 changes: 15 additions & 0 deletions lua/codesnap/utils/platform.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
local platform_utils = {}

local current_os_name = vim.loop.os_uname().sysname

function platform_utils.match_os(matches_table)
local fn = matches_table[current_os_name]

if fn == nil then
error("codesnap.nvim not supported on " .. current_os_name)
end

return fn()
end

return platform_utils

0 comments on commit ef8c9bc

Please sign in to comment.