blob: 95e9fda186fc8f5b884215f7bea251b515e72cae [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
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050012from urllib.request import urlopen, Request, HTTPError
13from urllib.parse import urlparse
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -040014from distutils.errors import DistutilsError, DistutilsOptionError
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -040015from distutils.core import PyPIRCCommand
16from distutils.spawn import spawn
17from distutils import log
Tarek Ziadé36797272010-07-22 12:50:05 +000018
Christian Heimese572c7f2020-05-20 16:37:25 +020019
20# PyPI Warehouse supports MD5, SHA256, and Blake2 (blake2-256)
21# https://bugs.python.org/issue40698
22_FILE_CONTENT_DIGESTS = {
23 "md5_digest": getattr(hashlib, "md5", None),
24 "sha256_digest": getattr(hashlib, "sha256", None),
25 "blake2_256_digest": getattr(hashlib, "blake2b", None),
26}
27
28
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000029class upload(PyPIRCCommand):
Martin v. Löwis98858c92005-03-21 21:00:59 +000030
31 description = "upload binary package to PyPI"
32
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000033 user_options = PyPIRCCommand.user_options + [
Martin v. Löwisf74b9232005-03-22 15:51:14 +000034 ('sign', 's',
35 'sign files to upload using gpg'),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000036 ('identity=', 'i', 'GPG identity used to sign files'),
Martin v. Löwis98858c92005-03-21 21:00:59 +000037 ]
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000038
39 boolean_options = PyPIRCCommand.boolean_options + ['sign']
Martin v. Löwis98858c92005-03-21 21:00:59 +000040
41 def initialize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000042 PyPIRCCommand.initialize_options(self)
Martin v. Löwis98858c92005-03-21 21:00:59 +000043 self.username = ''
44 self.password = ''
Martin v. Löwis98858c92005-03-21 21:00:59 +000045 self.show_response = 0
Martin v. Löwisf74b9232005-03-22 15:51:14 +000046 self.sign = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000047 self.identity = None
Martin v. Löwis98858c92005-03-21 21:00:59 +000048
49 def finalize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000050 PyPIRCCommand.finalize_options(self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051 if self.identity and not self.sign:
52 raise DistutilsOptionError(
53 "Must use --sign for --identity to have meaning"
54 )
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000055 config = self._read_pypirc()
56 if config != {}:
57 self.username = config['username']
58 self.password = config['password']
59 self.repository = config['repository']
60 self.realm = config['realm']
Martin v. Löwis98858c92005-03-21 21:00:59 +000061
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +000062 # getting the password from the distribution
63 # if previously set by the register command
64 if not self.password and self.distribution.password:
65 self.password = self.distribution.password
66
Martin v. Löwis98858c92005-03-21 21:00:59 +000067 def run(self):
68 if not self.distribution.dist_files:
Éric Araujo08a69262018-02-18 18:14:54 -050069 msg = ("Must create and upload files in one command "
70 "(e.g. setup.py sdist upload)")
Jason R. Coombs09122f82014-05-10 13:24:58 -040071 raise DistutilsOptionError(msg)
Martin v. Löwis98da5622005-03-23 18:54:36 +000072 for command, pyversion, filename in self.distribution.dist_files:
73 self.upload_file(command, pyversion, filename)
Martin v. Löwis98858c92005-03-21 21:00:59 +000074
Martin v. Löwis98da5622005-03-23 18:54:36 +000075 def upload_file(self, command, pyversion, filename):
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050076 # Makes sure the repository URL is compliant
77 schema, netloc, url, params, query, fragments = \
78 urlparse(self.repository)
79 if params or query or fragments:
80 raise AssertionError("Incompatible url %s" % self.repository)
81
82 if schema not in ('http', 'https'):
83 raise AssertionError("unsupported schema " + schema)
84
Martin v. Löwisf74b9232005-03-22 15:51:14 +000085 # Sign if requested
86 if self.sign:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087 gpg_args = ["gpg", "--detach-sign", "-a", filename]
88 if self.identity:
89 gpg_args[2:2] = ["--local-user", self.identity]
90 spawn(gpg_args,
Martin v. Löwisf74b9232005-03-22 15:51:14 +000091 dry_run=self.dry_run)
Martin v. Löwis98858c92005-03-21 21:00:59 +000092
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000093 # Fill in the data - send all the meta-data in case we need to
94 # register a new release
Éric Araujobee5cef2010-11-05 23:51:56 +000095 f = open(filename,'rb')
96 try:
97 content = f.read()
98 finally:
99 f.close()
Christian Heimese572c7f2020-05-20 16:37:25 +0200100
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000101 meta = self.distribution.metadata
Martin v. Löwis98858c92005-03-21 21:00:59 +0000102 data = {
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000103 # action
104 ':action': 'file_upload',
Berker Peksag56fe4742016-06-18 21:42:37 +0300105 'protocol_version': '1',
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000106
107 # identify release
108 'name': meta.get_name(),
109 'version': meta.get_version(),
110
111 # file content
112 'content': (os.path.basename(filename),content),
113 'filetype': command,
114 'pyversion': pyversion,
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000115
116 # additional meta-data
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400117 'metadata_version': '1.0',
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000118 'summary': meta.get_description(),
119 'home_page': meta.get_url(),
120 'author': meta.get_contact(),
121 'author_email': meta.get_contact_email(),
122 'license': meta.get_licence(),
123 'description': meta.get_long_description(),
124 'keywords': meta.get_keywords(),
125 'platform': meta.get_platforms(),
126 'classifiers': meta.get_classifiers(),
127 'download_url': meta.get_download_url(),
128 # PEP 314
129 'provides': meta.get_provides(),
130 'requires': meta.get_requires(),
131 'obsoletes': meta.get_obsoletes(),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000132 }
Paul Ganssle4e80f5c2018-12-17 02:59:02 -0500133
134 data['comment'] = ''
Martin v. Löwis98858c92005-03-21 21:00:59 +0000135
Christian Heimese572c7f2020-05-20 16:37:25 +0200136 # file content digests
137 for digest_name, digest_cons in _FILE_CONTENT_DIGESTS.items():
138 if digest_cons is None:
139 continue
140 try:
141 data[digest_name] = digest_cons(content).hexdigest()
142 except ValueError:
143 # hash digest not available or blocked by security policy
144 pass
145
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000146 if self.sign:
Mickaël Schoentgen58721a92019-04-08 13:08:48 +0000147 with open(filename + ".asc", "rb") as f:
148 data['gpg_signature'] = (os.path.basename(filename) + ".asc",
149 f.read())
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000150
Martin v. Löwis98858c92005-03-21 21:00:59 +0000151 # set up the authentication
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000152 user_pass = (self.username + ":" + self.password).encode('ascii')
153 # The exact encoding of the authentication string is debated.
154 # Anyway PyPI only accepts ascii for both username or password.
Tarek Ziadé8b9361a2009-12-21 00:02:20 +0000155 auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000156
157 # Build up the MIME payload for the POST data
158 boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
R David Murray9ce69672014-09-27 16:56:15 -0400159 sep_boundary = b'\r\n--' + boundary.encode('ascii')
160 end_boundary = sep_boundary + b'--\r\n'
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000161 body = io.BytesIO()
Martin v. Löwis98858c92005-03-21 21:00:59 +0000162 for key, value in data.items():
R David Murray9ce69672014-09-27 16:56:15 -0400163 title = '\r\nContent-Disposition: form-data; name="%s"' % key
Martin v. Löwis98858c92005-03-21 21:00:59 +0000164 # handle multiple entries for the same name
Jason R. Coombs03756532014-05-10 13:24:18 -0400165 if not isinstance(value, list):
Martin v. Löwis98858c92005-03-21 21:00:59 +0000166 value = [value]
167 for value in value:
Tarek Ziadé36797272010-07-22 12:50:05 +0000168 if type(value) is tuple:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000169 title += '; filename="%s"' % value[0]
Martin v. Löwis98858c92005-03-21 21:00:59 +0000170 value = value[1]
171 else:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000172 value = str(value).encode('utf-8')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000173 body.write(sep_boundary)
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000174 body.write(title.encode('utf-8'))
R David Murray9ce69672014-09-27 16:56:15 -0400175 body.write(b"\r\n\r\n")
Martin v. Löwis98858c92005-03-21 21:00:59 +0000176 body.write(value)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000177 body.write(end_boundary)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000178 body = body.getvalue()
179
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400180 msg = "Submitting %s to %s" % (filename, self.repository)
181 self.announce(msg, log.INFO)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000182
183 # build the Request
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400184 headers = {
185 'Content-type': 'multipart/form-data; boundary=%s' % boundary,
186 'Content-length': str(len(body)),
187 'Authorization': auth,
188 }
Martin v. Löwis98858c92005-03-21 21:00:59 +0000189
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500190 request = Request(self.repository, data=body,
191 headers=headers)
192 # send the data
Martin v. Löwis98858c92005-03-21 21:00:59 +0000193 try:
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500194 result = urlopen(request)
195 status = result.getcode()
196 reason = result.msg
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500197 except HTTPError as e:
198 status = e.code
199 reason = e.msg
Berker Peksag6a8e6262016-06-02 13:45:53 -0700200 except OSError as e:
201 self.announce(str(e), log.ERROR)
202 raise
Martin v. Löwis98858c92005-03-21 21:00:59 +0000203
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500204 if status == 200:
205 self.announce('Server response (%s): %s' % (status, reason),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000206 log.INFO)
Berker Peksag6a8e6262016-06-02 13:45:53 -0700207 if self.show_response:
208 text = self._read_pypi_response(result)
209 msg = '\n'.join(('-' * 75, text, '-' * 75))
210 self.announce(msg, log.INFO)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000211 else:
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -0400212 msg = 'Upload failed (%s): %s' % (status, reason)
213 self.announce(msg, log.ERROR)
214 raise DistutilsError(msg)