Skip to content

Commit bac360a

Browse files
committed
xrefs wip
1 parent 58f6261 commit bac360a

File tree

7 files changed

+134
-166
lines changed

7 files changed

+134
-166
lines changed

calango/src/calango/xrefs.py

Lines changed: 0 additions & 122 deletions
This file was deleted.

calango/tests/test_xrefs.py

Lines changed: 0 additions & 33 deletions
This file was deleted.

online/cap08.adoc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2313,8 +2313,8 @@ Já existem mais de 20 delas.
23132313
A audiência alvo das PEPs são os core developers (_desenvolvedores principais da linguagem em si_) e o Steering Council de Python, então elas pressupõe uma grande quantidade de conhecimento prévio, e certamente não são uma leitura leve.
23142314

23152315
Como já mencionado, o <<ch_more_types>> cobre outros tópicos sobre tipagem, e a
2316-
<<more_type_hints_further_sec>> traz referências adicionais, incluindo a
2317-
<<typing_peps_tbl>>, com a lista das PEPs sobre tipagem aprovadas ou em discussão até o final de 2021.
2316+
<<more_type_hints_further_sec>> traz referências adicionais,
2317+
incluindo uma tabela com a longa lista de PEPs sobre tipagem aprovadas ou em discussão até o final de 2021.
23182318

23192319
https://fpy.li/8-47["Awesome Python Typing"] é uma ótima coleção de links para ferramentas e referências.
23202320

online/cap24.adoc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ Quando Python lê uma instrução `class`, invoca `type` para construir um objet
120120
[NOTE]
121121
====
122122
O construtor `type` aceita argumentos nomeados opcionais, que são ignorados por `type`, mas que são passados como recebidos para `+__init_subclass__+`, que deve consumi-los.
123-
Vamos estudar esse método especial na <<enhancing_with_init_subclass>>, mas não vou tratar do uso de argumentos nomeados. Para saber mais sobre isso, por favor leia a https://fpy.li/pep487[PEP 487—Simpler customization of class creation (_PEP 487—Uma customização mais simples da criação de classes_)] (EN).
123+
Vamos estudar esse método especial na <<enhancing_with_init_subclass_sec>>, mas não vou tratar do uso de argumentos nomeados. Para saber mais sobre isso, por favor leia a https://fpy.li/pep487[PEP 487—Simpler customization of class creation (_PEP 487—Uma customização mais simples da criação de classes_)] (EN).
124124
====
125125

126126
A classe `type` é uma((("metaclasses", "definition of term"))) _metaclasse_: uma classe que cria classes.
@@ -456,7 +456,7 @@ include::../code/24-class-metaprog/checked/decorator/checkeddeco.py[tags=MOVIE_D
456456

457457
A única diferença entre o <<checkeddeco_demo1_ex>> e o <<checked_demo1_ex>> é a forma como a classe `Movie` é declarada: ela é decorada com `@checked` em vez de ser uma subclasse de `Checked`.
458458
Fora isso, o comportamento externo é o mesmo, incluindo a validação de tipo e a atribuição de valores default, apresentados após
459-
o <<checked_demo1_ex>>, na <<enhancing_with_init_subclass>>.
459+
o <<checked_demo1_ex>>, na <<enhancing_with_init_subclass_sec>>.
460460

461461
Vamos olhar agora para a implementação de _checkeddeco.py_.
462462
As importações e a classe `Field` são as mesmas de _checkedlib.py_, listadas no <<checked_field_ex>>.

print/xrefs/formatos.adoc

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,6 @@ Ex. do cap01, l.745:
3939
<<ch_seq_methods>>
4040
----
4141

42-
[source, html]
43-
----
44-
<h2 id="ch_seq_methods"><a class="link" href="#ch_seq_methods">12. Métodos especiais para sequências</a></h2>
45-
----
46-
4742
Saída:
4843

4944
Capítulo 12 [vol.2, fpy.li/xyz]

print/xrefs/xvol_xrefs.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#!/usr/bin/env python
2+
3+
import subprocess
4+
from bs4 import BeautifulSoup
5+
from pathlib import Path
6+
7+
CHAPTER_ID = {
8+
1 : 'ch_data_model',
9+
2 : 'ch_sequences',
10+
3 : 'ch_dicts_sets',
11+
4 : 'ch_str_bytes',
12+
5 : 'ch_dataclass',
13+
6 : 'ch_refs_mut_mem',
14+
7 : 'ch_func_objects',
15+
8 : 'ch_type_hints_def',
16+
9 : 'ch_closure_decorator',
17+
10 : 'ch_design_patterns',
18+
11 : 'ch_pythonic_obj',
19+
12 : 'ch_seq_methods',
20+
13 : 'ch_ifaces_prot_abc',
21+
14 : 'ch_inheritance',
22+
15 : 'ch_more_types',
23+
16 : 'ch_op_overload',
24+
17 : 'ch_generators',
25+
18 : 'ch_with_match',
26+
19 : 'ch_concurrency_models',
27+
20 : 'ch_executors',
28+
21 : 'ch_async',
29+
22 : 'ch_dynamic_attrs',
30+
23 : 'ch_descriptors',
31+
24 : 'ch_class_metaprog',
32+
}
33+
34+
CHAPTER_NUMBER = {i:n for (n, i) in CHAPTER_ID.items()}
35+
36+
37+
def find_git_root():
38+
path = Path(__file__).resolve()
39+
while path != path.parent:
40+
if (path / '.git').is_dir():
41+
return path
42+
path = path.parent
43+
raise LookupError(f'no .git dir found in {path} or parents')
44+
45+
46+
INVALID_MSG = 'asciidoctor: INFO: possible invalid reference: '
47+
48+
49+
def list_invalid_xrefs() -> list[str]:
50+
adoc = find_git_root() / 'vol1/vol1.adoc'
51+
cmd = f'''asciidoctor -v {adoc} -o lixo'''
52+
result = subprocess.run(cmd, shell=True, stderr=subprocess.PIPE, text=True)
53+
seen = set()
54+
xrefs = []
55+
for line in result.stderr.splitlines():
56+
assert line.startswith(INVALID_MSG), '? msg: ' + line
57+
xref = line[len(INVALID_MSG):].strip()
58+
if xref not in seen:
59+
xrefs.append(xref)
60+
seen.add(xref)
61+
62+
return xrefs
63+
64+
65+
def get_section_title(ident: str, root: BeautifulSoup) -> str:
66+
element = root.find(id=ident)
67+
if element:
68+
return element.get_text(strip=True)
69+
raise LookupError(f'element {ident!r} not found')
70+
71+
72+
def section_numbers(sec_title: str):
73+
parts = sec_title.split('.')
74+
numbers = []
75+
for part in parts:
76+
try:
77+
numbers.append(int(part))
78+
except ValueError:
79+
break
80+
assert len(numbers) > 0, 'no number prefix: ' + repr(sec_title)
81+
return numbers
82+
83+
BASE_URL = 'https://pythonfluente.com/2/'
84+
85+
PART_VOL = {
86+
'data_structures_part': 1,
87+
# 'function_objects_part': 2, # may be vol 2 or 3
88+
'classes_protocols_part': 2,
89+
'control_flow_part': 3,
90+
'metaprog_part': 3,
91+
}
92+
93+
PART_TITLE = {
94+
'data_structures_part': 'I—Estruturas de dados',
95+
'function_objects_part': 'II—Funções como objetos',
96+
'classes_protocols_part': 'III—Classes e protocolos',
97+
'control_flow_part': 'IV—Controle de fluxo',
98+
'metaprog_part': 'V—Metaprogramação',
99+
}
100+
101+
def replace_xrefs_to_vols():
102+
html_path = find_git_root() / 'online/index.html'
103+
with open(html_path) as fp:
104+
html = fp.read()
105+
root = BeautifulSoup(html, 'html.parser')
106+
for xref in list_invalid_xrefs():
107+
if xref.startswith('ch_'):
108+
chapter = CHAPTER_NUMBER[xref]
109+
text = f'Capítulo {chapter}'
110+
volume = (chapter - 1) // 8 + 1
111+
elif xref.endswith('_part'):
112+
volume = PART_VOL[xref]
113+
text = PART_TITLE[xref]
114+
elif xref.endswith('_sec'):
115+
title = get_section_title(xref, root)
116+
numbers = section_numbers(title)
117+
number_str = '.'.join(str(n) for n in numbers)
118+
chapter = numbers[0]
119+
volume = (chapter - 1) // 8 + 1
120+
text = f'Seção {number_str}'
121+
else:
122+
raise ValueError(f'unexpected xref: {xref!r}')
123+
link = BASE_URL + '#' + xref
124+
print(f'<<{xref}>>', f'{text} [vol.{volume}, {link}]')
125+
126+
if __name__ == '__main__':
127+
replace_xrefs_to_vols()

vol1/cap08.adoc

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2313,8 +2313,9 @@ Já existem mais de 20 delas.
23132313
A audiência alvo das PEPs são os core developers (_desenvolvedores principais da linguagem em si_) e o Steering Council de Python, então elas pressupõe uma grande quantidade de conhecimento prévio, e certamente não são uma leitura leve.
23142314

23152315
Como já mencionado, o <<ch_more_types>> cobre outros tópicos sobre tipagem, e a
2316-
<<more_type_hints_further_sec>> traz referências adicionais, incluindo a
2317-
<<typing_peps_tbl>>, com a lista das PEPs sobre tipagem aprovadas ou em discussão até o final de 2021.
2316+
<<more_type_hints_further_sec>> traz referências adicionais,
2317+
incluindo uma tabela com a longa lista das PEPs
2318+
sobre tipagem aprovadas ou em discussão até o final de 2021.
23182319

23192320
https://fpy.li/8-47["Awesome Python Typing"] é uma ótima coleção de links para ferramentas e referências.
23202321

0 commit comments

Comments
 (0)