blob: e0ecb655b93fafaeaad82062591e055219921f7d [file] [log] [blame]
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -04001"""
2distutils.command.upload
Martin v. Löwis55f1bb82005-03-21 20:56:35 +00003
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -04004Implements the Distutils 'upload' subcommand (upload package to a package
5index).
6"""
Martin v. Löwis98858c92005-03-21 21:00:59 +00007
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -04008import os
9import io
Jason R. Coombsa3846522014-05-10 13:22:43 -040010import hashlib
Tarek Ziadé36797272010-07-22 12:50:05 +000011from base64 import standard_b64encode
Miss Islington (bot)60982142021-05-11 16:18:13 -070012from urllib.error import HTTPError
13from urllib.request import urlopen, Request
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050014from urllib.parse import urlparse
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -040015from distutils.errors import DistutilsError, DistutilsOptionError
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -040016from distutils.core import PyPIRCCommand
17from distutils.spawn import spawn
18from distutils import log
Tarek Ziadé36797272010-07-22 12:50:05 +000019
Christian Heimese572c7f2020-05-20 16:37:25 +020020
21# PyPI Warehouse supports MD5, SHA256, and Blake2 (blake2-256)
22# https://bugs.python.org/issue40698
23_FILE_CONTENT_DIGESTS = {
24 "md5_digest": getattr(hashlib, "md5", None),
25 "sha256_digest": getattr(hashlib, "sha256", None),
26 "blake2_256_digest": getattr(hashlib, "blake2b", None),
27}
28
29
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000030class upload(PyPIRCCommand):
Martin v. Löwis98858c92005-03-21 21:00:59 +000031
32 description = "upload binary package to PyPI"
33
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000034 user_options = PyPIRCCommand.user_options + [
Martin v. Löwisf74b9232005-03-22 15:51:14 +000035 ('sign', 's',
36 'sign files to upload using gpg'),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000037 ('identity=', 'i', 'GPG identity used to sign files'),
Martin v. Löwis98858c92005-03-21 21:00:59 +000038 ]
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000039
40 boolean_options = PyPIRCCommand.boolean_options + ['sign']
Martin v. Löwis98858c92005-03-21 21:00:59 +000041
42 def initialize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000043 PyPIRCCommand.initialize_options(self)
Martin v. Löwis98858c92005-03-21 21:00:59 +000044 self.username = ''
45 self.password = ''
Martin v. Löwis98858c92005-03-21 21:00:59 +000046 self.show_response = 0
Martin v. Löwisf74b9232005-03-22 15:51:14 +000047 self.sign = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048 self.identity = None
Martin v. Löwis98858c92005-03-21 21:00:59 +000049
50 def finalize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000051 PyPIRCCommand.finalize_options(self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052 if self.identity and not self.sign:
53 raise DistutilsOptionError(
54 "Must use --sign for --identity to have meaning"
55 )
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000056 config = self._read_pypirc()
57 if config != {}:
58 self.username = config['username']
59 self.password = config['password']
60 self.repository = config['repository']
61 self.realm = config['realm']
Martin v. Löwis98858c92005-03-21 21:00:59 +000062
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +000063 # getting the password from the distribution
64 # if previously set by the register command
65 if not self.password and self.distribution.password:
66 self.password = self.distribution.password
67
Martin v. Löwis98858c92005-03-21 21:00:59 +000068 def run(self):
69 if not self.distribution.dist_files:
Éric Araujo08a69262018-02-18 18:14:54 -050070 msg = ("Must create and upload files in one command "
71 "(e.g. setup.py sdist upload)")
Jason R. Coombs09122f82014-05-10 13:24:58 -040072 raise DistutilsOptionError(msg)
Martin v. Löwis98da5622005-03-23 18:54:36 +000073 for command, pyversion, filename in self.distribution.dist_files:
74 self.upload_file(command, pyversion, filename)
Martin v. Löwis98858c92005-03-21 21:00:59 +000075
Martin v. Löwis98da5622005-03-23 18:54:36 +000076 def upload_file(self, command, pyversion, filename):
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050077 # Makes sure the repository URL is compliant
78 schema, netloc, url, params, query, fragments = \
79 urlparse(self.repository)
80 if params or query or fragments:
81 raise AssertionError("Incompatible url %s" % self.repository)
82
83 if schema not in ('http', 'https'):
84 raise AssertionError("unsupported schema " + schema)
85
Martin v. Löwisf74b9232005-03-22 15:51:14 +000086 # Sign if requested
87 if self.sign:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088 gpg_args = ["gpg", "--detach-sign", "-a", filename]
89 if self.identity:
90 gpg_args[2:2] = ["--local-user", self.identity]
91 spawn(gpg_args,
Martin v. Löwisf74b9232005-03-22 15:51:14 +000092 dry_run=self.dry_run)
Martin v. Löwis98858c92005-03-21 21:00:59 +000093
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000094 # Fill in the data - send all the meta-data in case we need to
95 # register a new release
Éric Araujobee5cef2010-11-05 23:51:56 +000096 f = open(filename,'rb')
97 try:
98 content = f.read()
99 finally:
100 f.close()
Christian Heimese572c7f2020-05-20 16:37:25 +0200101
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000102 meta = self.distribution.metadata
Martin v. Löwis98858c92005-03-21 21:00:59 +0000103 data = {
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000104 # action
105 ':action': 'file_upload',
Berker Peksag56fe4742016-06-18 21:42:37 +0300106 'protocol_version': '1',
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000107
108 # identify release
109 'name': meta.get_name(),
110 'version': meta.get_version(),
111
112 # file content
113 'content': (os.path.basename(filename),content),
114 'filetype': command,
115 'pyversion': pyversion,
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000116
117 # additional meta-data
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400118 'metadata_version': '1.0',
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000119 'summary': meta.get_description(),
120 'home_page': meta.get_url(),
121 'author': meta.get_contact(),
122 'author_email': meta.get_contact_email(),
123 'license': meta.get_licence(),
124 'description': meta.get_long_description(),
125 'keywords': meta.get_keywords(),
126 'platform': meta.get_platforms(),
127 'classifiers': meta.get_classifiers(),
128 'download_url': meta.get_download_url(),
129 # PEP 314
130 'provides': meta.get_provides(),
131 'requires': meta.get_requires(),
132 'obsoletes': meta.get_obsoletes(),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000133 }
Paul Ganssle4e80f5c2018-12-17 02:59:02 -0500134
135 data['comment'] = ''
Martin v. Löwis98858c92005-03-21 21:00:59 +0000136
Christian Heimese572c7f2020-05-20 16:37:25 +0200137 # file content digests
138 for digest_name, digest_cons in _FILE_CONTENT_DIGESTS.items():
139 if digest_cons is None:
140 continue
141 try:
142 data[digest_name] = digest_cons(content).hexdigest()
143 except ValueError:
144 # hash digest not available or blocked by security policy
145 pass
146
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000147 if self.sign:
Mickaël Schoentgen58721a92019-04-08 13:08:48 +0000148 with open(filename + ".asc", "rb") as f:
149 data['gpg_signature'] = (os.path.basename(filename) + ".asc",
150 f.read())
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000151
Martin v. Löwis98858c92005-03-21 21:00:59 +0000152 # set up the authentication
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000153 user_pass = (self.username + ":" + self.password).encode('ascii')
154 # The exact encoding of the authentication string is debated.
155 # Anyway PyPI only accepts ascii for both username or password.
Tarek Ziadé8b9361a2009-12-21 00:02:20 +0000156 auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000157
158 # Build up the MIME payload for the POST data
159 boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
R David Murray9ce69672014-09-27 16:56:15 -0400160 sep_boundary = b'\r\n--' + boundary.encode('ascii')
161 end_boundary = sep_boundary + b'--\r\n'
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000162 body = io.BytesIO()
Martin v. Löwis98858c92005-03-21 21:00:59 +0000163 for key, value in data.items():
R David Murray9ce69672014-09-27 16:56:15 -0400164 title = '\r\nContent-Disposition: form-data; name="%s"' % key
Martin v. Löwis98858c92005-03-21 21:00:59 +0000165 # handle multiple entries for the same name
Jason R. Coombs03756532014-05-10 13:24:18 -0400166 if not isinstance(value, list):
Martin v. Löwis98858c92005-03-21 21:00:59 +0000167 value = [value]
168 for value in value:
Tarek Ziadé36797272010-07-22 12:50:05 +0000169 if type(value) is tuple:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000170 title += '; filename="%s"' % value[0]
Martin v. Löwis98858c92005-03-21 21:00:59 +0000171 value = value[1]
172 else:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000173 value = str(value).encode('utf-8')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000174 body.write(sep_boundary)
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000175 body.write(title.encode('utf-8'))
R David Murray9ce69672014-09-27 16:56:15 -0400176 body.write(b"\r\n\r\n")
Martin v. Löwis98858c92005-03-21 21:00:59 +0000177 body.write(value)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000178 body.write(end_boundary)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000179 body = body.getvalue()
180
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400181 msg = "Submitting %s to %s" % (filename, self.repository)
182 self.announce(msg, log.INFO)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000183
184 # build the Request
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400185 headers = {
186 'Content-type': 'multipart/form-data; boundary=%s' % boundary,
187 'Content-length': str(len(body)),
188 'Authorization': auth,
189 }
Martin v. Löwis98858c92005-03-21 21:00:59 +0000190
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500191 request = Request(self.repository, data=body,
192 headers=headers)
193 # send the data
Martin v. Löwis98858c92005-03-21 21:00:59 +0000194 try:
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500195 result = urlopen(request)
196 status = result.getcode()
197 reason = result.msg
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500198 except HTTPError as e:
199 status = e.code
200 reason = e.msg
Berker Peksag6a8e6262016-06-02 13:45:53 -0700201 except OSError as e:
202 self.announce(str(e), log.ERROR)
203 raise
Martin v. Löwis98858c92005-03-21 21:00:59 +0000204
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500205 if status == 200:
206 self.announce('Server response (%s): %s' % (status, reason),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000207 log.INFO)
Berker Peksag6a8e6262016-06-02 13:45:53 -0700208 if self.show_response:
209 text = self._read_pypi_response(result)
210 msg = '\n'.join(('-' * 75, text, '-' * 75))
211 self.announce(msg, log.INFO)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000212 else:
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -0400213 msg = 'Upload failed (%s): %s' % (status, reason)
214 self.announce(msg, log.ERROR)
215 raise DistutilsError(msg)