-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·91 lines (84 loc) · 2.87 KB
/
main.py
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
#!/usr/bin/env python3
import os
import re
import subprocess
from sys import argv, stderr, stdout
NOTE_FOLDER_PATH = os.path.normpath(os.environ['NOTE_FOLDER'])
EDITOR = os.environ['EDITOR']
def parse_argv() -> ("relative_path", "vim_flags", int):
""" converts argv into a more usable format
:returns: a tuple of the relative path name and the flags for vim and the number of rotations to encode
"""
_ = argv.pop(0)
relative_paths = []
vim_flags = ""
next_arg_is_n = False
n = 0
for arg in argv:
if arg == '--rotn':
next_arg_is_n = True
elif arg.startswith('-'):
vim_flags += arg + " "
elif next_arg_is_n:
n = int(arg)
next_arg_is_n = False
else:
if '.' not in arg:
arg += ".txt"
relative_paths.append(os.path.normpath(arg))
length = len(relative_paths)
if length < 1:
raise(Exception("Too few arguments"))
return relative_paths, vim_flags, n
def open_file(relative_paths: list, vim_flags: str, n: int) -> None:
""" Opens the file in vim
:relative_path: a list of relative paths
:vim_flags: flags to pass to vim directly
:n: spaces to rotate in ROTN
:returns: None
"""
file_paths = []
for relative_path in relative_paths:
if "\\" in relative_path or "/" in relative_path:
lst = re.split(r" |\\|/", relative_path)
file_name = lst.pop(-1)
folder_name = os.path.normpath("/".join(lst) + "/")
else:
folder_name = ""
file_name = relative_path
file_path = NOTE_FOLDER_PATH
if '.' not in file_name:
file_name += ".txt"
if folder_name != "":
file_path = os.path.join(file_path, folder_name)
if os.path.exists(file_path):
if not os.path.isdir(file_path):
raise(Exception("Folder name already in use by another file"))
else:
os.makedirs(file_path)
file_path = os.path.join(file_path, file_name)
file_paths.append(file_path)
if n != 0:
os.system(f'rotne {n} {" ". join(file_paths)} {vim_flags}')
else:
os.system(f'{EDITOR} {" ". join(file_paths)} {vim_flags}')
def print_usage(file=stdout) -> None:
"""Print the correct usage of the command"""
print(
"Usage of command:\n" +
"\tnote {relative path(s)} {vim flag(optional)}\n" +
"\t\tsee vim --help for info on flags\n" +
"\t\tMore flags:\n" +
"\t\t\t--rotn - next input is how many spaces rotated",
file=file
)
def main():
try:
relative_path, vim_flags, n = parse_argv()
except Exception as e:
print("Error: " + str(e), file=stderr)
print_usage(stderr)
exit(1)
open_file(relative_path, vim_flags, n)
if __name__ == "__main__":
main()