-
Notifications
You must be signed in to change notification settings - Fork 2
/
rec.py
executable file
·160 lines (135 loc) · 5.79 KB
/
rec.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/usr/bin/python3
from __future__ import print_function, division, absolute_import, \
unicode_literals
import base64
import collections
import glob
import json
import os
import pyinotify
import subprocess
import sys
import tempfile
from os.path import join as pjoin
from os.path import dirname, exists, isfile, isdir, relpath
CONFIG_FILE_NAME = '.rec.json'
def find_config(startdir):
path = pjoin(startdir, CONFIG_FILE_NAME)
if exists(path):
return path
elif (startdir == '/'):
return None
else:
return find_config(dirname(startdir))
def get_session_file_name(working_dir, file_name_prefix):
prefix = pjoin(working_dir, file_name_prefix)
extension = '.json'
existing = glob.glob(prefix + '??' + extension)
if existing:
last = sorted(existing)[-1]
last_num = int(last[len(prefix): -len(extension)])
fname = '{}{:02d}.json'.format(file_name_prefix, last_num + 1)
else:
fname = file_name_prefix + '01.json'
return fname
def main():
config_file = find_config(os.getcwd())
if config_file:
wd = dirname(config_file)
config = json.load(open(config_file))
else:
config = {}
wd = os.getcwd()
command = config.get('command', 'bash')
session_fname = get_session_file_name(wd,
config.get('session_file_prefix', 'session_'))
index_fname = config.get('index_file', 'index.html')
session_dir = dirname(pjoin(wd, session_fname))
if not isdir(pjoin(wd, session_dir)):
os.makedirs(pjoin(wd, session_dir))
# create session file to prevent race condition
open(pjoin(wd, session_fname), 'a').close()
git_root = subprocess.check_output(['git', 'rev-parse',
'--show-toplevel'])
git_root = str(git_root, encoding='utf-8').strip()
server_path = '/' + relpath(wd, start=git_root) + '/'
with tempfile.NamedTemporaryFile() as logfile, \
tempfile.NamedTemporaryFile() as timingfile, \
open(pjoin(wd, session_fname), 'w') as outfile, \
open(pjoin(wd, index_fname), 'r+', encoding='UTF-8') as indexfile:
wm = pyinotify.WatchManager()
wm.add_watch(pjoin(wd, session_dir), pyinotify.IN_CLOSE_WRITE)
proc = subprocess.Popen(['script', '--flush', '--quiet',
'--command={}'.format(command),
'--timing={}'.format(timingfile.name),
logfile.name],
cwd=pjoin(wd, session_dir))
proc.wait()
events = []
notifier = pyinotify.Notifier(wm, events.append)
if notifier.check_events(0):
notifier.read_events()
notifier.process_events()
wm.close()
touched_files = [e.name for e in events
if isfile(pjoin(wd, session_dir, e.name))]
touched_files = list(collections.OrderedDict.fromkeys(touched_files))
columns = int(subprocess.check_output(['tput', 'cols']).strip())
lines = int(subprocess.check_output(['tput', 'lines']).strip())
data = {
'script': str(base64.b64encode(b''.join(logfile.readlines()[1:])),
encoding='ascii'),
'timings': [(float(time), int(cnt)) for time, cnt in
(line.split() for line in timingfile.readlines())],
'columns': columns,
'lines': lines,
}
json.dump(data, outfile)
try:
session_title = input("Session title: ")
except KeyboardInterrupt:
os.remove(pjoin(wd, session_fname))
exit(1)
if not session_title:
session_title = session_fname.replace('.json', '')\
.replace('_', ' ')\
.capitalize()
added_files = []
for f in touched_files:
answer = input("Add file '{}'? [Y/n] ".format(f)).strip().lower()
if answer == '' or answer[0] == 'y':
added_files.append(f)
term_session_cursor = config.get('index_file_cursor',
'<!-- REC-TERM-SESSION -->')
term_session_templ = config.get('term_session_template',
'<a href="/console.html?data=' \
+ server_path \
+ '{filename}">{title}</a><br/>')
files_cursor = config.get('files_cursor',
'<!-- REC-FILES -->')
files_templ = config.get('files_template',
'<a href="{path}">{filename}</a><br/>')
data = indexfile.read()
term_session = term_session_templ.format(filename=session_fname,
title=session_title)
data = data.replace(term_session_cursor,
term_session + term_session_cursor)
files = ''.join(files_templ.format(
filename=pjoin(dirname(session_fname), f),
title=f,
path=pjoin(session_dir, f)
) for f in added_files)
data = data.replace(files_cursor, files + files_cursor)
indexfile.seek(0)
indexfile.truncate()
indexfile.write(data)
if config.get('commit', False):
subprocess.call(['git', 'add', pjoin(wd, index_fname),
pjoin(wd, session_fname)]\
+ [pjoin(wd, session_dir, f) for f in added_files])
subprocess.call(['git', 'commit', '-m',
'Auto-commit: ' + session_title])
if config.get('push', False):
subprocess.call(['git', 'push'])
if __name__ == '__main__':
main(*sys.argv[1:])