pure-docs-br 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 guilhermegor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,234 @@
1
+ Metadata-Version: 2.4
2
+ Name: pure-docs-br
3
+ Version: 1.0.0
4
+ Summary: Valida, aplica e remove a máscara de documentos brasileiros
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: pure-docs-br,python,library
8
+ Author: guilhermegor
9
+ Requires-Python: >=3.11,<4.0
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Project-URL: Bug Reports, https://github.com/guilhermegor/pure-docs-br/issues
22
+ Project-URL: Documentation, https://guilhermegor.github.io/pure-docs-br/
23
+ Project-URL: Homepage, https://guilhermegor.github.io/pure-docs-br/
24
+ Project-URL: Repository, https://github.com/guilhermegor/pure-docs-br
25
+ Project-URL: Source, https://github.com/guilhermegor/pure-docs-br
26
+ Description-Content-Type: text/markdown
27
+
28
+ <!-- readme-archetype: library -->
29
+ # pure-docs-br
30
+
31
+ <p align="center"><img src="https://raw.githubusercontent.com/guilhermegor/pure-docs-br/main/assets/logo.png" width="200" alt="pure-docs-br logo"></p>
32
+
33
+ [![Project Status: Active](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)
34
+ ![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)
35
+ [![PyPI](https://img.shields.io/pypi/v/pure-docs-br.svg)](https://pypi.org/project/pure-docs-br/)
36
+ [![Downloads](https://img.shields.io/pepy/dt/pure-docs-br)](https://pepy.tech/projects/pure-docs-br)
37
+ [![Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://guilhermegor.github.io/pure-docs-br/)
38
+ [![Linting](https://img.shields.io/badge/linting-ruff_%7C_codespell-blue)](https://github.com/astral-sh/ruff)
39
+ [![Mypy](https://img.shields.io/badge/type--checked-mypy-blue)](https://mypy-lang.org)
40
+ ![Test Coverage](https://raw.githubusercontent.com/guilhermegor/pure-docs-br/badges/coverage.svg)
41
+ ![License](https://img.shields.io/badge/license-MIT-green.svg)
42
+ ![Open Issues](https://img.shields.io/github/issues/guilhermegor/pure-docs-br)
43
+ ![Contributions Welcome](https://img.shields.io/badge/contributions-welcome-darkgreen.svg)
44
+
45
+ <!-- slug: overview -->
46
+ ## Visão geral
47
+
48
+ Valida, aplica e remove a máscara de documentos brasileiros
49
+
50
+ <!-- optional section: delete it when the project has no feature list -->
51
+ <!-- slug: features -->
52
+ ## Funcionalidades
53
+
54
+ - Valida CPF e CNPJ pelos dígitos verificadores, inclusive o CNPJ alfanumérico que passa a existir em 2026.
55
+ - Aplica e remove a máscara (`XXX.XXX.XXX-XX` e `XX.XXX.XXX/XXXX-XX`).
56
+ - Tolera texto sujo: pontuação, zeros à esquerda perdidos e a cauda `.0` de um número que virou `str` (por exemplo `"52998224725.0"`).
57
+ - Funções puras, sem I/O e sem dependências de execução.
58
+
59
+ <!-- slug: documentation -->
60
+ ## Documentação
61
+
62
+ O site de documentação fica em https://guilhermegor.github.io/pure-docs-br/. Para servi-lo localmente, rode `poetry run poe docs_serve`.
63
+
64
+ <!-- slug: getting-started -->
65
+ ## Primeiros passos
66
+
67
+ O Python 3.11+ é o único pré-requisito; o `bin/venv.sh` instala o [Poetry](https://python-poetry.org/) quando ele estiver ausente.
68
+
69
+ <!-- slug: install -->
70
+ ### Instalação
71
+
72
+ ```bash
73
+ git clone https://github.com/guilhermegor/pure-docs-br.git
74
+ cd pure-docs-br
75
+ bash bin/venv.sh
76
+ poetry run poe init
77
+ ```
78
+
79
+ O `poe` vive dentro do virtualenv, então o `bin/venv.sh` o cria primeiro; em seguida o
80
+ `poetry run poe init` o executa sem ativar nada. Se o `poetry` não estiver no `PATH` (por exemplo
81
+ logo depois de o `bin/venv.sh` instalá-lo com `--user`), use `bash bin/poe_exec.sh init`, que
82
+ encontra o `poe` do venv sozinho.
83
+
84
+ <!-- slug: usage -->
85
+ ### Uso
86
+
87
+ ```bash
88
+ pip install pure-docs-br
89
+ ```
90
+
91
+ Toda função recebe e devolve `str` (ou `bool`) e aceita o documento com ou sem máscara.
92
+
93
+ ```python
94
+ from pure_docs_br import (
95
+ is_valid_cnpj,
96
+ is_valid_cpf,
97
+ mask_cnpj,
98
+ mask_cpf,
99
+ unmask_cnpj,
100
+ unmask_cpf,
101
+ )
102
+
103
+ mask_cpf("52998224725") # "529.982.247-25"
104
+ unmask_cpf("529.982.247-25") # "52998224725"
105
+ unmask_cpf("1234567") # "00001234567", completa com zeros à esquerda
106
+ is_valid_cpf("529.982.247-25") # True
107
+ is_valid_cpf("11111111111") # False, dígitos repetidos
108
+
109
+ mask_cnpj("11222333000181") # "11.222.333/0001-81"
110
+ mask_cnpj("12ABC34501DE35") # "12.ABC.345/01DE-35"
111
+ unmask_cnpj("12.abc.345/01de-35") # "12ABC34501DE35", maiúsculas
112
+ unmask_cnpj("11222333000181.0") # "11222333000181", descarta a cauda ".0"
113
+ is_valid_cnpj("11.222.333/0001-81") # True
114
+ is_valid_cnpj("12.ABC.345/01DE-35") # True, formato alfanumérico
115
+ is_valid_cnpj("11222333000182") # False, dígito verificador errado
116
+ ```
117
+
118
+ ### Entrada inválida
119
+
120
+ - Toda função exige `str`: qualquer outro tipo (`None`, `float`, `int`, inclusive o `NaN` de uma
121
+ coluna do pandas) lança `TypeError`. Converta antes, por exemplo com `.astype(str)`, ou filtre
122
+ os nulos.
123
+ - Dado um `str`, nenhuma função lança exceção. `is_valid_*` devolve `False` para texto vazio,
124
+ com tamanho errado ou com dígito verificador errado, então uma linha ruim não interrompe a
125
+ transformação de uma coluna inteira.
126
+ - `mask_*` devolve o valor sem máscara (o que `unmask_*` produz) quando ele não tem o tamanho do
127
+ documento. Isso ocorre com texto vazio, com mais de 11 dígitos (CPF) ou 14 caracteres (CNPJ) e
128
+ com CNPJ alfanumérico curto; um CPF ou CNPJ só de dígitos nunca é curto, pois `unmask_*` o
129
+ completa com zeros.
130
+ - Entrada numérica curta é completada com zeros à esquerda (11 para CPF, 14 para CNPJ) antes de
131
+ os dígitos verificadores serem testados, o mesmo preenchimento que `unmask_*` aplica. É
132
+ intencional: recupera documentos guardados como número que perderam os zeros (Excel, pandas).
133
+ Por consequência, `is_valid_cpf("191")` e `is_valid_cnpj("191")` devolvem `True`, pois `"191"`
134
+ vira `00000000191`. Valores de um só dígito repetido continuam rejeitados: `"0"` vira
135
+ `00000000000` e `is_valid_cpf("0")` é `False`.
136
+ - A cauda `.0` é descartada por `unmask_cpf` e `unmask_cnpj`. A notação científica
137
+ (`"1.1222333000181e+13"`) não é tratada: converta o número para texto sem expoente antes.
138
+
139
+ O dígito verificador do CNPJ segue o cálculo de módulo 11 do
140
+ [Serpro](https://www.serpro.gov.br/menu/noticias/videos/calculodvcnpjalfanaumerico.pdf) e da
141
+ [Receita Federal](https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/perguntas-e-respostas/cnpj/cnpj-alfanumerico.pdf).
142
+
143
+ <!-- slug: project-structure -->
144
+ ## Estrutura do projeto
145
+
146
+ ```text
147
+ pure-docs-br/
148
+ ├── .github/ workflows, CODEOWNERS e template de PR
149
+ ├── .specs/ specs de funcionalidades e trackers de backlog
150
+ ├── bin/ scripts de gate e utilitários
151
+ ├── docs/ documentação publicada
152
+ ├── src/ o pacote `pure_docs_br`
153
+ ├── tests/
154
+ │ ├── unit/
155
+ │ └── integration/
156
+ ├── pyproject.toml
157
+ └── poe_tasks.toml pontos de entrada do task runner
158
+ ```
159
+
160
+ <!-- slug: development -->
161
+ ## Desenvolvimento
162
+
163
+ Depois do bootstrap descrito em Instalação, qualquer tarefa pode ser executada com
164
+ `poetry run poe <task>`; e `poetry run poe` sem tarefa lista todas elas.
165
+
166
+ ```bash
167
+ poetry run poe unit_tests
168
+ poetry run poe integration_tests
169
+ ```
170
+
171
+ Quando o deploy da documentação do primeiro release tiver criado a branch `gh-pages`, rode
172
+ `poetry run poe enable_pages` uma vez: até que essa branch exista, o `init` deixa o Pages intocado.
173
+
174
+ ### `poetry run poe` ou `bash bin/poe_exec.sh`?
175
+
176
+ Os dois rodam a mesma tarefa do mesmo `poe` do venv. Use `poetry run poe`, o comando que a
177
+ comunidade conhece; o `bin/poe_exec.sh` cobre os casos em que ele não basta:
178
+
179
+ | Situação | `poetry run poe` | `bash bin/poe_exec.sh` |
180
+ |---|---|---|
181
+ | Máquina comum, `poetry` no `PATH` | funciona | funciona |
182
+ | `poetry` fora do `PATH` (ex.: recém-instalado com `--user`) | falha: `poetry: command not found` | funciona: acha `.venv/bin/poe` (ou `.venv/Scripts/poe.exe` no Windows) sem o `poetry` |
183
+ | Rede corporativa com inspeção TLS (`bin/corporate_ca.pem` presente) | tarefas que baixam algo podem falhar com erro de certificado | funciona: monta o bundle de CAs e o exporta antes de rodar a tarefa |
184
+ | `poe` não instalado | erro genérico do Poetry | lista as formas de instalar (`bin/venv.sh`, `pipx`, plugin do Poetry) |
185
+
186
+ <!-- slug: public-api -->
187
+ ## API pública
188
+
189
+ A superfície pública é o que o `__init__.py` do pacote lista em `__all__`:
190
+ `__version__`, `is_valid_cnpj`, `is_valid_cpf`, `mask_cnpj`, `mask_cpf`, `unmask_cnpj` e
191
+ `unmask_cpf`.
192
+
193
+ ### Garantia de API da 1.x
194
+
195
+ A partir da 1.0.0 vale o semver completo. Dentro da 1.x, esses nomes continuam importáveis da raiz
196
+ do pacote com a mesma assinatura e o mesmo comportamento documentado: remover ou alterar um deles
197
+ exige uma 2.0. Uma versão MINOR só acrescenta, e uma PATCH só corrige defeitos. Tudo sob
198
+ `pure_docs_br._internal` é privado e fica fora da garantia.
199
+
200
+ <!-- slug: publishing -->
201
+ ## Publicação
202
+
203
+ Os lançamentos saem dos workflows de release em `.github/workflows/`; a tag do git é a versão.
204
+
205
+ O caminho até a 1.0.0, e o gate de lançamento que o protege, está em
206
+ [docs/releasing-1-0-0.md](docs/releasing-1-0-0.md).
207
+
208
+ <!-- slug: contributing -->
209
+ ## Contribuindo
210
+
211
+ Veja o [CONTRIBUTING.md](CONTRIBUTING.md) para as regras de branch, commit e revisão.
212
+
213
+ <!-- slug: license -->
214
+ ## Licença
215
+
216
+ Este projeto é licenciado sob MIT; veja [LICENSE](LICENSE).
217
+
218
+ <!-- slug: authors -->
219
+ ## Autores
220
+
221
+ - guilhermegor — [GitHub](https://github.com/guilhermegor) | [LinkedIn](https://www.linkedin.com/in/guilhermegor)
222
+
223
+ <!-- slug: useful-links -->
224
+ ## Links úteis
225
+
226
+ - [Repositório no GitHub](https://github.com/guilhermegor/pure-docs-br)
227
+ - [Issue Tracker](https://github.com/guilhermegor/pure-docs-br/issues)
228
+ - [Documentação](https://guilhermegor.github.io/pure-docs-br/)
229
+
230
+ ---
231
+
232
+ <sub>Gerado a partir do template lib-minimal via [BlueprintX](https://github.com/guilhermegor/blueprintx).</sub>
233
+ <!-- add any project disclaimer inside the sub tag above; for a library wrapping a third party, e.g. "Unofficial, community library. Not affiliated with or endorsed by ORG_NAME." -->
234
+
@@ -0,0 +1,206 @@
1
+ <!-- readme-archetype: library -->
2
+ # pure-docs-br
3
+
4
+ <p align="center"><img src="https://raw.githubusercontent.com/guilhermegor/pure-docs-br/main/assets/logo.png" width="200" alt="pure-docs-br logo"></p>
5
+
6
+ [![Project Status: Active](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)
7
+ ![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)
8
+ [![PyPI](https://img.shields.io/pypi/v/pure-docs-br.svg)](https://pypi.org/project/pure-docs-br/)
9
+ [![Downloads](https://img.shields.io/pepy/dt/pure-docs-br)](https://pepy.tech/projects/pure-docs-br)
10
+ [![Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://guilhermegor.github.io/pure-docs-br/)
11
+ [![Linting](https://img.shields.io/badge/linting-ruff_%7C_codespell-blue)](https://github.com/astral-sh/ruff)
12
+ [![Mypy](https://img.shields.io/badge/type--checked-mypy-blue)](https://mypy-lang.org)
13
+ ![Test Coverage](https://raw.githubusercontent.com/guilhermegor/pure-docs-br/badges/coverage.svg)
14
+ ![License](https://img.shields.io/badge/license-MIT-green.svg)
15
+ ![Open Issues](https://img.shields.io/github/issues/guilhermegor/pure-docs-br)
16
+ ![Contributions Welcome](https://img.shields.io/badge/contributions-welcome-darkgreen.svg)
17
+
18
+ <!-- slug: overview -->
19
+ ## Visão geral
20
+
21
+ Valida, aplica e remove a máscara de documentos brasileiros
22
+
23
+ <!-- optional section: delete it when the project has no feature list -->
24
+ <!-- slug: features -->
25
+ ## Funcionalidades
26
+
27
+ - Valida CPF e CNPJ pelos dígitos verificadores, inclusive o CNPJ alfanumérico que passa a existir em 2026.
28
+ - Aplica e remove a máscara (`XXX.XXX.XXX-XX` e `XX.XXX.XXX/XXXX-XX`).
29
+ - Tolera texto sujo: pontuação, zeros à esquerda perdidos e a cauda `.0` de um número que virou `str` (por exemplo `"52998224725.0"`).
30
+ - Funções puras, sem I/O e sem dependências de execução.
31
+
32
+ <!-- slug: documentation -->
33
+ ## Documentação
34
+
35
+ O site de documentação fica em https://guilhermegor.github.io/pure-docs-br/. Para servi-lo localmente, rode `poetry run poe docs_serve`.
36
+
37
+ <!-- slug: getting-started -->
38
+ ## Primeiros passos
39
+
40
+ O Python 3.11+ é o único pré-requisito; o `bin/venv.sh` instala o [Poetry](https://python-poetry.org/) quando ele estiver ausente.
41
+
42
+ <!-- slug: install -->
43
+ ### Instalação
44
+
45
+ ```bash
46
+ git clone https://github.com/guilhermegor/pure-docs-br.git
47
+ cd pure-docs-br
48
+ bash bin/venv.sh
49
+ poetry run poe init
50
+ ```
51
+
52
+ O `poe` vive dentro do virtualenv, então o `bin/venv.sh` o cria primeiro; em seguida o
53
+ `poetry run poe init` o executa sem ativar nada. Se o `poetry` não estiver no `PATH` (por exemplo
54
+ logo depois de o `bin/venv.sh` instalá-lo com `--user`), use `bash bin/poe_exec.sh init`, que
55
+ encontra o `poe` do venv sozinho.
56
+
57
+ <!-- slug: usage -->
58
+ ### Uso
59
+
60
+ ```bash
61
+ pip install pure-docs-br
62
+ ```
63
+
64
+ Toda função recebe e devolve `str` (ou `bool`) e aceita o documento com ou sem máscara.
65
+
66
+ ```python
67
+ from pure_docs_br import (
68
+ is_valid_cnpj,
69
+ is_valid_cpf,
70
+ mask_cnpj,
71
+ mask_cpf,
72
+ unmask_cnpj,
73
+ unmask_cpf,
74
+ )
75
+
76
+ mask_cpf("52998224725") # "529.982.247-25"
77
+ unmask_cpf("529.982.247-25") # "52998224725"
78
+ unmask_cpf("1234567") # "00001234567", completa com zeros à esquerda
79
+ is_valid_cpf("529.982.247-25") # True
80
+ is_valid_cpf("11111111111") # False, dígitos repetidos
81
+
82
+ mask_cnpj("11222333000181") # "11.222.333/0001-81"
83
+ mask_cnpj("12ABC34501DE35") # "12.ABC.345/01DE-35"
84
+ unmask_cnpj("12.abc.345/01de-35") # "12ABC34501DE35", maiúsculas
85
+ unmask_cnpj("11222333000181.0") # "11222333000181", descarta a cauda ".0"
86
+ is_valid_cnpj("11.222.333/0001-81") # True
87
+ is_valid_cnpj("12.ABC.345/01DE-35") # True, formato alfanumérico
88
+ is_valid_cnpj("11222333000182") # False, dígito verificador errado
89
+ ```
90
+
91
+ ### Entrada inválida
92
+
93
+ - Toda função exige `str`: qualquer outro tipo (`None`, `float`, `int`, inclusive o `NaN` de uma
94
+ coluna do pandas) lança `TypeError`. Converta antes, por exemplo com `.astype(str)`, ou filtre
95
+ os nulos.
96
+ - Dado um `str`, nenhuma função lança exceção. `is_valid_*` devolve `False` para texto vazio,
97
+ com tamanho errado ou com dígito verificador errado, então uma linha ruim não interrompe a
98
+ transformação de uma coluna inteira.
99
+ - `mask_*` devolve o valor sem máscara (o que `unmask_*` produz) quando ele não tem o tamanho do
100
+ documento. Isso ocorre com texto vazio, com mais de 11 dígitos (CPF) ou 14 caracteres (CNPJ) e
101
+ com CNPJ alfanumérico curto; um CPF ou CNPJ só de dígitos nunca é curto, pois `unmask_*` o
102
+ completa com zeros.
103
+ - Entrada numérica curta é completada com zeros à esquerda (11 para CPF, 14 para CNPJ) antes de
104
+ os dígitos verificadores serem testados, o mesmo preenchimento que `unmask_*` aplica. É
105
+ intencional: recupera documentos guardados como número que perderam os zeros (Excel, pandas).
106
+ Por consequência, `is_valid_cpf("191")` e `is_valid_cnpj("191")` devolvem `True`, pois `"191"`
107
+ vira `00000000191`. Valores de um só dígito repetido continuam rejeitados: `"0"` vira
108
+ `00000000000` e `is_valid_cpf("0")` é `False`.
109
+ - A cauda `.0` é descartada por `unmask_cpf` e `unmask_cnpj`. A notação científica
110
+ (`"1.1222333000181e+13"`) não é tratada: converta o número para texto sem expoente antes.
111
+
112
+ O dígito verificador do CNPJ segue o cálculo de módulo 11 do
113
+ [Serpro](https://www.serpro.gov.br/menu/noticias/videos/calculodvcnpjalfanaumerico.pdf) e da
114
+ [Receita Federal](https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/perguntas-e-respostas/cnpj/cnpj-alfanumerico.pdf).
115
+
116
+ <!-- slug: project-structure -->
117
+ ## Estrutura do projeto
118
+
119
+ ```text
120
+ pure-docs-br/
121
+ ├── .github/ workflows, CODEOWNERS e template de PR
122
+ ├── .specs/ specs de funcionalidades e trackers de backlog
123
+ ├── bin/ scripts de gate e utilitários
124
+ ├── docs/ documentação publicada
125
+ ├── src/ o pacote `pure_docs_br`
126
+ ├── tests/
127
+ │ ├── unit/
128
+ │ └── integration/
129
+ ├── pyproject.toml
130
+ └── poe_tasks.toml pontos de entrada do task runner
131
+ ```
132
+
133
+ <!-- slug: development -->
134
+ ## Desenvolvimento
135
+
136
+ Depois do bootstrap descrito em Instalação, qualquer tarefa pode ser executada com
137
+ `poetry run poe <task>`; e `poetry run poe` sem tarefa lista todas elas.
138
+
139
+ ```bash
140
+ poetry run poe unit_tests
141
+ poetry run poe integration_tests
142
+ ```
143
+
144
+ Quando o deploy da documentação do primeiro release tiver criado a branch `gh-pages`, rode
145
+ `poetry run poe enable_pages` uma vez: até que essa branch exista, o `init` deixa o Pages intocado.
146
+
147
+ ### `poetry run poe` ou `bash bin/poe_exec.sh`?
148
+
149
+ Os dois rodam a mesma tarefa do mesmo `poe` do venv. Use `poetry run poe`, o comando que a
150
+ comunidade conhece; o `bin/poe_exec.sh` cobre os casos em que ele não basta:
151
+
152
+ | Situação | `poetry run poe` | `bash bin/poe_exec.sh` |
153
+ |---|---|---|
154
+ | Máquina comum, `poetry` no `PATH` | funciona | funciona |
155
+ | `poetry` fora do `PATH` (ex.: recém-instalado com `--user`) | falha: `poetry: command not found` | funciona: acha `.venv/bin/poe` (ou `.venv/Scripts/poe.exe` no Windows) sem o `poetry` |
156
+ | Rede corporativa com inspeção TLS (`bin/corporate_ca.pem` presente) | tarefas que baixam algo podem falhar com erro de certificado | funciona: monta o bundle de CAs e o exporta antes de rodar a tarefa |
157
+ | `poe` não instalado | erro genérico do Poetry | lista as formas de instalar (`bin/venv.sh`, `pipx`, plugin do Poetry) |
158
+
159
+ <!-- slug: public-api -->
160
+ ## API pública
161
+
162
+ A superfície pública é o que o `__init__.py` do pacote lista em `__all__`:
163
+ `__version__`, `is_valid_cnpj`, `is_valid_cpf`, `mask_cnpj`, `mask_cpf`, `unmask_cnpj` e
164
+ `unmask_cpf`.
165
+
166
+ ### Garantia de API da 1.x
167
+
168
+ A partir da 1.0.0 vale o semver completo. Dentro da 1.x, esses nomes continuam importáveis da raiz
169
+ do pacote com a mesma assinatura e o mesmo comportamento documentado: remover ou alterar um deles
170
+ exige uma 2.0. Uma versão MINOR só acrescenta, e uma PATCH só corrige defeitos. Tudo sob
171
+ `pure_docs_br._internal` é privado e fica fora da garantia.
172
+
173
+ <!-- slug: publishing -->
174
+ ## Publicação
175
+
176
+ Os lançamentos saem dos workflows de release em `.github/workflows/`; a tag do git é a versão.
177
+
178
+ O caminho até a 1.0.0, e o gate de lançamento que o protege, está em
179
+ [docs/releasing-1-0-0.md](docs/releasing-1-0-0.md).
180
+
181
+ <!-- slug: contributing -->
182
+ ## Contribuindo
183
+
184
+ Veja o [CONTRIBUTING.md](CONTRIBUTING.md) para as regras de branch, commit e revisão.
185
+
186
+ <!-- slug: license -->
187
+ ## Licença
188
+
189
+ Este projeto é licenciado sob MIT; veja [LICENSE](LICENSE).
190
+
191
+ <!-- slug: authors -->
192
+ ## Autores
193
+
194
+ - guilhermegor — [GitHub](https://github.com/guilhermegor) | [LinkedIn](https://www.linkedin.com/in/guilhermegor)
195
+
196
+ <!-- slug: useful-links -->
197
+ ## Links úteis
198
+
199
+ - [Repositório no GitHub](https://github.com/guilhermegor/pure-docs-br)
200
+ - [Issue Tracker](https://github.com/guilhermegor/pure-docs-br/issues)
201
+ - [Documentação](https://guilhermegor.github.io/pure-docs-br/)
202
+
203
+ ---
204
+
205
+ <sub>Gerado a partir do template lib-minimal via [BlueprintX](https://github.com/guilhermegor/blueprintx).</sub>
206
+ <!-- add any project disclaimer inside the sub tag above; for a library wrapping a third party, e.g. "Unofficial, community library. Not affiliated with or endorsed by ORG_NAME." -->
@@ -0,0 +1,71 @@
1
+ [tool.poetry]
2
+ name = "pure-docs-br"
3
+ version = "1.0.0" # set from the git tag, see docs/contributing.md#releasing
4
+ description = "Valida, aplica e remove a máscara de documentos brasileiros"
5
+ authors = ["guilhermegor"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ homepage = "https://guilhermegor.github.io/pure-docs-br/"
9
+ documentation = "https://guilhermegor.github.io/pure-docs-br/"
10
+ repository = "https://github.com/guilhermegor/pure-docs-br"
11
+ keywords = ["pure-docs-br", "python", "library"]
12
+ packages = [{ include = "pure_docs_br", from = "src" }]
13
+ exclude = ["src/**/CLAUDE.md"]
14
+ package-mode = true
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Operating System :: OS Independent",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Development Status :: 5 - Production/Stable",
24
+ "Intended Audience :: Developers",
25
+ "Topic :: Software Development :: Libraries",
26
+ ]
27
+
28
+ [tool.poetry.urls]
29
+ "Bug Reports" = "https://github.com/guilhermegor/pure-docs-br/issues"
30
+ "Source" = "https://github.com/guilhermegor/pure-docs-br"
31
+ "Documentation" = "https://guilhermegor.github.io/pure-docs-br/"
32
+
33
+ [tool.poetry.dependencies]
34
+ python = ">=3.11,<4.0"
35
+
36
+ [tool.poetry.group.dev.dependencies]
37
+ poethepoet = ">=0.35"
38
+ pre-commit = ">=4.1.0"
39
+ pretty-errors = ">=1.2.25"
40
+ commitizen = ">=4.4.1"
41
+ build = ">=1.2.2"
42
+ twine = ">=6.1.0"
43
+ ruff = ">=0.17.5"
44
+ codespell = ">=2.4.1"
45
+ pydocstyle = ">=6.3.0"
46
+ pytest = ">=8.0.0"
47
+ pytest-cov = ">=6.0.0"
48
+ pytest-randomly = ">=3.15.0"
49
+ coverage = ">=7.6.0"
50
+ genbadge = {extras = ["coverage"], version = ">=1.1.0"}
51
+ mypy = ">=1.8.0"
52
+ sqlfluff = ">=3.0.0"
53
+ yamllint = ">=1.35.0"
54
+ shfmt-py = ">=3.7.0"
55
+ shellcheck-py = ">=0.10.0"
56
+ deptry = ">=0.20"
57
+
58
+ [tool.poetry.group.docs.dependencies]
59
+ mkdocs = ">=1.6.0"
60
+ mkdocs-material = ">=9.5.0"
61
+ pymdown-extensions = ">=10.0"
62
+ mike = ">=2.1.0"
63
+
64
+ [tool.poetry-dynamic-versioning]
65
+ enable = false
66
+ vcs = "git"
67
+ style = "pep440"
68
+
69
+ [build-system]
70
+ requires = ["poetry-core>=1.7.0", "poetry-dynamic-versioning>=1.4.0,<2.0.0"]
71
+ build-backend = "poetry_dynamic_versioning.backend"
@@ -0,0 +1,29 @@
1
+ """pure-docs-br package."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .br_identifiers import (
6
+ is_valid_cnpj,
7
+ is_valid_cpf,
8
+ mask_cnpj,
9
+ mask_cpf,
10
+ unmask_cnpj,
11
+ unmask_cpf,
12
+ )
13
+
14
+
15
+ try:
16
+ __version__ = version("pure-docs-br")
17
+ except PackageNotFoundError: # pragma: no cover - source tree without an installed dist
18
+ __version__ = "0.0.0"
19
+
20
+
21
+ __all__ = [
22
+ "__version__",
23
+ "is_valid_cnpj",
24
+ "is_valid_cpf",
25
+ "mask_cnpj",
26
+ "mask_cpf",
27
+ "unmask_cnpj",
28
+ "unmask_cpf",
29
+ ]
@@ -0,0 +1 @@
1
+ """Private internals of the pure_docs_br package (not a public API)."""
@@ -0,0 +1 @@
1
+ """Private helpers shared by the public modules."""
@@ -0,0 +1,8 @@
1
+ """Dependency-free runtime type checking."""
2
+
3
+ from pure_docs_br._internal.utils.typing.type_checker import type_checker
4
+
5
+
6
+ __all__ = [
7
+ "type_checker",
8
+ ]
@@ -0,0 +1,103 @@
1
+ """Standard-library runtime type checking for plain annotated parameters.
2
+
3
+ The package ships with no runtime dependencies, so this decorator replaces a third-party
4
+ checker. It validates every argument whose annotation is a plain class (``str``, ``int``)
5
+ and leaves generic, union and string-forward annotations to mypy.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ import functools
12
+ import inspect
13
+ from typing import ParamSpec, TypeVar, get_type_hints
14
+
15
+
16
+ _P = ParamSpec("_P")
17
+ _R = TypeVar("_R")
18
+
19
+
20
+ def _check_argument(*, str_name: str, value: object, dict_hints: dict[str, object]) -> None:
21
+ """Raise ``TypeError`` when a value is not an instance of its plain-class annotation.
22
+
23
+ Parameters
24
+ ----------
25
+ str_name : str
26
+ Parameter name.
27
+ value : object
28
+ Argument bound to that parameter.
29
+ dict_hints : dict[str, object]
30
+ Resolved annotations of the decorated function.
31
+
32
+ Returns
33
+ -------
34
+ None
35
+ Nothing; the check either passes or raises.
36
+
37
+ Raises
38
+ ------
39
+ TypeError
40
+ If the annotation is a plain class and ``value`` is not an instance of it.
41
+ """
42
+ cls_expected = dict_hints.get(str_name)
43
+ if isinstance(cls_expected, type) and not isinstance(value, cls_expected):
44
+ raise TypeError(
45
+ f"parameter {str_name}={value!r} violates type hint {cls_expected.__name__}, "
46
+ f"got {type(value).__name__}"
47
+ )
48
+
49
+
50
+ def _check_arguments(
51
+ *,
52
+ cls_signature: inspect.Signature,
53
+ dict_hints: dict[str, object],
54
+ args: tuple[object, ...],
55
+ kwargs: dict[str, object],
56
+ ) -> None:
57
+ """Check every bound argument of one call against the resolved annotations.
58
+
59
+ Parameters
60
+ ----------
61
+ cls_signature : inspect.Signature
62
+ Signature of the decorated function.
63
+ dict_hints : dict[str, object]
64
+ Resolved annotations of the decorated function.
65
+ args : tuple[object, ...]
66
+ Positional arguments of the call.
67
+ kwargs : dict[str, object]
68
+ Keyword arguments of the call.
69
+
70
+ Returns
71
+ -------
72
+ None
73
+ Nothing; the check either passes or raises ``TypeError``.
74
+ """
75
+ for str_name, value in cls_signature.bind(*args, **kwargs).arguments.items():
76
+ _check_argument(str_name=str_name, value=value, dict_hints=dict_hints)
77
+
78
+
79
+ def type_checker(fn_target: Callable[_P, _R]) -> Callable[_P, _R]:
80
+ """Validate the annotated parameters of ``fn_target`` on every call.
81
+
82
+ Parameters
83
+ ----------
84
+ fn_target : Callable[_P, _R]
85
+ Function whose plain-class annotated parameters are checked at call time.
86
+
87
+ Returns
88
+ -------
89
+ Callable[_P, _R]
90
+ The wrapped function, with its signature and docstring preserved.
91
+ """
92
+ cls_signature = inspect.signature(fn_target)
93
+ dict_hints = get_type_hints(fn_target)
94
+
95
+ @functools.wraps(fn_target)
96
+ def fn_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
97
+ """Check the bound arguments, then call the wrapped function."""
98
+ _check_arguments(
99
+ cls_signature=cls_signature, dict_hints=dict_hints, args=args, kwargs=kwargs
100
+ )
101
+ return fn_target(*args, **kwargs)
102
+
103
+ return fn_wrapper
@@ -0,0 +1,283 @@
1
+ """Brazilian identifier helpers — mask, unmask and validate CNPJ and CPF.
2
+
3
+ These are pure, stateless functions (no class — there is no state or lifecycle to
4
+ own). They are deliberately tolerant on input so they can be mapped over a whole
5
+ ``pandas`` column: ``unmask_*`` strips punctuation, the spurious ``".0"`` left by a
6
+ float→str coercion, and (for CNPJ) handles the **2026 alphanumeric format** by keeping
7
+ ``A-Z``/``0-9`` and only zero-padding when the value is purely numeric. ``is_valid_*``
8
+ return ``bool`` rather than raising on any ``str``, so a bad row never aborts a bulk
9
+ transformation. A non-``str`` (``None``, ``float``/``NaN``) raises ``TypeError`` from the
10
+ runtime type checker: stringify or drop nulls first. Short numeric values are zero-padded
11
+ before validation, on purpose, to recover identifiers stored as numbers that lost leading
12
+ zeros: ``is_valid_cpf("191")`` is ``True`` (it becomes ``00000000191``), while ``"0"`` is
13
+ rejected as a repeated-digit value.
14
+
15
+ The CNPJ check digits use ASCII-48 weighting, which makes a single mod-11 routine
16
+ validate both legacy-numeric and new-alphanumeric CNPJs (a digit's value equals itself).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+
23
+ from pure_docs_br._internal.utils.typing import type_checker
24
+
25
+
26
+ _INT_MODULUS = 11
27
+ _INT_MIN_REMAINDER = 2
28
+
29
+ _LEN_CNPJ: int = 14
30
+ _LEN_CPF: int = 11
31
+ _ASCII_ZERO: int = ord("0")
32
+
33
+ _CNPJ_WEIGHTS_DV1: tuple[int, ...] = (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
34
+ _CNPJ_WEIGHTS_DV2: tuple[int, ...] = (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
35
+
36
+ _RE_FLOAT_ARTIFACT: re.Pattern[str] = re.compile(r"^\s*(\d+)\.0+\s*$")
37
+ _RE_NON_ALNUM: re.Pattern[str] = re.compile(r"[^0-9A-Za-z]")
38
+ _RE_NON_DIGIT: re.Pattern[str] = re.compile(r"\D")
39
+
40
+
41
+ @type_checker
42
+ def _strip_float_artifact(str_value: str) -> str:
43
+ """Drop a trailing ``.0`` left by a float→str coercion; otherwise trim whitespace.
44
+
45
+ Parameters
46
+ ----------
47
+ str_value : str
48
+ Raw identifier as read from a source (CSV cell, DataFrame value, API field).
49
+
50
+ Returns
51
+ -------
52
+ str
53
+ ``str_value`` with a ``".0…"`` tail removed when it is an integer-with-float-tail,
54
+ else the whitespace-trimmed input.
55
+ """
56
+ cls_match = _RE_FLOAT_ARTIFACT.match(str_value)
57
+ if cls_match is not None:
58
+ return cls_match.group(1)
59
+ return str_value.strip()
60
+
61
+
62
+ @type_checker
63
+ def unmask_cnpj(str_value: str) -> str:
64
+ """Normalise a CNPJ to its bare 14-character form (alphanumeric-aware).
65
+
66
+ Parameters
67
+ ----------
68
+ str_value : str
69
+ A CNPJ in any shape — masked, zero-stripped, or carrying a float ``.0`` tail.
70
+
71
+ Returns
72
+ -------
73
+ str
74
+ Uppercased value containing only ``A-Z``/``0-9``, with a ``.0`` tail dropped
75
+ (scientific notation such as ``1e+13`` is not handled). Purely numeric values are
76
+ left-zero-padded to 14; alphanumeric values are returned as-is (already 14).
77
+ An empty input yields an empty string.
78
+ """
79
+ str_clean = _strip_float_artifact(str_value)
80
+ str_clean = _RE_NON_ALNUM.sub("", str_clean).upper()
81
+ if str_clean.isdigit():
82
+ str_clean = str_clean.zfill(_LEN_CNPJ)
83
+ return str_clean
84
+
85
+
86
+ @type_checker
87
+ def mask_cnpj(str_value: str) -> str:
88
+ """Format a CNPJ as ``XX.XXX.XXX/XXXX-XX``.
89
+
90
+ Parameters
91
+ ----------
92
+ str_value : str
93
+ A CNPJ in any shape (it is unmasked first).
94
+
95
+ Returns
96
+ -------
97
+ str
98
+ The punctuated CNPJ when it normalises to 14 characters; otherwise the bare
99
+ unmasked value (so malformed input is surfaced, not silently reformatted). That
100
+ covers empty input, short alphanumeric values and values over 14 characters; a
101
+ purely numeric value is never short, since it is zero-padded to 14.
102
+ """
103
+ str_clean = unmask_cnpj(str_value)
104
+ if len(str_clean) != _LEN_CNPJ:
105
+ return str_clean
106
+ return f"{str_clean[:2]}.{str_clean[2:5]}.{str_clean[5:8]}/{str_clean[8:12]}-{str_clean[12:]}"
107
+
108
+
109
+ @type_checker
110
+ def _cnpj_check_digit(str_base: str, *, tuple_weights: tuple[int, ...]) -> int:
111
+ """Compute one CNPJ check digit via ASCII-48 mod-11 weighting.
112
+
113
+ Parameters
114
+ ----------
115
+ str_base : str
116
+ The base characters the weights apply to (12 for DV1, 13 for DV2).
117
+ tuple_weights : tuple of int
118
+ Mod-11 weights, paired left-to-right with ``str_base``.
119
+
120
+ Returns
121
+ -------
122
+ int
123
+ The check digit (0 when the remainder is below 2, else ``11 - remainder``).
124
+ """
125
+ int_sum = sum(
126
+ (ord(str_char) - _ASCII_ZERO) * int_weight
127
+ for str_char, int_weight in zip(str_base, tuple_weights, strict=True)
128
+ )
129
+ int_rest = int_sum % 11
130
+ return 0 if int_rest < _INT_MIN_REMAINDER else _INT_MODULUS - int_rest
131
+
132
+
133
+ @type_checker
134
+ def is_valid_cnpj(str_value: str) -> bool:
135
+ """Validate a CNPJ's two check digits (legacy numeric or 2026 alphanumeric).
136
+
137
+ Parameters
138
+ ----------
139
+ str_value : str
140
+ A CNPJ in any shape (it is unmasked first).
141
+
142
+ Returns
143
+ -------
144
+ bool
145
+ ``True`` when the value normalises to 14 characters whose last two are the
146
+ correct numeric check digits. Repeated-character numeric values (e.g. all
147
+ zeros) are rejected.
148
+ """
149
+ str_clean = unmask_cnpj(str_value)
150
+ return (
151
+ len(str_clean) == _LEN_CNPJ
152
+ and str_clean[12:].isdigit()
153
+ and not (str_clean.isdigit() and len(set(str_clean)) == 1)
154
+ and str_clean[12:] == _cnpj_check_digits(str_clean[:12])
155
+ )
156
+
157
+
158
+ @type_checker
159
+ def _cnpj_check_digits(str_base: str) -> str:
160
+ """Return the two check digits for a 12-character CNPJ base.
161
+
162
+ Parameters
163
+ ----------
164
+ str_base : str
165
+ The first 12 characters of an unmasked CNPJ.
166
+
167
+ Returns
168
+ -------
169
+ str
170
+ The two check digits, concatenated.
171
+ """
172
+ int_dv1 = _cnpj_check_digit(str_base, tuple_weights=_CNPJ_WEIGHTS_DV1)
173
+ int_dv2 = _cnpj_check_digit(f"{str_base}{int_dv1}", tuple_weights=_CNPJ_WEIGHTS_DV2)
174
+ return f"{int_dv1}{int_dv2}"
175
+
176
+
177
+ @type_checker
178
+ def unmask_cpf(str_value: str) -> str:
179
+ """Normalise a CPF to its bare 11-digit form.
180
+
181
+ Parameters
182
+ ----------
183
+ str_value : str
184
+ A CPF in any shape — masked, zero-stripped, or carrying a float ``.0`` tail.
185
+
186
+ Returns
187
+ -------
188
+ str
189
+ Digits only, left-zero-padded to 11 when non-empty; empty input yields ``""``.
190
+ """
191
+ str_clean = _strip_float_artifact(str_value)
192
+ str_clean = _RE_NON_DIGIT.sub("", str_clean)
193
+ if str_clean:
194
+ str_clean = str_clean.zfill(_LEN_CPF)
195
+ return str_clean
196
+
197
+
198
+ @type_checker
199
+ def mask_cpf(str_value: str) -> str:
200
+ """Format a CPF as ``XXX.XXX.XXX-XX``.
201
+
202
+ Parameters
203
+ ----------
204
+ str_value : str
205
+ A CPF in any shape (it is unmasked first).
206
+
207
+ Returns
208
+ -------
209
+ str
210
+ The punctuated CPF when it normalises to 11 digits; otherwise the bare
211
+ unmasked value. That covers empty input and values over 11 digits; a shorter
212
+ non-empty value is never returned, since it is zero-padded to 11.
213
+ """
214
+ str_clean = unmask_cpf(str_value)
215
+ if len(str_clean) != _LEN_CPF:
216
+ return str_clean
217
+ return f"{str_clean[:3]}.{str_clean[3:6]}.{str_clean[6:9]}-{str_clean[9:]}"
218
+
219
+
220
+ @type_checker
221
+ def _cpf_check_digit(str_base: str, *, int_start_weight: int) -> int:
222
+ """Compute one CPF check digit via descending mod-11 weighting.
223
+
224
+ Parameters
225
+ ----------
226
+ str_base : str
227
+ The base digits the weights apply to (9 for DV1, 10 for DV2).
228
+ int_start_weight : int
229
+ The first (largest) weight; subsequent weights descend by one.
230
+
231
+ Returns
232
+ -------
233
+ int
234
+ The check digit (0 when the remainder is below 2, else ``11 - remainder``).
235
+ """
236
+ int_sum = sum(
237
+ int(str_char) * (int_start_weight - int_idx) for int_idx, str_char in enumerate(str_base)
238
+ )
239
+ int_rest = int_sum % 11
240
+ return 0 if int_rest < _INT_MIN_REMAINDER else _INT_MODULUS - int_rest
241
+
242
+
243
+ @type_checker
244
+ def is_valid_cpf(str_value: str) -> bool:
245
+ """Validate a CPF's two check digits.
246
+
247
+ Parameters
248
+ ----------
249
+ str_value : str
250
+ A CPF in any shape (it is unmasked first).
251
+
252
+ Returns
253
+ -------
254
+ bool
255
+ ``True`` when the value normalises to 11 digits whose last two are the correct
256
+ check digits. Repeated-digit values (e.g. all ones) are rejected.
257
+ """
258
+ str_clean = unmask_cpf(str_value)
259
+ return (
260
+ len(str_clean) == _LEN_CPF
261
+ and str_clean.isdigit()
262
+ and len(set(str_clean)) > 1
263
+ and str_clean[9:] == _cpf_check_digits(str_clean)
264
+ )
265
+
266
+
267
+ @type_checker
268
+ def _cpf_check_digits(str_clean: str) -> str:
269
+ """Return the two check digits for an 11-digit CPF.
270
+
271
+ Parameters
272
+ ----------
273
+ str_clean : str
274
+ An unmasked, 11-digit CPF.
275
+
276
+ Returns
277
+ -------
278
+ str
279
+ The two check digits, concatenated.
280
+ """
281
+ int_dv1 = _cpf_check_digit(str_clean[:9], int_start_weight=10)
282
+ int_dv2 = _cpf_check_digit(str_clean[:10], int_start_weight=11)
283
+ return f"{int_dv1}{int_dv2}"
File without changes