blob: 1a96e2221e17455a53b40afefae6e1fc9f16a9da [file] [log] [blame]
Martin v. Löwis55f1bb82005-03-21 20:56:35 +00001"""distutils.command.upload
2
3Implements the Distutils 'upload' subcommand (upload package to PyPI)."""
Martin v. Löwis98858c92005-03-21 21:00:59 +00004
Tarek Ziadé36797272010-07-22 12:50:05 +00005import sys
6import os, io
7import socket
8import platform
Tarek Ziadé36797272010-07-22 12:50:05 +00009from base64 import standard_b64encode
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050010from urllib.request import urlopen, Request, HTTPError
11from urllib.parse import urlparse
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -040012from distutils.errors import DistutilsError, DistutilsOptionError
13from distutils.core import PyPIRCCommand
14from distutils.spawn import spawn
15from distutils import log
Tarek Ziadé36797272010-07-22 12:50:05 +000016
17# this keeps compatibility for 2.3 and 2.4
18if sys.version < "2.5":
19 from md5 import md5
20else:
21 from hashlib import md5
Tarek Ziadé38e3d512009-02-27 12:58:56 +000022
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000023class upload(PyPIRCCommand):
Martin v. Löwis98858c92005-03-21 21:00:59 +000024
25 description = "upload binary package to PyPI"
26
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000027 user_options = PyPIRCCommand.user_options + [
Martin v. Löwisf74b9232005-03-22 15:51:14 +000028 ('sign', 's',
29 'sign files to upload using gpg'),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000030 ('identity=', 'i', 'GPG identity used to sign files'),
Martin v. Löwis98858c92005-03-21 21:00:59 +000031 ]
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000032
33 boolean_options = PyPIRCCommand.boolean_options + ['sign']
Martin v. Löwis98858c92005-03-21 21:00:59 +000034
35 def initialize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000036 PyPIRCCommand.initialize_options(self)
Martin v. Löwis98858c92005-03-21 21:00:59 +000037 self.username = ''
38 self.password = ''
Martin v. Löwis98858c92005-03-21 21:00:59 +000039 self.show_response = 0
Martin v. Löwisf74b9232005-03-22 15:51:14 +000040 self.sign = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041 self.identity = None
Martin v. Löwis98858c92005-03-21 21:00:59 +000042
43 def finalize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000044 PyPIRCCommand.finalize_options(self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000045 if self.identity and not self.sign:
46 raise DistutilsOptionError(
47 "Must use --sign for --identity to have meaning"
48 )
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000049 config = self._read_pypirc()
50 if config != {}:
51 self.username = config['username']
52 self.password = config['password']
53 self.repository = config['repository']
54 self.realm = config['realm']
Martin v. Löwis98858c92005-03-21 21:00:59 +000055
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +000056 # getting the password from the distribution
57 # if previously set by the register command
58 if not self.password and self.distribution.password:
59 self.password = self.distribution.password
60
Martin v. Löwis98858c92005-03-21 21:00:59 +000061 def run(self):
62 if not self.distribution.dist_files:
63 raise DistutilsOptionError("No dist file created in earlier command")
Martin v. Löwis98da5622005-03-23 18:54:36 +000064 for command, pyversion, filename in self.distribution.dist_files:
65 self.upload_file(command, pyversion, filename)
Martin v. Löwis98858c92005-03-21 21:00:59 +000066
Martin v. Löwis98da5622005-03-23 18:54:36 +000067 def upload_file(self, command, pyversion, filename):
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -050068 # Makes sure the repository URL is compliant
69 schema, netloc, url, params, query, fragments = \
70 urlparse(self.repository)
71 if params or query or fragments:
72 raise AssertionError("Incompatible url %s" % self.repository)
73
74 if schema not in ('http', 'https'):
75 raise AssertionError("unsupported schema " + schema)
76
Martin v. Löwisf74b9232005-03-22 15:51:14 +000077 # Sign if requested
78 if self.sign:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079 gpg_args = ["gpg", "--detach-sign", "-a", filename]
80 if self.identity:
81 gpg_args[2:2] = ["--local-user", self.identity]
82 spawn(gpg_args,
Martin v. Löwisf74b9232005-03-22 15:51:14 +000083 dry_run=self.dry_run)
Martin v. Löwis98858c92005-03-21 21:00:59 +000084
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000085 # Fill in the data - send all the meta-data in case we need to
86 # register a new release
Éric Araujobee5cef2010-11-05 23:51:56 +000087 f = open(filename,'rb')
88 try:
89 content = f.read()
90 finally:
91 f.close()
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000092 meta = self.distribution.metadata
Martin v. Löwis98858c92005-03-21 21:00:59 +000093 data = {
Martin v. Löwis6d0c85a2006-01-08 10:48:54 +000094 # action
95 ':action': 'file_upload',
96 'protcol_version': '1',
97
98 # identify release
99 'name': meta.get_name(),
100 'version': meta.get_version(),
101
102 # file content
103 'content': (os.path.basename(filename),content),
104 'filetype': command,
105 'pyversion': pyversion,
106 'md5_digest': md5(content).hexdigest(),
107
108 # additional meta-data
109 'metadata_version' : '1.0',
110 'summary': meta.get_description(),
111 'home_page': meta.get_url(),
112 'author': meta.get_contact(),
113 'author_email': meta.get_contact_email(),
114 'license': meta.get_licence(),
115 'description': meta.get_long_description(),
116 'keywords': meta.get_keywords(),
117 'platform': meta.get_platforms(),
118 'classifiers': meta.get_classifiers(),
119 'download_url': meta.get_download_url(),
120 # PEP 314
121 'provides': meta.get_provides(),
122 'requires': meta.get_requires(),
123 'obsoletes': meta.get_obsoletes(),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000124 }
125 comment = ''
126 if command == 'bdist_rpm':
127 dist, version, id = platform.dist()
128 if dist:
129 comment = 'built for %s %s' % (dist, version)
130 elif command == 'bdist_dumb':
131 comment = 'built for %s' % platform.platform(terse=1)
132 data['comment'] = comment
133
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000134 if self.sign:
135 data['gpg_signature'] = (os.path.basename(filename) + ".asc",
Antoine Pitrou24319ac2012-06-29 01:05:26 +0200136 open(filename+".asc", "rb").read())
Martin v. Löwisf74b9232005-03-22 15:51:14 +0000137
Martin v. Löwis98858c92005-03-21 21:00:59 +0000138 # set up the authentication
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000139 user_pass = (self.username + ":" + self.password).encode('ascii')
140 # The exact encoding of the authentication string is debated.
141 # Anyway PyPI only accepts ascii for both username or password.
Tarek Ziadé8b9361a2009-12-21 00:02:20 +0000142 auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000143
144 # Build up the MIME payload for the POST data
145 boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
R David Murray9ce69672014-09-27 16:56:15 -0400146 sep_boundary = b'\r\n--' + boundary.encode('ascii')
147 end_boundary = sep_boundary + b'--\r\n'
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000148 body = io.BytesIO()
Martin v. Löwis98858c92005-03-21 21:00:59 +0000149 for key, value in data.items():
R David Murray9ce69672014-09-27 16:56:15 -0400150 title = '\r\nContent-Disposition: form-data; name="%s"' % key
Martin v. Löwis98858c92005-03-21 21:00:59 +0000151 # handle multiple entries for the same name
Tarek Ziadé36797272010-07-22 12:50:05 +0000152 if type(value) != type([]):
Martin v. Löwis98858c92005-03-21 21:00:59 +0000153 value = [value]
154 for value in value:
Tarek Ziadé36797272010-07-22 12:50:05 +0000155 if type(value) is tuple:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000156 title += '; filename="%s"' % value[0]
Martin v. Löwis98858c92005-03-21 21:00:59 +0000157 value = value[1]
158 else:
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000159 value = str(value).encode('utf-8')
Martin v. Löwis98858c92005-03-21 21:00:59 +0000160 body.write(sep_boundary)
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000161 body.write(title.encode('utf-8'))
R David Murray9ce69672014-09-27 16:56:15 -0400162 body.write(b"\r\n\r\n")
Martin v. Löwis98858c92005-03-21 21:00:59 +0000163 body.write(value)
Amaury Forgeot d'Arc836b6702008-11-20 23:53:46 +0000164 if value and value[-1:] == b'\r':
165 body.write(b'\n') # write an extra newline (lurve Macs)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000166 body.write(end_boundary)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000167 body = body.getvalue()
168
169 self.announce("Submitting %s to %s" % (filename, self.repository), log.INFO)
170
171 # build the Request
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500172 headers = {'Content-type':
173 'multipart/form-data; boundary=%s' % boundary,
174 'Content-length': str(len(body)),
175 'Authorization': auth}
Martin v. Löwis98858c92005-03-21 21:00:59 +0000176
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500177 request = Request(self.repository, data=body,
178 headers=headers)
179 # send the data
Martin v. Löwis98858c92005-03-21 21:00:59 +0000180 try:
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500181 result = urlopen(request)
182 status = result.getcode()
183 reason = result.msg
Andrew Svetlov0832af62012-12-18 23:10:48 +0200184 except OSError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185 self.announce(str(e), log.ERROR)
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -0400186 raise
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500187 except HTTPError as e:
188 status = e.code
189 reason = e.msg
Martin v. Löwis98858c92005-03-21 21:00:59 +0000190
Jason R. Coombsa2ebfd02013-11-10 18:50:10 -0500191 if status == 200:
192 self.announce('Server response (%s): %s' % (status, reason),
Martin v. Löwis98858c92005-03-21 21:00:59 +0000193 log.INFO)
194 else:
Antoine Pitrou2e4d3b12014-06-18 23:07:46 -0400195 msg = 'Upload failed (%s): %s' % (status, reason)
196 self.announce(msg, log.ERROR)
197 raise DistutilsError(msg)
Martin v. Löwis98858c92005-03-21 21:00:59 +0000198 if self.show_response:
Antoine Pitrou335a5122013-12-22 18:13:51 +0100199 text = self._read_pypi_response(result)
200 msg = '\n'.join(('-' * 75, text, '-' * 75))
Éric Araujo480504b2010-09-07 23:08:57 +0000201 self.announce(msg, log.INFO)