Skip to content

Commit ef8c9bc

Browse files
authored
[Perf] wrap platform utils and refactor the logic to get default (#126)
save_path
1 parent a8bba8a commit ef8c9bc

File tree

3 files changed

+34
-12
lines changed

3 files changed

+34
-12
lines changed

lua/codesnap/static.lua

+1-12
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,4 @@
11
local path_utils = require("codesnap.utils.path")
2-
-- Get user os
3-
-- If linux, use XDG_PICTURE_DIR, if mac use ~/Pictures, if windows use FOLDERID_Pictures (If support is added back)
4-
local default_save_path = nil
5-
local os_name = vim.loop.os_uname().sysname
6-
if os_name == "Linux" then
7-
default_save_path = os.getenv("XDG_PICTURES_DIR") or (os.getenv("HOME") .. "/Pictures")
8-
elseif os_name == "Darwin" then
9-
default_save_path = os.getenv("HOME") .. "/Pictures"
10-
else
11-
error("codesnap.nvim only supports Linux and MacOS")
12-
end
132

143
return {
154
config = {
@@ -26,7 +15,7 @@ return {
2615
min_width = 0,
2716
bg_x_padding = 122,
2817
bg_y_padding = 82,
29-
save_path = default_save_path,
18+
save_path = path_utils.get_default_save_path(),
3019
},
3120
cwd = path_utils.back(path_utils.back(debug.getinfo(1, "S").source:sub(2):match("(.*[/\\])"))),
3221
preview_switch = true,

lua/codesnap/utils/path.lua

+18
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
local string_utils = require("codesnap.utils.string")
2+
local platform_utils = require("codesnap.utils.platform")
23
local path_utils = {}
34

45
function path_utils.get_escaped_cwd()
@@ -26,4 +27,21 @@ function path_utils.get_relative_path()
2627
return full_file_path:gsub(path_utils.get_escaped_cwd(), ""):sub(2)
2728
end
2829

30+
-- Get default save path by OS
31+
-- If Linux, use XDG_PICTURE_DIR
32+
-- if mac use ~/Pictures
33+
-- if windows use FOLDERID_Pictures (If support is added back)
34+
function path_utils.get_default_save_path()
35+
local home_picture_folder = os.getenv("HOME") .. "/Pictures"
36+
37+
return platform_utils.match_os({
38+
Darwin = function()
39+
return home_picture_folder
40+
end,
41+
Linux = function()
42+
return os.getenv("XDG_PICTURES_DIR") or home_picture_folder
43+
end,
44+
})
45+
end
46+
2947
return path_utils

lua/codesnap/utils/platform.lua

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
local platform_utils = {}
2+
3+
local current_os_name = vim.loop.os_uname().sysname
4+
5+
function platform_utils.match_os(matches_table)
6+
local fn = matches_table[current_os_name]
7+
8+
if fn == nil then
9+
error("codesnap.nvim not supported on " .. current_os_name)
10+
end
11+
12+
return fn()
13+
end
14+
15+
return platform_utils

0 commit comments

Comments
 (0)