Skip to content

Commit ddef847

Browse files
committed
support make link when creating doc
1 parent 65a7be9 commit ddef847

File tree

3 files changed

+58
-14
lines changed

3 files changed

+58
-14
lines changed

dargs/dargs.py

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,8 @@ def set_default(self, default_tag : Union[bool, str]):
408408
self.optional = False
409409
self.default_tag = ""
410410
else:
411-
assert default_tag in self.choice_dict
411+
if default_tag not in self.choice_dict:
412+
raise ValueError(f"trying to set invalid default_tag {default_tag}")
412413
self.optional = True
413414
self.default_tag = default_tag
414415

@@ -423,7 +424,7 @@ def extend_choices(self, choices: Optional[Iterable["Argument"]]):
423424
exclude={self.flag_name},
424425
err_msg=f"Variant with flag `{self.flag_name}`")
425426
update_nodup(self.choice_alias,
426-
*(((a, c.name) for a in c.alias) for c in choices),
427+
*[[(a, c.name) for a in c.alias] for c in choices],
427428
exclude={self.flag_name, *self.choice_dict.keys()},
428429
err_msg=f"building alias dict for Variant with flag `{self.flag_name}`")
429430

@@ -450,7 +451,12 @@ def dummy_argument(self):
450451
def get_choice(self, argdict: dict) -> "Argument":
451452
if self.flag_name in argdict:
452453
tag = argdict[self.flag_name]
453-
return self.choice_dict[tag]
454+
if tag in self.choice_dict:
455+
return self.choice_dict[tag]
456+
elif tag in self.choice_alias:
457+
return self.choice_dict[self.choice_alias[tag]]
458+
else:
459+
raise KeyError(f"get invalid choice {tag} for flag {self.flag_name}.")
454460
elif self.optional:
455461
return self.choice_dict[self.default_tag]
456462
else:
@@ -477,19 +483,23 @@ def gen_doc(self, paths: Optional[List[str]] = None,
477483
body_list = [""]
478484
body_list.append(f"Depending on the value of *{self.flag_name}*, "
479485
"different sub args are accepted. \n")
480-
body_list.append(self.gen_doc_flag(paths, **kwargs))
486+
body_list.append(self.gen_doc_flag(paths, showflag=showflag, **kwargs))
487+
fnstr = f"*{self.flag_name}*"
488+
if kwargs.get("make_link"):
489+
if not kwargs.get("make_anchor"):
490+
raise ValueError("`make_link` only works with `make_anchor` set")
491+
fnstr, target = make_ref_pair(paths+[self.flag_name], fnstr, "emph")
492+
body_list.append("\n" + target)
481493
for choice in self.choice_dict.values():
482-
f_str = f"{self.flag_name}=" if showflag else ""
483-
c_str = f"[{f_str}{choice.name}]"
484-
choice_path = [*paths[:-1], paths[-1]+c_str] if paths else [c_str]
485494
body_list.append("")
495+
choice_path = self._make_cpath(choice.name, paths, showflag)
486496
if kwargs.get("make_anchor"):
487497
body_list.append(make_rst_refid(choice_path))
488498
c_alias = (f" (or its alias{'es' if len(choice.alias) > 1 else ''} "
489499
+ ", ".join(f"``{al}``" for al in choice.alias) + ")"
490500
if choice.alias else "")
491501
body_list.extend([
492-
f"When *{self.flag_name}* is set to ``{choice.name}``{c_alias}: \n",
502+
f"When {fnstr} is set to ``{choice.name}``{c_alias}: \n",
493503
choice.gen_doc_body(choice_path, **kwargs),
494504
])
495505
body = "\n".join(body_list)
@@ -504,11 +514,31 @@ def gen_doc_flag(self, paths: Optional[List[str]] = None, **kwargs) -> str:
504514
if paths is None:
505515
paths = []
506516
arg_path = [*paths, self.flag_name]
507-
pathdoc = indent(f"| argument path: ``{'/'.join(arg_path)}`` \n", INDENT)
517+
pathdoc = indent(f"| argument path: ``{'/'.join(arg_path)}`` ", INDENT)
518+
if kwargs.get("make_link"):
519+
if not kwargs.get("make_anchor"):
520+
raise ValueError("`make_link` only works with `make_anchor` set")
521+
l_choice, l_target = zip(*(make_ref_pair(
522+
self._make_cpath(c.name, paths, kwargs["showflag"]),
523+
text=f"``{c.name}``", prefix="code")
524+
for c in self.choice_dict.values()))
525+
targetdoc = indent('\n' + '\n'.join(l_target), INDENT)
526+
else:
527+
l_choice = [c.name for c in self.choice_dict.values()]
528+
targetdoc = None
529+
choicedoc = indent("| possible choices: " + ", ".join(l_choice), INDENT)
508530
realdoc = indent(self.doc + "\n", INDENT) if self.doc else None
509531
anchor = make_rst_refid(arg_path) if kwargs.get("make_anchor") else None
510-
allparts = [anchor, headdoc, typedoc, pathdoc, realdoc]
511-
return "\n".join(filter(None, allparts))
532+
allparts = [anchor, headdoc, typedoc, pathdoc, choicedoc, "", realdoc, targetdoc]
533+
return "\n".join(filter(None.__ne__, allparts))
534+
535+
def _make_cpath(self, cname: str,
536+
paths: Optional[List[str]] = None,
537+
showflag : bool = False):
538+
f_str = f"{self.flag_name}=" if showflag else ""
539+
c_str = f"[{f_str}{cname}]"
540+
cpath = [*paths[:-1], paths[-1]+c_str] if paths else [c_str]
541+
return cpath
512542

513543

514544
def make_rst_refid(name):
@@ -517,6 +547,18 @@ def make_rst_refid(name):
517547
return f'.. raw:: html\n\n <a id="{name}"></a>'
518548

519549

550+
def make_ref_pair(path, text=None, prefix=None):
551+
if not isinstance(path, str):
552+
path = '/'.join(path)
553+
url = "#" + path
554+
ref = ("" if not prefix else f"{prefix}:") + path
555+
inline = f'`{ref}`_' if not text else f'|{ref}|_'
556+
target = f'.. _`{ref}`: {url}'
557+
if text:
558+
target = f'.. |{ref}| replace:: {text}\n' + target
559+
return inline, target
560+
561+
520562
def update_nodup(this : dict,
521563
*others : Union[dict, Iterable[tuple]],
522564
exclude : Optional[Iterable] = None,

tests/test_checker.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def test_sub_variants(self):
140140
Argument("type2", dict, [
141141
Argument("shared", int),
142142
Argument("vnt2_1", int),
143-
]),
143+
], alias=['type2a']),
144144
Argument("type3", dict, [
145145
Argument("vnt3_1", int)
146146
], [ # testing cascade variants here
@@ -186,7 +186,9 @@ def test_sub_variants(self):
186186
"vnt2_1": 21}}
187187
self.assertSetEqual(set(ca.flatten_sub(test_dict2["base"]).keys()),
188188
set(test_dict2["base"].keys()))
189-
ca.check(test_dict2)
189+
ca.check(test_dict2, strict=True)
190+
test_dict2["base"]["vnt_flag"] = "type2a"
191+
ca.check(test_dict2, strict=True)
190192
err_dict1 = {
191193
"base": {
192194
"sub1": 1,

tests/test_docgen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def test_multi_variants(self):
114114

115115
def test_dpmd(self):
116116
from dpmdargs import gen_doc
117-
docstr = gen_doc(make_anchor=True)
117+
docstr = gen_doc(make_anchor=True, make_link=True)
118118
# print("\n\n"+docstr)
119119
# with open("out.rst", "w") as of:
120120
# print(docstr, file=of)

0 commit comments

Comments
 (0)