-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrgp.py
More file actions
116 lines (90 loc) · 2.66 KB
/
brgp.py
File metadata and controls
116 lines (90 loc) · 2.66 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""brgp main file"""
import os
import sys
import codecs
from pathlib import Path
CURDIR = Path(os.path.abspath(os.curdir))
BRGP_NAME = os.path.basename(__file__)
BRGP_FILE = os.path.abspath(__file__)
HOOK_DIR = CURDIR / ".git" / "hooks"
PRE_COMMIT = HOOK_DIR / "pre-commit"
HELP_TEXT = \
"""brgp
usage:
%s [help]
print help infomation.
%s install [python exec]
init brgp and write to git pre-commit.
%s clear [add|noadd]
clear all boms and add (optionally) it in git.
noadd is default.
""" % (BRGP_NAME, BRGP_NAME, BRGP_NAME)
PRECOMMIT = \
"""#!/bin/sh
cd $GIT_DIR
cd ..
%s "%s" clear add
"""
DEFAULT_PYTHON_EXEC = "python"
def process_single_file(file: str, noadd: bool) -> None:
"""remove bom for a single file"""
cont_rb = None
try:
cont_rb = open(file, "rb")
except PermissionError:
print("rejected %s" % file)
if cont_rb is None:
return
if cont_rb.read(3) == codecs.BOM_UTF8:
cont_rb.close()
cont_rt = open(file, 'r+', encoding='utf-8')
cont = cont_rt.read()
cont_rt.seek(0)
cont_rt.truncate(0)
cont_rt.write(cont[1:])
cont_rt.flush()
cont_rt.close()
print("processed %s" % file)
if not noadd:
os.system("git add %s" % file)
print("git add %s" % file)
else:
cont_rb.close()
print("skip %s" % file)
def clear(argv: list) -> None:
"""clear bom of all files under current directory recursively"""
noadd = (not argv) or argv[0].lower() == "noadd"
gitdir = os.path.join(CURDIR, ".git")
for path, _, files in os.walk(CURDIR):
if os.path.relpath(path, gitdir)[:2] != '..':
continue
for file in files:
# if f.split('.')[-1] in EXTS:
process_single_file(os.path.join(path, file), noadd)
def get_precommit_file_content(python_exec: str) -> str:
"""get pre-commit file content"""
return PRECOMMIT % (python_exec, BRGP_FILE)
def install(argv: list):
"""write pre-commit"""
python_exec = DEFAULT_PYTHON_EXEC if not argv else argv[0]
precommit = get_precommit_file_content(python_exec)
precommit_file = open(str(PRE_COMMIT), 'w', encoding="utf-8")
precommit_file.write(precommit)
precommit_file.flush()
precommit_file.close()
def print_helpinfo():
"""print help infomation"""
print(HELP_TEXT)
def main():
"""entry point"""
argv = sys.argv[1:]
if (not argv) or argv[0] == "help":
print_helpinfo()
elif argv[0] == "install":
install(argv[1:])
elif argv[0] == "clear":
clear(argv[1:])
if __name__ == "__main__":
main()