-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproj
More file actions
executable file
·89 lines (64 loc) · 2.51 KB
/
Copy pathproj
File metadata and controls
executable file
·89 lines (64 loc) · 2.51 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
#!/usr/bin/env python3
import os
from pathlib import Path
import re
import subprocess
import sys
"""
This script searches through a few paths found in the PROJ_PATH environment variable and its main purpose
is to run the command 'code /some/path --reuse-window' with the best fitting project name available,
to make it easy to open project folders in VSCode via a few keystrokes, e.g.
'proj sat' --> 'code /home/caius/py_projects/satellite --reuse-window'
"""
def main():
PROJ_PATH = os.environ.get("PROJ_PATH")
if PROJ_PATH is None:
sys.exit("Couldn't find environment variable $PROJ_PATH")
paths = PROJ_PATH.split(":")
# just running "proj" in the command line lists the paths in PROJ_PATH env. variable
if len(sys.argv) == 1:
print_proj_paths(paths)
elif len(sys.argv) == 2:
find_proj(paths, sys.argv[1])
def print_proj_paths(paths: list):
for path in paths:
print(path)
def find_proj(paths: list, search_str: str):
proj_dict = build_proj_dict(paths)
match_dict = get_match_dict(proj_dict, search_str)
match_dict = sort_by_proj_name_length(match_dict) # likely want shortest named one, keep it simple
if not match_dict:
sys.exit("Couldn't find a matching project name")
project = list(match_dict)[0]
reopen_code_window(match_dict[project])
def build_proj_dict(paths: list) -> dict:
proj_dict = {}
for path in paths:
path = Path(path)
for subpath in path.iterdir():
if not subpath.is_dir():
continue
dir_name = subpath.name
if dir_name not in proj_dict:
proj_dict[dir_name] = str(subpath)
elif isinstance(proj_dict[dir_name], str):
proj_dict[dir_name] = [proj_dict[dir_name], str(subpath)]
else:
proj_dict[dir_name].append(str(subpath))
return proj_dict
def get_match_dict(proj_dict: dict, search_str: str) -> dict:
match_dict = {}
for proj_name in proj_dict:
if re.search(search_str, proj_name) is not None:
match_dict[proj_name] = proj_dict[proj_name]
return match_dict
def sort_by_proj_name_length(proj_dict: dict) -> dict:
return dict(sorted(proj_dict.items(), key=lambda x: len(x[0])))
def reopen_code_window(path: str):
command = f"code {path} --reuse-window"
if Path("/bin/zsh").exists:
subprocess.run(command, shell=True, executable="/bin/zsh")
else:
subprocess.run(command, shell=True)
if __name__ == "__main__":
main()