blob: 32dda359badb32bc4a215e4c1e8a7859204c898b [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
Tarek Ziadé36797272010-07-22 12:50:05 +000010import platform
Jason R. Coombsa3846522014-05-10 13:22:43 -040011import hashlib
Tarek Ziadé36797272010-07-22 12:50:05 +000012from base64 import standard_b64encode
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050013from urllib.request import urlopen, Request, HTTPError
14from 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
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000020class upload(PyPIRCCommand):
Martin v. Löwis98858c92005-03-21 21:00:59 +000021
22 description = "upload binary package to PyPI"
23
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000024 user_options = PyPIRCCommand.user_options + [
Martin v. Löwisf74b9232005-03-22 15:51:14 +000025 ('sign', 's',
26 'sign files to upload using gpg'),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027 ('identity=', 'i', 'GPG identity used to sign files'),
Martin v. Löwis98858c92005-03-21 21:00:59 +000028 ]
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000029
30 boolean_options = PyPIRCCommand.boolean_options + ['sign']
Martin v. Löwis98858c92005-03-21 21:00:59 +000031
32 def initialize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000033 PyPIRCCommand.initialize_options(self)
Martin v. Löwis98858c92005-03-21 21:00:59 +000034 self.username = ''
35 self.password = ''
Martin v. Löwis98858c92005-03-21 21:00:59 +000036 self.show_response = 0
Martin v. Löwisf74b9232005-03-22 15:51:14 +000037 self.sign = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038 self.identity = None
Martin v. Löwis98858c92005-03-21 21:00:59 +000039
40 def finalize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000041 PyPIRCCommand.finalize_options(self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042 if self.identity and not self.sign:
43 raise DistutilsOptionError(
44 "Must use --sign for --identity to have meaning"
45 )
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000046 config = self._read_pypirc()
47 if config != {}:
48 self.username = config['username']
49 self.password = config['password']
50 self.repository = config['repository']
51 self.realm = config['realm']
Martin v. Löwis98858c92005-03-21 21:00:59 +000052
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +000053 # getting the password from the distribution
54 # if previously set by the register command
55 if not self.password and self.distribution.password:
56 self.password = self.distribution.password
57
Martin v. Löwis98858c92005-03-21 21:00:59 +000058 def run(self):
59 if not self.distribution.dist_files:
Éric Araujo08a69262018-02-18 18:14:54 -050060 msg = ("Must create and upload files in one command "
61 "(e.g. setup.py sdist upload)")
Jason R. Coombs09122f82014-05-10 13:24:58 -040062 raise DistutilsOptionError(msg)
Martin v. Löwis98da5622005-03-23 18:54:36 +000063 for command, pyversion, filename in self.distribution.dist_files:
64 self.upload_file(command, pyversion, filename)
Martin v. Löwis98858c92005-03-21 21:00:59 +000065
Martin v. Löwis98da5622005-03-23 18:54:36 +000066 def upload_file(self, command, pyversion, filename):
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050067 # Makes sure the repository URL is compliant
68 schema, netloc, url, params, query, fragments = \
69 urlparse(self.repository)
70 if params or query or fragments:
71 raise AssertionError("Incompatible url %s" % self.repository)
72
73 if schema not in ('http', 'https'):
74 raise AssertionError("unsupported schema " + schema)
75
Martin v. Löwisf74b9232005-03-22 15:51:14 +000076 # Sign if requested
77 if self.sign:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078 gpg_args = ["gpg", "--detach-sign", "-a", filename]
79 if self.identity:
80 gpg_args[2:2] = ["--local-user", self.identity]
81 spawn(gpg_args,
Martin v. Löwisf74b9232005-03-22 15:51:14 +000082 dry_run=self.dry_run)
Martin v. Löwis98858c92005-03-21 21:00:59 +000083
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000084 # Fill in the data - send all the meta-data in case we need to
85 # register a new release
Éric Araujobee5cef2010-11-05 23:51:56 +000086 f = open(filename,'rb')
87 try:
88 content = f.read()
89 finally:
90 f.close()
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000091 meta = self.distribution.metadata
Martin v. Löwis98858c92005-03-21 21:00:59 +000092 data = {
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000093 # action
94 ':action': 'file_upload',
Berker Peksag56fe4742016-06-18 21:42:37 +030095 'protocol_version': '1',
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000096
97 # identify release
98 'name': meta.get_name(),
99 'version': meta.get_version(),
100
101 # file content
102 'content': (os.path.basename(filename),content),
103 'filetype': command,
104 'pyversion': pyversion,
Jason R. Coombsa3846522014-05-10 13:22:43 -0400105 'md5_digest': hashlib.md5(content).hexdigest(),
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000106
107 # additional meta-data
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400108 'metadata_version': '1.0',
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +0000109 'summary': meta.get_description(),
110 'home_page': meta.get_url(),
111 'author': meta.get_contact(),
112 'author_email': meta.get_contact_email(),
113 'license': meta.get_licence(),
114 'description': meta.get_long_description(),
115 'keywords': meta.get_keywords(),
116 'platform': meta.get_platforms(),
117 'classifiers': meta.get_classifiers(),
118 'download_url': meta.get_download_url(),
119 # PEP 314
120 'provides': meta.get_provides(),
121 'requires': meta.get_requires(),
122 'obsoletes': meta.get_obsoletes(),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000123 }
124 comment = ''
125 if command == 'bdist_rpm':
126 dist, version, id = platform.dist()
127 if dist:
128 comment = 'built for %s %s' % (dist, version)
129 elif command == 'bdist_dumb':
130 comment = 'built for %s' % platform.platform(terse=1)
131 data['comment'] = comment
132
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000133 if self.sign:
134 data['gpg_signature'] = (os.path.basename(filename) + ".asc",
Antoine Pitrou24319ac2012-06-29 01:05:26 +0200135 open(filename+".asc", "rb").read())
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000136
Martin v. Löwis98858c92005-03-21 21:00:59 +0000137 # set up the authentication
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000138 user_pass = (self.username + ":" + self.password).encode('ascii')
139 # The exact encoding of the authentication string is debated.
140 # Anyway PyPI only accepts ascii for both username or password.
Tarek Ziadé8b9361a2009-12-21 00:02:20 +0000141 auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000142
143 # Build up the MIME payload for the POST data
144 boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
R David Murray9ce69672014-09-27 16:56:15 -0400145 sep_boundary = b'\r\n--' + boundary.encode('ascii')
146 end_boundary = sep_boundary + b'--\r\n'
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000147 body = io.BytesIO()
Martin v. Löwis98858c92005-03-21 21:00:59 +0000148 for key, value in data.items():
R David Murray9ce69672014-09-27 16:56:15 -0400149 title = '\r\nContent-Disposition: form-data; name="%s"' % key
Martin v. Löwis98858c92005-03-21 21:00:59 +0000150 # handle multiple entries for the same name
Jason R. Coombs03756532014-05-10 13:24:18 -0400151 if not isinstance(value, list):
Martin v. Löwis98858c92005-03-21 21:00:59 +0000152 value = [value]
153 for value in value:
Tarek Ziadé36797272010-07-22 12:50:05 +0000154 if type(value) is tuple:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000155 title += '; filename="%s"' % value[0]
Martin v. Löwis98858c92005-03-21 21:00:59 +0000156 value = value[1]
157 else:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000158 value = str(value).encode('utf-8')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000159 body.write(sep_boundary)
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000160 body.write(title.encode('utf-8'))
R David Murray9ce69672014-09-27 16:56:15 -0400161 body.write(b"\r\n\r\n")
Martin v. Löwis98858c92005-03-21 21:00:59 +0000162 body.write(value)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000163 body.write(end_boundary)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000164 body = body.getvalue()
165
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400166 msg = "Submitting %s to %s" % (filename, self.repository)
167 self.announce(msg, log.INFO)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000168
169 # build the Request
Jason R. Coombs7ae0fde2014-05-10 13:20:28 -0400170 headers = {
171 'Content-type': 'multipart/form-data; boundary=%s' % boundary,
172 'Content-length': str(len(body)),
173 'Authorization': auth,
174 }
Martin v. Löwis98858c92005-03-21 21:00:59 +0000175
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500176 request = Request(self.repository, data=body,
177 headers=headers)
178 # send the data
Martin v. Löwis98858c92005-03-21 21:00:59 +0000179 try:
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500180 result = urlopen(request)
181 status = result.getcode()
182 reason = result.msg
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500183 except HTTPError as e:
184 status = e.code
185 reason = e.msg
Berker Peksag6a8e6262016-06-02 13:45:53 -0700186 except OSError as e:
187 self.announce(str(e), log.ERROR)
188 raise
Martin v. Löwis98858c92005-03-21 21:00:59 +0000189
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500190 if status == 200:
191 self.announce('Server response (%s): %s' % (status, reason),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000192 log.INFO)
Berker Peksag6a8e6262016-06-02 13:45:53 -0700193 if self.show_response:
194 text = self._read_pypi_response(result)
195 msg = '\n'.join(('-' * 75, text, '-' * 75))
196 self.announce(msg, log.INFO)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000197 else:
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -0400198 msg = 'Upload failed (%s): %s' % (status, reason)
199 self.announce(msg, log.ERROR)
200 raise DistutilsError(msg)