forked from aosabook/500lines
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcogutil.py
More file actions
47 lines (40 loc) · 1.25 KB
/
Copy pathcogutil.py
File metadata and controls
47 lines (40 loc) · 1.25 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
import textwrap
import cog
LAST_LINES = None
LAST_FILENAME = None
def include(filename, first=None, after=None, numlines=None, numblanks=None, dedent=True):
"""
Include text from a file.
"""
global LAST_LINES, LAST_FILENAME
if filename != LAST_FILENAME:
with open(filename) as f:
lines = LAST_LINES = f.readlines()
LAST_FILENAME = filename
else:
lines = LAST_LINES
including = "".join(selected_lines(lines, first, after, numlines, numblanks))
if dedent:
including = textwrap.dedent(including)
cog.outl("```")
cog.out(including)
cog.outl("```")
def selected_lines(lines, first=None, after=None, numlines=None, numblanks=None):
ready = after is None
including = False
for line in lines:
if not ready:
if after in line:
ready = True
if ready and first is not None and first in line:
including = True
if including:
if numblanks is not None and not line.strip():
numblanks -= 1
if not numblanks:
break
yield line
if numlines is not None:
numlines -= 1
if not numlines:
break