-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdetect.py
More file actions
96 lines (65 loc) · 2.39 KB
/
detect.py
File metadata and controls
96 lines (65 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# =========================================
# IMPORTS
# --------------------------------------
import sys
import os
import re
import six
from os import path, listdir
# =========================================
# CONSTANTS
# --------------------------------------
DEFAULT_PATH = "."
DEFAULT_ROOT_FILENAME_MATCH_PATTERN = ".git|requirements.txt|pyproject.toml"
# =========================================
# FUNCTIONS
# --------------------------------------
def detect(current_path=None, pattern=None):
"""
Find project root path from specified file/directory path,
based on common project root file pattern.
Examples:
import rootpath
rootpath.detect()
rootpath.detect(__file__)
rootpath.detect('./src')
"""
current_path = current_path or os.getcwd()
current_path = path.abspath(path.normpath(path.expanduser(current_path)))
pattern = pattern or DEFAULT_ROOT_FILENAME_MATCH_PATTERN
if not path.isdir(current_path):
current_path = path.dirname(current_path)
def find_root_path(current_path, pattern):
if isinstance(pattern, six.string_types):
pattern = re.compile(pattern)
detecting = True
found_more_files = None
found_root = None
found_system_root = None
file_names = None
root_file_names = None
while detecting:
try:
file_names = listdir(current_path)
found_more_files = bool(len(file_names) > 0)
except FileNotFoundError:
return None
if not found_more_files:
detecting = False
return None
root_file_names = filter(pattern.match, file_names)
root_file_names = list(root_file_names)
found_root = bool(len(root_file_names) > 0)
if found_root:
detecting = False
return current_path
found_system_root = bool(current_path == path.sep)
if found_system_root:
return None
system_root = sys.executable
while os.path.split(system_root)[1]:
system_root = os.path.split(system_root)[0]
if current_path == system_root:
return None
current_path = path.abspath(path.join(current_path, ".."))
return find_root_path(current_path, pattern)