cdate 0.2.1__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.
- cdate-0.2.1/.gitignore +10 -0
- cdate-0.2.1/LICENSES/Apache-2.0.txt +203 -0
- cdate-0.2.1/PKG-INFO +117 -0
- cdate-0.2.1/README.md +102 -0
- cdate-0.2.1/cdate/__init__.py +126 -0
- cdate-0.2.1/cdate/__main__.py +50 -0
- cdate-0.2.1/cdate/_tables.py +151 -0
- cdate-0.2.1/cdate/py.typed +0 -0
- cdate-0.2.1/pyproject.toml +26 -0
- cdate-0.2.1/scripts/conformance.py +56 -0
- cdate-0.2.1/scripts/consumer.py +104 -0
cdate-0.2.1/.gitignore
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Copyright 2026 Julian Y. Richard Corbet
|
|
2
|
+
|
|
3
|
+
Apache License
|
|
4
|
+
Version 2.0, January 2004
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
12
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
26
|
+
exercising permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
38
|
+
Object form, made available under the License, as indicated by a
|
|
39
|
+
copyright notice that is included in or attached to the work
|
|
40
|
+
(an example is provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original version of the Work and any modifications or additions
|
|
52
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
53
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
54
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
55
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
56
|
+
means any form of electronic, verbal, or written communication sent
|
|
57
|
+
to the Licensor or its representatives, including but not limited to
|
|
58
|
+
communication on electronic mailing lists, source code control systems,
|
|
59
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
60
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
61
|
+
excluding communication that is conspicuously marked or otherwise
|
|
62
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
65
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
66
|
+
subsequently incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, then any Derivative Works that You distribute must
|
|
110
|
+
include a readable copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
122
|
+
that such additional attribution notices cannot be construed
|
|
123
|
+
as modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions stated in this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for reasonable and customary use in describing the
|
|
143
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
169
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
170
|
+
or other liability obligations and/or rights consistent with this
|
|
171
|
+
License. However, in accepting such obligations, You may act only
|
|
172
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
173
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
174
|
+
defend, and hold each Contributor harmless for any liability
|
|
175
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
176
|
+
of your accepting any such warranty or additional liability.
|
|
177
|
+
|
|
178
|
+
END OF TERMS AND CONDITIONS
|
|
179
|
+
|
|
180
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
181
|
+
|
|
182
|
+
To apply the Apache License to your work, attach the following
|
|
183
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
184
|
+
replaced with your own identifying information. (Don't include
|
|
185
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
186
|
+
comment syntax for the file format. We also recommend that a
|
|
187
|
+
file or class name and description of purpose be included on the
|
|
188
|
+
same "printed page" as the copyright notice for easier
|
|
189
|
+
identification within third-party archives.
|
|
190
|
+
|
|
191
|
+
Copyright [yyyy] [name of copyright owner]
|
|
192
|
+
|
|
193
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
194
|
+
you may not use this file except in compliance with the License.
|
|
195
|
+
You may obtain a copy of the License at
|
|
196
|
+
|
|
197
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
198
|
+
|
|
199
|
+
Unless required by applicable law or agreed to in writing, software
|
|
200
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
201
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
202
|
+
See the License for the specific language governing permissions and
|
|
203
|
+
limitations under the License.
|
cdate-0.2.1/PKG-INFO
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cdate
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Deterministic locale-correct date formats for formal correspondence
|
|
5
|
+
Project-URL: Homepage, https://github.com/corbet-labs/cdate#readme
|
|
6
|
+
Project-URL: Repository, https://github.com/corbet-labs/cdate
|
|
7
|
+
Project-URL: Issues, https://github.com/corbet-labs/cdate/issues
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSES/Apache-2.0.txt
|
|
10
|
+
Keywords: correspondence,i18n,locale
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# cdate
|
|
17
|
+
|
|
18
|
+
**Reproducible date formats for correspondence.**
|
|
19
|
+
|
|
20
|
+
[](https://crates.io/crates/cdate) [](https://www.npmjs.com/package/@corbet-labs/cdate) [](https://docs.rs/cdate)
|
|
21
|
+
|
|
22
|
+
Format a Gregorian calendar date without a timezone, operating-system locale, or network dependency. The same inputs produce the same text in Rust, JavaScript, Python, and Typst.
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
import { longDate } from '@corbet-labs/cdate';
|
|
26
|
+
|
|
27
|
+
longDate('de-ch', 2026, 9, 7);
|
|
28
|
+
// 7. September 2026
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
| Environment | Command |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| Rust / Cargo | `cargo add cdate` |
|
|
36
|
+
| Node.js / npm | `npm install @corbet-labs/cdate` |
|
|
37
|
+
| pnpm | `pnpm add @corbet-labs/cdate` |
|
|
38
|
+
| Yarn | `yarn add @corbet-labs/cdate` |
|
|
39
|
+
| Bun | `bun add @corbet-labs/cdate` |
|
|
40
|
+
| Deno | `deno add npm:@corbet-labs/cdate` |
|
|
41
|
+
|
|
42
|
+
The 0.2.1 JavaScript distribution includes compiled ESM, CommonJS,
|
|
43
|
+
TypeScript declarations, and a standalone browser module. Node.js 20+ is
|
|
44
|
+
supported; no TypeScript loader is required.
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
// CommonJS
|
|
48
|
+
const { longDate } = require('@corbet-labs/cdate');
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```html
|
|
52
|
+
<script type="module">
|
|
53
|
+
import { longDate } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cdate@0.2.1/dist/browser.js';
|
|
54
|
+
console.log(longDate('de-ch', 2026, 9, 7));
|
|
55
|
+
</script>
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Python wheels, source distributions, and CLI instructions are in the
|
|
59
|
+
[installation guide](https://github.com/corbet-labs/cdate/blob/main/docs/installation.md).
|
|
60
|
+
JSR publication and Typst availability are listed there explicitly.
|
|
61
|
+
|
|
62
|
+
## Rust
|
|
63
|
+
|
|
64
|
+
```rust
|
|
65
|
+
use cdate::{long_date, month_year};
|
|
66
|
+
|
|
67
|
+
assert_eq!(long_date("de-ch", 2026, 9, 7).as_deref(), Some("7. September 2026"));
|
|
68
|
+
assert_eq!(month_year("en", 2026, 9).as_deref(), Some("September 2026"));
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Python
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from cdate import long_date
|
|
75
|
+
|
|
76
|
+
assert long_date("de-ch", 2026, 9, 7) == '7. September 2026'
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## API
|
|
80
|
+
|
|
81
|
+
| JavaScript / Python or Rust | Example for `de-ch` |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| `longDate` / `long_date` | `7. September 2026` |
|
|
84
|
+
| `mediumDate` / `medium_date` | `07.09.2026` |
|
|
85
|
+
| `shortDate` / `short_date` | `07.09.26` |
|
|
86
|
+
| `monthYear` / `month_year` | `September 2026` |
|
|
87
|
+
| `isValidDate` / `is_valid_date` | Calendar-date validation |
|
|
88
|
+
|
|
89
|
+
The seven date-table entries are `de`, `de-at`, `de-ch`, `de-li`, `en`, `en-gb`, and `en-us`. Matching is case-insensitive; other locales fall back through the base language to English. Impossible calendar dates return `null`/`None`. Inputs are calendar components, not timestamps. Other family libraries have broader locale coverage.
|
|
90
|
+
|
|
91
|
+
## Correspondence family
|
|
92
|
+
|
|
93
|
+
| Library | Responsibility |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
|
|
96
|
+
| [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
|
|
97
|
+
| [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
|
|
98
|
+
| [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
|
|
99
|
+
| [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
## Development
|
|
103
|
+
|
|
104
|
+
Behavior is defined by [the locale tables](https://github.com/corbet-labs/cdate/tree/main/tables)
|
|
105
|
+
and [shared conformance vectors](https://github.com/corbet-labs/cdate/tree/main/tests/vectors).
|
|
106
|
+
Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
|
|
107
|
+
installed JavaScript tarballs, Python wheels and command-line entrypoints, and
|
|
108
|
+
Typst packages. Release validation records the actual runtime and platform;
|
|
109
|
+
Linux results do not establish native Windows or macOS coverage.
|
|
110
|
+
All five Rust crates forbid unsafe code in their own source.
|
|
111
|
+
|
|
112
|
+
See [the release guide](https://github.com/corbet-labs/cdate/blob/main/docs/releasing.md)
|
|
113
|
+
for generation, verification, and publication commands.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
[Apache-2.0](https://github.com/corbet-labs/cdate/blob/main/LICENSES/Apache-2.0.txt), effective immediately from version 0.2.1 across all language distributions. Copyright 2026 Julian Y. Richard Corbet. Previously published versions retain their original license grants.
|
cdate-0.2.1/README.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# cdate
|
|
2
|
+
|
|
3
|
+
**Reproducible date formats for correspondence.**
|
|
4
|
+
|
|
5
|
+
[](https://crates.io/crates/cdate) [](https://www.npmjs.com/package/@corbet-labs/cdate) [](https://docs.rs/cdate)
|
|
6
|
+
|
|
7
|
+
Format a Gregorian calendar date without a timezone, operating-system locale, or network dependency. The same inputs produce the same text in Rust, JavaScript, Python, and Typst.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { longDate } from '@corbet-labs/cdate';
|
|
11
|
+
|
|
12
|
+
longDate('de-ch', 2026, 9, 7);
|
|
13
|
+
// 7. September 2026
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
| Environment | Command |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| Rust / Cargo | `cargo add cdate` |
|
|
21
|
+
| Node.js / npm | `npm install @corbet-labs/cdate` |
|
|
22
|
+
| pnpm | `pnpm add @corbet-labs/cdate` |
|
|
23
|
+
| Yarn | `yarn add @corbet-labs/cdate` |
|
|
24
|
+
| Bun | `bun add @corbet-labs/cdate` |
|
|
25
|
+
| Deno | `deno add npm:@corbet-labs/cdate` |
|
|
26
|
+
|
|
27
|
+
The 0.2.1 JavaScript distribution includes compiled ESM, CommonJS,
|
|
28
|
+
TypeScript declarations, and a standalone browser module. Node.js 20+ is
|
|
29
|
+
supported; no TypeScript loader is required.
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
// CommonJS
|
|
33
|
+
const { longDate } = require('@corbet-labs/cdate');
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```html
|
|
37
|
+
<script type="module">
|
|
38
|
+
import { longDate } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cdate@0.2.1/dist/browser.js';
|
|
39
|
+
console.log(longDate('de-ch', 2026, 9, 7));
|
|
40
|
+
</script>
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Python wheels, source distributions, and CLI instructions are in the
|
|
44
|
+
[installation guide](https://github.com/corbet-labs/cdate/blob/main/docs/installation.md).
|
|
45
|
+
JSR publication and Typst availability are listed there explicitly.
|
|
46
|
+
|
|
47
|
+
## Rust
|
|
48
|
+
|
|
49
|
+
```rust
|
|
50
|
+
use cdate::{long_date, month_year};
|
|
51
|
+
|
|
52
|
+
assert_eq!(long_date("de-ch", 2026, 9, 7).as_deref(), Some("7. September 2026"));
|
|
53
|
+
assert_eq!(month_year("en", 2026, 9).as_deref(), Some("September 2026"));
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Python
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from cdate import long_date
|
|
60
|
+
|
|
61
|
+
assert long_date("de-ch", 2026, 9, 7) == '7. September 2026'
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## API
|
|
65
|
+
|
|
66
|
+
| JavaScript / Python or Rust | Example for `de-ch` |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| `longDate` / `long_date` | `7. September 2026` |
|
|
69
|
+
| `mediumDate` / `medium_date` | `07.09.2026` |
|
|
70
|
+
| `shortDate` / `short_date` | `07.09.26` |
|
|
71
|
+
| `monthYear` / `month_year` | `September 2026` |
|
|
72
|
+
| `isValidDate` / `is_valid_date` | Calendar-date validation |
|
|
73
|
+
|
|
74
|
+
The seven date-table entries are `de`, `de-at`, `de-ch`, `de-li`, `en`, `en-gb`, and `en-us`. Matching is case-insensitive; other locales fall back through the base language to English. Impossible calendar dates return `null`/`None`. Inputs are calendar components, not timestamps. Other family libraries have broader locale coverage.
|
|
75
|
+
|
|
76
|
+
## Correspondence family
|
|
77
|
+
|
|
78
|
+
| Library | Responsibility |
|
|
79
|
+
| --- | --- |
|
|
80
|
+
| [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
|
|
81
|
+
| [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
|
|
82
|
+
| [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
|
|
83
|
+
| [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
|
|
84
|
+
| [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
## Development
|
|
88
|
+
|
|
89
|
+
Behavior is defined by [the locale tables](https://github.com/corbet-labs/cdate/tree/main/tables)
|
|
90
|
+
and [shared conformance vectors](https://github.com/corbet-labs/cdate/tree/main/tests/vectors).
|
|
91
|
+
Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
|
|
92
|
+
installed JavaScript tarballs, Python wheels and command-line entrypoints, and
|
|
93
|
+
Typst packages. Release validation records the actual runtime and platform;
|
|
94
|
+
Linux results do not establish native Windows or macOS coverage.
|
|
95
|
+
All five Rust crates forbid unsafe code in their own source.
|
|
96
|
+
|
|
97
|
+
See [the release guide](https://github.com/corbet-labs/cdate/blob/main/docs/releasing.md)
|
|
98
|
+
for generation, verification, and publication commands.
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
[Apache-2.0](https://github.com/corbet-labs/cdate/blob/main/LICENSES/Apache-2.0.txt), effective immediately from version 0.2.1 across all language distributions. Copyright 2026 Julian Y. Richard Corbet. Previously published versions retain their original license grants.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Deterministic locale-correct date formats for formal correspondence.
|
|
2
|
+
|
|
3
|
+
Pure-Python port of the cdate Rust crate: standard library only, no I/O.
|
|
4
|
+
Behavior is defined by ``tables/*.json`` at the repository root;
|
|
5
|
+
``tests/vectors/*.json`` is the shared conformance suite
|
|
6
|
+
(``py/scripts/conformance.py``).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._tables import TABLES
|
|
10
|
+
|
|
11
|
+
_RAW = TABLES["dates"]
|
|
12
|
+
|
|
13
|
+
_LOCALES = _RAW["locales"]
|
|
14
|
+
_SUPPORTED = _RAW["supported"]
|
|
15
|
+
_FALLBACK = _RAW["fallback"]
|
|
16
|
+
|
|
17
|
+
_CANONICAL_BY_LOWER = {key.lower(): key for key in _LOCALES}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _base_language(locale: str) -> str:
|
|
21
|
+
return locale.split("-", 1)[0]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _resolve_key(locale: str) -> str:
|
|
25
|
+
if locale in _LOCALES:
|
|
26
|
+
return locale
|
|
27
|
+
lowered = locale.lower()
|
|
28
|
+
if lowered in _CANONICAL_BY_LOWER:
|
|
29
|
+
return _CANONICAL_BY_LOWER[lowered]
|
|
30
|
+
base = _CANONICAL_BY_LOWER.get(_base_language(lowered))
|
|
31
|
+
if base is not None:
|
|
32
|
+
return base
|
|
33
|
+
return _FALLBACK
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _days_in_month(year: int, month: int) -> int:
|
|
37
|
+
if month in (1, 3, 5, 7, 8, 10, 12):
|
|
38
|
+
return 31
|
|
39
|
+
if month in (4, 6, 9, 11):
|
|
40
|
+
return 30
|
|
41
|
+
if month == 2:
|
|
42
|
+
leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
|
|
43
|
+
return 29 if leap else 28
|
|
44
|
+
return 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_valid_date(year: int, month: int, day: int) -> bool:
|
|
48
|
+
"""Whether a proleptic Gregorian calendar date exists."""
|
|
49
|
+
return (
|
|
50
|
+
type(year) is int
|
|
51
|
+
and type(month) is int
|
|
52
|
+
and type(day) is int
|
|
53
|
+
and 1 <= month <= 12
|
|
54
|
+
and 1 <= day <= _days_in_month(year, month)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _pad_two(value: int) -> str:
|
|
59
|
+
return f"{value:02d}"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _pad_year(year: int) -> str:
|
|
63
|
+
text = str(year)
|
|
64
|
+
if year < 0 or year >= 1000:
|
|
65
|
+
return text
|
|
66
|
+
if year >= 100:
|
|
67
|
+
return "0" + text
|
|
68
|
+
if year >= 10:
|
|
69
|
+
return "00" + text
|
|
70
|
+
return "000" + text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _render(entry: dict, pattern: str, year: int, month: int, day: int) -> str:
|
|
74
|
+
return (
|
|
75
|
+
pattern.replace("{yyyy}", _pad_year(year))
|
|
76
|
+
.replace("{yy}", _pad_two(year % 100))
|
|
77
|
+
.replace("{month_long}", entry["months_long"][month - 1])
|
|
78
|
+
.replace("{month_short}", entry.get("months_short", [])[month - 1] if entry.get("months_short") else "")
|
|
79
|
+
.replace("{dd}", _pad_two(day))
|
|
80
|
+
.replace("{mm}", _pad_two(month))
|
|
81
|
+
.replace("{day}", str(day))
|
|
82
|
+
.replace("{month}", str(month))
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _format_with(locale: str, field: str, year: int, month: int, day: int) -> str | None:
|
|
87
|
+
if not is_valid_date(year, month, day):
|
|
88
|
+
return None
|
|
89
|
+
entry = _LOCALES[_resolve_key(locale)]
|
|
90
|
+
return _render(entry, entry[field], year, month, day)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def long_date(locale: str, year: int, month: int, day: int) -> str | None:
|
|
94
|
+
"""Long date: ``7. September 2026`` (de), ``September 7, 2026`` (en)."""
|
|
95
|
+
return _format_with(locale, "long", year, month, day)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def medium_date(locale: str, year: int, month: int, day: int) -> str | None:
|
|
99
|
+
"""Medium date: ``07.09.2026`` (de), ``Sep 7, 2026`` (en)."""
|
|
100
|
+
return _format_with(locale, "medium", year, month, day)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def short_date(locale: str, year: int, month: int, day: int) -> str | None:
|
|
104
|
+
"""Short numeric date: ``07.09.26`` (de), ``9/7/26`` (en)."""
|
|
105
|
+
return _format_with(locale, "short", year, month, day)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def month_year(locale: str, year: int, month: int) -> str | None:
|
|
109
|
+
"""Month and year for a correspondence dateline: ``September 2026``."""
|
|
110
|
+
if not type(year) is int or not type(month) is int or not 1 <= month <= 12:
|
|
111
|
+
return None
|
|
112
|
+
entry = _LOCALES[_resolve_key(locale)]
|
|
113
|
+
return _render(entry, entry["month_year"], year, month, 1)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def available_locales() -> list:
|
|
117
|
+
"""BCP 47 locale codes with a date-format entry, sorted."""
|
|
118
|
+
return sorted(_LOCALES)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def is_supported(locale: str) -> bool:
|
|
122
|
+
"""Whether a locale code is supported directly or via its base language."""
|
|
123
|
+
return locale in _SUPPORTED or _base_language(locale.lower()) in _SUPPORTED
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
__all__ = ["is_valid_date", "long_date", "medium_date", "short_date", "month_year", "available_locales", "is_supported"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""JSON command-line bridge for callers in any programming language."""
|
|
2
|
+
import argparse
|
|
3
|
+
import base64
|
|
4
|
+
import dataclasses
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
import cdate as api
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _json_default(value):
|
|
11
|
+
if dataclasses.is_dataclass(value):
|
|
12
|
+
return dataclasses.asdict(value)
|
|
13
|
+
if isinstance(value, bytes):
|
|
14
|
+
return base64.b64encode(value).decode("ascii")
|
|
15
|
+
raise TypeError(f"Cannot serialize {type(value).__name__}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _reject_constant(value):
|
|
19
|
+
raise ValueError(f"{value} is not a JSON number")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main():
|
|
23
|
+
parser = argparse.ArgumentParser(description="Call cdate functions with JSON arguments.")
|
|
24
|
+
parser.add_argument("function", choices=api.__all__)
|
|
25
|
+
parser.add_argument("arguments", nargs="?", default="[]", help="JSON array of positional arguments or object of keyword arguments; '-' reads UTF-8 stdin")
|
|
26
|
+
args = parser.parse_args()
|
|
27
|
+
try:
|
|
28
|
+
values = json.loads(sys.stdin.buffer.read().decode("utf-8") if args.arguments == "-" else args.arguments, parse_constant=_reject_constant)
|
|
29
|
+
if not isinstance(values, (list, dict)):
|
|
30
|
+
raise ValueError("arguments must be a JSON array or object")
|
|
31
|
+
# Image operations accept the JSON object returned by normalize.
|
|
32
|
+
if args.function in ("exceeds_limits", "scale_to_fit", "signature_size"):
|
|
33
|
+
raw = values[0] if isinstance(values, list) else values["image"]
|
|
34
|
+
if isinstance(raw, dict):
|
|
35
|
+
raw = dict(raw)
|
|
36
|
+
raw["bytes"] = base64.b64decode(raw["bytes"], validate=True)
|
|
37
|
+
image = api.DecodedImage(**raw)
|
|
38
|
+
if isinstance(values, list):
|
|
39
|
+
values[0] = image
|
|
40
|
+
else:
|
|
41
|
+
values["image"] = image
|
|
42
|
+
fn = getattr(api, args.function)
|
|
43
|
+
result = fn(*values) if isinstance(values, list) else fn(**values)
|
|
44
|
+
print(json.dumps(result, default=_json_default, ensure_ascii=True, allow_nan=False))
|
|
45
|
+
except (ValueError, TypeError, KeyError, IndexError, AttributeError, OverflowError) as error:
|
|
46
|
+
parser.error(str(error))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == "__main__":
|
|
50
|
+
main()
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Generated by scripts/sync-python.py; edit tables/*.json instead.
|
|
2
|
+
TABLES = {'dates': {'fallback': 'en',
|
|
3
|
+
'locales': {'de': {'long': '{day}. {month_long} {yyyy}',
|
|
4
|
+
'medium': '{dd}.{mm}.{yyyy}',
|
|
5
|
+
'month_year': '{month_long} {yyyy}',
|
|
6
|
+
'months_long': ['Januar',
|
|
7
|
+
'Februar',
|
|
8
|
+
'März',
|
|
9
|
+
'April',
|
|
10
|
+
'Mai',
|
|
11
|
+
'Juni',
|
|
12
|
+
'Juli',
|
|
13
|
+
'August',
|
|
14
|
+
'September',
|
|
15
|
+
'Oktober',
|
|
16
|
+
'November',
|
|
17
|
+
'Dezember'],
|
|
18
|
+
'short': '{dd}.{mm}.{yy}'},
|
|
19
|
+
'de-at': {'long': '{day}. {month_long} {yyyy}',
|
|
20
|
+
'medium': '{dd}.{mm}.{yyyy}',
|
|
21
|
+
'month_year': '{month_long} {yyyy}',
|
|
22
|
+
'months_long': ['Januar',
|
|
23
|
+
'Februar',
|
|
24
|
+
'März',
|
|
25
|
+
'April',
|
|
26
|
+
'Mai',
|
|
27
|
+
'Juni',
|
|
28
|
+
'Juli',
|
|
29
|
+
'August',
|
|
30
|
+
'September',
|
|
31
|
+
'Oktober',
|
|
32
|
+
'November',
|
|
33
|
+
'Dezember'],
|
|
34
|
+
'short': '{dd}.{mm}.{yy}'},
|
|
35
|
+
'de-ch': {'long': '{day}. {month_long} {yyyy}',
|
|
36
|
+
'medium': '{dd}.{mm}.{yyyy}',
|
|
37
|
+
'month_year': '{month_long} {yyyy}',
|
|
38
|
+
'months_long': ['Januar',
|
|
39
|
+
'Februar',
|
|
40
|
+
'März',
|
|
41
|
+
'April',
|
|
42
|
+
'Mai',
|
|
43
|
+
'Juni',
|
|
44
|
+
'Juli',
|
|
45
|
+
'August',
|
|
46
|
+
'September',
|
|
47
|
+
'Oktober',
|
|
48
|
+
'November',
|
|
49
|
+
'Dezember'],
|
|
50
|
+
'short': '{dd}.{mm}.{yy}'},
|
|
51
|
+
'de-li': {'long': '{day}. {month_long} {yyyy}',
|
|
52
|
+
'medium': '{dd}.{mm}.{yyyy}',
|
|
53
|
+
'month_year': '{month_long} {yyyy}',
|
|
54
|
+
'months_long': ['Januar',
|
|
55
|
+
'Februar',
|
|
56
|
+
'März',
|
|
57
|
+
'April',
|
|
58
|
+
'Mai',
|
|
59
|
+
'Juni',
|
|
60
|
+
'Juli',
|
|
61
|
+
'August',
|
|
62
|
+
'September',
|
|
63
|
+
'Oktober',
|
|
64
|
+
'November',
|
|
65
|
+
'Dezember'],
|
|
66
|
+
'short': '{dd}.{mm}.{yy}'},
|
|
67
|
+
'en': {'long': '{month_long} {day}, {yyyy}',
|
|
68
|
+
'medium': '{month_short} {day}, {yyyy}',
|
|
69
|
+
'month_year': '{month_long} {yyyy}',
|
|
70
|
+
'months_long': ['January',
|
|
71
|
+
'February',
|
|
72
|
+
'March',
|
|
73
|
+
'April',
|
|
74
|
+
'May',
|
|
75
|
+
'June',
|
|
76
|
+
'July',
|
|
77
|
+
'August',
|
|
78
|
+
'September',
|
|
79
|
+
'October',
|
|
80
|
+
'November',
|
|
81
|
+
'December'],
|
|
82
|
+
'months_short': ['Jan',
|
|
83
|
+
'Feb',
|
|
84
|
+
'Mar',
|
|
85
|
+
'Apr',
|
|
86
|
+
'May',
|
|
87
|
+
'Jun',
|
|
88
|
+
'Jul',
|
|
89
|
+
'Aug',
|
|
90
|
+
'Sep',
|
|
91
|
+
'Oct',
|
|
92
|
+
'Nov',
|
|
93
|
+
'Dec'],
|
|
94
|
+
'short': '{month}/{day}/{yy}'},
|
|
95
|
+
'en-gb': {'long': '{day} {month_long} {yyyy}',
|
|
96
|
+
'medium': '{day} {month_short} {yyyy}',
|
|
97
|
+
'month_year': '{month_long} {yyyy}',
|
|
98
|
+
'months_long': ['January',
|
|
99
|
+
'February',
|
|
100
|
+
'March',
|
|
101
|
+
'April',
|
|
102
|
+
'May',
|
|
103
|
+
'June',
|
|
104
|
+
'July',
|
|
105
|
+
'August',
|
|
106
|
+
'September',
|
|
107
|
+
'October',
|
|
108
|
+
'November',
|
|
109
|
+
'December'],
|
|
110
|
+
'months_short': ['Jan',
|
|
111
|
+
'Feb',
|
|
112
|
+
'Mar',
|
|
113
|
+
'Apr',
|
|
114
|
+
'May',
|
|
115
|
+
'Jun',
|
|
116
|
+
'Jul',
|
|
117
|
+
'Aug',
|
|
118
|
+
'Sept',
|
|
119
|
+
'Oct',
|
|
120
|
+
'Nov',
|
|
121
|
+
'Dec'],
|
|
122
|
+
'short': '{dd}/{mm}/{yyyy}'},
|
|
123
|
+
'en-us': {'long': '{month_long} {day}, {yyyy}',
|
|
124
|
+
'medium': '{month_short} {day}, {yyyy}',
|
|
125
|
+
'month_year': '{month_long} {yyyy}',
|
|
126
|
+
'months_long': ['January',
|
|
127
|
+
'February',
|
|
128
|
+
'March',
|
|
129
|
+
'April',
|
|
130
|
+
'May',
|
|
131
|
+
'June',
|
|
132
|
+
'July',
|
|
133
|
+
'August',
|
|
134
|
+
'September',
|
|
135
|
+
'October',
|
|
136
|
+
'November',
|
|
137
|
+
'December'],
|
|
138
|
+
'months_short': ['Jan',
|
|
139
|
+
'Feb',
|
|
140
|
+
'Mar',
|
|
141
|
+
'Apr',
|
|
142
|
+
'May',
|
|
143
|
+
'Jun',
|
|
144
|
+
'Jul',
|
|
145
|
+
'Aug',
|
|
146
|
+
'Sep',
|
|
147
|
+
'Oct',
|
|
148
|
+
'Nov',
|
|
149
|
+
'Dec'],
|
|
150
|
+
'short': '{month}/{day}/{yy}'}},
|
|
151
|
+
'supported': ['de', 'de-at', 'de-ch', 'de-li', 'en', 'en-gb', 'en-us']}}
|
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27,<2"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cdate"
|
|
7
|
+
version = "0.2.1"
|
|
8
|
+
description = "Deterministic locale-correct date formats for formal correspondence"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSES/*"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
keywords = ["i18n", "correspondence", "locale"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://github.com/corbet-labs/cdate#readme"
|
|
19
|
+
Repository = "https://github.com/corbet-labs/cdate"
|
|
20
|
+
Issues = "https://github.com/corbet-labs/cdate/issues"
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
cdate = "cdate.__main__:main"
|
|
24
|
+
|
|
25
|
+
[tool.hatch.build.targets.wheel]
|
|
26
|
+
packages = ["cdate"]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Run canonical vectors against either the source port or an installed wheel."""
|
|
2
|
+
import base64
|
|
3
|
+
import importlib
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
9
|
+
if "--installed" not in sys.argv:
|
|
10
|
+
sys.path.insert(0, str(ROOT / "py"))
|
|
11
|
+
api = importlib.import_module("cdate")
|
|
12
|
+
|
|
13
|
+
ARGUMENTS = {
|
|
14
|
+
"region_parse": ["input"], "region_uses_comma": ["input"],
|
|
15
|
+
"salutation_last_name": ["input"], "salutation_honorific": ["input"],
|
|
16
|
+
"salutation_titles": ["input"], "salutation_surname": ["input"],
|
|
17
|
+
"de_salutation": ["input", "region"],
|
|
18
|
+
"recipient_salutation_warning": ["location", "input"],
|
|
19
|
+
"de_honorific_warning": ["location", "input"],
|
|
20
|
+
"closing": ["locale", "override"], "available_locales": [],
|
|
21
|
+
"long_date": ["locale", "year", "month", "day"],
|
|
22
|
+
"medium_date": ["locale", "year", "month", "day"],
|
|
23
|
+
"short_date": ["locale", "year", "month", "day"],
|
|
24
|
+
"month_year": ["locale", "year", "month"], "is_supported": ["locale"],
|
|
25
|
+
"supported_formats": [], "normalize": ["input"],
|
|
26
|
+
"exceeds_limits": ["image", "max_pixels"], "scale_to_fit": ["image", "max_pixels"],
|
|
27
|
+
"signature_size": ["image", "height_pt", "max_width_pt"],
|
|
28
|
+
"image_snippet": ["path", "height_pt", "width_pt"],
|
|
29
|
+
"resolve_locale": ["language", "location"],
|
|
30
|
+
"opening": ["locale", "person", "override"],
|
|
31
|
+
"subject": ["locale", "title", "prefix_override"],
|
|
32
|
+
"salutation": ["locale", "person"], "apply_ortho": ["locale", "text"],
|
|
33
|
+
"warnings": ["location", "locale", "person"],
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
files = sorted((ROOT / "tests/vectors").glob("*.json"))
|
|
37
|
+
assert files, "No conformance vectors"
|
|
38
|
+
count = 0
|
|
39
|
+
for file in files:
|
|
40
|
+
for vector in json.loads(file.read_text(encoding="utf-8")):
|
|
41
|
+
name = vector["fn"]
|
|
42
|
+
values = dict(vector)
|
|
43
|
+
if "fixture" in vector:
|
|
44
|
+
values["input"] = base64.b64encode((ROOT / "tests/fixtures" / vector["fixture"]).read_bytes()).decode("ascii")
|
|
45
|
+
if name != "normalize":
|
|
46
|
+
values["image"] = api.normalize(values["input"])
|
|
47
|
+
fn = getattr(api, "parse_region" if name == "region_parse" else name)
|
|
48
|
+
actual = fn(*(values.get(key) for key in ARGUMENTS[name]))
|
|
49
|
+
if name == "normalize" and actual is not None:
|
|
50
|
+
actual = {key: getattr(actual, key) for key in ("mime", "width", "height")}
|
|
51
|
+
if isinstance(actual, tuple):
|
|
52
|
+
actual = list(actual)
|
|
53
|
+
if actual != vector["expected"]:
|
|
54
|
+
raise AssertionError(f"{file.name} :: {vector['name']}: {actual!r} != {vector['expected']!r}")
|
|
55
|
+
count += 1
|
|
56
|
+
print(f"Python cdate: {count} vectors passed across {len(files)} files")
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Verify wheel/sdist contents and installed Python/console entrypoints.
|
|
2
|
+
|
|
3
|
+
Run with the interpreter in a fresh environment containing the wheel and its
|
|
4
|
+
declared dependencies. This script never adds the source package to sys.path.
|
|
5
|
+
"""
|
|
6
|
+
import argparse
|
|
7
|
+
import base64
|
|
8
|
+
from email.parser import BytesParser
|
|
9
|
+
import importlib
|
|
10
|
+
import importlib.metadata
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tarfile
|
|
17
|
+
import tempfile
|
|
18
|
+
import zipfile
|
|
19
|
+
|
|
20
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
21
|
+
PACKAGES = [path.name for path in (ROOT / "py").iterdir() if (path / "__init__.py").is_file()]
|
|
22
|
+
if len(PACKAGES) != 1:
|
|
23
|
+
raise RuntimeError("Expected exactly one source package")
|
|
24
|
+
NAME = PACKAGES[0]
|
|
25
|
+
CASES = {
|
|
26
|
+
"cgreet": ("de_salutation", ["Frau Dr. Müller", "ch"],
|
|
27
|
+
{"name": "Frau Dr. Müller", "region": "ch"}, "Sehr geehrte Frau Dr. Müller"),
|
|
28
|
+
"cfarewell": ("closing", ["DE-LI"], {"locale": "DE-LI"}, "Freundliche Grüsse"),
|
|
29
|
+
"cdate": ("long_date", ["EN-GB", 2026, 9, 7],
|
|
30
|
+
{"locale": "EN-GB", "year": 2026, "month": 9, "day": 7}, "7 September 2026"),
|
|
31
|
+
"cink": ("image_snippet", ["signature.png", 20],
|
|
32
|
+
{"path": "signature.png", "height_pt": 20}, '#image("signature.png", height: 20pt)'),
|
|
33
|
+
"cletter": ("salutation", ["DE-LI", "Frau Dr. Müller"],
|
|
34
|
+
{"locale": "DE-LI", "name": "Frau Dr. Müller"}, "Sehr geehrte Frau Dr. Müller"),
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check(condition, message):
|
|
39
|
+
if not condition:
|
|
40
|
+
raise AssertionError(message)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
44
|
+
parser.add_argument("--wheel", type=Path, required=True)
|
|
45
|
+
parser.add_argument("--sdist", type=Path, required=True)
|
|
46
|
+
args = parser.parse_args()
|
|
47
|
+
licenses = {path.name: path.read_bytes() for path in (ROOT / "LICENSES").iterdir() if path.is_file()}
|
|
48
|
+
check(bool(licenses), "Source licenses are missing")
|
|
49
|
+
with zipfile.ZipFile(args.wheel) as wheel:
|
|
50
|
+
files = wheel.namelist()
|
|
51
|
+
check(f"{NAME}/py.typed" in files, "Wheel is missing py.typed")
|
|
52
|
+
metadata_paths = [path for path in files if path.endswith(".dist-info/METADATA")]
|
|
53
|
+
check(len(metadata_paths) == 1, "Expected one wheel distribution")
|
|
54
|
+
metadata = BytesParser().parsebytes(wheel.read(metadata_paths[0]))
|
|
55
|
+
check(metadata["Name"] == NAME, "Wheel package name differs from repository")
|
|
56
|
+
for name, expected in licenses.items():
|
|
57
|
+
check(any(path.endswith("/LICENSES/" + name) and wheel.read(path) == expected for path in files),
|
|
58
|
+
f"Wheel is missing the original {name}")
|
|
59
|
+
with tarfile.open(args.sdist, "r:gz") as sdist:
|
|
60
|
+
files = {member.name: member for member in sdist.getmembers() if member.isfile()}
|
|
61
|
+
for name, expected in licenses.items():
|
|
62
|
+
check(any(path.endswith("/LICENSES/" + name) and sdist.extractfile(member).read() == expected
|
|
63
|
+
for path, member in files.items()), f"Source distribution is missing {name}")
|
|
64
|
+
|
|
65
|
+
distribution = importlib.metadata.distribution(NAME)
|
|
66
|
+
check(distribution.version == metadata["Version"], "Installed version differs from wheel")
|
|
67
|
+
check(any(entry.group == "console_scripts" and entry.name == NAME and entry.value == f"{NAME}.__main__:main"
|
|
68
|
+
for entry in distribution.entry_points), "Missing console entrypoint metadata")
|
|
69
|
+
api = importlib.import_module(NAME)
|
|
70
|
+
check(not Path(api.__file__).resolve().is_relative_to(ROOT / "py"), "Imported source tree instead of installed wheel")
|
|
71
|
+
entrypoint = Path(sys.executable).parent / (NAME + (".exe" if os.name == "nt" else ""))
|
|
72
|
+
check(entrypoint.is_file(), "Installer did not create the console entrypoint")
|
|
73
|
+
function, positional, keywords, expected = CASES[NAME]
|
|
74
|
+
|
|
75
|
+
with tempfile.TemporaryDirectory(prefix=f"{NAME}-python-consumer-") as cwd:
|
|
76
|
+
def call(command, function, values, *, stdin=False, valid=True):
|
|
77
|
+
payload = values if isinstance(values, str) else json.dumps(values, ensure_ascii=False)
|
|
78
|
+
result = subprocess.run(command + [function, "-" if stdin else payload],
|
|
79
|
+
input=payload if stdin else None, cwd=cwd, text=True,
|
|
80
|
+
encoding="utf-8", capture_output=True, timeout=30)
|
|
81
|
+
if valid:
|
|
82
|
+
check(result.returncode == 0, result.stderr)
|
|
83
|
+
return json.loads(result.stdout)
|
|
84
|
+
check(result.returncode == 2 and not result.stdout and "Traceback" not in result.stderr,
|
|
85
|
+
f"Invalid arguments did not produce a clean CLI error: {result}")
|
|
86
|
+
|
|
87
|
+
for command in ([sys.executable, "-m", NAME], [str(entrypoint)]):
|
|
88
|
+
check(call(command, function, positional) == expected, "Positional JSON invocation failed")
|
|
89
|
+
check(call(command, function, keywords, stdin=True) == expected, "Keyword/stdin invocation failed")
|
|
90
|
+
call(command, function, "null", valid=False)
|
|
91
|
+
call(command, function, "[NaN]", valid=False)
|
|
92
|
+
call(command, function, [], valid=False)
|
|
93
|
+
if NAME in ("cink", "cletter"):
|
|
94
|
+
encoded = base64.b64encode(b'<svg xmlns="http://www.w3.org/2000/svg"/>').decode("ascii")
|
|
95
|
+
decoded = call([str(entrypoint)], "normalize", [encoded])
|
|
96
|
+
check(decoded["bytes"] == encoded and decoded["mime"] == "svg", "Image JSON output lost encoded bytes")
|
|
97
|
+
check(call([str(entrypoint)], "signature_size", {"image": decoded, "height_pt": 20}) is None,
|
|
98
|
+
"Image JSON output cannot be used as a subsequent input")
|
|
99
|
+
raster = {"mime": "png", "width": 1, "height": 1, "bytes": ""}
|
|
100
|
+
check(call([str(entrypoint)], "signature_size", {"image": raster, "height_pt": 10**400}) is None,
|
|
101
|
+
"An unrepresentable height escaped the JSON bridge")
|
|
102
|
+
check(call([str(entrypoint)], "signature_size", {"image": raster, "height_pt": 20, "max_width_pt": 10**400}) is None,
|
|
103
|
+
"An unrepresentable maximum width escaped the JSON bridge")
|
|
104
|
+
print(f"Python {NAME}: installed module, console JSON calls, wheel/sdist licenses and metadata passed")
|