Skip to content

Commit 2d52f2e

Browse files
author
Gunther Klessinger
committed
fmt
1 parent 6ca98f3 commit 2d52f2e

1 file changed

Lines changed: 47 additions & 47 deletions

File tree

src/lcdoc/mkdocs/lp/plugs/python/__init__.py

Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,18 @@
2121

2222
err = lp.err
2323
multi_line_to_list = False
24-
fmt_default = 'unset'
24+
fmt_default = "unset"
2525

2626
sessions = S = {}
2727

28-
config = lambda: Session.kw['LP'].config
29-
page = lambda: Session.kw['LP'].page
28+
config = lambda: Session.kw["LP"].config
29+
page = lambda: Session.kw["LP"].page
3030
lpkw = lambda: Session.kw
3131
stats = lambda: page().stats
3232

3333

3434
def new_session_ctx():
35-
return {'out': [], 'locals': {}, 'assets': {}}
35+
return {"out": [], "locals": {}, "assets": {}}
3636

3737

3838
class Session(lp.SessionNS):
@@ -53,20 +53,20 @@ def pre(cls, session_name, kw):
5353

5454
@classmethod
5555
def post(cls, session_name, kw):
56-
Session.cur['out'].clear()
56+
Session.cur["out"].clear()
5757
if cls.name is None:
58-
Session.cur['locals'].clear()
58+
Session.cur["locals"].clear()
5959
sessions.pop(None) # forget it, no name was given
6060
# we support post param to run system stuff before python
6161
lp.SessionNS.post(session_name, kw)
6262

6363

6464
def out(s, t=None, innerkw=None):
65-
Session.cur['out'].append([t, s, innerkw])
65+
Session.cur["out"].append([t, s, innerkw])
6666

6767

6868
def printed(s, **innerkw):
69-
out(s, 'printed', innerkw=innerkw)
69+
out(s, "printed", innerkw=innerkw)
7070

7171

7272
def show(s, **innerkw):
@@ -78,7 +78,7 @@ def show(s, **innerkw):
7878
# if 'nocache' in s:
7979
# lpkw()['nocache'] = s['nocache']
8080
# s = s['res']
81-
out(s, 'md', innerkw=innerkw)
81+
out(s, "md", innerkw=innerkw)
8282

8383

8484
# keys: matching strings on s and s class, with s the argument of `show()`:
@@ -88,7 +88,7 @@ def show(s, **innerkw):
8888

8989
def matching_pyplug(s, innerkw):
9090
"""find rendering pyplug based on type of output"""
91-
if innerkw.get('md'):
91+
if innerkw.get("md"):
9292
return # markdown was forced (show('> foo', md=True)
9393
if isinstance(s, str) and s in fmts:
9494
return fmts[s]
@@ -100,11 +100,11 @@ def matching_pyplug(s, innerkw):
100100
elif k in str([s, s.__class__]):
101101
return fmts[k]
102102
if not isinstance(s, str):
103-
app.die('No formatter matched', s=s, **innerkw)
103+
app.die("No formatter matched", s=s, **innerkw)
104104

105105

106106
def fmt(t, s, kw):
107-
if t == 'md':
107+
if t == "md":
108108
o = (False, s)
109109
elif isinstance(s, str):
110110
o = (True, s)
@@ -113,51 +113,51 @@ def fmt(t, s, kw):
113113
return o
114114

115115

116-
D_lp_py = lambda: project.root() + '/build/autodocs/lp_python/'
116+
D_lp_py = lambda: project.root() + "/build/autodocs/lp_python/"
117117

118118

119119
def cmd_to_module_file(cmd, kw):
120120
dr = D_lp_py()
121-
fn = dr + dirname(kw['LP'].page.file.src_path) + '/%(id)s.py' % kw
122-
h = 'from lcdoc.mkdocs.lp.plugs import python'
123-
h += '\nprint = python.printed'
124-
h += '\nshow = python.show'
125-
h += '\ndef run_lp_flow():'
126-
cmd = ('\n' + cmd).replace('\n', '\n ')
127-
write_file(fn, h + '\n' + cmd, mkdir=1)
121+
fn = dr + dirname(kw["LP"].page.file.src_path) + "/%(id)s.py" % kw
122+
h = "from lcdoc.mkdocs.lp.plugs import python"
123+
h += "\nprint = python.printed"
124+
h += "\nshow = python.show"
125+
h += "\ndef run_lp_flow():"
126+
cmd = ("\n" + cmd).replace("\n", "\n ")
127+
write_file(fn, h + "\n" + cmd, mkdir=1)
128128
sys.path.insert(0, dirname(fn)) if not dirname(fn) in sys.path else 0
129129
return fn
130130

131131

132132
def build_res(plug_res):
133-
m = {'res': ''}
133+
m = {"res": ""}
134134
for r in plug_res:
135135
if isinstance(r, str):
136-
m['res'] += '\n\n' + r
136+
m["res"] += "\n\n" + r
137137
elif isinstance(r, dict):
138138
for k, v in r.items():
139139
vh = m.get(k)
140140
if vh == None:
141141
m[k] = v
142142
elif isinstance(vh, str):
143-
m[k] += vh + '\n\n' + v
143+
m[k] += vh + "\n\n" + v
144144
elif isinstance(vh, dict):
145145
deep_update(vh, v)
146146
elif r is None:
147147
pass
148148
else:
149-
app.die('Not supported result type', res=r)
149+
app.die("Not supported result type", res=r)
150150
return m
151151

152152

153153
def run(cmd, kw):
154154
"""
155155
interpret the command as python
156156
"""
157-
l = kw['mode'].split(':')
157+
l = kw["mode"].split(":")
158158
# set if not yet done:
159-
project.root(kw['LP'].config)
160-
plug_res = ['']
159+
project.root(kw["LP"].config)
160+
plug_res = [""]
161161

162162
def add(r):
163163
plug_res.append(r)
@@ -166,28 +166,28 @@ def add(r):
166166
add(fmts[l[1]](l[1], **kw))
167167
else:
168168
# short form convenience: `lp:python show=project_dependencies`
169-
shw = kw.pop('show', '')
169+
shw = kw.pop("show", "")
170170
if shw and isinstance(cmd, str):
171171
cmd = 'show("%s")' % shw + cmd
172-
if kw.get('cfl'):
172+
if kw.get("cfl"):
173173
modfn = cmd_to_module_file(cmd, kw)
174-
m = importlib.import_module(kw['id'])
174+
m = importlib.import_module(kw["id"])
175175
m.run_lp_flow()
176176
else:
177-
loc = Session.cur['locals']
178-
g = {'print': printed, 'show': show, 'ctx': kw}
177+
loc = Session.cur["locals"]
178+
g = {"print": printed, "show": show, "ctx": kw}
179179
loc.update(g)
180180
exec(cmd, loc)
181-
o = Session.cur['out']
181+
o = Session.cur["out"]
182182
res = [fmt(*i) for i in o]
183183
fncd = False
184184
# if the fmt is given (mk_console usually), then we show the command (python code)
185185
# and the output within the usual lp fenced code block.
186186
# if it was unset then we open and close fenced code only for print outs
187187
fstart, fstop = (None, None)
188-
if kw['fmt'] == 'unset':
189-
fstart = '```python'
190-
fstop = '```'
188+
if kw["fmt"] == "unset":
189+
fstart = "```python"
190+
fstop = "```"
191191
while res:
192192
is_fenced, o = res.pop(0)
193193
if is_fenced and not fncd:
@@ -201,31 +201,31 @@ def add(r):
201201
add(fstop)
202202
r = build_res(plug_res)
203203
# python code may explicitly set a result as object, ready to process e.g. in a mode pipe
204-
rslt = Session.cur['locals'].get('result')
204+
rslt = Session.cur["locals"].get("result")
205205
if rslt:
206-
r['result'] = rslt
206+
r["result"] = rslt
207207
# was fmt given by user?
208-
if kw['fmt'] == 'unset':
209-
r['formatted'] = True
210-
if 'nocache' in kw:
211-
r['nocache'] = kw['nocache']
212-
r.update(Session.cur['assets'])
208+
if kw["fmt"] == "unset":
209+
r["formatted"] = True
210+
if "nocache" in kw:
211+
r["nocache"] = kw["nocache"]
212+
r.update(Session.cur["assets"])
213213
return r
214214

215215

216216
def import_pyplugs(frm):
217217
m = import_module(frm)
218-
for k in [i for i in dir(m) if not i.startswith('_')]:
218+
for k in [i for i in dir(m) if not i.startswith("_")]:
219219
v = getattr(m, k)
220-
if hasattr(v, 'register'):
220+
if hasattr(v, "register"):
221221
if callable(v.register):
222222
v.register(fmts)
223223
else:
224224
fmts.update(v.register)
225225

226226

227-
import_pyplugs('lcdoc.mkdocs.lp.plugs.python.pyplugs')
227+
import_pyplugs("lcdoc.mkdocs.lp.plugs.python.pyplugs")
228228
try:
229-
import_pyplugs('lp_python_plugins') # allow customs
229+
import_pyplugs("lp_python_plugins") # allow customs
230230
except ModuleNotFoundError as ex:
231231
pass

0 commit comments

Comments
 (0)