googlecode_upload.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. <!-- saved from url=(0068)http://support.googlecode.com/svn/trunk/scripts/googlecode_upload.py -->
  2. <html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/env python
  3. #
  4. # Copyright 2006, 2007 Google Inc. All Rights Reserved.
  5. # Author: danderson@google.com (David Anderson)
  6. #
  7. # Script for uploading files to a Google Code project.
  8. #
  9. # This is intended to be both a useful script for people who want to
  10. # streamline project uploads and a reference implementation for
  11. # uploading files to Google Code projects.
  12. #
  13. # To upload a file to Google Code, you need to provide a path to the
  14. # file on your local machine, a small summary of what the file is, a
  15. # project name, and a valid account that is a member or owner of that
  16. # project. You can optionally provide a list of labels that apply to
  17. # the file. The file will be uploaded under the same name that it has
  18. # in your local filesystem (that is, the "basename" or last path
  19. # component). Run the script with '--help' to get the exact syntax
  20. # and available options.
  21. #
  22. # Note that the upload script requests that you enter your
  23. # googlecode.com password. This is NOT your Gmail account password!
  24. # This is the password you use on googlecode.com for committing to
  25. # Subversion and uploading files. You can find your password by going
  26. # to http://code.google.com/hosting/settings when logged in with your
  27. # Gmail account. If you have already committed to your project's
  28. # Subversion repository, the script will automatically retrieve your
  29. # credentials from there (unless disabled, see the output of '--help'
  30. # for details).
  31. #
  32. # If you are looking at this script as a reference for implementing
  33. # your own Google Code file uploader, then you should take a look at
  34. # the upload() function, which is the meat of the uploader. You
  35. # basically need to build a multipart/form-data POST request with the
  36. # right fields and send it to https://PROJECT.googlecode.com/files .
  37. # Authenticate the request using HTTP Basic authentication, as is
  38. # shown below.
  39. #
  40. # Licensed under the terms of the Apache Software License 2.0:
  41. # http://www.apache.org/licenses/LICENSE-2.0
  42. #
  43. # Questions, comments, feature requests and patches are most welcome.
  44. # Please direct all of these to the Google Code users group:
  45. # http://groups.google.com/group/google-code-hosting
  46. """Google Code file uploader script.
  47. """
  48. __author__ = 'danderson@google.com (David Anderson)'
  49. import httplib
  50. import os.path
  51. import optparse
  52. import getpass
  53. import base64
  54. import sys
  55. def upload(file, project_name, user_name, password, summary, labels=None):
  56. """Upload a file to a Google Code project's file server.
  57. Args:
  58. file: The local path to the file.
  59. project_name: The name of your project on Google Code.
  60. user_name: Your Google account name.
  61. password: The googlecode.com password for your account.
  62. Note that this is NOT your global Google Account password!
  63. summary: A small description for the file.
  64. labels: an optional list of label strings with which to tag the file.
  65. Returns: a tuple:
  66. http_status: 201 if the upload succeeded, something else if an
  67. error occured.
  68. http_reason: The human-readable string associated with http_status
  69. file_url: If the upload succeeded, the URL of the file on Google
  70. Code, None otherwise.
  71. """
  72. # The login is the user part of user@gmail.com. If the login provided
  73. # is in the full user@domain form, strip it down.
  74. if user_name.endswith('@gmail.com'):
  75. user_name = user_name[:user_name.index('@gmail.com')]
  76. form_fields = [('summary', summary)]
  77. if labels is not None:
  78. form_fields.extend([('label', l.strip()) for l in labels])
  79. content_type, body = encode_upload_request(form_fields, file)
  80. upload_host = '%s.googlecode.com' % project_name
  81. upload_uri = '/files'
  82. auth_token = base64.b64encode('%s:%s'% (user_name, password))
  83. headers = {
  84. 'Authorization': 'Basic %s' % auth_token,
  85. 'User-Agent': 'Googlecode.com uploader v0.9.4',
  86. 'Content-Type': content_type,
  87. }
  88. server = httplib.HTTPSConnection(upload_host)
  89. server.request('POST', upload_uri, body, headers)
  90. resp = server.getresponse()
  91. server.close()
  92. if resp.status == 201:
  93. location = resp.getheader('Location', None)
  94. else:
  95. location = None
  96. return resp.status, resp.reason, location
  97. def encode_upload_request(fields, file_path):
  98. """Encode the given fields and file into a multipart form body.
  99. fields is a sequence of (name, value) pairs. file is the path of
  100. the file to upload. The file will be uploaded to Google Code with
  101. the same file name.
  102. Returns: (content_type, body) ready for httplib.HTTP instance
  103. """
  104. BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
  105. CRLF = '\r\n'
  106. body = []
  107. # Add the metadata about the upload first
  108. for key, value in fields:
  109. body.extend(
  110. ['--' + BOUNDARY,
  111. 'Content-Disposition: form-data; name="%s"' % key,
  112. '',
  113. value,
  114. ])
  115. # Now add the file itself
  116. file_name = os.path.basename(file_path)
  117. f = open(file_path, 'rb')
  118. file_content = f.read()
  119. f.close()
  120. body.extend(
  121. ['--' + BOUNDARY,
  122. 'Content-Disposition: form-data; name="filename"; filename="%s"'
  123. % file_name,
  124. # The upload server determines the mime-type, no need to set it.
  125. 'Content-Type: application/octet-stream',
  126. '',
  127. file_content,
  128. ])
  129. # Finalize the form body
  130. body.extend(['--' + BOUNDARY + '--', ''])
  131. return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
  132. def upload_find_auth(file_path, project_name, summary, labels=None,
  133. user_name=None, password=None, tries=3):
  134. """Find credentials and upload a file to a Google Code project's file server.
  135. file_path, project_name, summary, and labels are passed as-is to upload.
  136. Args:
  137. file_path: The local path to the file.
  138. project_name: The name of your project on Google Code.
  139. summary: A small description for the file.
  140. labels: an optional list of label strings with which to tag the file.
  141. config_dir: Path to Subversion configuration directory, 'none', or None.
  142. user_name: Your Google account name.
  143. tries: How many attempts to make.
  144. """
  145. while tries &gt; 0:
  146. if user_name is None:
  147. # Read username if not specified or loaded from svn config, or on
  148. # subsequent tries.
  149. sys.stdout.write('Please enter your googlecode.com username: ')
  150. sys.stdout.flush()
  151. user_name = sys.stdin.readline().rstrip()
  152. if password is None:
  153. # Read password if not loaded from svn config, or on subsequent tries.
  154. print 'Please enter your googlecode.com password.'
  155. print '** Note that this is NOT your Gmail account password! **'
  156. print 'It is the password you use to access Subversion repositories,'
  157. print 'and can be found here: http://code.google.com/hosting/settings'
  158. password = getpass.getpass()
  159. status, reason, url = upload(file_path, project_name, user_name, password,
  160. summary, labels)
  161. # Returns 403 Forbidden instead of 401 Unauthorized for bad
  162. # credentials as of 2007-07-17.
  163. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
  164. # Rest for another try.
  165. user_name = password = None
  166. tries = tries - 1
  167. else:
  168. # We're done.
  169. break
  170. return status, reason, url
  171. def main():
  172. parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
  173. '-p PROJECT [options] FILE')
  174. parser.add_option('-s', '--summary', dest='summary',
  175. help='Short description of the file')
  176. parser.add_option('-p', '--project', dest='project',
  177. help='Google Code project name')
  178. parser.add_option('-u', '--user', dest='user',
  179. help='Your Google Code username')
  180. parser.add_option('-w', '--password', dest='password',
  181. help='Your Google Code password')
  182. parser.add_option('-l', '--labels', dest='labels',
  183. help='An optional list of comma-separated labels to attach '
  184. 'to the file')
  185. options, args = parser.parse_args()
  186. if not options.summary:
  187. parser.error('File summary is missing.')
  188. elif not options.project:
  189. parser.error('Project name is missing.')
  190. elif len(args) &lt; 1:
  191. parser.error('File to upload not provided.')
  192. elif len(args) &gt; 1:
  193. parser.error('Only one file may be specified.')
  194. file_path = args[0]
  195. if options.labels:
  196. labels = options.labels.split(',')
  197. else:
  198. labels = None
  199. status, reason, url = upload_find_auth(file_path, options.project,
  200. options.summary, labels,
  201. options.user, options.password)
  202. if url:
  203. print 'The file was uploaded successfully.'
  204. print 'URL: %s' % url
  205. return 0
  206. else:
  207. print 'An error occurred. Your file was not uploaded.'
  208. print 'Google Code upload server said: %s (%s)' % (reason, status)
  209. return 1
  210. if __name__ == '__main__':
  211. sys.exit(main())
  212. </pre></body></html>