-
Notifications
You must be signed in to change notification settings - Fork 5
/
wheelfile.py
2445 lines (1978 loc) · 89.5 KB
/
wheelfile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2020-2021 Blazej Michalik
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""API for handling ".whl" files.
Use :class:`WheelFile` to create or read a wheel.
Managing metadata is done via `metadata`, `wheeldata`, and `record` attributes.
See :class:`MetaData`, :class:`WheelData`, and :class:`WheelRecord` for
documentation of the objects returned by these attributes.
Example
-------
Here's how to create a simple package under a specific directory path::
with WheelFile('path/to/directory/', mode='w'
distname="mywheel", version="1") as wf:
wf.write('path/to/a/module.py', arcname="mywheel.py")
"""
import base64
import csv
import hashlib
import io
import os
import warnings
import zipfile
from collections import namedtuple
from email import message_from_string
from email.message import EmailMessage
from email.policy import EmailPolicy
from inspect import signature
from pathlib import Path
from string import ascii_letters, digits
from typing import IO, BinaryIO, Dict, List, Optional, Union
from packaging.tags import parse_tag
from packaging.utils import canonicalize_name
from packaging.version import InvalidVersion, Version
__version__ = "0.0.9"
# TODO: ensure that writing into `file` arcname and then into `file/not/really`
# fails.
# TODO: the file-directory confusion should also be checked on the WheelRecord
# level, and inside WheelFile.validate()
# TODO: idea: Corrupted class: denotes that something is present, but could not
# be parsed. Would take a type and contents to parse, compare falsely to
# the objects of given type, and not compare with anything else.
# Validate would raise errors with messages about parsing if it finds something
# corrupted, and about missing file otherwise.
# TODO: change AssertionErrors to custom exceptions?
# TODO: idea - install wheel - w/ INSTALLER file
# TODO: idea - wheel from an installed distribution?
# TODO: fix inconsistent referencing style of symbols in docstrings
# TODO: parameters for path-like values should accept bytes
# TODO: idea - wheeldata -> wheelinfo, but it contradicts the idea below
# TODO: idea - might be better to provide WheelInfo objects via a getinfo(),
# which would inherit from ZipInfo but also cointain the hash from the RECORD.
# It would simplify the whole implementation.
# TODO: fix usage of UnnamedDistributionError and ValueError - it is ambiguous
def _slots_from_params(func):
"""List out slot names based on the names of parameters of func
Usage: __slots__ = _slots_from_signature(__init__)
"""
funcsig = signature(func)
slots = list(funcsig.parameters)
slots.remove("self")
return slots
def _clone_zipinfo(zinfo: zipfile.ZipInfo, **to_replace) -> zipfile.ZipInfo:
"""Clone a ZipInfo object and update its attributes using to_replace."""
PRESERVED_ZIPINFO_ATTRS = [
"date_time",
"compress_type",
"_compresslevel",
"comment",
"extra",
"create_system",
"create_version",
"extract_version",
"volume",
"internal_attr",
"external_attr",
]
# `orig_filename` instead of `filename` is used to prevent any possibility
# of confusing ZipInfo filename normalization.
new_name = zinfo.orig_filename
if "filename" in to_replace:
new_name = to_replace["filename"]
del to_replace["filename"]
new_zinfo = zipfile.ZipInfo(filename=new_name)
for attr in PRESERVED_ZIPINFO_ATTRS:
replaced = to_replace.get(attr)
if replaced is not None:
setattr(new_zinfo, attr, replaced)
else:
setattr(new_zinfo, attr, getattr(zinfo, attr))
return new_zinfo
# TODO: accept packaging.requirements.Requirement in requires_dist, fix this in
# example, ensure such objects are converted on __str__
# TODO: reimplement using dataclasses
# TODO: add version to the class name, reword the "Note"
# name regex for validation: ^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$
# TODO: helper-function or consts for description_content_type
# TODO: parse version using packaging.version.parse?
# TODO: values validation
# TODO: validate provides_extras ↔ requires_dists?
# TODO: validate values charset-wise
# TODO: ensure name is the same as wheelfile namepath
# TODO: PEP-643 - v2.2
# TODO: don't raise invalid version, assign a degenerated version object instead
class MetaData:
"""Implements Wheel Metadata format v2.1.
Descriptions of parameters based on
https://packaging.python.org/specifications/core-metadata/. All parameters
are keyword only. Attributes of objects of this class follow parameter
names.
All parameters except "name" and "version" are optional.
Note
----
Metadata-Version, the metadata format version specifier, is unchangable.
Version "2.1" is used.
Parameters
----------
name
Primary identifier for the distribution that uses this metadata. Must
start and end with a letter or number, and consists only of ASCII
alphanumerics, hyphen, underscore, and period.
version
A string that contains PEP-440 compatible version identifier.
Can be specified using packaging.version.Version object, or a string,
where the latter is always converted to the former.
summary
A one-line sentence describing this distribution.
description
Longer text that describes this distribution in detail. Can be written
using plaintext, reStructuredText, or Markdown (see
"description_content_type" parameter below).
The string given for this field should not include RFC 822 indentation
followed by a "|" symbol. Newline characters are permitted
description_content_type
Defines content format of the text put in the "description" argument.
The field value should follow the following structure:
<type/subtype>; charset=<charset>[; <param_name>=<param value> ...]
Valid type/subtype strings are:
- text/plain
- text/x-rst
- text/markdown
For charset parameter, the only legal value is UTF-8.
For text/markdown, parameter "variant=<variant>" specifies variant of
the markdown used. Currently recognized variants include "GFM" and
"CommonMark".
Examples:
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Description-Content-Type: text/markdown
keywords
List of search keywords for this distribution. Optionally a single
string literal with keywords separated by commas.
Note: despite the name being a plural noun, the specification defines
this field as a single-use field. In this implementation however, the
value of the attribute after instance initialization is a list of
strings, and conversions to and from string follow the spec - they
require a comma-separated list.
classifiers
List PEP-301 classification values for this distribution, optionally
followed by a semicolon and an environmental marker.
Example of a classifier:
Operating System :: Microsoft :: Windows :: Windows 10
author
Name and, optionally, contact information of the original author of the
distribution.
author_email
Email address of the person specified in the "author" parameter. Format
of this field must follow the format of RFC-822 "From:" header field.
maintainer
Name and, optionally, contact information of person currently
maintaining the project to which this distribution belongs to.
Omit this parameter if the author and current maintainer is the same
person.
maintainer_email
Email address of the person specified in the "maintainer" parameter.
Format of this field must follow the format of RFC-822 "From:" header
field.
Omit this parameter if the author and current maintainer is the same
person.
license
Text of the license that covers this distribution. If license
classifier is used, this parameter may be omitted or used to specify the
particular version of the intended legal text.
home_page
URL of the home page for this distribution (project).
download_url
URL from which this distribution (in this version) can be downloaded.
project_urls
List of URLs with labels for them, in the following format:
<label>, <url>
The label must be at most 32 characters.
Example of an item of this list:
Repository, https://github.com/MrMino/wheelfile
platforms
List of strings that signify supported operating systems. Use only if
an OS cannot be listed by using a classifier.
supported_platforms
In binary distributions list of strings, each defining an operating
system and a CPU for which the distribution was compiled.
Semantics of this field aren't formalized by metadata specifications.
requires_python
PEP-440 version identifier, that specifies the set Python language
versions that this distribution is compatible with.
Some package management tools (most notably pip) use the value of this
field to filter out installation candidates.
Example:
~=3.5,!=3.5.1,!=3.5.0
requires_dists
List of PEP-508 dependency specifiers (think line-split contents of
requirements.txt).
requires_externals
List of system dependencies that this distribution requires.
Each item is a string with a name of the dependency optionally followed
by a version (in the same way items in "requires_dists") are specified.
Each item may end with a semicolon followed by a PEP-496 environment
markers.
provides_extras
List of names of optional features provided by a distribution. Used to
specify which dependencies should be installed depending on which of
these optional features are requested.
For example, if you specified "network" and "ssh" as optional features,
the following requirement specifier can be used in "requires_externals"
list to indicate, that the "paramiko" dependency should only be
installed when "ssh" feature is requested:
paramiko; extra == "ssh"
or
paramiko[ssh]
If a dependency is required by multiple features, the features can be
specified in a square brackets, separated by commas:
ipython[repl, jupyter_kernel]
Specifying an optional feature without using it in "requires_externals"
is considered invalid.
Feature names "tests" and "doc" are reserved in their semantics. They
can be used for dependencies of automated testing or documentation
generation.
provides_dists
List of names of other distributions contained within this one. Each
entry must follow the same format that entries in "requires_dists" list
do.
Different distributions may use a name that does not correspond to any
particular project, to indicate a capability to provide a certain
feature, e.g. "relational_db" may be used to say that a project
provides relational database capabilities
obsoletes_dists
List of names of distributions obsoleted by installing this one,
indicating that they should not coexist in a single environment with
this one. Each entry must follow the same format that entries in
"requires_dists" list do.
"""
def __init__(
self,
*,
name: str,
version: Union[str, Version],
summary: Optional[str] = None,
description: Optional[str] = None,
description_content_type: Optional[str] = None,
keywords: Union[List[str], str, None] = None,
classifiers: Optional[List[str]] = None,
author: Optional[str] = None,
author_email: Optional[str] = None,
maintainer: Optional[str] = None,
maintainer_email: Optional[str] = None,
license: Optional[str] = None,
home_page: Optional[str] = None,
download_url: Optional[str] = None,
project_urls: Optional[List[str]] = None,
platforms: Optional[List[str]] = None,
supported_platforms: Optional[List[str]] = None,
requires_python: Optional[str] = None,
requires_dists: Optional[List[str]] = None,
requires_externals: Optional[List[str]] = None,
provides_extras: Optional[List[str]] = None,
provides_dists: Optional[List[str]] = None,
obsoletes_dists: Optional[List[str]] = None,
):
# self.metadata_version = '2.1' by property
self.name = name
self.version = Version(version) if isinstance(version, str) else version
self.summary = summary
self.description = description
self.description_content_type = description_content_type
if keywords is None:
keywords = []
self.keywords = keywords if isinstance(keywords, list) else keywords.split(",")
self.classifiers = classifiers or []
self.author = author
self.author_email = author_email
self.maintainer = maintainer
self.maintainer_email = maintainer_email
self.license = license
self.home_page = home_page
self.download_url = download_url
self.project_urls = project_urls or []
self.platforms = platforms or []
self.supported_platforms = supported_platforms or []
self.requires_python = requires_python
self.requires_dists = requires_dists or []
self.requires_externals = requires_externals or []
self.provides_extras = provides_extras or []
self.provides_dists = provides_dists or []
self.obsoletes_dists = obsoletes_dists or []
__slots__ = _slots_from_params(__init__)
@property
def metadata_version(self):
return self._metadata_version
_metadata_version = "2.1"
@classmethod
def field_is_multiple_use(cls, field_name: str) -> bool:
field_name = field_name.lower().replace("-", "_").rstrip("s")
if field_name in cls.__slots__ or field_name == "keyword":
return False
if field_name + "s" in cls.__slots__:
return True
else:
raise ValueError(f"Unknown field: {repr(field_name)}.")
@classmethod
def _field_name(cls, attribute_name: str) -> str:
if cls.field_is_multiple_use(attribute_name):
attribute_name = attribute_name[:-1]
field_name = attribute_name.title()
field_name = field_name.replace("_", "-")
field_name = field_name.replace("Url", "URL")
field_name = field_name.replace("-Page", "-page")
field_name = field_name.replace("-Email", "-email")
return field_name
@classmethod
def _attr_name(cls, field_name: str) -> str:
if cls.field_is_multiple_use(field_name):
field_name += "s"
return field_name.lower().replace("-", "_")
def __str__(self) -> str:
m = EmailMessage(EmailPolicy(max_line_length=None))
m.add_header("Metadata-Version", self.metadata_version)
for attr_name in self.__slots__:
content = getattr(self, attr_name)
if not content:
continue
field_name = self._field_name(attr_name)
if field_name == "Keywords":
content = ",".join(content)
elif field_name == "Version":
content = str(content)
if self.field_is_multiple_use(field_name):
assert not isinstance(
content, str
), f"Single string in multiple use attribute: {attr_name}"
for value in content:
m.add_header(field_name, value)
elif field_name == "Description":
m.set_payload(content)
else:
assert isinstance(
content, str
), f"Expected string, got {type(content)} instead: {attr_name}"
m.add_header(field_name, content)
return str(m)
def __eq__(self, other):
if isinstance(other, MetaData):
# Having None as a description is the same as having an empty string
# in it. The former is put there by having an Optional[str]
# argument, the latter is there due to semantics of email-style
# parsing.
# Ensure these two values compare equally in the description.
mine = "" if self.description is None else self.description
theirs = "" if other.description is None else other.description
descriptions_equal = mine == theirs
return (
all(
getattr(self, field) == getattr(other, field)
for field in self.__slots__
if field != "description"
)
and descriptions_equal
)
else:
return NotImplemented
@classmethod
def from_str(cls, s: str) -> "MetaData":
m = message_from_string(s)
# TODO: validate this when the rest of the versions are implemented
# assert m['Metadata-Version'] == cls._metadata_version
del m["Metadata-Version"]
args = {}
for field_name in m.keys():
attr = cls._attr_name(field_name)
if not attr.endswith("s"):
args[attr] = m.get(field_name)
else:
if field_name == "Keywords":
args[attr] = m.get(field_name).split(",")
else:
args[attr] = m.get_all(field_name)
args["description"] = m.get_payload()
return cls(**args)
# TODO: reimplement using dataclasses?
# TODO: add version to the class name, reword the "Note"
# TODO: values validation
class WheelData:
"""Implements .dist-info/WHEEL file format.
Descriptions of parameters based on PEP-427. All parameters are keyword
only. Attributes of objects of this class follow parameter names.
Note
----
Wheel-Version, the wheel format version specifier, is unchangeable. Version
"1.0" is used.
Parameters
----------
generator
Name and (optionally) version of the generator that generated the wheel
file. By default, "wheelfile {__version__}" is used.
root_is_purelib
Defines whether the root of the wheel file should be first unpacked into
purelib directory (see distutils.command.install.INSTALL_SCHEMES).
tags
See PEP-425 - "Compatibility Tags for Built Distributions". Either a
single string denoting one tag or a list of tags. Tags may contain
compressed tag sets, in which case they will be expanded.
By default, "py3-none-any" is used.
build
Optional build number. Used as a tie breaker when two wheels have the
same version.
"""
def __init__(
self,
*,
generator: str = "wheelfile " + __version__,
root_is_purelib: bool = True,
tags: Union[List[str], str] = "py3-none-any",
build: Optional[int] = None,
):
# self.wheel_version = '1.0' by property
self.generator = generator
self.root_is_purelib = root_is_purelib
self.tags = self._extend_tags(tags if isinstance(tags, list) else [tags])
self.build = build
__slots__ = _slots_from_params(__init__)
@property
def wheel_version(self) -> str:
return "1.0"
def _extend_tags(self, tags: List[str]) -> List[str]:
extended_tags = []
for tag in tags:
extended_tags.extend([str(t) for t in parse_tag(tag)])
return extended_tags
def __str__(self) -> str:
# TODO Custom exception? Exception message?
assert isinstance(
self.generator, str
), f"'generator' must be a string, got {type(self.generator)} instead"
assert isinstance(self.root_is_purelib, bool), (
f"'root_is_purelib' must be a boolean, got"
f"{type(self.root_is_purelib)} instead"
)
assert isinstance(
self.tags, list
), f"Expected a list in 'tags', got {type(self.tags)} instead"
assert self.tags, "'tags' cannot be empty"
assert (
isinstance(self.build, int) or self.build is None
), f"'build' must be an int, got {type(self.build)} instead"
m = EmailMessage()
m.add_header("Wheel-Version", self.wheel_version)
m.add_header("Generator", self.generator)
m.add_header("Root-Is-Purelib", "true" if self.root_is_purelib else "false")
for tag in self.tags:
m.add_header("Tag", tag)
if self.build is not None:
m.add_header("Build", str(self.build))
return str(m)
@classmethod
def from_str(cls, s: str) -> "WheelData":
m = message_from_string(s)
assert m["Wheel-Version"] == "1.0"
args = {
"generator": m.get("Generator"),
"root_is_purelib": bool(m.get("Root-Is-Purelib")),
"tags": m.get_all("Tag"),
}
if "build" in m:
args["build"] = int(m.get("build"))
return cls(**args)
def __eq__(self, other):
if isinstance(other, WheelData):
return all(getattr(self, f) == getattr(other, f) for f in self.__slots__)
else:
return NotImplemented
# TODO: add_entry method, that raises if entry for a path already exists
# TODO: leave out hashes of *.pyc files?
class WheelRecord:
"""Contains logic for creation and modification of RECORD files.
Keeps track of files in the wheel and their hashes.
For the full spec, see PEP-376 "RECORD" section, PEP-627,
"The .dist-info directory" section of PEP-427, and
https://packaging.python.org/specifications/recording-installed-packages/.
"""
HASH_BUF_SIZE = 65536
_RecordEntry = namedtuple("_RecordEntry", "path hash size")
def __init__(self, hash_algo: str = "sha256"):
self._records: Dict[str, WheelRecord._RecordEntry] = {}
self._hash_algo = ""
self.hash_algo = hash_algo
@property
def hash_algo(self) -> str:
"""Hash algorithm to use to generate RECORD file entries"""
return self._hash_algo
@hash_algo.setter
def hash_algo(self, value: str):
# per PEP-376
if value not in hashlib.algorithms_guaranteed:
raise UnsupportedHashTypeError(f"{repr(value)} is not a valid record hash.")
# per PEP 427
if value in ("md5", "sha1"):
raise UnsupportedHashTypeError(f"{repr(value)} is a forbidden hash type.")
# PEP-427 says the RECORD hash must be sha256 or better. Does that mean
# hashes such as sha224 are forbidden as well though not specifically
# called out?
self._hash_algo = value
def hash_of(self, arcpath) -> str:
"""Return the hash of a file in the archive this RECORD describes
Parameters
----------
arcpath
Location of the file inside the archive.
Returns
-------
str
String in the form <algorithm>=<base64_str>, where algorithm is the
name of the hashing agorithm used to generate the hash (see
hash_algo), and base64_str is a string containing a base64 encoded
version of the hash with any trailing '=' removed.
"""
return self._records[arcpath].hash
def __str__(self) -> str:
buf = io.StringIO()
records = csv.DictWriter(buf, fieldnames=self._RecordEntry._fields)
for entry in self._records.values():
records.writerow(entry._asdict())
return buf.getvalue()
@classmethod
def from_str(cls, s) -> "WheelRecord":
record = WheelRecord()
buf = io.StringIO(s)
reader = csv.DictReader(buf, cls._RecordEntry._fields)
for row in reader:
entry = cls._RecordEntry(**row)
if entry.path.endswith("/"):
raise RecordContainsDirectoryError(
"RECORD of this wheel contains an entry with for a "
"directory: {repr(entry.path)}."
)
record._records[entry.path] = entry
return record
def update(self, arcpath: str, buf: IO[bytes]):
"""Add a record entry for a file in the archive.
Parameters
----------
arcpath
Path in the archive of the file that the entry describes.
buf
Buffer from which the data will be read in HASH_BUF_SIZE chunks.
Must be fresh, i.e. seek(0)-ed.
Raises
------
RecordContainsDirectoryError
If ``arcpath`` is a path to a directory.
"""
assert buf.tell() == 0, f"Stale buffer given - current position: {buf.tell()}."
# if .dist-info/RECORD is not in a subdirectory, it is not allowed
assert "/" in arcpath.replace(".dist-info/RECORD", "") or not arcpath.endswith(
".dist-info/RECORD"
), (
f"Attempt to add an entry for a RECORD file to the RECORD: "
f"{repr(arcpath)}."
)
if arcpath.endswith("/"):
raise RecordContainsDirectoryError(
f"Attempt to add an entry for a directory: {repr(arcpath)}"
)
self._records[arcpath] = self._entry(arcpath, buf)
def remove(self, arcpath: str):
del self._records[arcpath]
def _entry(self, arcpath: str, buf: IO[bytes]) -> _RecordEntry:
size = 0
hasher = getattr(hashlib, self.hash_algo)()
while True:
data = buf.read(self.HASH_BUF_SIZE)
size += len(data)
if not data:
break
hasher.update(data)
hash_entry = f"{hasher.name}={self._hash_encoder(hasher.digest())}"
return self._RecordEntry(arcpath, hash_entry, size)
@staticmethod
def _hash_encoder(data: bytes) -> str:
"""
Encode a file hash per PEP 376 spec
From the spec:
The hash is either the empty string or the hash algorithm as named in
hashlib.algorithms_guaranteed, followed by the equals character =,
followed by the urlsafe-base64-nopad encoding of the digest
(base64.urlsafe_b64encode(digest) with trailing = removed).
"""
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def __eq__(self, other):
if isinstance(other, WheelRecord):
return str(self) == str(other)
else:
return NotImplemented
def __contains__(self, path):
return path in self._records
class UnsupportedHashTypeError(ValueError):
"""The given hash name is not allowed by the spec."""
class RecordContainsDirectoryError(ValueError):
"""Record contains an entry path that ends with a slash (a directory)."""
class BadWheelFileError(ValueError):
"""The given file cannot be interpreted as a wheel nor fixed."""
class UnnamedDistributionError(BadWheelFileError):
"""Distribution name cannot be deduced from arguments."""
class ProhibitedWriteError(ValueError):
"""Writing into given arcname would result in a corrupted package."""
def resolved(path: Union[str, Path]) -> str:
"""Get the name of the file or directory the path points to.
This is a convenience function over the functionality provided by
`resolve` argument of `WheelFile.write` and similar methods. Since
`resolve=True` is ignored when `arcname` is given, it is impossible to add
arbitrary prefix to `arcname` without resolving the path first - and this
is what this function provides.
Using this, you can have both custom `arcname` prefix and the "resolve"
functionality, like so::
wf = WheelFile(...)
wf.write(some_path, arcname="arc/dir/" + resolved(some_path))
Parameters
----------
path
Path to resolve.
Returns
-------
str
The name of the file or directory the `path` points to.
"""
return os.path.basename(os.path.abspath(path))
# TODO: read
# TODO: read_distinfo
# TODO: read_data
# TODO: prevent arbitrary writes to METADATA, WHEEL, and RECORD - or make sure
# the writes are reflected internally
# TODO: prevent adding .dist-info directories if there's one already there
# TODO: ensure distname and varsion have no weird characters (!slashes!)
# TODO: debug propery, as with ZipFile.debug
# TODO: comment property
# TODO: append mode
# TODO: writing inexistent metadata in lazy mode
# TODO: better repr
# TODO: comparison operators for comparing version + build number
class WheelFile:
"""An archive that follows the wheel specification.
Used to read, create, validate, or modify `.whl` files.
Can be used as a context manager, in which case `close()` is called upon
exiting the context.
Attributes
----------
filename : str
Depending on what the class was initialized with, this attribute is either:
- If initialized with an IO buffer: the filename that the wheel
would have after saving it onto filesystem, considering other
parameters given to `__init__`: `distname`, `version`,
`build_tag`, `language_tag`, `abi_tag` and `platform_tag`.
- If initialized with a path to a directory: the path to the wheel
composed from the given path, and the filename that was generated
using other parameters given to `__init__`.
- A path to a file: that path, even if it is not compliant with the
spec (in lazy mode).
**Returned path is not resolved, and so might be relative and/or
contain `../` and `./` segments**.
distname : str
Name of the distribution (project). Either given to __init__()
explicitly or inferred from its file_or_path argument.
version : packaging.version.Version
Version of the distribution. Either given to __init__() explicitly or
inferred from its file_or_path argument.
build_tag : Optional[int]
Distribution's build number. Either given to __init__() explicitly or
inferred from its file_or_path argument, otherwise `None` in lazy mode.
language_tag : str
Interpretter implementation compatibility specifier. See PEP-425 for
the full specification. Either given to __init__() explicitly or
inferred from its file_or_path argument otherwise an empty string in
lazy mode.
abi_tag : str
ABI compatibility specifier. See PEP-425 for the full specification.
Either given to __init__() explicitly or inferred from its file_or_path
argument, otherwise an empty string in lazy mode.
platform_tag : str
Platform compatibility specifier. See PEP-425 for the full
specification. Either given to __init__() explicitly or inferred from
its file_or_path argument, otherwise an empty string in lazy mode.
record : Optional[WheelRecord]
Current state of .dist-info/RECORD file.
When reading wheels in lazy mode, if the file does not exist or is
misformatted, this attribute becomes None.
In non-lazy modes this file is always read & validated on
initialization.
In write and exclusive-write modes, written to the archive on close().
metadata : Optional[MetaData]
Current state of .dist-info/METADATA file.
Values from `distname` and `version` are used to provide required
arguments when the file is created from scratch by `__init__()`.
When reading wheels in lazy mode, if the file does not exist or is
misformatted, this attribute becomes None.
In non-lazy modes this file is always read & validated on
initialization.
In write and exclusive-write modes, written to the archive on close().
wheeldata : Optional[WheelData]
Current state of .dist-info/WHEELDATA file.
Values from `build_tag`, `language_tag`, `abi_tag`, `platform_tag`, or
their substitutes inferred from the filename are used to initialize
this object.
When reading wheels in lazy mode, if the file does not exist or is
misformatted, this attribute becomes None.
In non-lazy modes this file is always read & validated on
initialization.
In write and exclusive-write modes, written to the archive on close().
distinfo_dirname
Name of the ``.dist-info`` directory inside the archive wheel,
without the trailing slash.
data_dirname
Name of the ``.data`` directory inside the archive wheel, without
the trailing slash.
closed : bool
True if the underlying `ZipFile` object is closed, false otherwise.
"""
VALID_DISTNAME_CHARS = set(ascii_letters + digits + "._")
METADATA_FILENAMES = {"WHEEL", "METADATA", "RECORD"}
# TODO: implement lazy mode
# TODO: in lazy mode, log reading/missing metadata errors
# TODO: warn on 'w' modes if filename does not end with .whl
def __init__(
self,
file_or_path: Union[str, Path, BinaryIO] = "./",
mode: str = "r",
*,
distname: Optional[str] = None,
version: Optional[Union[str, Version]] = None,
build_tag: Optional[Union[int, str]] = None,
language_tag: Optional[str] = None,
abi_tag: Optional[str] = None,
platform_tag: Optional[str] = None,
compression: int = zipfile.ZIP_DEFLATED,
allowZip64: bool = True,
compresslevel: Optional[int] = None,
strict_timestamps: bool = True,
) -> None:
# FIXME: Validation does not fail if filename differs from generated
# filename, yet it validates the extension
"""Open or create a wheel file.
In write and exclusive-write modes, if `file_or_path` is not specified,
it is assumed to be the current directory. If the specified path is a
directory, the wheelfile will be created inside it, with filename
generated using the values given via `distname`, `version`,
`build_tag`, `language_tag`, `abi_tag`, and `platfrom_tag` arguments.
Each of these parameters is stored in a read-only property of the same
name.
If `file_or_path` is a path to a file, the wheel will be created
under the specified path.
If lazy mode is not specified:
- In read and append modes, the file is validated using validate().
Contents of metadata files inside .dist-info directory are read
and converted into their respective object representations (see
"metadata", "wheeldata", and "record" attributes).
- In write and exclusive-write modes, object representations for
each metadata file are created from scratch. They will be written
to each of their respective .dist-info/ files on close().