Skip to content

Commit ead9a24

Browse files
committed
feat(utils): find project root
1 parent 589e12d commit ead9a24

File tree

2 files changed

+47
-11
lines changed

2 files changed

+47
-11
lines changed

lua/copy-python-path/init.lua

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
local rooter_utils = require("copy-python-path.utils.rooter")
12
local symbol_utils = require("copy-python-path.utils.symbol")
23

34
local M = {}
@@ -6,20 +7,13 @@ function M.copy_dotted_path()
67
-- TODO: Early return if not `*.py` file
78

89
local current_file_path = vim.fs.normalize(vim.fn.expand("%:p"))
10+
local root_dir_path = rooter_utils.find_root_dir_path(current_file_path)
911

10-
-- TODO: Use a more robust method to get root path
11-
local root_path = vim.fs.root(current_file_path, ".git")
12-
13-
if root_path == nil then
14-
-- TODO: Obtain root path in another method
15-
return
16-
end
17-
18-
if not root_path:match("/$") then
19-
root_path = root_path .. "/"
12+
if not root_dir_path:match("/$") then
13+
root_dir_path = root_dir_path .. "/"
2014
end
2115

22-
local relative_path = current_file_path:sub(#root_path + 1)
16+
local relative_path = current_file_path:sub(#root_dir_path + 1)
2317
local current_file_dotted_path = relative_path:gsub("/", "."):gsub(".py$", "")
2418

2519
-- TODO: Check if symbol at cursor is an import alias
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
local M = {}
2+
3+
local markers = {
4+
-- Version control systems
5+
".git",
6+
".hg",
7+
".svn",
8+
9+
-- Python specific project markers
10+
"pyproject.toml",
11+
"setup.py",
12+
"setup.cfg",
13+
"requirements.txt",
14+
"Pipfile",
15+
"poetry.lock",
16+
17+
-- Configuration files often at project root
18+
".python-version",
19+
"tox.ini",
20+
"pytest.ini",
21+
".flake8",
22+
".isort.cfg",
23+
"mypy.ini",
24+
}
25+
26+
--- Find the absolute path of the Python project's root. Defaults to `path`'s current directory
27+
--- opened file if failed to locate the root.
28+
---@param path string The absolute path to search from
29+
---@return string root_dir_path Normalized absolute path of the project root directory.
30+
function M.find_root_dir_path(path)
31+
local current_dir = vim.fs.dirname(path)
32+
33+
local marker_path = vim.fs.find(markers, {
34+
path = path,
35+
upward = true,
36+
limit = 1,
37+
})[1]
38+
39+
return marker_path and vim.fs.dirname(marker_path) or current_dir
40+
end
41+
42+
return M

0 commit comments

Comments
 (0)