plunger 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
data/.rvmrc ADDED
@@ -0,0 +1 @@
1
+ rvm ruby-1.9.2
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source "http://rubygems.org"
2
+
3
+ gemspec
@@ -0,0 +1,21 @@
1
+ <img src="https://github.com/railsware/plunger/raw/master/plunger.jpg" style="float:right" />
2
+
3
+ # Plunger
4
+
5
+ Plumber is code review tool.
6
+
7
+ Its ruby wrapper for [Rietveld Code Review, hosted on Google App Engine](http://code.google.com/p/rietveld/)
8
+
9
+ ## Commands
10
+
11
+ To see all commands:
12
+
13
+ plunger --help
14
+
15
+ ### Configure
16
+
17
+ Synopsis:
18
+
19
+ plunger configure
20
+
21
+ It will ask your about required options and store configuration to ~/.gem/plumber
@@ -0,0 +1 @@
1
+ require 'bundler/gem_tasks'
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'plunger'
4
+
5
+ Plunger::Runner.new(ARGV).run!
@@ -0,0 +1,7 @@
1
+ require "plunger/version"
2
+
3
+ module Plunger
4
+ autoload :Runner, 'plunger/runner'
5
+ autoload :Command, 'plunger/command'
6
+ autoload :Utils, 'plunger/utils'
7
+ end
@@ -0,0 +1,31 @@
1
+ module Plunger
2
+ module Command
3
+ class << self
4
+ def names
5
+ %w(push upgrade configure)
6
+ end
7
+
8
+ def classes
9
+ @classes ||= self.names.map { |name| command_class(name) }
10
+ end
11
+
12
+ def autorun
13
+ names.each do |name|
14
+ run(name) if command_class(name).autorun?
15
+ end
16
+ end
17
+
18
+ def run(name)
19
+ command_class(name).new.run
20
+ end
21
+
22
+ def command_class(name)
23
+ Plunger::Command.const_get(Utils.camelize(name))
24
+ end
25
+ end
26
+ end
27
+ end
28
+
29
+ Plunger::Command.names.each do |name|
30
+ require "plunger/command/#{name}"
31
+ end
@@ -0,0 +1,71 @@
1
+ require 'rubygems/user_interaction'
2
+
3
+ module Plunger
4
+ module Command
5
+ class Configure
6
+ class << self
7
+ def command
8
+ 'configure'
9
+ end
10
+
11
+ def description
12
+ 'Configure plunger'
13
+ end
14
+
15
+ def autorun?
16
+ !File.exists?(config_path)
17
+ end
18
+
19
+ def config_path
20
+ @config_path ||= File.join(Gem.user_home, '.gem', 'plunger')
21
+ end
22
+ end
23
+
24
+ def run
25
+ ui.say "Please configure plunger"
26
+ [
27
+ ['server', 'Code review server', 'coderev.railsware.com'],
28
+ ['python_bin', 'Path to python v2 binary', 'python']
29
+ ].each do |args|
30
+ configure_option(*args)
31
+ end
32
+
33
+ save_configuration
34
+ ui.say "Configuration saved to #{config_path}"
35
+ end
36
+
37
+ protected
38
+
39
+ def ui
40
+ @ui ||= Gem::ConsoleUI.new
41
+ end
42
+
43
+ def config_path
44
+ self.class.config_path
45
+ end
46
+
47
+ def configuration
48
+ @configuration ||= Gem.configuration.load_file(config_path)
49
+ end
50
+
51
+ def configure_option(name, description, default)
52
+ configuration[name] ||= default
53
+ value = configuration[name]
54
+ value = ui.ask("#{description} (#{value}):")
55
+ configuration[name] ||= default
56
+ configuration[name] = value unless value.empty?
57
+ end
58
+
59
+ def save_configuration
60
+ dirname = File.dirname(config_path)
61
+
62
+ Dir.mkdir(dirname) unless File.exists?(dirname)
63
+
64
+ File.open(config_path, 'w') do |f|
65
+ f.write configuration.to_yaml
66
+ end
67
+ end
68
+
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,23 @@
1
+ module Plunger
2
+ module Command
3
+ class Push
4
+ class << self
5
+ def command
6
+ 'push'
7
+ end
8
+
9
+ def description
10
+ 'Push code diff for review'
11
+ end
12
+
13
+ def autorun?
14
+ false
15
+ end
16
+ end
17
+
18
+ def run
19
+ p "PUSH"
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,23 @@
1
+ module Plunger
2
+ module Command
3
+ class Upgrade
4
+ class << self
5
+ def command
6
+ 'upgrade'
7
+ end
8
+
9
+ def description
10
+ 'Upgrade plunger gem'
11
+ end
12
+
13
+ def autorun?
14
+ false
15
+ end
16
+ end
17
+
18
+ def run
19
+ p "UPGRADE"
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,44 @@
1
+ require 'optparse'
2
+
3
+ module Plunger
4
+ class Runner
5
+ def initialize(argv)
6
+ @argv = argv
7
+ end
8
+
9
+ def run!
10
+ @parser = OptionParser.new do |o|
11
+ o.banner = "Usage: plunger [options] #{Command.names.join('|')}"
12
+
13
+ o.separator ""
14
+ o.separator "Commands:"
15
+
16
+ o.separator ""
17
+ Command.classes.each do |klass|
18
+ o.separator " %-20s %s" % [klass.command, klass.description]
19
+ end
20
+
21
+ o.separator ""
22
+ o.separator "Common options:"
23
+ o.on_tail("-h", "--help", "Show this message") { puts o; exit }
24
+ o.on_tail('-v', '--version', "Show version") { puts Plunger::VERSION; exit }
25
+ end
26
+
27
+ begin
28
+ @parser.parse!(@argv)
29
+ rescue OptionParser::InvalidOption => e
30
+ abort e.message
31
+ end
32
+
33
+ @command = @argv.shift
34
+
35
+ unless Command.names.include?(@command)
36
+ abort "Unknown command #{@command.inspect}"
37
+ end
38
+
39
+ Command.autorun
40
+ Command.run(@command)
41
+ end
42
+
43
+ end
44
+ end
@@ -0,0 +1,9 @@
1
+ module Plunger
2
+ module Utils
3
+ extend self
4
+
5
+ def camelize(string)
6
+ string.split('_').map{ |s| s.capitalize }.join
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,3 @@
1
+ module Plunger
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,22 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "plunger/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "plunger"
7
+ s.version = Plunger::VERSION
8
+ s.authors = ["Andriy Yanko"]
9
+ s.email = ["andriy.yanko@gmail.com"]
10
+ s.homepage = "https://github.com/railsware/plunger"
11
+ s.summary = %q{Code Review Tool}
12
+ s.description = %q{Ruby Wrapper for Rietveld Code Review, hosted on Google App Engine}
13
+
14
+ s.rubyforge_project = "plunger"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ s.add_dependency "grit", "2.4.1"
22
+ end
Binary file
@@ -0,0 +1,2330 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2007 Google Inc.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Tool for uploading diffs from a version control system to the codereview app.
18
+
19
+ Usage summary: upload.py [options] [-- diff_options] [path...]
20
+
21
+ Diff options are passed to the diff command of the underlying system.
22
+
23
+ Supported version control systems:
24
+ Git
25
+ Mercurial
26
+ Subversion
27
+ Perforce
28
+ CVS
29
+
30
+ It is important for Git/Mercurial users to specify a tree/node/branch to diff
31
+ against by using the '--rev' option.
32
+ """
33
+ # This code is derived from appcfg.py in the App Engine SDK (open source),
34
+ # and from ASPN recipe #146306.
35
+
36
+ import ConfigParser
37
+ import cookielib
38
+ import errno
39
+ import fnmatch
40
+ import getpass
41
+ import logging
42
+ import marshal
43
+ import mimetypes
44
+ import optparse
45
+ import os
46
+ import re
47
+ import socket
48
+ import subprocess
49
+ import sys
50
+ import urllib
51
+ import urllib2
52
+ import urlparse
53
+
54
+ # The md5 module was deprecated in Python 2.5.
55
+ try:
56
+ from hashlib import md5
57
+ except ImportError:
58
+ from md5 import md5
59
+
60
+ try:
61
+ import readline
62
+ except ImportError:
63
+ pass
64
+
65
+ try:
66
+ import keyring
67
+ except ImportError:
68
+ keyring = None
69
+
70
+ # The logging verbosity:
71
+ # 0: Errors only.
72
+ # 1: Status messages.
73
+ # 2: Info logs.
74
+ # 3: Debug logs.
75
+ verbosity = 1
76
+
77
+ # The account type used for authentication.
78
+ # This line could be changed by the review server (see handler for
79
+ # upload.py).
80
+ AUTH_ACCOUNT_TYPE = "GOOGLE"
81
+
82
+ # URL of the default review server. As for AUTH_ACCOUNT_TYPE, this line could be
83
+ # changed by the review server (see handler for upload.py).
84
+ DEFAULT_REVIEW_SERVER = "codereview.appspot.com"
85
+
86
+ # Max size of patch or base file.
87
+ MAX_UPLOAD_SIZE = 900 * 1024
88
+
89
+ # Constants for version control names. Used by GuessVCSName.
90
+ VCS_GIT = "Git"
91
+ VCS_MERCURIAL = "Mercurial"
92
+ VCS_SUBVERSION = "Subversion"
93
+ VCS_PERFORCE = "Perforce"
94
+ VCS_CVS = "CVS"
95
+ VCS_UNKNOWN = "Unknown"
96
+
97
+ VCS_ABBREVIATIONS = {
98
+ VCS_MERCURIAL.lower(): VCS_MERCURIAL,
99
+ "hg": VCS_MERCURIAL,
100
+ VCS_SUBVERSION.lower(): VCS_SUBVERSION,
101
+ "svn": VCS_SUBVERSION,
102
+ VCS_PERFORCE.lower(): VCS_PERFORCE,
103
+ "p4": VCS_PERFORCE,
104
+ VCS_GIT.lower(): VCS_GIT,
105
+ VCS_CVS.lower(): VCS_CVS,
106
+ }
107
+
108
+ # The result of parsing Subversion's [auto-props] setting.
109
+ svn_auto_props_map = None
110
+
111
+ def GetEmail(prompt):
112
+ """Prompts the user for their email address and returns it.
113
+
114
+ The last used email address is saved to a file and offered up as a suggestion
115
+ to the user. If the user presses enter without typing in anything the last
116
+ used email address is used. If the user enters a new address, it is saved
117
+ for next time we prompt.
118
+
119
+ """
120
+ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
121
+ last_email = ""
122
+ if os.path.exists(last_email_file_name):
123
+ try:
124
+ last_email_file = open(last_email_file_name, "r")
125
+ last_email = last_email_file.readline().strip("\n")
126
+ last_email_file.close()
127
+ prompt += " [%s]" % last_email
128
+ except IOError, e:
129
+ pass
130
+ email = raw_input(prompt + ": ").strip()
131
+ if email:
132
+ try:
133
+ last_email_file = open(last_email_file_name, "w")
134
+ last_email_file.write(email)
135
+ last_email_file.close()
136
+ except IOError, e:
137
+ pass
138
+ else:
139
+ email = last_email
140
+ return email
141
+
142
+
143
+ def StatusUpdate(msg):
144
+ """Print a status message to stdout.
145
+
146
+ If 'verbosity' is greater than 0, print the message.
147
+
148
+ Args:
149
+ msg: The string to print.
150
+ """
151
+ if verbosity > 0:
152
+ print msg
153
+
154
+
155
+ def ErrorExit(msg):
156
+ """Print an error message to stderr and exit."""
157
+ print >>sys.stderr, msg
158
+ sys.exit(1)
159
+
160
+
161
+ class ClientLoginError(urllib2.HTTPError):
162
+ """Raised to indicate there was an error authenticating with ClientLogin."""
163
+
164
+ def __init__(self, url, code, msg, headers, args):
165
+ urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
166
+ self.args = args
167
+ self.reason = args["Error"]
168
+ self.info = args.get("Info", None)
169
+
170
+
171
+ class AbstractRpcServer(object):
172
+ """Provides a common interface for a simple RPC server."""
173
+
174
+ def __init__(self, host, auth_function, host_override=None, extra_headers={},
175
+ save_cookies=False, account_type=AUTH_ACCOUNT_TYPE):
176
+ """Creates a new HttpRpcServer.
177
+
178
+ Args:
179
+ host: The host to send requests to.
180
+ auth_function: A function that takes no arguments and returns an
181
+ (email, password) tuple when called. Will be called if authentication
182
+ is required.
183
+ host_override: The host header to send to the server (defaults to host).
184
+ extra_headers: A dict of extra headers to append to every request.
185
+ save_cookies: If True, save the authentication cookies to local disk.
186
+ If False, use an in-memory cookiejar instead. Subclasses must
187
+ implement this functionality. Defaults to False.
188
+ account_type: Account type used for authentication. Defaults to
189
+ AUTH_ACCOUNT_TYPE.
190
+ """
191
+ self.host = host
192
+ if (not self.host.startswith("http://") and
193
+ not self.host.startswith("https://")):
194
+ self.host = "http://" + self.host
195
+ self.host_override = host_override
196
+ self.auth_function = auth_function
197
+ self.authenticated = False
198
+ self.extra_headers = extra_headers
199
+ self.save_cookies = save_cookies
200
+ self.account_type = account_type
201
+ self.opener = self._GetOpener()
202
+ if self.host_override:
203
+ logging.info("Server: %s; Host: %s", self.host, self.host_override)
204
+ else:
205
+ logging.info("Server: %s", self.host)
206
+
207
+ def _GetOpener(self):
208
+ """Returns an OpenerDirector for making HTTP requests.
209
+
210
+ Returns:
211
+ A urllib2.OpenerDirector object.
212
+ """
213
+ raise NotImplementedError()
214
+
215
+ def _CreateRequest(self, url, data=None):
216
+ """Creates a new urllib request."""
217
+ logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
218
+ req = urllib2.Request(url, data=data)
219
+ if self.host_override:
220
+ req.add_header("Host", self.host_override)
221
+ for key, value in self.extra_headers.iteritems():
222
+ req.add_header(key, value)
223
+ return req
224
+
225
+ def _GetAuthToken(self, email, password):
226
+ """Uses ClientLogin to authenticate the user, returning an auth token.
227
+
228
+ Args:
229
+ email: The user's email address
230
+ password: The user's password
231
+
232
+ Raises:
233
+ ClientLoginError: If there was an error authenticating with ClientLogin.
234
+ HTTPError: If there was some other form of HTTP error.
235
+
236
+ Returns:
237
+ The authentication token returned by ClientLogin.
238
+ """
239
+ account_type = self.account_type
240
+ if self.host.endswith(".google.com"):
241
+ # Needed for use inside Google.
242
+ account_type = "HOSTED"
243
+ req = self._CreateRequest(
244
+ url="https://www.google.com/accounts/ClientLogin",
245
+ data=urllib.urlencode({
246
+ "Email": email,
247
+ "Passwd": password,
248
+ "service": "ah",
249
+ "source": "rietveld-codereview-upload",
250
+ "accountType": account_type,
251
+ }),
252
+ )
253
+ try:
254
+ response = self.opener.open(req)
255
+ response_body = response.read()
256
+ response_dict = dict(x.split("=")
257
+ for x in response_body.split("\n") if x)
258
+ return response_dict["Auth"]
259
+ except urllib2.HTTPError, e:
260
+ if e.code == 403:
261
+ body = e.read()
262
+ response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
263
+ raise ClientLoginError(req.get_full_url(), e.code, e.msg,
264
+ e.headers, response_dict)
265
+ else:
266
+ raise
267
+
268
+ def _GetAuthCookie(self, auth_token):
269
+ """Fetches authentication cookies for an authentication token.
270
+
271
+ Args:
272
+ auth_token: The authentication token returned by ClientLogin.
273
+
274
+ Raises:
275
+ HTTPError: If there was an error fetching the authentication cookies.
276
+ """
277
+ # This is a dummy value to allow us to identify when we're successful.
278
+ continue_location = "http://localhost/"
279
+ args = {"continue": continue_location, "auth": auth_token}
280
+ req = self._CreateRequest("%s/_ah/login?%s" %
281
+ (self.host, urllib.urlencode(args)))
282
+ try:
283
+ response = self.opener.open(req)
284
+ except urllib2.HTTPError, e:
285
+ response = e
286
+ if (response.code != 302 or
287
+ response.info()["location"] != continue_location):
288
+ raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
289
+ response.headers, response.fp)
290
+ self.authenticated = True
291
+
292
+ def _Authenticate(self):
293
+ """Authenticates the user.
294
+
295
+ The authentication process works as follows:
296
+ 1) We get a username and password from the user
297
+ 2) We use ClientLogin to obtain an AUTH token for the user
298
+ (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
299
+ 3) We pass the auth token to /_ah/login on the server to obtain an
300
+ authentication cookie. If login was successful, it tries to redirect
301
+ us to the URL we provided.
302
+
303
+ If we attempt to access the upload API without first obtaining an
304
+ authentication cookie, it returns a 401 response (or a 302) and
305
+ directs us to authenticate ourselves with ClientLogin.
306
+ """
307
+ for i in range(3):
308
+ credentials = self.auth_function()
309
+ try:
310
+ auth_token = self._GetAuthToken(credentials[0], credentials[1])
311
+ except ClientLoginError, e:
312
+ print >>sys.stderr, ''
313
+ if e.reason == "BadAuthentication":
314
+ if e.info == "InvalidSecondFactor":
315
+ print >>sys.stderr, (
316
+ "Use an application-specific password instead "
317
+ "of your regular account password.\n"
318
+ "See http://www.google.com/"
319
+ "support/accounts/bin/answer.py?answer=185833")
320
+ else:
321
+ print >>sys.stderr, "Invalid username or password."
322
+ elif e.reason == "CaptchaRequired":
323
+ print >>sys.stderr, (
324
+ "Please go to\n"
325
+ "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
326
+ "and verify you are a human. Then try again.\n"
327
+ "If you are using a Google Apps account the URL is:\n"
328
+ "https://www.google.com/a/yourdomain.com/UnlockCaptcha")
329
+ elif e.reason == "NotVerified":
330
+ print >>sys.stderr, "Account not verified."
331
+ elif e.reason == "TermsNotAgreed":
332
+ print >>sys.stderr, "User has not agreed to TOS."
333
+ elif e.reason == "AccountDeleted":
334
+ print >>sys.stderr, "The user account has been deleted."
335
+ elif e.reason == "AccountDisabled":
336
+ print >>sys.stderr, "The user account has been disabled."
337
+ break
338
+ elif e.reason == "ServiceDisabled":
339
+ print >>sys.stderr, ("The user's access to the service has been "
340
+ "disabled.")
341
+ elif e.reason == "ServiceUnavailable":
342
+ print >>sys.stderr, "The service is not available; try again later."
343
+ else:
344
+ # Unknown error.
345
+ raise
346
+ print >>sys.stderr, ''
347
+ continue
348
+ self._GetAuthCookie(auth_token)
349
+ return
350
+
351
+ def Send(self, request_path, payload=None,
352
+ content_type="application/octet-stream",
353
+ timeout=None,
354
+ extra_headers=None,
355
+ **kwargs):
356
+ """Sends an RPC and returns the response.
357
+
358
+ Args:
359
+ request_path: The path to send the request to, eg /api/appversion/create.
360
+ payload: The body of the request, or None to send an empty request.
361
+ content_type: The Content-Type header to use.
362
+ timeout: timeout in seconds; default None i.e. no timeout.
363
+ (Note: for large requests on OS X, the timeout doesn't work right.)
364
+ extra_headers: Dict containing additional HTTP headers that should be
365
+ included in the request (string header names mapped to their values),
366
+ or None to not include any additional headers.
367
+ kwargs: Any keyword arguments are converted into query string parameters.
368
+
369
+ Returns:
370
+ The response body, as a string.
371
+ """
372
+ # TODO: Don't require authentication. Let the server say
373
+ # whether it is necessary.
374
+ if not self.authenticated:
375
+ self._Authenticate()
376
+
377
+ old_timeout = socket.getdefaulttimeout()
378
+ socket.setdefaulttimeout(timeout)
379
+ try:
380
+ tries = 0
381
+ while True:
382
+ tries += 1
383
+ args = dict(kwargs)
384
+ url = "%s%s" % (self.host, request_path)
385
+ if args:
386
+ url += "?" + urllib.urlencode(args)
387
+ req = self._CreateRequest(url=url, data=payload)
388
+ req.add_header("Content-Type", content_type)
389
+ if extra_headers:
390
+ for header, value in extra_headers.items():
391
+ req.add_header(header, value)
392
+ try:
393
+ f = self.opener.open(req)
394
+ response = f.read()
395
+ f.close()
396
+ return response
397
+ except urllib2.HTTPError, e:
398
+ if tries > 3:
399
+ raise
400
+ elif e.code == 401 or e.code == 302:
401
+ self._Authenticate()
402
+ ## elif e.code >= 500 and e.code < 600:
403
+ ## # Server Error - try again.
404
+ ## continue
405
+ elif e.code == 301:
406
+ # Handle permanent redirect manually.
407
+ url = e.info()["location"]
408
+ url_loc = urlparse.urlparse(url)
409
+ self.host = '%s://%s' % (url_loc[0], url_loc[1])
410
+ else:
411
+ raise
412
+ finally:
413
+ socket.setdefaulttimeout(old_timeout)
414
+
415
+
416
+ class HttpRpcServer(AbstractRpcServer):
417
+ """Provides a simplified RPC-style interface for HTTP requests."""
418
+
419
+ def _Authenticate(self):
420
+ """Save the cookie jar after authentication."""
421
+ super(HttpRpcServer, self)._Authenticate()
422
+ if self.save_cookies:
423
+ StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
424
+ self.cookie_jar.save()
425
+
426
+ def _GetOpener(self):
427
+ """Returns an OpenerDirector that supports cookies and ignores redirects.
428
+
429
+ Returns:
430
+ A urllib2.OpenerDirector object.
431
+ """
432
+ opener = urllib2.OpenerDirector()
433
+ opener.add_handler(urllib2.ProxyHandler())
434
+ opener.add_handler(urllib2.UnknownHandler())
435
+ opener.add_handler(urllib2.HTTPHandler())
436
+ opener.add_handler(urllib2.HTTPDefaultErrorHandler())
437
+ opener.add_handler(urllib2.HTTPSHandler())
438
+ opener.add_handler(urllib2.HTTPErrorProcessor())
439
+ if self.save_cookies:
440
+ self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
441
+ self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
442
+ if os.path.exists(self.cookie_file):
443
+ try:
444
+ self.cookie_jar.load()
445
+ self.authenticated = True
446
+ StatusUpdate("Loaded authentication cookies from %s" %
447
+ self.cookie_file)
448
+ except (cookielib.LoadError, IOError):
449
+ # Failed to load cookies - just ignore them.
450
+ pass
451
+ else:
452
+ # Create an empty cookie file with mode 600
453
+ fd = os.open(self.cookie_file, os.O_CREAT, 0600)
454
+ os.close(fd)
455
+ # Always chmod the cookie file
456
+ os.chmod(self.cookie_file, 0600)
457
+ else:
458
+ # Don't save cookies across runs of update.py.
459
+ self.cookie_jar = cookielib.CookieJar()
460
+ opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
461
+ return opener
462
+
463
+
464
+ class CondensedHelpFormatter(optparse.IndentedHelpFormatter):
465
+ """Frees more horizontal space by removing indentation from group
466
+ options and collapsing arguments between short and long, e.g.
467
+ '-o ARG, --opt=ARG' to -o --opt ARG"""
468
+
469
+ def format_heading(self, heading):
470
+ return "%s:\n" % heading
471
+
472
+ def format_option(self, option):
473
+ self.dedent()
474
+ res = optparse.HelpFormatter.format_option(self, option)
475
+ self.indent()
476
+ return res
477
+
478
+ def format_option_strings(self, option):
479
+ self.set_long_opt_delimiter(" ")
480
+ optstr = optparse.HelpFormatter.format_option_strings(self, option)
481
+ optlist = optstr.split(", ")
482
+ if len(optlist) > 1:
483
+ if option.takes_value():
484
+ # strip METAVAR from all but the last option
485
+ optlist = [x.split()[0] for x in optlist[:-1]] + optlist[-1:]
486
+ optstr = " ".join(optlist)
487
+ return optstr
488
+
489
+
490
+ parser = optparse.OptionParser(
491
+ usage="%prog [options] [-- diff_options] [path...]",
492
+ add_help_option=False,
493
+ formatter=CondensedHelpFormatter()
494
+ )
495
+ parser.add_option("-h", "--help", action="store_true",
496
+ help="Show this help message and exit.")
497
+ parser.add_option("-y", "--assume_yes", action="store_true",
498
+ dest="assume_yes", default=False,
499
+ help="Assume that the answer to yes/no questions is 'yes'.")
500
+ # Logging
501
+ group = parser.add_option_group("Logging options")
502
+ group.add_option("-q", "--quiet", action="store_const", const=0,
503
+ dest="verbose", help="Print errors only.")
504
+ group.add_option("-v", "--verbose", action="store_const", const=2,
505
+ dest="verbose", default=1,
506
+ help="Print info level logs.")
507
+ group.add_option("--noisy", action="store_const", const=3,
508
+ dest="verbose", help="Print all logs.")
509
+ group.add_option("--print_diffs", dest="print_diffs", action="store_true",
510
+ help="Print full diffs.")
511
+ # Review server
512
+ group = parser.add_option_group("Review server options")
513
+ group.add_option("-s", "--server", action="store", dest="server",
514
+ default=DEFAULT_REVIEW_SERVER,
515
+ metavar="SERVER",
516
+ help=("The server to upload to. The format is host[:port]. "
517
+ "Defaults to '%default'."))
518
+ group.add_option("-e", "--email", action="store", dest="email",
519
+ metavar="EMAIL", default=None,
520
+ help="The username to use. Will prompt if omitted.")
521
+ group.add_option("-H", "--host", action="store", dest="host",
522
+ metavar="HOST", default=None,
523
+ help="Overrides the Host header sent with all RPCs.")
524
+ group.add_option("--no_cookies", action="store_false",
525
+ dest="save_cookies", default=True,
526
+ help="Do not save authentication cookies to local disk.")
527
+ group.add_option("--account_type", action="store", dest="account_type",
528
+ metavar="TYPE", default=AUTH_ACCOUNT_TYPE,
529
+ choices=["GOOGLE", "HOSTED"],
530
+ help=("Override the default account type "
531
+ "(defaults to '%default', "
532
+ "valid choices are 'GOOGLE' and 'HOSTED')."))
533
+ # Issue
534
+ group = parser.add_option_group("Issue options")
535
+ group.add_option("-d", "--description", action="store", dest="description",
536
+ metavar="DESCRIPTION", default=None,
537
+ help="Optional description when creating an issue.")
538
+ group.add_option("-f", "--description_file", action="store",
539
+ dest="description_file", metavar="DESCRIPTION_FILE",
540
+ default=None,
541
+ help="Optional path of a file that contains "
542
+ "the description when creating an issue.")
543
+ group.add_option("-r", "--reviewers", action="store", dest="reviewers",
544
+ metavar="REVIEWERS", default=None,
545
+ help="Add reviewers (comma separated email addresses).")
546
+ group.add_option("--cc", action="store", dest="cc",
547
+ metavar="CC", default=None,
548
+ help="Add CC (comma separated email addresses).")
549
+ group.add_option("--private", action="store_true", dest="private",
550
+ default=False,
551
+ help="Make the issue restricted to reviewers and those CCed")
552
+ # Upload options
553
+ group = parser.add_option_group("Patch options")
554
+ group.add_option("-m", "--message", action="store", dest="message",
555
+ metavar="MESSAGE", default=None,
556
+ help="A message to identify the patch. "
557
+ "Will prompt if omitted.")
558
+ group.add_option("-i", "--issue", type="int", action="store",
559
+ metavar="ISSUE", default=None,
560
+ help="Issue number to which to add. Defaults to new issue.")
561
+ group.add_option("--base_url", action="store", dest="base_url", default=None,
562
+ help="Base URL path for files (listed as \"Base URL\" when "
563
+ "viewing issue). If omitted, will be guessed automatically "
564
+ "for SVN repos and left blank for others.")
565
+ group.add_option("--download_base", action="store_true",
566
+ dest="download_base", default=False,
567
+ help="Base files will be downloaded by the server "
568
+ "(side-by-side diffs may not work on files with CRs).")
569
+ group.add_option("--rev", action="store", dest="revision",
570
+ metavar="REV", default=None,
571
+ help="Base revision/branch/tree to diff against. Use "
572
+ "rev1:rev2 range to review already committed changeset.")
573
+ group.add_option("--send_mail", action="store_true",
574
+ dest="send_mail", default=False,
575
+ help="Send notification email to reviewers.")
576
+ group.add_option("-p", "--send_patch", action="store_true",
577
+ dest="send_patch", default=False,
578
+ help="Same as --send_mail, but include diff as an "
579
+ "attachment, and prepend email subject with 'PATCH:'.")
580
+ group.add_option("--vcs", action="store", dest="vcs",
581
+ metavar="VCS", default=None,
582
+ help=("Version control system (optional, usually upload.py "
583
+ "already guesses the right VCS)."))
584
+ group.add_option("--emulate_svn_auto_props", action="store_true",
585
+ dest="emulate_svn_auto_props", default=False,
586
+ help=("Emulate Subversion's auto properties feature."))
587
+ # Perforce-specific
588
+ group = parser.add_option_group("Perforce-specific options "
589
+ "(overrides P4 environment variables)")
590
+ group.add_option("--p4_port", action="store", dest="p4_port",
591
+ metavar="P4_PORT", default=None,
592
+ help=("Perforce server and port (optional)"))
593
+ group.add_option("--p4_changelist", action="store", dest="p4_changelist",
594
+ metavar="P4_CHANGELIST", default=None,
595
+ help=("Perforce changelist id"))
596
+ group.add_option("--p4_client", action="store", dest="p4_client",
597
+ metavar="P4_CLIENT", default=None,
598
+ help=("Perforce client/workspace"))
599
+ group.add_option("--p4_user", action="store", dest="p4_user",
600
+ metavar="P4_USER", default=None,
601
+ help=("Perforce user"))
602
+
603
+ def GetRpcServer(server, email=None, host_override=None, save_cookies=True,
604
+ account_type=AUTH_ACCOUNT_TYPE):
605
+ """Returns an instance of an AbstractRpcServer.
606
+
607
+ Args:
608
+ server: String containing the review server URL.
609
+ email: String containing user's email address.
610
+ host_override: If not None, string containing an alternate hostname to use
611
+ in the host header.
612
+ save_cookies: Whether authentication cookies should be saved to disk.
613
+ account_type: Account type for authentication, either 'GOOGLE'
614
+ or 'HOSTED'. Defaults to AUTH_ACCOUNT_TYPE.
615
+
616
+ Returns:
617
+ A new AbstractRpcServer, on which RPC calls can be made.
618
+ """
619
+
620
+ rpc_server_class = HttpRpcServer
621
+
622
+ # If this is the dev_appserver, use fake authentication.
623
+ host = (host_override or server).lower()
624
+ if re.match(r'(http://)?localhost([:/]|$)', host):
625
+ if email is None:
626
+ email = "test@example.com"
627
+ logging.info("Using debug user %s. Override with --email" % email)
628
+ server = rpc_server_class(
629
+ server,
630
+ lambda: (email, "password"),
631
+ host_override=host_override,
632
+ extra_headers={"Cookie":
633
+ 'dev_appserver_login="%s:False"' % email},
634
+ save_cookies=save_cookies,
635
+ account_type=account_type)
636
+ # Don't try to talk to ClientLogin.
637
+ server.authenticated = True
638
+ return server
639
+
640
+ def GetUserCredentials():
641
+ """Prompts the user for a username and password."""
642
+ # Create a local alias to the email variable to avoid Python's crazy
643
+ # scoping rules.
644
+ global keyring
645
+ local_email = email
646
+ if local_email is None:
647
+ local_email = GetEmail("Email (login for uploading to %s)" % server)
648
+ password = None
649
+ if keyring:
650
+ try:
651
+ password = keyring.get_password(host, local_email)
652
+ except:
653
+ # Sadly, we have to trap all errors here as
654
+ # gnomekeyring.IOError inherits from object. :/
655
+ print "Failed to get password from keyring"
656
+ keyring = None
657
+ if password is not None:
658
+ print "Using password from system keyring."
659
+ else:
660
+ password = getpass.getpass("Password for %s: " % local_email)
661
+ if keyring:
662
+ answer = raw_input("Store password in system keyring?(y/N) ").strip()
663
+ if answer == "y":
664
+ keyring.set_password(host, local_email, password)
665
+ return (local_email, password)
666
+
667
+ return rpc_server_class(server,
668
+ GetUserCredentials,
669
+ host_override=host_override,
670
+ save_cookies=save_cookies)
671
+
672
+
673
+ def EncodeMultipartFormData(fields, files):
674
+ """Encode form fields for multipart/form-data.
675
+
676
+ Args:
677
+ fields: A sequence of (name, value) elements for regular form fields.
678
+ files: A sequence of (name, filename, value) elements for data to be
679
+ uploaded as files.
680
+ Returns:
681
+ (content_type, body) ready for httplib.HTTP instance.
682
+
683
+ Source:
684
+ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
685
+ """
686
+ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
687
+ CRLF = '\r\n'
688
+ lines = []
689
+ for (key, value) in fields:
690
+ lines.append('--' + BOUNDARY)
691
+ lines.append('Content-Disposition: form-data; name="%s"' % key)
692
+ lines.append('')
693
+ if isinstance(value, unicode):
694
+ value = value.encode('utf-8')
695
+ lines.append(value)
696
+ for (key, filename, value) in files:
697
+ lines.append('--' + BOUNDARY)
698
+ lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
699
+ (key, filename))
700
+ lines.append('Content-Type: %s' % GetContentType(filename))
701
+ lines.append('')
702
+ if isinstance(value, unicode):
703
+ value = value.encode('utf-8')
704
+ lines.append(value)
705
+ lines.append('--' + BOUNDARY + '--')
706
+ lines.append('')
707
+ body = CRLF.join(lines)
708
+ content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
709
+ return content_type, body
710
+
711
+
712
+ def GetContentType(filename):
713
+ """Helper to guess the content-type from the filename."""
714
+ return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
715
+
716
+
717
+ # Use a shell for subcommands on Windows to get a PATH search.
718
+ use_shell = sys.platform.startswith("win")
719
+
720
+ def RunShellWithReturnCodeAndStderr(command, print_output=False,
721
+ universal_newlines=True,
722
+ env=os.environ):
723
+ """Executes a command and returns the output from stdout, stderr and the return code.
724
+
725
+ Args:
726
+ command: Command to execute.
727
+ print_output: If True, the output is printed to stdout.
728
+ If False, both stdout and stderr are ignored.
729
+ universal_newlines: Use universal_newlines flag (default: True).
730
+
731
+ Returns:
732
+ Tuple (stdout, stderr, return code)
733
+ """
734
+ logging.info("Running %s", command)
735
+ env = env.copy()
736
+ env['LC_MESSAGES'] = 'C'
737
+ p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
738
+ shell=use_shell, universal_newlines=universal_newlines,
739
+ env=env)
740
+ if print_output:
741
+ output_array = []
742
+ while True:
743
+ line = p.stdout.readline()
744
+ if not line:
745
+ break
746
+ print line.strip("\n")
747
+ output_array.append(line)
748
+ output = "".join(output_array)
749
+ else:
750
+ output = p.stdout.read()
751
+ p.wait()
752
+ errout = p.stderr.read()
753
+ if print_output and errout:
754
+ print >>sys.stderr, errout
755
+ p.stdout.close()
756
+ p.stderr.close()
757
+ return output, errout, p.returncode
758
+
759
+ def RunShellWithReturnCode(command, print_output=False,
760
+ universal_newlines=True,
761
+ env=os.environ):
762
+ """Executes a command and returns the output from stdout and the return code."""
763
+ out, err, retcode = RunShellWithReturnCodeAndStderr(command, print_output,
764
+ universal_newlines, env)
765
+ return out, retcode
766
+
767
+ def RunShell(command, silent_ok=False, universal_newlines=True,
768
+ print_output=False, env=os.environ):
769
+ data, retcode = RunShellWithReturnCode(command, print_output,
770
+ universal_newlines, env)
771
+ if retcode:
772
+ ErrorExit("Got error status from %s:\n%s" % (command, data))
773
+ if not silent_ok and not data:
774
+ ErrorExit("No output from %s" % command)
775
+ return data
776
+
777
+
778
+ class VersionControlSystem(object):
779
+ """Abstract base class providing an interface to the VCS."""
780
+
781
+ def __init__(self, options):
782
+ """Constructor.
783
+
784
+ Args:
785
+ options: Command line options.
786
+ """
787
+ self.options = options
788
+
789
+ def GetGUID(self):
790
+ """Return string to distinguish the repository from others, for example to
791
+ query all opened review issues for it"""
792
+ raise NotImplementedError(
793
+ "abstract method -- subclass %s must override" % self.__class__)
794
+
795
+ def PostProcessDiff(self, diff):
796
+ """Return the diff with any special post processing this VCS needs, e.g.
797
+ to include an svn-style "Index:"."""
798
+ return diff
799
+
800
+ def GenerateDiff(self, args):
801
+ """Return the current diff as a string.
802
+
803
+ Args:
804
+ args: Extra arguments to pass to the diff command.
805
+ """
806
+ raise NotImplementedError(
807
+ "abstract method -- subclass %s must override" % self.__class__)
808
+
809
+ def GetUnknownFiles(self):
810
+ """Return a list of files unknown to the VCS."""
811
+ raise NotImplementedError(
812
+ "abstract method -- subclass %s must override" % self.__class__)
813
+
814
+ def CheckForUnknownFiles(self):
815
+ """Show an "are you sure?" prompt if there are unknown files."""
816
+ unknown_files = self.GetUnknownFiles()
817
+ if unknown_files:
818
+ print "The following files are not added to version control:"
819
+ for line in unknown_files:
820
+ print line
821
+ prompt = "Are you sure to continue?(y/N) "
822
+ answer = raw_input(prompt).strip()
823
+ if answer != "y":
824
+ ErrorExit("User aborted")
825
+
826
+ def GetBaseFile(self, filename):
827
+ """Get the content of the upstream version of a file.
828
+
829
+ Returns:
830
+ A tuple (base_content, new_content, is_binary, status)
831
+ base_content: The contents of the base file.
832
+ new_content: For text files, this is empty. For binary files, this is
833
+ the contents of the new file, since the diff output won't contain
834
+ information to reconstruct the current file.
835
+ is_binary: True iff the file is binary.
836
+ status: The status of the file.
837
+ """
838
+
839
+ raise NotImplementedError(
840
+ "abstract method -- subclass %s must override" % self.__class__)
841
+
842
+
843
+ def GetBaseFiles(self, diff):
844
+ """Helper that calls GetBase file for each file in the patch.
845
+
846
+ Returns:
847
+ A dictionary that maps from filename to GetBaseFile's tuple. Filenames
848
+ are retrieved based on lines that start with "Index:" or
849
+ "Property changes on:".
850
+ """
851
+ files = {}
852
+ for line in diff.splitlines(True):
853
+ if line.startswith('Index:') or line.startswith('Property changes on:'):
854
+ unused, filename = line.split(':', 1)
855
+ # On Windows if a file has property changes its filename uses '\'
856
+ # instead of '/'.
857
+ filename = filename.strip().replace('\\', '/')
858
+ files[filename] = self.GetBaseFile(filename)
859
+ return files
860
+
861
+
862
+ def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
863
+ files):
864
+ """Uploads the base files (and if necessary, the current ones as well)."""
865
+
866
+ def UploadFile(filename, file_id, content, is_binary, status, is_base):
867
+ """Uploads a file to the server."""
868
+ file_too_large = False
869
+ if is_base:
870
+ type = "base"
871
+ else:
872
+ type = "current"
873
+ if len(content) > MAX_UPLOAD_SIZE:
874
+ print ("Not uploading the %s file for %s because it's too large." %
875
+ (type, filename))
876
+ file_too_large = True
877
+ content = ""
878
+ checksum = md5(content).hexdigest()
879
+ if options.verbose > 0 and not file_too_large:
880
+ print "Uploading %s file for %s" % (type, filename)
881
+ url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
882
+ form_fields = [("filename", filename),
883
+ ("status", status),
884
+ ("checksum", checksum),
885
+ ("is_binary", str(is_binary)),
886
+ ("is_current", str(not is_base)),
887
+ ]
888
+ if file_too_large:
889
+ form_fields.append(("file_too_large", "1"))
890
+ if options.email:
891
+ form_fields.append(("user", options.email))
892
+ ctype, body = EncodeMultipartFormData(form_fields,
893
+ [("data", filename, content)])
894
+ response_body = rpc_server.Send(url, body,
895
+ content_type=ctype)
896
+ if not response_body.startswith("OK"):
897
+ StatusUpdate(" --> %s" % response_body)
898
+ sys.exit(1)
899
+
900
+ patches = dict()
901
+ [patches.setdefault(v, k) for k, v in patch_list]
902
+ for filename in patches.keys():
903
+ base_content, new_content, is_binary, status = files[filename]
904
+ file_id_str = patches.get(filename)
905
+ if file_id_str.find("nobase") != -1:
906
+ base_content = None
907
+ file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
908
+ file_id = int(file_id_str)
909
+ if base_content != None:
910
+ UploadFile(filename, file_id, base_content, is_binary, status, True)
911
+ if new_content != None:
912
+ UploadFile(filename, file_id, new_content, is_binary, status, False)
913
+
914
+ def IsImage(self, filename):
915
+ """Returns true if the filename has an image extension."""
916
+ mimetype = mimetypes.guess_type(filename)[0]
917
+ if not mimetype:
918
+ return False
919
+ return mimetype.startswith("image/")
920
+
921
+ def IsBinaryData(self, data):
922
+ """Returns true if data contains a null byte."""
923
+ # Derived from how Mercurial's heuristic, see
924
+ # http://selenic.com/hg/file/848a6658069e/mercurial/util.py#l229
925
+ return bool(data and "\0" in data)
926
+
927
+
928
+ class SubversionVCS(VersionControlSystem):
929
+ """Implementation of the VersionControlSystem interface for Subversion."""
930
+
931
+ def __init__(self, options):
932
+ super(SubversionVCS, self).__init__(options)
933
+ if self.options.revision:
934
+ match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
935
+ if not match:
936
+ ErrorExit("Invalid Subversion revision %s." % self.options.revision)
937
+ self.rev_start = match.group(1)
938
+ self.rev_end = match.group(3)
939
+ else:
940
+ self.rev_start = self.rev_end = None
941
+ # Cache output from "svn list -r REVNO dirname".
942
+ # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
943
+ self.svnls_cache = {}
944
+ # Base URL is required to fetch files deleted in an older revision.
945
+ # Result is cached to not guess it over and over again in GetBaseFile().
946
+ required = self.options.download_base or self.options.revision is not None
947
+ self.svn_base = self._GuessBase(required)
948
+
949
+ def GetGUID(self):
950
+ return self._GetInfo("Repository UUID")
951
+
952
+ def GuessBase(self, required):
953
+ """Wrapper for _GuessBase."""
954
+ return self.svn_base
955
+
956
+ def _GuessBase(self, required):
957
+ """Returns base URL for current diff.
958
+
959
+ Args:
960
+ required: If true, exits if the url can't be guessed, otherwise None is
961
+ returned.
962
+ """
963
+ url = self._GetInfo("URL")
964
+ if url:
965
+ scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
966
+ guess = ""
967
+ # TODO(anatoli) - repository specific hacks should be handled by server
968
+ if netloc == "svn.python.org" and scheme == "svn+ssh":
969
+ path = "projects" + path
970
+ scheme = "http"
971
+ guess = "Python "
972
+ elif netloc.endswith(".googlecode.com"):
973
+ scheme = "http"
974
+ guess = "Google Code "
975
+ path = path + "/"
976
+ base = urlparse.urlunparse((scheme, netloc, path, params,
977
+ query, fragment))
978
+ logging.info("Guessed %sbase = %s", guess, base)
979
+ return base
980
+ if required:
981
+ ErrorExit("Can't find URL in output from svn info")
982
+ return None
983
+
984
+ def _GetInfo(self, key):
985
+ """Parses 'svn info' for current dir. Returns value for key or None"""
986
+ for line in RunShell(["svn", "info"]).splitlines():
987
+ if line.startswith(key + ": "):
988
+ return line.split(":", 1)[1].strip()
989
+
990
+ def _EscapeFilename(self, filename):
991
+ """Escapes filename for SVN commands."""
992
+ if "@" in filename and not filename.endswith("@"):
993
+ filename = "%s@" % filename
994
+ return filename
995
+
996
+ def GenerateDiff(self, args):
997
+ cmd = ["svn", "diff"]
998
+ if self.options.revision:
999
+ cmd += ["-r", self.options.revision]
1000
+ cmd.extend(args)
1001
+ data = RunShell(cmd)
1002
+ count = 0
1003
+ for line in data.splitlines():
1004
+ if line.startswith("Index:") or line.startswith("Property changes on:"):
1005
+ count += 1
1006
+ logging.info(line)
1007
+ if not count:
1008
+ ErrorExit("No valid patches found in output from svn diff")
1009
+ return data
1010
+
1011
+ def _CollapseKeywords(self, content, keyword_str):
1012
+ """Collapses SVN keywords."""
1013
+ # svn cat translates keywords but svn diff doesn't. As a result of this
1014
+ # behavior patching.PatchChunks() fails with a chunk mismatch error.
1015
+ # This part was originally written by the Review Board development team
1016
+ # who had the same problem (http://reviews.review-board.org/r/276/).
1017
+ # Mapping of keywords to known aliases
1018
+ svn_keywords = {
1019
+ # Standard keywords
1020
+ 'Date': ['Date', 'LastChangedDate'],
1021
+ 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
1022
+ 'Author': ['Author', 'LastChangedBy'],
1023
+ 'HeadURL': ['HeadURL', 'URL'],
1024
+ 'Id': ['Id'],
1025
+
1026
+ # Aliases
1027
+ 'LastChangedDate': ['LastChangedDate', 'Date'],
1028
+ 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
1029
+ 'LastChangedBy': ['LastChangedBy', 'Author'],
1030
+ 'URL': ['URL', 'HeadURL'],
1031
+ }
1032
+
1033
+ def repl(m):
1034
+ if m.group(2):
1035
+ return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
1036
+ return "$%s$" % m.group(1)
1037
+ keywords = [keyword
1038
+ for name in keyword_str.split(" ")
1039
+ for keyword in svn_keywords.get(name, [])]
1040
+ return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
1041
+
1042
+ def GetUnknownFiles(self):
1043
+ status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
1044
+ unknown_files = []
1045
+ for line in status.split("\n"):
1046
+ if line and line[0] == "?":
1047
+ unknown_files.append(line)
1048
+ return unknown_files
1049
+
1050
+ def ReadFile(self, filename):
1051
+ """Returns the contents of a file."""
1052
+ file = open(filename, 'rb')
1053
+ result = ""
1054
+ try:
1055
+ result = file.read()
1056
+ finally:
1057
+ file.close()
1058
+ return result
1059
+
1060
+ def GetStatus(self, filename):
1061
+ """Returns the status of a file."""
1062
+ if not self.options.revision:
1063
+ status = RunShell(["svn", "status", "--ignore-externals",
1064
+ self._EscapeFilename(filename)])
1065
+ if not status:
1066
+ ErrorExit("svn status returned no output for %s" % filename)
1067
+ status_lines = status.splitlines()
1068
+ # If file is in a cl, the output will begin with
1069
+ # "\n--- Changelist 'cl_name':\n". See
1070
+ # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
1071
+ if (len(status_lines) == 3 and
1072
+ not status_lines[0] and
1073
+ status_lines[1].startswith("--- Changelist")):
1074
+ status = status_lines[2]
1075
+ else:
1076
+ status = status_lines[0]
1077
+ # If we have a revision to diff against we need to run "svn list"
1078
+ # for the old and the new revision and compare the results to get
1079
+ # the correct status for a file.
1080
+ else:
1081
+ dirname, relfilename = os.path.split(filename)
1082
+ if dirname not in self.svnls_cache:
1083
+ cmd = ["svn", "list", "-r", self.rev_start,
1084
+ self._EscapeFilename(dirname) or "."]
1085
+ out, err, returncode = RunShellWithReturnCodeAndStderr(cmd)
1086
+ if returncode:
1087
+ # Directory might not yet exist at start revison
1088
+ # svn: Unable to find repository location for 'abc' in revision nnn
1089
+ if re.match('^svn: Unable to find repository location for .+ in revision \d+', err):
1090
+ old_files = ()
1091
+ else:
1092
+ ErrorExit("Failed to get status for %s:\n%s" % (filename, err))
1093
+ else:
1094
+ old_files = out.splitlines()
1095
+ args = ["svn", "list"]
1096
+ if self.rev_end:
1097
+ args += ["-r", self.rev_end]
1098
+ cmd = args + [self._EscapeFilename(dirname) or "."]
1099
+ out, returncode = RunShellWithReturnCode(cmd)
1100
+ if returncode:
1101
+ ErrorExit("Failed to run command %s" % cmd)
1102
+ self.svnls_cache[dirname] = (old_files, out.splitlines())
1103
+ old_files, new_files = self.svnls_cache[dirname]
1104
+ if relfilename in old_files and relfilename not in new_files:
1105
+ status = "D "
1106
+ elif relfilename in old_files and relfilename in new_files:
1107
+ status = "M "
1108
+ else:
1109
+ status = "A "
1110
+ return status
1111
+
1112
+ def GetBaseFile(self, filename):
1113
+ status = self.GetStatus(filename)
1114
+ base_content = None
1115
+ new_content = None
1116
+
1117
+ # If a file is copied its status will be "A +", which signifies
1118
+ # "addition-with-history". See "svn st" for more information. We need to
1119
+ # upload the original file or else diff parsing will fail if the file was
1120
+ # edited.
1121
+ if status[0] == "A" and status[3] != "+":
1122
+ # We'll need to upload the new content if we're adding a binary file
1123
+ # since diff's output won't contain it.
1124
+ mimetype = RunShell(["svn", "propget", "svn:mime-type",
1125
+ self._EscapeFilename(filename)], silent_ok=True)
1126
+ base_content = ""
1127
+ is_binary = bool(mimetype) and not mimetype.startswith("text/")
1128
+ if is_binary and self.IsImage(filename):
1129
+ new_content = self.ReadFile(filename)
1130
+ elif (status[0] in ("M", "D", "R") or
1131
+ (status[0] == "A" and status[3] == "+") or # Copied file.
1132
+ (status[0] == " " and status[1] == "M")): # Property change.
1133
+ args = []
1134
+ if self.options.revision:
1135
+ # filename must not be escaped. We already add an ampersand here.
1136
+ url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
1137
+ else:
1138
+ # Don't change filename, it's needed later.
1139
+ url = filename
1140
+ args += ["-r", "BASE"]
1141
+ cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
1142
+ mimetype, returncode = RunShellWithReturnCode(cmd)
1143
+ if returncode:
1144
+ # File does not exist in the requested revision.
1145
+ # Reset mimetype, it contains an error message.
1146
+ mimetype = ""
1147
+ else:
1148
+ mimetype = mimetype.strip()
1149
+ get_base = False
1150
+ # this test for binary is exactly the test prescribed by the
1151
+ # official SVN docs at
1152
+ # http://subversion.apache.org/faq.html#binary-files
1153
+ is_binary = (bool(mimetype) and
1154
+ not mimetype.startswith("text/") and
1155
+ mimetype not in ("image/x-xbitmap", "image/x-xpixmap"))
1156
+ if status[0] == " ":
1157
+ # Empty base content just to force an upload.
1158
+ base_content = ""
1159
+ elif is_binary:
1160
+ if self.IsImage(filename):
1161
+ get_base = True
1162
+ if status[0] == "M":
1163
+ if not self.rev_end:
1164
+ new_content = self.ReadFile(filename)
1165
+ else:
1166
+ url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
1167
+ new_content = RunShell(["svn", "cat", url],
1168
+ universal_newlines=True, silent_ok=True)
1169
+ else:
1170
+ base_content = ""
1171
+ else:
1172
+ get_base = True
1173
+
1174
+ if get_base:
1175
+ if is_binary:
1176
+ universal_newlines = False
1177
+ else:
1178
+ universal_newlines = True
1179
+ if self.rev_start:
1180
+ # "svn cat -r REV delete_file.txt" doesn't work. cat requires
1181
+ # the full URL with "@REV" appended instead of using "-r" option.
1182
+ url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
1183
+ base_content = RunShell(["svn", "cat", url],
1184
+ universal_newlines=universal_newlines,
1185
+ silent_ok=True)
1186
+ else:
1187
+ base_content, ret_code = RunShellWithReturnCode(
1188
+ ["svn", "cat", self._EscapeFilename(filename)],
1189
+ universal_newlines=universal_newlines)
1190
+ if ret_code and status[0] == "R":
1191
+ # It's a replaced file without local history (see issue208).
1192
+ # The base file needs to be fetched from the server.
1193
+ url = "%s/%s" % (self.svn_base, filename)
1194
+ base_content = RunShell(["svn", "cat", url],
1195
+ universal_newlines=universal_newlines,
1196
+ silent_ok=True)
1197
+ elif ret_code:
1198
+ ErrorExit("Got error status from 'svn cat %s'" % filename)
1199
+ if not is_binary:
1200
+ args = []
1201
+ if self.rev_start:
1202
+ url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
1203
+ else:
1204
+ url = filename
1205
+ args += ["-r", "BASE"]
1206
+ cmd = ["svn"] + args + ["propget", "svn:keywords", url]
1207
+ keywords, returncode = RunShellWithReturnCode(cmd)
1208
+ if keywords and not returncode:
1209
+ base_content = self._CollapseKeywords(base_content, keywords)
1210
+ else:
1211
+ StatusUpdate("svn status returned unexpected output: %s" % status)
1212
+ sys.exit(1)
1213
+ return base_content, new_content, is_binary, status[0:5]
1214
+
1215
+
1216
+ class GitVCS(VersionControlSystem):
1217
+ """Implementation of the VersionControlSystem interface for Git."""
1218
+
1219
+ def __init__(self, options):
1220
+ super(GitVCS, self).__init__(options)
1221
+ # Map of filename -> (hash before, hash after) of base file.
1222
+ # Hashes for "no such file" are represented as None.
1223
+ self.hashes = {}
1224
+ # Map of new filename -> old filename for renames.
1225
+ self.renames = {}
1226
+
1227
+ def GetGUID(self):
1228
+ revlist = RunShell("git rev-list --parents HEAD".split()).splitlines()
1229
+ # M-A: Return the 1st root hash, there could be multiple when a
1230
+ # subtree is merged. In that case, more analysis would need to
1231
+ # be done to figure out which HEAD is the 'most representative'.
1232
+ for r in revlist:
1233
+ if ' ' not in r:
1234
+ return r
1235
+
1236
+ def PostProcessDiff(self, gitdiff):
1237
+ """Converts the diff output to include an svn-style "Index:" line as well
1238
+ as record the hashes of the files, so we can upload them along with our
1239
+ diff."""
1240
+ # Special used by git to indicate "no such content".
1241
+ NULL_HASH = "0"*40
1242
+
1243
+ def IsFileNew(filename):
1244
+ return filename in self.hashes and self.hashes[filename][0] is None
1245
+
1246
+ def AddSubversionPropertyChange(filename):
1247
+ """Add svn's property change information into the patch if given file is
1248
+ new file.
1249
+
1250
+ We use Subversion's auto-props setting to retrieve its property.
1251
+ See http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.2 for
1252
+ Subversion's [auto-props] setting.
1253
+ """
1254
+ if self.options.emulate_svn_auto_props and IsFileNew(filename):
1255
+ svnprops = GetSubversionPropertyChanges(filename)
1256
+ if svnprops:
1257
+ svndiff.append("\n" + svnprops + "\n")
1258
+
1259
+ svndiff = []
1260
+ filecount = 0
1261
+ filename = None
1262
+ for line in gitdiff.splitlines():
1263
+ match = re.match(r"diff --git a/(.*) b/(.*)$", line)
1264
+ if match:
1265
+ # Add auto property here for previously seen file.
1266
+ if filename is not None:
1267
+ AddSubversionPropertyChange(filename)
1268
+ filecount += 1
1269
+ # Intentionally use the "after" filename so we can show renames.
1270
+ filename = match.group(2)
1271
+ svndiff.append("Index: %s\n" % filename)
1272
+ if match.group(1) != match.group(2):
1273
+ self.renames[match.group(2)] = match.group(1)
1274
+ else:
1275
+ # The "index" line in a git diff looks like this (long hashes elided):
1276
+ # index 82c0d44..b2cee3f 100755
1277
+ # We want to save the left hash, as that identifies the base file.
1278
+ match = re.match(r"index (\w+)\.\.(\w+)", line)
1279
+ if match:
1280
+ before, after = (match.group(1), match.group(2))
1281
+ if before == NULL_HASH:
1282
+ before = None
1283
+ if after == NULL_HASH:
1284
+ after = None
1285
+ self.hashes[filename] = (before, after)
1286
+ svndiff.append(line + "\n")
1287
+ if not filecount:
1288
+ ErrorExit("No valid patches found in output from git diff")
1289
+ # Add auto property for the last seen file.
1290
+ assert filename is not None
1291
+ AddSubversionPropertyChange(filename)
1292
+ return "".join(svndiff)
1293
+
1294
+ def GenerateDiff(self, extra_args):
1295
+ extra_args = extra_args[:]
1296
+ if self.options.revision:
1297
+ if ":" in self.options.revision:
1298
+ extra_args = self.options.revision.split(":", 1) + extra_args
1299
+ else:
1300
+ extra_args = [self.options.revision] + extra_args
1301
+
1302
+ # --no-ext-diff is broken in some versions of Git, so try to work around
1303
+ # this by overriding the environment (but there is still a problem if the
1304
+ # git config key "diff.external" is used).
1305
+ env = os.environ.copy()
1306
+ if 'GIT_EXTERNAL_DIFF' in env: del env['GIT_EXTERNAL_DIFF']
1307
+ return RunShell(["git", "diff", "--no-ext-diff", "--full-index",
1308
+ "--ignore-submodules", "-M"] + extra_args, env=env)
1309
+
1310
+ def GetUnknownFiles(self):
1311
+ status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
1312
+ silent_ok=True)
1313
+ return status.splitlines()
1314
+
1315
+ def GetFileContent(self, file_hash, is_binary):
1316
+ """Returns the content of a file identified by its git hash."""
1317
+ data, retcode = RunShellWithReturnCode(["git", "show", file_hash],
1318
+ universal_newlines=not is_binary)
1319
+ if retcode:
1320
+ ErrorExit("Got error status from 'git show %s'" % file_hash)
1321
+ return data
1322
+
1323
+ def GetBaseFile(self, filename):
1324
+ hash_before, hash_after = self.hashes.get(filename, (None,None))
1325
+ base_content = None
1326
+ new_content = None
1327
+ status = None
1328
+
1329
+ if filename in self.renames:
1330
+ status = "A +" # Match svn attribute name for renames.
1331
+ if filename not in self.hashes:
1332
+ # If a rename doesn't change the content, we never get a hash.
1333
+ base_content = RunShell(["git", "show", "HEAD:" + filename])
1334
+ elif not hash_before:
1335
+ status = "A"
1336
+ base_content = ""
1337
+ elif not hash_after:
1338
+ status = "D"
1339
+ else:
1340
+ status = "M"
1341
+
1342
+ is_binary = self.IsBinaryData(base_content)
1343
+ is_image = self.IsImage(filename)
1344
+
1345
+ # Grab the before/after content if we need it.
1346
+ # We should include file contents if it's text or it's an image.
1347
+ if not is_binary or is_image:
1348
+ # Grab the base content if we don't have it already.
1349
+ if base_content is None and hash_before:
1350
+ base_content = self.GetFileContent(hash_before, is_binary)
1351
+ # Only include the "after" file if it's an image; otherwise it
1352
+ # it is reconstructed from the diff.
1353
+ if is_image and hash_after:
1354
+ new_content = self.GetFileContent(hash_after, is_binary)
1355
+
1356
+ return (base_content, new_content, is_binary, status)
1357
+
1358
+
1359
+ class CVSVCS(VersionControlSystem):
1360
+ """Implementation of the VersionControlSystem interface for CVS."""
1361
+
1362
+ def __init__(self, options):
1363
+ super(CVSVCS, self).__init__(options)
1364
+
1365
+ def GetGUID(self):
1366
+ """For now we don't know how to get repository ID for CVS"""
1367
+ return
1368
+
1369
+ def GetOriginalContent_(self, filename):
1370
+ RunShell(["cvs", "up", filename], silent_ok=True)
1371
+ # TODO need detect file content encoding
1372
+ content = open(filename).read()
1373
+ return content.replace("\r\n", "\n")
1374
+
1375
+ def GetBaseFile(self, filename):
1376
+ base_content = None
1377
+ new_content = None
1378
+ status = "A"
1379
+
1380
+ output, retcode = RunShellWithReturnCode(["cvs", "status", filename])
1381
+ if retcode:
1382
+ ErrorExit("Got error status from 'cvs status %s'" % filename)
1383
+
1384
+ if output.find("Status: Locally Modified") != -1:
1385
+ status = "M"
1386
+ temp_filename = "%s.tmp123" % filename
1387
+ os.rename(filename, temp_filename)
1388
+ base_content = self.GetOriginalContent_(filename)
1389
+ os.rename(temp_filename, filename)
1390
+ elif output.find("Status: Locally Added"):
1391
+ status = "A"
1392
+ base_content = ""
1393
+ elif output.find("Status: Needs Checkout"):
1394
+ status = "D"
1395
+ base_content = self.GetOriginalContent_(filename)
1396
+
1397
+ return (base_content, new_content, self.IsBinaryData(base_content), status)
1398
+
1399
+ def GenerateDiff(self, extra_args):
1400
+ cmd = ["cvs", "diff", "-u", "-N"]
1401
+ if self.options.revision:
1402
+ cmd += ["-r", self.options.revision]
1403
+
1404
+ cmd.extend(extra_args)
1405
+ data, retcode = RunShellWithReturnCode(cmd)
1406
+ count = 0
1407
+ if retcode in [0, 1]:
1408
+ for line in data.splitlines():
1409
+ if line.startswith("Index:"):
1410
+ count += 1
1411
+ logging.info(line)
1412
+
1413
+ if not count:
1414
+ ErrorExit("No valid patches found in output from cvs diff")
1415
+
1416
+ return data
1417
+
1418
+ def GetUnknownFiles(self):
1419
+ data, retcode = RunShellWithReturnCode(["cvs", "diff"])
1420
+ if retcode not in [0, 1]:
1421
+ ErrorExit("Got error status from 'cvs diff':\n%s" % (data,))
1422
+ unknown_files = []
1423
+ for line in data.split("\n"):
1424
+ if line and line[0] == "?":
1425
+ unknown_files.append(line)
1426
+ return unknown_files
1427
+
1428
+ class MercurialVCS(VersionControlSystem):
1429
+ """Implementation of the VersionControlSystem interface for Mercurial."""
1430
+
1431
+ def __init__(self, options, repo_dir):
1432
+ super(MercurialVCS, self).__init__(options)
1433
+ # Absolute path to repository (we can be in a subdir)
1434
+ self.repo_dir = os.path.normpath(repo_dir)
1435
+ # Compute the subdir
1436
+ cwd = os.path.normpath(os.getcwd())
1437
+ assert cwd.startswith(self.repo_dir)
1438
+ self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
1439
+ if self.options.revision:
1440
+ self.base_rev = self.options.revision
1441
+ else:
1442
+ self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
1443
+
1444
+ def GetGUID(self):
1445
+ # See chapter "Uniquely identifying a repository"
1446
+ # http://hgbook.red-bean.com/read/customizing-the-output-of-mercurial.html
1447
+ info = RunShell("hg log -r0 --template {node}".split())
1448
+ return info.strip()
1449
+
1450
+ def _GetRelPath(self, filename):
1451
+ """Get relative path of a file according to the current directory,
1452
+ given its logical path in the repo."""
1453
+ assert filename.startswith(self.subdir), (filename, self.subdir)
1454
+ return filename[len(self.subdir):].lstrip(r"\/")
1455
+
1456
+ def GenerateDiff(self, extra_args):
1457
+ cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
1458
+ data = RunShell(cmd, silent_ok=True)
1459
+ svndiff = []
1460
+ filecount = 0
1461
+ for line in data.splitlines():
1462
+ m = re.match("diff --git a/(\S+) b/(\S+)", line)
1463
+ if m:
1464
+ # Modify line to make it look like as it comes from svn diff.
1465
+ # With this modification no changes on the server side are required
1466
+ # to make upload.py work with Mercurial repos.
1467
+ # NOTE: for proper handling of moved/copied files, we have to use
1468
+ # the second filename.
1469
+ filename = m.group(2)
1470
+ svndiff.append("Index: %s" % filename)
1471
+ svndiff.append("=" * 67)
1472
+ filecount += 1
1473
+ logging.info(line)
1474
+ else:
1475
+ svndiff.append(line)
1476
+ if not filecount:
1477
+ ErrorExit("No valid patches found in output from hg diff")
1478
+ return "\n".join(svndiff) + "\n"
1479
+
1480
+ def GetUnknownFiles(self):
1481
+ """Return a list of files unknown to the VCS."""
1482
+ args = []
1483
+ status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
1484
+ silent_ok=True)
1485
+ unknown_files = []
1486
+ for line in status.splitlines():
1487
+ st, fn = line.split(" ", 1)
1488
+ if st == "?":
1489
+ unknown_files.append(fn)
1490
+ return unknown_files
1491
+
1492
+ def GetBaseFile(self, filename):
1493
+ # "hg status" and "hg cat" both take a path relative to the current subdir
1494
+ # rather than to the repo root, but "hg diff" has given us the full path
1495
+ # to the repo root.
1496
+ base_content = ""
1497
+ new_content = None
1498
+ is_binary = False
1499
+ oldrelpath = relpath = self._GetRelPath(filename)
1500
+ # "hg status -C" returns two lines for moved/copied files, one otherwise
1501
+ out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
1502
+ out = out.splitlines()
1503
+ # HACK: strip error message about missing file/directory if it isn't in
1504
+ # the working copy
1505
+ if out[0].startswith('%s: ' % relpath):
1506
+ out = out[1:]
1507
+ status, _ = out[0].split(' ', 1)
1508
+ if len(out) > 1 and status == "A":
1509
+ # Moved/copied => considered as modified, use old filename to
1510
+ # retrieve base contents
1511
+ oldrelpath = out[1].strip()
1512
+ status = "M"
1513
+ if ":" in self.base_rev:
1514
+ base_rev = self.base_rev.split(":", 1)[0]
1515
+ else:
1516
+ base_rev = self.base_rev
1517
+ if status != "A":
1518
+ base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
1519
+ silent_ok=True)
1520
+ is_binary = self.IsBinaryData(base_content)
1521
+ if status != "R":
1522
+ new_content = open(relpath, "rb").read()
1523
+ is_binary = is_binary or self.IsBinaryData(new_content)
1524
+ if is_binary and base_content:
1525
+ # Fetch again without converting newlines
1526
+ base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
1527
+ silent_ok=True, universal_newlines=False)
1528
+ if not is_binary or not self.IsImage(relpath):
1529
+ new_content = None
1530
+ return base_content, new_content, is_binary, status
1531
+
1532
+
1533
+ class PerforceVCS(VersionControlSystem):
1534
+ """Implementation of the VersionControlSystem interface for Perforce."""
1535
+
1536
+ def __init__(self, options):
1537
+
1538
+ def ConfirmLogin():
1539
+ # Make sure we have a valid perforce session
1540
+ while True:
1541
+ data, retcode = self.RunPerforceCommandWithReturnCode(
1542
+ ["login", "-s"], marshal_output=True)
1543
+ if not data:
1544
+ ErrorExit("Error checking perforce login")
1545
+ if not retcode and (not "code" in data or data["code"] != "error"):
1546
+ break
1547
+ print "Enter perforce password: "
1548
+ self.RunPerforceCommandWithReturnCode(["login"])
1549
+
1550
+ super(PerforceVCS, self).__init__(options)
1551
+
1552
+ self.p4_changelist = options.p4_changelist
1553
+ if not self.p4_changelist:
1554
+ ErrorExit("A changelist id is required")
1555
+ if (options.revision):
1556
+ ErrorExit("--rev is not supported for perforce")
1557
+
1558
+ self.p4_port = options.p4_port
1559
+ self.p4_client = options.p4_client
1560
+ self.p4_user = options.p4_user
1561
+
1562
+ ConfirmLogin()
1563
+
1564
+ if not options.message:
1565
+ description = self.RunPerforceCommand(["describe", self.p4_changelist],
1566
+ marshal_output=True)
1567
+ if description and "desc" in description:
1568
+ # Rietveld doesn't support multi-line descriptions
1569
+ raw_message = description["desc"].strip()
1570
+ lines = raw_message.splitlines()
1571
+ if len(lines):
1572
+ options.message = lines[0]
1573
+
1574
+ def GetGUID(self):
1575
+ """For now we don't know how to get repository ID for Perforce"""
1576
+ return
1577
+
1578
+ def RunPerforceCommandWithReturnCode(self, extra_args, marshal_output=False,
1579
+ universal_newlines=True):
1580
+ args = ["p4"]
1581
+ if marshal_output:
1582
+ # -G makes perforce format its output as marshalled python objects
1583
+ args.extend(["-G"])
1584
+ if self.p4_port:
1585
+ args.extend(["-p", self.p4_port])
1586
+ if self.p4_client:
1587
+ args.extend(["-c", self.p4_client])
1588
+ if self.p4_user:
1589
+ args.extend(["-u", self.p4_user])
1590
+ args.extend(extra_args)
1591
+
1592
+ data, retcode = RunShellWithReturnCode(
1593
+ args, print_output=False, universal_newlines=universal_newlines)
1594
+ if marshal_output and data:
1595
+ data = marshal.loads(data)
1596
+ return data, retcode
1597
+
1598
+ def RunPerforceCommand(self, extra_args, marshal_output=False,
1599
+ universal_newlines=True):
1600
+ # This might be a good place to cache call results, since things like
1601
+ # describe or fstat might get called repeatedly.
1602
+ data, retcode = self.RunPerforceCommandWithReturnCode(
1603
+ extra_args, marshal_output, universal_newlines)
1604
+ if retcode:
1605
+ ErrorExit("Got error status from %s:\n%s" % (extra_args, data))
1606
+ return data
1607
+
1608
+ def GetFileProperties(self, property_key_prefix = "", command = "describe"):
1609
+ description = self.RunPerforceCommand(["describe", self.p4_changelist],
1610
+ marshal_output=True)
1611
+
1612
+ changed_files = {}
1613
+ file_index = 0
1614
+ # Try depotFile0, depotFile1, ... until we don't find a match
1615
+ while True:
1616
+ file_key = "depotFile%d" % file_index
1617
+ if file_key in description:
1618
+ filename = description[file_key]
1619
+ change_type = description[property_key_prefix + str(file_index)]
1620
+ changed_files[filename] = change_type
1621
+ file_index += 1
1622
+ else:
1623
+ break
1624
+ return changed_files
1625
+
1626
+ def GetChangedFiles(self):
1627
+ return self.GetFileProperties("action")
1628
+
1629
+ def GetUnknownFiles(self):
1630
+ # Perforce doesn't detect new files, they have to be explicitly added
1631
+ return []
1632
+
1633
+ def IsBaseBinary(self, filename):
1634
+ base_filename = self.GetBaseFilename(filename)
1635
+ return self.IsBinaryHelper(base_filename, "files")
1636
+
1637
+ def IsPendingBinary(self, filename):
1638
+ return self.IsBinaryHelper(filename, "describe")
1639
+
1640
+ def IsBinaryHelper(self, filename, command):
1641
+ file_types = self.GetFileProperties("type", command)
1642
+ if not filename in file_types:
1643
+ ErrorExit("Trying to check binary status of unknown file %s." % filename)
1644
+ # This treats symlinks, macintosh resource files, temporary objects, and
1645
+ # unicode as binary. See the Perforce docs for more details:
1646
+ # http://www.perforce.com/perforce/doc.current/manuals/cmdref/o.ftypes.html
1647
+ return not file_types[filename].endswith("text")
1648
+
1649
+ def GetFileContent(self, filename, revision, is_binary):
1650
+ file_arg = filename
1651
+ if revision:
1652
+ file_arg += "#" + revision
1653
+ # -q suppresses the initial line that displays the filename and revision
1654
+ return self.RunPerforceCommand(["print", "-q", file_arg],
1655
+ universal_newlines=not is_binary)
1656
+
1657
+ def GetBaseFilename(self, filename):
1658
+ actionsWithDifferentBases = [
1659
+ "move/add", # p4 move
1660
+ "branch", # p4 integrate (to a new file), similar to hg "add"
1661
+ "add", # p4 integrate (to a new file), after modifying the new file
1662
+ ]
1663
+
1664
+ # We only see a different base for "add" if this is a downgraded branch
1665
+ # after a file was branched (integrated), then edited.
1666
+ if self.GetAction(filename) in actionsWithDifferentBases:
1667
+ # -Or shows information about pending integrations/moves
1668
+ fstat_result = self.RunPerforceCommand(["fstat", "-Or", filename],
1669
+ marshal_output=True)
1670
+
1671
+ baseFileKey = "resolveFromFile0" # I think it's safe to use only file0
1672
+ if baseFileKey in fstat_result:
1673
+ return fstat_result[baseFileKey]
1674
+
1675
+ return filename
1676
+
1677
+ def GetBaseRevision(self, filename):
1678
+ base_filename = self.GetBaseFilename(filename)
1679
+
1680
+ have_result = self.RunPerforceCommand(["have", base_filename],
1681
+ marshal_output=True)
1682
+ if "haveRev" in have_result:
1683
+ return have_result["haveRev"]
1684
+
1685
+ def GetLocalFilename(self, filename):
1686
+ where = self.RunPerforceCommand(["where", filename], marshal_output=True)
1687
+ if "path" in where:
1688
+ return where["path"]
1689
+
1690
+ def GenerateDiff(self, args):
1691
+ class DiffData:
1692
+ def __init__(self, perforceVCS, filename, action):
1693
+ self.perforceVCS = perforceVCS
1694
+ self.filename = filename
1695
+ self.action = action
1696
+ self.base_filename = perforceVCS.GetBaseFilename(filename)
1697
+
1698
+ self.file_body = None
1699
+ self.base_rev = None
1700
+ self.prefix = None
1701
+ self.working_copy = True
1702
+ self.change_summary = None
1703
+
1704
+ def GenerateDiffHeader(diffData):
1705
+ header = []
1706
+ header.append("Index: %s" % diffData.filename)
1707
+ header.append("=" * 67)
1708
+
1709
+ if diffData.base_filename != diffData.filename:
1710
+ if diffData.action.startswith("move"):
1711
+ verb = "rename"
1712
+ else:
1713
+ verb = "copy"
1714
+ header.append("%s from %s" % (verb, diffData.base_filename))
1715
+ header.append("%s to %s" % (verb, diffData.filename))
1716
+
1717
+ suffix = "\t(revision %s)" % diffData.base_rev
1718
+ header.append("--- " + diffData.base_filename + suffix)
1719
+ if diffData.working_copy:
1720
+ suffix = "\t(working copy)"
1721
+ header.append("+++ " + diffData.filename + suffix)
1722
+ if diffData.change_summary:
1723
+ header.append(diffData.change_summary)
1724
+ return header
1725
+
1726
+ def GenerateMergeDiff(diffData, args):
1727
+ # -du generates a unified diff, which is nearly svn format
1728
+ diffData.file_body = self.RunPerforceCommand(
1729
+ ["diff", "-du", diffData.filename] + args)
1730
+ diffData.base_rev = self.GetBaseRevision(diffData.filename)
1731
+ diffData.prefix = ""
1732
+
1733
+ # We have to replace p4's file status output (the lines starting
1734
+ # with +++ or ---) to match svn's diff format
1735
+ lines = diffData.file_body.splitlines()
1736
+ first_good_line = 0
1737
+ while (first_good_line < len(lines) and
1738
+ not lines[first_good_line].startswith("@@")):
1739
+ first_good_line += 1
1740
+ diffData.file_body = "\n".join(lines[first_good_line:])
1741
+ return diffData
1742
+
1743
+ def GenerateAddDiff(diffData):
1744
+ fstat = self.RunPerforceCommand(["fstat", diffData.filename],
1745
+ marshal_output=True)
1746
+ if "headRev" in fstat:
1747
+ diffData.base_rev = fstat["headRev"] # Re-adding a deleted file
1748
+ else:
1749
+ diffData.base_rev = "0" # Brand new file
1750
+ diffData.working_copy = False
1751
+ rel_path = self.GetLocalFilename(diffData.filename)
1752
+ diffData.file_body = open(rel_path, 'r').read()
1753
+ # Replicate svn's list of changed lines
1754
+ line_count = len(diffData.file_body.splitlines())
1755
+ diffData.change_summary = "@@ -0,0 +1"
1756
+ if line_count > 1:
1757
+ diffData.change_summary += ",%d" % line_count
1758
+ diffData.change_summary += " @@"
1759
+ diffData.prefix = "+"
1760
+ return diffData
1761
+
1762
+ def GenerateDeleteDiff(diffData):
1763
+ diffData.base_rev = self.GetBaseRevision(diffData.filename)
1764
+ is_base_binary = self.IsBaseBinary(diffData.filename)
1765
+ # For deletes, base_filename == filename
1766
+ diffData.file_body = self.GetFileContent(diffData.base_filename,
1767
+ None,
1768
+ is_base_binary)
1769
+ # Replicate svn's list of changed lines
1770
+ line_count = len(diffData.file_body.splitlines())
1771
+ diffData.change_summary = "@@ -1"
1772
+ if line_count > 1:
1773
+ diffData.change_summary += ",%d" % line_count
1774
+ diffData.change_summary += " +0,0 @@"
1775
+ diffData.prefix = "-"
1776
+ return diffData
1777
+
1778
+ changed_files = self.GetChangedFiles()
1779
+
1780
+ svndiff = []
1781
+ filecount = 0
1782
+ for (filename, action) in changed_files.items():
1783
+ svn_status = self.PerforceActionToSvnStatus(action)
1784
+ if svn_status == "SKIP":
1785
+ continue
1786
+
1787
+ diffData = DiffData(self, filename, action)
1788
+ # Is it possible to diff a branched file? Stackoverflow says no:
1789
+ # http://stackoverflow.com/questions/1771314/in-perforce-command-line-how-to-diff-a-file-reopened-for-add
1790
+ if svn_status == "M":
1791
+ diffData = GenerateMergeDiff(diffData, args)
1792
+ elif svn_status == "A":
1793
+ diffData = GenerateAddDiff(diffData)
1794
+ elif svn_status == "D":
1795
+ diffData = GenerateDeleteDiff(diffData)
1796
+ else:
1797
+ ErrorExit("Unknown file action %s (svn action %s)." % \
1798
+ (action, svn_status))
1799
+
1800
+ svndiff += GenerateDiffHeader(diffData)
1801
+
1802
+ for line in diffData.file_body.splitlines():
1803
+ svndiff.append(diffData.prefix + line)
1804
+ filecount += 1
1805
+ if not filecount:
1806
+ ErrorExit("No valid patches found in output from p4 diff")
1807
+ return "\n".join(svndiff) + "\n"
1808
+
1809
+ def PerforceActionToSvnStatus(self, status):
1810
+ # Mirroring the list at http://permalink.gmane.org/gmane.comp.version-control.mercurial.devel/28717
1811
+ # Is there something more official?
1812
+ return {
1813
+ "add" : "A",
1814
+ "branch" : "A",
1815
+ "delete" : "D",
1816
+ "edit" : "M", # Also includes changing file types.
1817
+ "integrate" : "M",
1818
+ "move/add" : "M",
1819
+ "move/delete": "SKIP",
1820
+ "purge" : "D", # How does a file's status become "purge"?
1821
+ }[status]
1822
+
1823
+ def GetAction(self, filename):
1824
+ changed_files = self.GetChangedFiles()
1825
+ if not filename in changed_files:
1826
+ ErrorExit("Trying to get base version of unknown file %s." % filename)
1827
+
1828
+ return changed_files[filename]
1829
+
1830
+ def GetBaseFile(self, filename):
1831
+ base_filename = self.GetBaseFilename(filename)
1832
+ base_content = ""
1833
+ new_content = None
1834
+
1835
+ status = self.PerforceActionToSvnStatus(self.GetAction(filename))
1836
+
1837
+ if status != "A":
1838
+ revision = self.GetBaseRevision(base_filename)
1839
+ if not revision:
1840
+ ErrorExit("Couldn't find base revision for file %s" % filename)
1841
+ is_base_binary = self.IsBaseBinary(base_filename)
1842
+ base_content = self.GetFileContent(base_filename,
1843
+ revision,
1844
+ is_base_binary)
1845
+
1846
+ is_binary = self.IsPendingBinary(filename)
1847
+ if status != "D" and status != "SKIP":
1848
+ relpath = self.GetLocalFilename(filename)
1849
+ if is_binary and self.IsImage(relpath):
1850
+ new_content = open(relpath, "rb").read()
1851
+
1852
+ return base_content, new_content, is_binary, status
1853
+
1854
+ # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
1855
+ def SplitPatch(data):
1856
+ """Splits a patch into separate pieces for each file.
1857
+
1858
+ Args:
1859
+ data: A string containing the output of svn diff.
1860
+
1861
+ Returns:
1862
+ A list of 2-tuple (filename, text) where text is the svn diff output
1863
+ pertaining to filename.
1864
+ """
1865
+ patches = []
1866
+ filename = None
1867
+ diff = []
1868
+ for line in data.splitlines(True):
1869
+ new_filename = None
1870
+ if line.startswith('Index:'):
1871
+ unused, new_filename = line.split(':', 1)
1872
+ new_filename = new_filename.strip()
1873
+ elif line.startswith('Property changes on:'):
1874
+ unused, temp_filename = line.split(':', 1)
1875
+ # When a file is modified, paths use '/' between directories, however
1876
+ # when a property is modified '\' is used on Windows. Make them the same
1877
+ # otherwise the file shows up twice.
1878
+ temp_filename = temp_filename.strip().replace('\\', '/')
1879
+ if temp_filename != filename:
1880
+ # File has property changes but no modifications, create a new diff.
1881
+ new_filename = temp_filename
1882
+ if new_filename:
1883
+ if filename and diff:
1884
+ patches.append((filename, ''.join(diff)))
1885
+ filename = new_filename
1886
+ diff = [line]
1887
+ continue
1888
+ if diff is not None:
1889
+ diff.append(line)
1890
+ if filename and diff:
1891
+ patches.append((filename, ''.join(diff)))
1892
+ return patches
1893
+
1894
+
1895
+ def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
1896
+ """Uploads a separate patch for each file in the diff output.
1897
+
1898
+ Returns a list of [patch_key, filename] for each file.
1899
+ """
1900
+ patches = SplitPatch(data)
1901
+ rv = []
1902
+ for patch in patches:
1903
+ if len(patch[1]) > MAX_UPLOAD_SIZE:
1904
+ print ("Not uploading the patch for " + patch[0] +
1905
+ " because the file is too large.")
1906
+ continue
1907
+ form_fields = [("filename", patch[0])]
1908
+ if not options.download_base:
1909
+ form_fields.append(("content_upload", "1"))
1910
+ files = [("data", "data.diff", patch[1])]
1911
+ ctype, body = EncodeMultipartFormData(form_fields, files)
1912
+ url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
1913
+ print "Uploading patch for " + patch[0]
1914
+ response_body = rpc_server.Send(url, body, content_type=ctype)
1915
+ lines = response_body.splitlines()
1916
+ if not lines or lines[0] != "OK":
1917
+ StatusUpdate(" --> %s" % response_body)
1918
+ sys.exit(1)
1919
+ rv.append([lines[1], patch[0]])
1920
+ return rv
1921
+
1922
+
1923
+ def GuessVCSName(options):
1924
+ """Helper to guess the version control system.
1925
+
1926
+ This examines the current directory, guesses which VersionControlSystem
1927
+ we're using, and returns an string indicating which VCS is detected.
1928
+
1929
+ Returns:
1930
+ A pair (vcs, output). vcs is a string indicating which VCS was detected
1931
+ and is one of VCS_GIT, VCS_MERCURIAL, VCS_SUBVERSION, VCS_PERFORCE,
1932
+ VCS_CVS, or VCS_UNKNOWN.
1933
+ Since local perforce repositories can't be easily detected, this method
1934
+ will only guess VCS_PERFORCE if any perforce options have been specified.
1935
+ output is a string containing any interesting output from the vcs
1936
+ detection routine, or None if there is nothing interesting.
1937
+ """
1938
+ for attribute, value in options.__dict__.iteritems():
1939
+ if attribute.startswith("p4") and value != None:
1940
+ return (VCS_PERFORCE, None)
1941
+
1942
+ def RunDetectCommand(vcs_type, command):
1943
+ """Helper to detect VCS by executing command.
1944
+
1945
+ Returns:
1946
+ A pair (vcs, output) or None. Throws exception on error.
1947
+ """
1948
+ try:
1949
+ out, returncode = RunShellWithReturnCode(command)
1950
+ if returncode == 0:
1951
+ return (vcs_type, out.strip())
1952
+ except OSError, (errcode, message):
1953
+ if errcode != errno.ENOENT: # command not found code
1954
+ raise
1955
+
1956
+ # Mercurial has a command to get the base directory of a repository
1957
+ # Try running it, but don't die if we don't have hg installed.
1958
+ # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
1959
+ res = RunDetectCommand(VCS_MERCURIAL, ["hg", "root"])
1960
+ if res != None:
1961
+ return res
1962
+
1963
+ # Subversion has a .svn in all working directories.
1964
+ if os.path.isdir('.svn'):
1965
+ logging.info("Guessed VCS = Subversion")
1966
+ return (VCS_SUBVERSION, None)
1967
+
1968
+ # Git has a command to test if you're in a git tree.
1969
+ # Try running it, but don't die if we don't have git installed.
1970
+ res = RunDetectCommand(VCS_GIT, ["git", "rev-parse",
1971
+ "--is-inside-work-tree"])
1972
+ if res != None:
1973
+ return res
1974
+
1975
+ # detect CVS repos use `cvs status && $? == 0` rules
1976
+ res = RunDetectCommand(VCS_CVS, ["cvs", "status"])
1977
+ if res != None:
1978
+ return res
1979
+
1980
+ return (VCS_UNKNOWN, None)
1981
+
1982
+
1983
+ def GuessVCS(options):
1984
+ """Helper to guess the version control system.
1985
+
1986
+ This verifies any user-specified VersionControlSystem (by command line
1987
+ or environment variable). If the user didn't specify one, this examines
1988
+ the current directory, guesses which VersionControlSystem we're using,
1989
+ and returns an instance of the appropriate class. Exit with an error
1990
+ if we can't figure it out.
1991
+
1992
+ Returns:
1993
+ A VersionControlSystem instance. Exits if the VCS can't be guessed.
1994
+ """
1995
+ vcs = options.vcs
1996
+ if not vcs:
1997
+ vcs = os.environ.get("CODEREVIEW_VCS")
1998
+ if vcs:
1999
+ v = VCS_ABBREVIATIONS.get(vcs.lower())
2000
+ if v is None:
2001
+ ErrorExit("Unknown version control system %r specified." % vcs)
2002
+ (vcs, extra_output) = (v, None)
2003
+ else:
2004
+ (vcs, extra_output) = GuessVCSName(options)
2005
+
2006
+ if vcs == VCS_MERCURIAL:
2007
+ if extra_output is None:
2008
+ extra_output = RunShell(["hg", "root"]).strip()
2009
+ return MercurialVCS(options, extra_output)
2010
+ elif vcs == VCS_SUBVERSION:
2011
+ return SubversionVCS(options)
2012
+ elif vcs == VCS_PERFORCE:
2013
+ return PerforceVCS(options)
2014
+ elif vcs == VCS_GIT:
2015
+ return GitVCS(options)
2016
+ elif vcs == VCS_CVS:
2017
+ return CVSVCS(options)
2018
+
2019
+ ErrorExit(("Could not guess version control system. "
2020
+ "Are you in a working copy directory?"))
2021
+
2022
+
2023
+ def CheckReviewer(reviewer):
2024
+ """Validate a reviewer -- either a nickname or an email addres.
2025
+
2026
+ Args:
2027
+ reviewer: A nickname or an email address.
2028
+
2029
+ Calls ErrorExit() if it is an invalid email address.
2030
+ """
2031
+ if "@" not in reviewer:
2032
+ return # Assume nickname
2033
+ parts = reviewer.split("@")
2034
+ if len(parts) > 2:
2035
+ ErrorExit("Invalid email address: %r" % reviewer)
2036
+ assert len(parts) == 2
2037
+ if "." not in parts[1]:
2038
+ ErrorExit("Invalid email address: %r" % reviewer)
2039
+
2040
+
2041
+ def LoadSubversionAutoProperties():
2042
+ """Returns the content of [auto-props] section of Subversion's config file as
2043
+ a dictionary.
2044
+
2045
+ Returns:
2046
+ A dictionary whose key-value pair corresponds the [auto-props] section's
2047
+ key-value pair.
2048
+ In following cases, returns empty dictionary:
2049
+ - config file doesn't exist, or
2050
+ - 'enable-auto-props' is not set to 'true-like-value' in [miscellany].
2051
+ """
2052
+ if os.name == 'nt':
2053
+ subversion_config = os.environ.get("APPDATA") + "\\Subversion\\config"
2054
+ else:
2055
+ subversion_config = os.path.expanduser("~/.subversion/config")
2056
+ if not os.path.exists(subversion_config):
2057
+ return {}
2058
+ config = ConfigParser.ConfigParser()
2059
+ config.read(subversion_config)
2060
+ if (config.has_section("miscellany") and
2061
+ config.has_option("miscellany", "enable-auto-props") and
2062
+ config.getboolean("miscellany", "enable-auto-props") and
2063
+ config.has_section("auto-props")):
2064
+ props = {}
2065
+ for file_pattern in config.options("auto-props"):
2066
+ props[file_pattern] = ParseSubversionPropertyValues(
2067
+ config.get("auto-props", file_pattern))
2068
+ return props
2069
+ else:
2070
+ return {}
2071
+
2072
+ def ParseSubversionPropertyValues(props):
2073
+ """Parse the given property value which comes from [auto-props] section and
2074
+ returns a list whose element is a (svn_prop_key, svn_prop_value) pair.
2075
+
2076
+ See the following doctest for example.
2077
+
2078
+ >>> ParseSubversionPropertyValues('svn:eol-style=LF')
2079
+ [('svn:eol-style', 'LF')]
2080
+ >>> ParseSubversionPropertyValues('svn:mime-type=image/jpeg')
2081
+ [('svn:mime-type', 'image/jpeg')]
2082
+ >>> ParseSubversionPropertyValues('svn:eol-style=LF;svn:executable')
2083
+ [('svn:eol-style', 'LF'), ('svn:executable', '*')]
2084
+ """
2085
+ key_value_pairs = []
2086
+ for prop in props.split(";"):
2087
+ key_value = prop.split("=")
2088
+ assert len(key_value) <= 2
2089
+ if len(key_value) == 1:
2090
+ # If value is not given, use '*' as a Subversion's convention.
2091
+ key_value_pairs.append((key_value[0], "*"))
2092
+ else:
2093
+ key_value_pairs.append((key_value[0], key_value[1]))
2094
+ return key_value_pairs
2095
+
2096
+
2097
+ def GetSubversionPropertyChanges(filename):
2098
+ """Return a Subversion's 'Property changes on ...' string, which is used in
2099
+ the patch file.
2100
+
2101
+ Args:
2102
+ filename: filename whose property might be set by [auto-props] config.
2103
+
2104
+ Returns:
2105
+ A string like 'Property changes on |filename| ...' if given |filename|
2106
+ matches any entries in [auto-props] section. None, otherwise.
2107
+ """
2108
+ global svn_auto_props_map
2109
+ if svn_auto_props_map is None:
2110
+ svn_auto_props_map = LoadSubversionAutoProperties()
2111
+
2112
+ all_props = []
2113
+ for file_pattern, props in svn_auto_props_map.items():
2114
+ if fnmatch.fnmatch(filename, file_pattern):
2115
+ all_props.extend(props)
2116
+ if all_props:
2117
+ return FormatSubversionPropertyChanges(filename, all_props)
2118
+ return None
2119
+
2120
+
2121
+ def FormatSubversionPropertyChanges(filename, props):
2122
+ """Returns Subversion's 'Property changes on ...' strings using given filename
2123
+ and properties.
2124
+
2125
+ Args:
2126
+ filename: filename
2127
+ props: A list whose element is a (svn_prop_key, svn_prop_value) pair.
2128
+
2129
+ Returns:
2130
+ A string which can be used in the patch file for Subversion.
2131
+
2132
+ See the following doctest for example.
2133
+
2134
+ >>> print FormatSubversionPropertyChanges('foo.cc', [('svn:eol-style', 'LF')])
2135
+ Property changes on: foo.cc
2136
+ ___________________________________________________________________
2137
+ Added: svn:eol-style
2138
+ + LF
2139
+ <BLANKLINE>
2140
+ """
2141
+ prop_changes_lines = [
2142
+ "Property changes on: %s" % filename,
2143
+ "___________________________________________________________________"]
2144
+ for key, value in props:
2145
+ prop_changes_lines.append("Added: " + key)
2146
+ prop_changes_lines.append(" + " + value)
2147
+ return "\n".join(prop_changes_lines) + "\n"
2148
+
2149
+
2150
+ def RealMain(argv, data=None):
2151
+ """The real main function.
2152
+
2153
+ Args:
2154
+ argv: Command line arguments.
2155
+ data: Diff contents. If None (default) the diff is generated by
2156
+ the VersionControlSystem implementation returned by GuessVCS().
2157
+
2158
+ Returns:
2159
+ A 2-tuple (issue id, patchset id).
2160
+ The patchset id is None if the base files are not uploaded by this
2161
+ script (applies only to SVN checkouts).
2162
+ """
2163
+ options, args = parser.parse_args(argv[1:])
2164
+ if options.help:
2165
+ if options.verbose < 2:
2166
+ # hide Perforce options
2167
+ parser.epilog = "Use '--help -v' to show additional Perforce options."
2168
+ parser.option_groups.remove(parser.get_option_group('--p4_port'))
2169
+ parser.print_help()
2170
+ sys.exit(0)
2171
+
2172
+ global verbosity
2173
+ verbosity = options.verbose
2174
+ if verbosity >= 3:
2175
+ logging.getLogger().setLevel(logging.DEBUG)
2176
+ elif verbosity >= 2:
2177
+ logging.getLogger().setLevel(logging.INFO)
2178
+
2179
+ vcs = GuessVCS(options)
2180
+
2181
+ base = options.base_url
2182
+ if isinstance(vcs, SubversionVCS):
2183
+ # Guessing the base field is only supported for Subversion.
2184
+ # Note: Fetching base files may become deprecated in future releases.
2185
+ guessed_base = vcs.GuessBase(options.download_base)
2186
+ if base:
2187
+ if guessed_base and base != guessed_base:
2188
+ print "Using base URL \"%s\" from --base_url instead of \"%s\"" % \
2189
+ (base, guessed_base)
2190
+ else:
2191
+ base = guessed_base
2192
+
2193
+ if not base and options.download_base:
2194
+ options.download_base = True
2195
+ logging.info("Enabled upload of base file")
2196
+ if not options.assume_yes:
2197
+ vcs.CheckForUnknownFiles()
2198
+ if data is None:
2199
+ data = vcs.GenerateDiff(args)
2200
+ data = vcs.PostProcessDiff(data)
2201
+ if options.print_diffs:
2202
+ print "Rietveld diff start:*****"
2203
+ print data
2204
+ print "Rietveld diff end:*****"
2205
+ files = vcs.GetBaseFiles(data)
2206
+ if verbosity >= 1:
2207
+ print "Upload server:", options.server, "(change with -s/--server)"
2208
+ if options.issue:
2209
+ prompt = "Message describing this patch set: "
2210
+ else:
2211
+ prompt = "New issue subject: "
2212
+ message = options.message or raw_input(prompt).strip()
2213
+ if not message:
2214
+ ErrorExit("A non-empty message is required")
2215
+ rpc_server = GetRpcServer(options.server,
2216
+ options.email,
2217
+ options.host,
2218
+ options.save_cookies,
2219
+ options.account_type)
2220
+ form_fields = [("subject", message)]
2221
+
2222
+ repo_guid = vcs.GetGUID()
2223
+ if repo_guid:
2224
+ form_fields.append(("repo_guid", repo_guid))
2225
+ if base:
2226
+ b = urlparse.urlparse(base)
2227
+ username, netloc = urllib.splituser(b.netloc)
2228
+ if username:
2229
+ logging.info("Removed username from base URL")
2230
+ base = urlparse.urlunparse((b.scheme, netloc, b.path, b.params,
2231
+ b.query, b.fragment))
2232
+ form_fields.append(("base", base))
2233
+ if options.issue:
2234
+ form_fields.append(("issue", str(options.issue)))
2235
+ if options.email:
2236
+ form_fields.append(("user", options.email))
2237
+ if options.reviewers:
2238
+ for reviewer in options.reviewers.split(','):
2239
+ CheckReviewer(reviewer)
2240
+ form_fields.append(("reviewers", options.reviewers))
2241
+ if options.cc:
2242
+ for cc in options.cc.split(','):
2243
+ CheckReviewer(cc)
2244
+ form_fields.append(("cc", options.cc))
2245
+ description = options.description
2246
+ if options.description_file:
2247
+ if options.description:
2248
+ ErrorExit("Can't specify description and description_file")
2249
+ file = open(options.description_file, 'r')
2250
+ description = file.read()
2251
+ file.close()
2252
+ if description:
2253
+ form_fields.append(("description", description))
2254
+ # Send a hash of all the base file so the server can determine if a copy
2255
+ # already exists in an earlier patchset.
2256
+ base_hashes = ""
2257
+ for file, info in files.iteritems():
2258
+ if not info[0] is None:
2259
+ checksum = md5(info[0]).hexdigest()
2260
+ if base_hashes:
2261
+ base_hashes += "|"
2262
+ base_hashes += checksum + ":" + file
2263
+ form_fields.append(("base_hashes", base_hashes))
2264
+ if options.private:
2265
+ if options.issue:
2266
+ print "Warning: Private flag ignored when updating an existing issue."
2267
+ else:
2268
+ form_fields.append(("private", "1"))
2269
+ if options.send_patch:
2270
+ options.send_mail = True
2271
+ # If we're uploading base files, don't send the email before the uploads, so
2272
+ # that it contains the file status.
2273
+ if options.send_mail and options.download_base:
2274
+ form_fields.append(("send_mail", "1"))
2275
+ if not options.download_base:
2276
+ form_fields.append(("content_upload", "1"))
2277
+ if len(data) > MAX_UPLOAD_SIZE:
2278
+ print "Patch is large, so uploading file patches separately."
2279
+ uploaded_diff_file = []
2280
+ form_fields.append(("separate_patches", "1"))
2281
+ else:
2282
+ uploaded_diff_file = [("data", "data.diff", data)]
2283
+ ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
2284
+ response_body = rpc_server.Send("/upload", body, content_type=ctype)
2285
+ patchset = None
2286
+ if not options.download_base or not uploaded_diff_file:
2287
+ lines = response_body.splitlines()
2288
+ if len(lines) >= 2:
2289
+ msg = lines[0]
2290
+ patchset = lines[1].strip()
2291
+ patches = [x.split(" ", 1) for x in lines[2:]]
2292
+ else:
2293
+ msg = response_body
2294
+ else:
2295
+ msg = response_body
2296
+ StatusUpdate(msg)
2297
+ if not response_body.startswith("Issue created.") and \
2298
+ not response_body.startswith("Issue updated."):
2299
+ sys.exit(0)
2300
+ issue = msg[msg.rfind("/")+1:]
2301
+
2302
+ if not uploaded_diff_file:
2303
+ result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
2304
+ if not options.download_base:
2305
+ patches = result
2306
+
2307
+ if not options.download_base:
2308
+ vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
2309
+ if options.send_mail:
2310
+ payload = ""
2311
+ if options.send_patch:
2312
+ payload=urllib.urlencode({"attach_patch": "yes"})
2313
+ rpc_server.Send("/" + issue + "/mail", payload=payload)
2314
+ return issue, patchset
2315
+
2316
+
2317
+ def main():
2318
+ try:
2319
+ logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
2320
+ "%(lineno)s %(message)s "))
2321
+ os.environ['LC_ALL'] = 'C'
2322
+ RealMain(sys.argv)
2323
+ except KeyboardInterrupt:
2324
+ print
2325
+ StatusUpdate("Interrupted.")
2326
+ sys.exit(1)
2327
+
2328
+
2329
+ if __name__ == "__main__":
2330
+ main()