PageRenderTime 72ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/codreview/codereview.py

https://bitbucket.org/rminnich/vx32/
Python | 3217 lines | 3060 code | 45 blank | 112 comment | 89 complexity | 5828bc46e5ef5554b1238d8831f8e138 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1
  1. # coding=utf-8
  2. # (The line above is necessary so that I can use 世界 in the
  3. # *comment* below without Python getting all bent out of shape.)
  4. # Copyright 2007-2009 Google Inc.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. '''Mercurial interface to codereview.appspot.com.
  18. To configure, set the following options in
  19. your repository's .hg/hgrc file.
  20. [extensions]
  21. codereview = path/to/codereview.py
  22. [codereview]
  23. server = codereview.appspot.com
  24. The server should be running Rietveld; see http://code.google.com/p/rietveld/.
  25. In addition to the new commands, this extension introduces
  26. the file pattern syntax @nnnnnn, where nnnnnn is a change list
  27. number, to mean the files included in that change list, which
  28. must be associated with the current client.
  29. For example, if change 123456 contains the files x.go and y.go,
  30. "hg diff @123456" is equivalent to"hg diff x.go y.go".
  31. '''
  32. from mercurial import cmdutil, commands, hg, util, error, match
  33. from mercurial.node import nullrev, hex, nullid, short
  34. import os, re, time
  35. import stat
  36. import subprocess
  37. import threading
  38. from HTMLParser import HTMLParser
  39. # The standard 'json' package is new in Python 2.6.
  40. # Before that it was an external package named simplejson.
  41. try:
  42. # Standard location in 2.6 and beyond.
  43. import json
  44. except Exception, e:
  45. try:
  46. # Conventional name for earlier package.
  47. import simplejson as json
  48. except:
  49. try:
  50. # Was also bundled with django, which is commonly installed.
  51. from django.utils import simplejson as json
  52. except:
  53. # We give up.
  54. raise e
  55. try:
  56. hgversion = util.version()
  57. except:
  58. from mercurial.version import version as v
  59. hgversion = v.get_version()
  60. try:
  61. from mercurial.discovery import findcommonincoming
  62. except:
  63. def findcommonincoming(repo, remote):
  64. return repo.findcommonincoming(remote)
  65. oldMessage = """
  66. The code review extension requires Mercurial 1.3 or newer.
  67. To install a new Mercurial,
  68. sudo easy_install mercurial
  69. works on most systems.
  70. """
  71. linuxMessage = """
  72. You may need to clear your current Mercurial installation by running:
  73. sudo apt-get remove mercurial mercurial-common
  74. sudo rm -rf /etc/mercurial
  75. """
  76. if hgversion < '1.3':
  77. msg = oldMessage
  78. if os.access("/etc/mercurial", 0):
  79. msg += linuxMessage
  80. raise util.Abort(msg)
  81. def promptyesno(ui, msg):
  82. # Arguments to ui.prompt changed between 1.3 and 1.3.1.
  83. # Even so, some 1.3.1 distributions seem to have the old prompt!?!?
  84. # What a terrible way to maintain software.
  85. try:
  86. return ui.promptchoice(msg, ["&yes", "&no"], 0) == 0
  87. except AttributeError:
  88. return ui.prompt(msg, ["&yes", "&no"], "y") != "n"
  89. # To experiment with Mercurial in the python interpreter:
  90. # >>> repo = hg.repository(ui.ui(), path = ".")
  91. #######################################################################
  92. # Normally I would split this into multiple files, but it simplifies
  93. # import path headaches to keep it all in one file. Sorry.
  94. import sys
  95. if __name__ == "__main__":
  96. print >>sys.stderr, "This is a Mercurial extension and should not be invoked directly."
  97. sys.exit(2)
  98. server = "codereview.appspot.com"
  99. server_url_base = None
  100. defaultcc = None
  101. contributors = {}
  102. missing_codereview = None
  103. real_rollback = None
  104. releaseBranch = None
  105. #######################################################################
  106. # RE: UNICODE STRING HANDLING
  107. #
  108. # Python distinguishes between the str (string of bytes)
  109. # and unicode (string of code points) types. Most operations
  110. # work on either one just fine, but some (like regexp matching)
  111. # require unicode, and others (like write) require str.
  112. #
  113. # As befits the language, Python hides the distinction between
  114. # unicode and str by converting between them silently, but
  115. # *only* if all the bytes/code points involved are 7-bit ASCII.
  116. # This means that if you're not careful, your program works
  117. # fine on "hello, world" and fails on "hello, 世界". And of course,
  118. # the obvious way to be careful - use static types - is unavailable.
  119. # So the only way is trial and error to find where to put explicit
  120. # conversions.
  121. #
  122. # Because more functions do implicit conversion to str (string of bytes)
  123. # than do implicit conversion to unicode (string of code points),
  124. # the convention in this module is to represent all text as str,
  125. # converting to unicode only when calling a unicode-only function
  126. # and then converting back to str as soon as possible.
  127. def typecheck(s, t):
  128. if type(s) != t:
  129. raise util.Abort("type check failed: %s has type %s != %s" % (repr(s), type(s), t))
  130. # If we have to pass unicode instead of str, ustr does that conversion clearly.
  131. def ustr(s):
  132. typecheck(s, str)
  133. return s.decode("utf-8")
  134. # Even with those, Mercurial still sometimes turns unicode into str
  135. # and then tries to use it as ascii. Change Mercurial's default.
  136. def set_mercurial_encoding_to_utf8():
  137. from mercurial import encoding
  138. encoding.encoding = 'utf-8'
  139. set_mercurial_encoding_to_utf8()
  140. # Even with those we still run into problems.
  141. # I tried to do things by the book but could not convince
  142. # Mercurial to let me check in a change with UTF-8 in the
  143. # CL description or author field, no matter how many conversions
  144. # between str and unicode I inserted and despite changing the
  145. # default encoding. I'm tired of this game, so set the default
  146. # encoding for all of Python to 'utf-8', not 'ascii'.
  147. def default_to_utf8():
  148. import sys
  149. reload(sys) # site.py deleted setdefaultencoding; get it back
  150. sys.setdefaultencoding('utf-8')
  151. default_to_utf8()
  152. #######################################################################
  153. # Change list parsing.
  154. #
  155. # Change lists are stored in .hg/codereview/cl.nnnnnn
  156. # where nnnnnn is the number assigned by the code review server.
  157. # Most data about a change list is stored on the code review server
  158. # too: the description, reviewer, and cc list are all stored there.
  159. # The only thing in the cl.nnnnnn file is the list of relevant files.
  160. # Also, the existence of the cl.nnnnnn file marks this repository
  161. # as the one where the change list lives.
  162. emptydiff = """Index: ~rietveld~placeholder~
  163. ===================================================================
  164. diff --git a/~rietveld~placeholder~ b/~rietveld~placeholder~
  165. new file mode 100644
  166. """
  167. class CL(object):
  168. def __init__(self, name):
  169. typecheck(name, str)
  170. self.name = name
  171. self.desc = ''
  172. self.files = []
  173. self.reviewer = []
  174. self.cc = []
  175. self.url = ''
  176. self.local = False
  177. self.web = False
  178. self.copied_from = None # None means current user
  179. self.mailed = False
  180. self.private = False
  181. def DiskText(self):
  182. cl = self
  183. s = ""
  184. if cl.copied_from:
  185. s += "Author: " + cl.copied_from + "\n\n"
  186. if cl.private:
  187. s += "Private: " + str(self.private) + "\n"
  188. s += "Mailed: " + str(self.mailed) + "\n"
  189. s += "Description:\n"
  190. s += Indent(cl.desc, "\t")
  191. s += "Files:\n"
  192. for f in cl.files:
  193. s += "\t" + f + "\n"
  194. typecheck(s, str)
  195. return s
  196. def EditorText(self):
  197. cl = self
  198. s = _change_prolog
  199. s += "\n"
  200. if cl.copied_from:
  201. s += "Author: " + cl.copied_from + "\n"
  202. if cl.url != '':
  203. s += 'URL: ' + cl.url + ' # cannot edit\n\n'
  204. if cl.private:
  205. s += "Private: True\n"
  206. s += "Reviewer: " + JoinComma(cl.reviewer) + "\n"
  207. s += "CC: " + JoinComma(cl.cc) + "\n"
  208. s += "\n"
  209. s += "Description:\n"
  210. if cl.desc == '':
  211. s += "\t<enter description here>\n"
  212. else:
  213. s += Indent(cl.desc, "\t")
  214. s += "\n"
  215. if cl.local or cl.name == "new":
  216. s += "Files:\n"
  217. for f in cl.files:
  218. s += "\t" + f + "\n"
  219. s += "\n"
  220. typecheck(s, str)
  221. return s
  222. def PendingText(self):
  223. cl = self
  224. s = cl.name + ":" + "\n"
  225. s += Indent(cl.desc, "\t")
  226. s += "\n"
  227. if cl.copied_from:
  228. s += "\tAuthor: " + cl.copied_from + "\n"
  229. s += "\tReviewer: " + JoinComma(cl.reviewer) + "\n"
  230. s += "\tCC: " + JoinComma(cl.cc) + "\n"
  231. s += "\tFiles:\n"
  232. for f in cl.files:
  233. s += "\t\t" + f + "\n"
  234. typecheck(s, str)
  235. return s
  236. def Flush(self, ui, repo):
  237. if self.name == "new":
  238. self.Upload(ui, repo, gofmt_just_warn=True, creating=True)
  239. dir = CodeReviewDir(ui, repo)
  240. path = dir + '/cl.' + self.name
  241. f = open(path+'!', "w")
  242. f.write(self.DiskText())
  243. f.close()
  244. if sys.platform == "win32" and os.path.isfile(path):
  245. os.remove(path)
  246. os.rename(path+'!', path)
  247. if self.web and not self.copied_from:
  248. EditDesc(self.name, desc=self.desc,
  249. reviewers=JoinComma(self.reviewer), cc=JoinComma(self.cc),
  250. private=self.private)
  251. def Delete(self, ui, repo):
  252. dir = CodeReviewDir(ui, repo)
  253. os.unlink(dir + "/cl." + self.name)
  254. def Subject(self):
  255. s = line1(self.desc)
  256. if len(s) > 60:
  257. s = s[0:55] + "..."
  258. if self.name != "new":
  259. s = "code review %s: %s" % (self.name, s)
  260. typecheck(s, str)
  261. return s
  262. def Upload(self, ui, repo, send_mail=False, gofmt=True, gofmt_just_warn=False, creating=False, quiet=False):
  263. if not self.files and not creating:
  264. ui.warn("no files in change list\n")
  265. set_status("uploading CL metadata + diffs")
  266. os.chdir(repo.root)
  267. form_fields = [
  268. ("content_upload", "1"),
  269. ("reviewers", JoinComma(self.reviewer)),
  270. ("cc", JoinComma(self.cc)),
  271. ("description", self.desc),
  272. ("base_hashes", ""),
  273. ]
  274. if self.name != "new":
  275. form_fields.append(("issue", self.name))
  276. vcs = None
  277. # We do not include files when creating the issue,
  278. # because we want the patch sets to record the repository
  279. # and base revision they are diffs against. We use the patch
  280. # set message for that purpose, but there is no message with
  281. # the first patch set. Instead the message gets used as the
  282. # new CL's overall subject. So omit the diffs when creating
  283. # and then we'll run an immediate upload.
  284. # This has the effect that every CL begins with an empty "Patch set 1".
  285. if self.files and not creating:
  286. vcs = MercurialVCS(upload_options, ui, repo)
  287. data = vcs.GenerateDiff(self.files)
  288. files = vcs.GetBaseFiles(data)
  289. if len(data) > MAX_UPLOAD_SIZE:
  290. uploaded_diff_file = []
  291. form_fields.append(("separate_patches", "1"))
  292. else:
  293. uploaded_diff_file = [("data", "data.diff", data)]
  294. else:
  295. uploaded_diff_file = [("data", "data.diff", emptydiff)]
  296. if vcs and self.name != "new":
  297. form_fields.append(("subject", "diff -r " + vcs.base_rev + " " + getremote(ui, repo, {}).path))
  298. else:
  299. # First upload sets the subject for the CL itself.
  300. form_fields.append(("subject", self.Subject()))
  301. ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
  302. response_body = MySend("/upload", body, content_type=ctype)
  303. patchset = None
  304. msg = response_body
  305. lines = msg.splitlines()
  306. if len(lines) >= 2:
  307. msg = lines[0]
  308. patchset = lines[1].strip()
  309. patches = [x.split(" ", 1) for x in lines[2:]]
  310. if response_body.startswith("Issue updated.") and quiet:
  311. pass
  312. else:
  313. ui.status(msg + "\n")
  314. set_status("uploaded CL metadata + diffs")
  315. if not response_body.startswith("Issue created.") and not response_body.startswith("Issue updated."):
  316. raise util.Abort("failed to update issue: " + response_body)
  317. issue = msg[msg.rfind("/")+1:]
  318. self.name = issue
  319. if not self.url:
  320. self.url = server_url_base + self.name
  321. if not uploaded_diff_file:
  322. set_status("uploading patches")
  323. patches = UploadSeparatePatches(issue, rpc, patchset, data, upload_options)
  324. if vcs:
  325. set_status("uploading base files")
  326. vcs.UploadBaseFiles(issue, rpc, patches, patchset, upload_options, files)
  327. if send_mail:
  328. set_status("sending mail")
  329. MySend("/" + issue + "/mail", payload="")
  330. self.web = True
  331. set_status("flushing changes to disk")
  332. self.Flush(ui, repo)
  333. return
  334. def Mail(self, ui, repo):
  335. pmsg = "Hello " + JoinComma(self.reviewer)
  336. if self.cc:
  337. pmsg += " (cc: %s)" % (', '.join(self.cc),)
  338. pmsg += ",\n"
  339. pmsg += "\n"
  340. repourl = getremote(ui, repo, {}).path
  341. if not self.mailed:
  342. pmsg += "I'd like you to review this change to\n" + repourl + "\n"
  343. else:
  344. pmsg += "Please take another look.\n"
  345. typecheck(pmsg, str)
  346. PostMessage(ui, self.name, pmsg, subject=self.Subject())
  347. self.mailed = True
  348. self.Flush(ui, repo)
  349. def GoodCLName(name):
  350. typecheck(name, str)
  351. return re.match("^[0-9]+$", name)
  352. def ParseCL(text, name):
  353. typecheck(text, str)
  354. typecheck(name, str)
  355. sname = None
  356. lineno = 0
  357. sections = {
  358. 'Author': '',
  359. 'Description': '',
  360. 'Files': '',
  361. 'URL': '',
  362. 'Reviewer': '',
  363. 'CC': '',
  364. 'Mailed': '',
  365. 'Private': '',
  366. }
  367. for line in text.split('\n'):
  368. lineno += 1
  369. line = line.rstrip()
  370. if line != '' and line[0] == '#':
  371. continue
  372. if line == '' or line[0] == ' ' or line[0] == '\t':
  373. if sname == None and line != '':
  374. return None, lineno, 'text outside section'
  375. if sname != None:
  376. sections[sname] += line + '\n'
  377. continue
  378. p = line.find(':')
  379. if p >= 0:
  380. s, val = line[:p].strip(), line[p+1:].strip()
  381. if s in sections:
  382. sname = s
  383. if val != '':
  384. sections[sname] += val + '\n'
  385. continue
  386. return None, lineno, 'malformed section header'
  387. for k in sections:
  388. sections[k] = StripCommon(sections[k]).rstrip()
  389. cl = CL(name)
  390. if sections['Author']:
  391. cl.copied_from = sections['Author']
  392. cl.desc = sections['Description']
  393. for line in sections['Files'].split('\n'):
  394. i = line.find('#')
  395. if i >= 0:
  396. line = line[0:i].rstrip()
  397. line = line.strip()
  398. if line == '':
  399. continue
  400. cl.files.append(line)
  401. cl.reviewer = SplitCommaSpace(sections['Reviewer'])
  402. cl.cc = SplitCommaSpace(sections['CC'])
  403. cl.url = sections['URL']
  404. if sections['Mailed'] != 'False':
  405. # Odd default, but avoids spurious mailings when
  406. # reading old CLs that do not have a Mailed: line.
  407. # CLs created with this update will always have
  408. # Mailed: False on disk.
  409. cl.mailed = True
  410. if sections['Private'] in ('True', 'true', 'Yes', 'yes'):
  411. cl.private = True
  412. if cl.desc == '<enter description here>':
  413. cl.desc = ''
  414. return cl, 0, ''
  415. def SplitCommaSpace(s):
  416. typecheck(s, str)
  417. s = s.strip()
  418. if s == "":
  419. return []
  420. return re.split(", *", s)
  421. def CutDomain(s):
  422. typecheck(s, str)
  423. i = s.find('@')
  424. if i >= 0:
  425. s = s[0:i]
  426. return s
  427. def JoinComma(l):
  428. for s in l:
  429. typecheck(s, str)
  430. return ", ".join(l)
  431. def ExceptionDetail():
  432. s = str(sys.exc_info()[0])
  433. if s.startswith("<type '") and s.endswith("'>"):
  434. s = s[7:-2]
  435. elif s.startswith("<class '") and s.endswith("'>"):
  436. s = s[8:-2]
  437. arg = str(sys.exc_info()[1])
  438. if len(arg) > 0:
  439. s += ": " + arg
  440. return s
  441. def IsLocalCL(ui, repo, name):
  442. return GoodCLName(name) and os.access(CodeReviewDir(ui, repo) + "/cl." + name, 0)
  443. # Load CL from disk and/or the web.
  444. def LoadCL(ui, repo, name, web=True):
  445. typecheck(name, str)
  446. set_status("loading CL " + name)
  447. if not GoodCLName(name):
  448. return None, "invalid CL name"
  449. dir = CodeReviewDir(ui, repo)
  450. path = dir + "cl." + name
  451. if os.access(path, 0):
  452. ff = open(path)
  453. text = ff.read()
  454. ff.close()
  455. cl, lineno, err = ParseCL(text, name)
  456. if err != "":
  457. return None, "malformed CL data: "+err
  458. cl.local = True
  459. else:
  460. cl = CL(name)
  461. if web:
  462. set_status("getting issue metadata from web")
  463. d = JSONGet(ui, "/api/" + name + "?messages=true")
  464. set_status(None)
  465. if d is None:
  466. return None, "cannot load CL %s from server" % (name,)
  467. if 'owner_email' not in d or 'issue' not in d or str(d['issue']) != name:
  468. return None, "malformed response loading CL data from code review server"
  469. cl.dict = d
  470. cl.reviewer = d.get('reviewers', [])
  471. cl.cc = d.get('cc', [])
  472. if cl.local and cl.copied_from and cl.desc:
  473. # local copy of CL written by someone else
  474. # and we saved a description. use that one,
  475. # so that committers can edit the description
  476. # before doing hg submit.
  477. pass
  478. else:
  479. cl.desc = d.get('description', "")
  480. cl.url = server_url_base + name
  481. cl.web = True
  482. cl.private = d.get('private', False) != False
  483. set_status("loaded CL " + name)
  484. return cl, ''
  485. global_status = None
  486. def set_status(s):
  487. # print >>sys.stderr, "\t", time.asctime(), s
  488. global global_status
  489. global_status = s
  490. class StatusThread(threading.Thread):
  491. def __init__(self):
  492. threading.Thread.__init__(self)
  493. def run(self):
  494. # pause a reasonable amount of time before
  495. # starting to display status messages, so that
  496. # most hg commands won't ever see them.
  497. time.sleep(30)
  498. # now show status every 15 seconds
  499. while True:
  500. time.sleep(15 - time.time() % 15)
  501. s = global_status
  502. if s is None:
  503. continue
  504. if s == "":
  505. s = "(unknown status)"
  506. print >>sys.stderr, time.asctime(), s
  507. def start_status_thread():
  508. t = StatusThread()
  509. t.setDaemon(True) # allowed to exit if t is still running
  510. t.start()
  511. class LoadCLThread(threading.Thread):
  512. def __init__(self, ui, repo, dir, f, web):
  513. threading.Thread.__init__(self)
  514. self.ui = ui
  515. self.repo = repo
  516. self.dir = dir
  517. self.f = f
  518. self.web = web
  519. self.cl = None
  520. def run(self):
  521. cl, err = LoadCL(self.ui, self.repo, self.f[3:], web=self.web)
  522. if err != '':
  523. self.ui.warn("loading "+self.dir+self.f+": " + err + "\n")
  524. return
  525. self.cl = cl
  526. # Load all the CLs from this repository.
  527. def LoadAllCL(ui, repo, web=True):
  528. dir = CodeReviewDir(ui, repo)
  529. m = {}
  530. files = [f for f in os.listdir(dir) if f.startswith('cl.')]
  531. if not files:
  532. return m
  533. active = []
  534. first = True
  535. for f in files:
  536. t = LoadCLThread(ui, repo, dir, f, web)
  537. t.start()
  538. if web and first:
  539. # first request: wait in case it needs to authenticate
  540. # otherwise we get lots of user/password prompts
  541. # running in parallel.
  542. t.join()
  543. if t.cl:
  544. m[t.cl.name] = t.cl
  545. first = False
  546. else:
  547. active.append(t)
  548. for t in active:
  549. t.join()
  550. if t.cl:
  551. m[t.cl.name] = t.cl
  552. return m
  553. # Find repository root. On error, ui.warn and return None
  554. def RepoDir(ui, repo):
  555. url = repo.url();
  556. if not url.startswith('file:'):
  557. ui.warn("repository %s is not in local file system\n" % (url,))
  558. return None
  559. url = url[5:]
  560. if url.endswith('/'):
  561. url = url[:-1]
  562. typecheck(url, str)
  563. return url
  564. # Find (or make) code review directory. On error, ui.warn and return None
  565. def CodeReviewDir(ui, repo):
  566. dir = RepoDir(ui, repo)
  567. if dir == None:
  568. return None
  569. dir += '/.hg/codereview/'
  570. if not os.path.isdir(dir):
  571. try:
  572. os.mkdir(dir, 0700)
  573. except:
  574. ui.warn('cannot mkdir %s: %s\n' % (dir, ExceptionDetail()))
  575. return None
  576. typecheck(dir, str)
  577. return dir
  578. # Turn leading tabs into spaces, so that the common white space
  579. # prefix doesn't get confused when people's editors write out
  580. # some lines with spaces, some with tabs. Only a heuristic
  581. # (some editors don't use 8 spaces either) but a useful one.
  582. def TabsToSpaces(line):
  583. i = 0
  584. while i < len(line) and line[i] == '\t':
  585. i += 1
  586. return ' '*(8*i) + line[i:]
  587. # Strip maximal common leading white space prefix from text
  588. def StripCommon(text):
  589. typecheck(text, str)
  590. ws = None
  591. for line in text.split('\n'):
  592. line = line.rstrip()
  593. if line == '':
  594. continue
  595. line = TabsToSpaces(line)
  596. white = line[:len(line)-len(line.lstrip())]
  597. if ws == None:
  598. ws = white
  599. else:
  600. common = ''
  601. for i in range(min(len(white), len(ws))+1):
  602. if white[0:i] == ws[0:i]:
  603. common = white[0:i]
  604. ws = common
  605. if ws == '':
  606. break
  607. if ws == None:
  608. return text
  609. t = ''
  610. for line in text.split('\n'):
  611. line = line.rstrip()
  612. line = TabsToSpaces(line)
  613. if line.startswith(ws):
  614. line = line[len(ws):]
  615. if line == '' and t == '':
  616. continue
  617. t += line + '\n'
  618. while len(t) >= 2 and t[-2:] == '\n\n':
  619. t = t[:-1]
  620. typecheck(t, str)
  621. return t
  622. # Indent text with indent.
  623. def Indent(text, indent):
  624. typecheck(text, str)
  625. typecheck(indent, str)
  626. t = ''
  627. for line in text.split('\n'):
  628. t += indent + line + '\n'
  629. typecheck(t, str)
  630. return t
  631. # Return the first line of l
  632. def line1(text):
  633. typecheck(text, str)
  634. return text.split('\n')[0]
  635. _change_prolog = """# Change list.
  636. # Lines beginning with # are ignored.
  637. # Multi-line values should be indented.
  638. """
  639. #######################################################################
  640. # Mercurial helper functions
  641. # Get effective change nodes taking into account applied MQ patches
  642. def effective_revpair(repo):
  643. try:
  644. return cmdutil.revpair(repo, ['qparent'])
  645. except:
  646. return cmdutil.revpair(repo, None)
  647. # Return list of changed files in repository that match pats.
  648. # Warn about patterns that did not match.
  649. def matchpats(ui, repo, pats, opts):
  650. matcher = cmdutil.match(repo, pats, opts)
  651. node1, node2 = effective_revpair(repo)
  652. modified, added, removed, deleted, unknown, ignored, clean = repo.status(node1, node2, matcher, ignored=True, clean=True, unknown=True)
  653. return (modified, added, removed, deleted, unknown, ignored, clean)
  654. # Return list of changed files in repository that match pats.
  655. # The patterns came from the command line, so we warn
  656. # if they have no effect or cannot be understood.
  657. def ChangedFiles(ui, repo, pats, opts, taken=None):
  658. taken = taken or {}
  659. # Run each pattern separately so that we can warn about
  660. # patterns that didn't do anything useful.
  661. for p in pats:
  662. modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts)
  663. redo = False
  664. for f in unknown:
  665. promptadd(ui, repo, f)
  666. redo = True
  667. for f in deleted:
  668. promptremove(ui, repo, f)
  669. redo = True
  670. if redo:
  671. modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts)
  672. for f in modified + added + removed:
  673. if f in taken:
  674. ui.warn("warning: %s already in CL %s\n" % (f, taken[f].name))
  675. if not modified and not added and not removed:
  676. ui.warn("warning: %s did not match any modified files\n" % (p,))
  677. # Again, all at once (eliminates duplicates)
  678. modified, added, removed = matchpats(ui, repo, pats, opts)[:3]
  679. l = modified + added + removed
  680. l.sort()
  681. if taken:
  682. l = Sub(l, taken.keys())
  683. return l
  684. # Return list of changed files in repository that match pats and still exist.
  685. def ChangedExistingFiles(ui, repo, pats, opts):
  686. modified, added = matchpats(ui, repo, pats, opts)[:2]
  687. l = modified + added
  688. l.sort()
  689. return l
  690. # Return list of files claimed by existing CLs
  691. def Taken(ui, repo):
  692. all = LoadAllCL(ui, repo, web=False)
  693. taken = {}
  694. for _, cl in all.items():
  695. for f in cl.files:
  696. taken[f] = cl
  697. return taken
  698. # Return list of changed files that are not claimed by other CLs
  699. def DefaultFiles(ui, repo, pats, opts):
  700. return ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo))
  701. def Sub(l1, l2):
  702. return [l for l in l1 if l not in l2]
  703. def Add(l1, l2):
  704. l = l1 + Sub(l2, l1)
  705. l.sort()
  706. return l
  707. def Intersect(l1, l2):
  708. return [l for l in l1 if l in l2]
  709. def getremote(ui, repo, opts):
  710. # save $http_proxy; creating the HTTP repo object will
  711. # delete it in an attempt to "help"
  712. proxy = os.environ.get('http_proxy')
  713. source = hg.parseurl(ui.expandpath("default"), None)[0]
  714. try:
  715. remoteui = hg.remoteui # hg 1.6
  716. except:
  717. remoteui = cmdutil.remoteui
  718. other = hg.repository(remoteui(repo, opts), source)
  719. if proxy is not None:
  720. os.environ['http_proxy'] = proxy
  721. return other
  722. def Incoming(ui, repo, opts):
  723. _, incoming, _ = findcommonincoming(repo, getremote(ui, repo, opts))
  724. return incoming
  725. desc_re = '^(.+: |(tag )?(release|weekly)\.|fix build|undo CL)'
  726. desc_msg = '''Your CL description appears not to use the standard form.
  727. The first line of your change description is conventionally a
  728. one-line summary of the change, prefixed by the primary affected package,
  729. and is used as the subject for code review mail; the rest of the description
  730. elaborates.
  731. Examples:
  732. encoding/rot13: new package
  733. math: add IsInf, IsNaN
  734. net: fix cname in LookupHost
  735. unicode: update to Unicode 5.0.2
  736. '''
  737. def promptremove(ui, repo, f):
  738. if promptyesno(ui, "hg remove %s (y/n)?" % (f,)):
  739. if commands.remove(ui, repo, 'path:'+f) != 0:
  740. ui.warn("error removing %s" % (f,))
  741. def promptadd(ui, repo, f):
  742. if promptyesno(ui, "hg add %s (y/n)?" % (f,)):
  743. if commands.add(ui, repo, 'path:'+f) != 0:
  744. ui.warn("error adding %s" % (f,))
  745. def EditCL(ui, repo, cl):
  746. set_status(None) # do not show status
  747. s = cl.EditorText()
  748. while True:
  749. s = ui.edit(s, ui.username())
  750. clx, line, err = ParseCL(s, cl.name)
  751. if err != '':
  752. if not promptyesno(ui, "error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err)):
  753. return "change list not modified"
  754. continue
  755. # Check description.
  756. if clx.desc == '':
  757. if promptyesno(ui, "change list should have a description\nre-edit (y/n)?"):
  758. continue
  759. elif re.search('<enter reason for undo>', clx.desc):
  760. if promptyesno(ui, "change list description omits reason for undo\nre-edit (y/n)?"):
  761. continue
  762. elif not re.match(desc_re, clx.desc.split('\n')[0]):
  763. if promptyesno(ui, desc_msg + "re-edit (y/n)?"):
  764. continue
  765. # Check file list for files that need to be hg added or hg removed
  766. # or simply aren't understood.
  767. pats = ['path:'+f for f in clx.files]
  768. modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, pats, {})
  769. files = []
  770. for f in clx.files:
  771. if f in modified or f in added or f in removed:
  772. files.append(f)
  773. continue
  774. if f in deleted:
  775. promptremove(ui, repo, f)
  776. files.append(f)
  777. continue
  778. if f in unknown:
  779. promptadd(ui, repo, f)
  780. files.append(f)
  781. continue
  782. if f in ignored:
  783. ui.warn("error: %s is excluded by .hgignore; omitting\n" % (f,))
  784. continue
  785. if f in clean:
  786. ui.warn("warning: %s is listed in the CL but unchanged\n" % (f,))
  787. files.append(f)
  788. continue
  789. p = repo.root + '/' + f
  790. if os.path.isfile(p):
  791. ui.warn("warning: %s is a file but not known to hg\n" % (f,))
  792. files.append(f)
  793. continue
  794. if os.path.isdir(p):
  795. ui.warn("error: %s is a directory, not a file; omitting\n" % (f,))
  796. continue
  797. ui.warn("error: %s does not exist; omitting\n" % (f,))
  798. clx.files = files
  799. cl.desc = clx.desc
  800. cl.reviewer = clx.reviewer
  801. cl.cc = clx.cc
  802. cl.files = clx.files
  803. cl.private = clx.private
  804. break
  805. return ""
  806. # For use by submit, etc. (NOT by change)
  807. # Get change list number or list of files from command line.
  808. # If files are given, make a new change list.
  809. def CommandLineCL(ui, repo, pats, opts, defaultcc=None):
  810. if len(pats) > 0 and GoodCLName(pats[0]):
  811. if len(pats) != 1:
  812. return None, "cannot specify change number and file names"
  813. if opts.get('message'):
  814. return None, "cannot use -m with existing CL"
  815. cl, err = LoadCL(ui, repo, pats[0], web=True)
  816. if err != "":
  817. return None, err
  818. else:
  819. cl = CL("new")
  820. cl.local = True
  821. cl.files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo))
  822. if not cl.files:
  823. return None, "no files changed"
  824. if opts.get('reviewer'):
  825. cl.reviewer = Add(cl.reviewer, SplitCommaSpace(opts.get('reviewer')))
  826. if opts.get('cc'):
  827. cl.cc = Add(cl.cc, SplitCommaSpace(opts.get('cc')))
  828. if defaultcc:
  829. cl.cc = Add(cl.cc, defaultcc)
  830. if cl.name == "new":
  831. if opts.get('message'):
  832. cl.desc = opts.get('message')
  833. else:
  834. err = EditCL(ui, repo, cl)
  835. if err != '':
  836. return None, err
  837. return cl, ""
  838. # reposetup replaces cmdutil.match with this wrapper,
  839. # which expands the syntax @clnumber to mean the files
  840. # in that CL.
  841. original_match = None
  842. def ReplacementForCmdutilMatch(repo, pats=None, opts=None, globbed=False, default='relpath'):
  843. taken = []
  844. files = []
  845. pats = pats or []
  846. opts = opts or {}
  847. for p in pats:
  848. if p.startswith('@'):
  849. taken.append(p)
  850. clname = p[1:]
  851. if not GoodCLName(clname):
  852. raise util.Abort("invalid CL name " + clname)
  853. cl, err = LoadCL(repo.ui, repo, clname, web=False)
  854. if err != '':
  855. raise util.Abort("loading CL " + clname + ": " + err)
  856. if not cl.files:
  857. raise util.Abort("no files in CL " + clname)
  858. files = Add(files, cl.files)
  859. pats = Sub(pats, taken) + ['path:'+f for f in files]
  860. return original_match(repo, pats=pats, opts=opts, globbed=globbed, default=default)
  861. def RelativePath(path, cwd):
  862. n = len(cwd)
  863. if path.startswith(cwd) and path[n] == '/':
  864. return path[n+1:]
  865. return path
  866. #######################################################################
  867. # Mercurial commands
  868. # every command must take a ui and and repo as arguments.
  869. # opts is a dict where you can find other command line flags
  870. #
  871. # Other parameters are taken in order from items on the command line that
  872. # don't start with a dash. If no default value is given in the parameter list,
  873. # they are required.
  874. #
  875. def change(ui, repo, *pats, **opts):
  876. """create, edit or delete a change list
  877. Create, edit or delete a change list.
  878. A change list is a group of files to be reviewed and submitted together,
  879. plus a textual description of the change.
  880. Change lists are referred to by simple alphanumeric names.
  881. Changes must be reviewed before they can be submitted.
  882. In the absence of options, the change command opens the
  883. change list for editing in the default editor.
  884. Deleting a change with the -d or -D flag does not affect
  885. the contents of the files listed in that change. To revert
  886. the files listed in a change, use
  887. hg revert @123456
  888. before running hg change -d 123456.
  889. """
  890. if missing_codereview:
  891. return missing_codereview
  892. dirty = {}
  893. if len(pats) > 0 and GoodCLName(pats[0]):
  894. name = pats[0]
  895. if len(pats) != 1:
  896. return "cannot specify CL name and file patterns"
  897. pats = pats[1:]
  898. cl, err = LoadCL(ui, repo, name, web=True)
  899. if err != '':
  900. return err
  901. if not cl.local and (opts["stdin"] or not opts["stdout"]):
  902. return "cannot change non-local CL " + name
  903. else:
  904. if repo[None].branch() != "default":
  905. return "cannot run hg change outside default branch"
  906. name = "new"
  907. cl = CL("new")
  908. dirty[cl] = True
  909. files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo))
  910. if opts["delete"] or opts["deletelocal"]:
  911. if opts["delete"] and opts["deletelocal"]:
  912. return "cannot use -d and -D together"
  913. flag = "-d"
  914. if opts["deletelocal"]:
  915. flag = "-D"
  916. if name == "new":
  917. return "cannot use "+flag+" with file patterns"
  918. if opts["stdin"] or opts["stdout"]:
  919. return "cannot use "+flag+" with -i or -o"
  920. if not cl.local:
  921. return "cannot change non-local CL " + name
  922. if opts["delete"]:
  923. if cl.copied_from:
  924. return "original author must delete CL; hg change -D will remove locally"
  925. PostMessage(ui, cl.name, "*** Abandoned ***", send_mail=cl.mailed)
  926. EditDesc(cl.name, closed=True, private=cl.private)
  927. cl.Delete(ui, repo)
  928. return
  929. if opts["stdin"]:
  930. s = sys.stdin.read()
  931. clx, line, err = ParseCL(s, name)
  932. if err != '':
  933. return "error parsing change list: line %d: %s" % (line, err)
  934. if clx.desc is not None:
  935. cl.desc = clx.desc;
  936. dirty[cl] = True
  937. if clx.reviewer is not None:
  938. cl.reviewer = clx.reviewer
  939. dirty[cl] = True
  940. if clx.cc is not None:
  941. cl.cc = clx.cc
  942. dirty[cl] = True
  943. if clx.files is not None:
  944. cl.files = clx.files
  945. dirty[cl] = True
  946. if clx.private != cl.private:
  947. cl.private = clx.private
  948. dirty[cl] = True
  949. if not opts["stdin"] and not opts["stdout"]:
  950. if name == "new":
  951. cl.files = files
  952. err = EditCL(ui, repo, cl)
  953. if err != "":
  954. return err
  955. dirty[cl] = True
  956. for d, _ in dirty.items():
  957. name = d.name
  958. d.Flush(ui, repo)
  959. if name == "new":
  960. d.Upload(ui, repo, quiet=True)
  961. if opts["stdout"]:
  962. ui.write(cl.EditorText())
  963. elif opts["pending"]:
  964. ui.write(cl.PendingText())
  965. elif name == "new":
  966. if ui.quiet:
  967. ui.write(cl.name)
  968. else:
  969. ui.write("CL created: " + cl.url + "\n")
  970. return
  971. def code_login(ui, repo, **opts):
  972. """log in to code review server
  973. Logs in to the code review server, saving a cookie in
  974. a file in your home directory.
  975. """
  976. if missing_codereview:
  977. return missing_codereview
  978. MySend(None)
  979. def clpatch(ui, repo, clname, **opts):
  980. """import a patch from the code review server
  981. Imports a patch from the code review server into the local client.
  982. If the local client has already modified any of the files that the
  983. patch modifies, this command will refuse to apply the patch.
  984. Submitting an imported patch will keep the original author's
  985. name as the Author: line but add your own name to a Committer: line.
  986. """
  987. if repo[None].branch() != "default":
  988. return "cannot run hg clpatch outside default branch"
  989. return clpatch_or_undo(ui, repo, clname, opts, mode="clpatch")
  990. def undo(ui, repo, clname, **opts):
  991. """undo the effect of a CL
  992. Creates a new CL that undoes an earlier CL.
  993. After creating the CL, opens the CL text for editing so that
  994. you can add the reason for the undo to the description.
  995. """
  996. if repo[None].branch() != "default":
  997. return "cannot run hg undo outside default branch"
  998. return clpatch_or_undo(ui, repo, clname, opts, mode="undo")
  999. def release_apply(ui, repo, clname, **opts):
  1000. """apply a CL to the release branch
  1001. Creates a new CL copying a previously committed change
  1002. from the main branch to the release branch.
  1003. The current client must either be clean or already be in
  1004. the release branch.
  1005. The release branch must be created by starting with a
  1006. clean client, disabling the code review plugin, and running:
  1007. hg update weekly.YYYY-MM-DD
  1008. hg branch release-branch.rNN
  1009. hg commit -m 'create release-branch.rNN'
  1010. hg push --new-branch
  1011. Then re-enable the code review plugin.
  1012. People can test the release branch by running
  1013. hg update release-branch.rNN
  1014. in a clean client. To return to the normal tree,
  1015. hg update default
  1016. Move changes since the weekly into the release branch
  1017. using hg release-apply followed by the usual code review
  1018. process and hg submit.
  1019. When it comes time to tag the release, record the
  1020. final long-form tag of the release-branch.rNN
  1021. in the *default* branch's .hgtags file. That is, run
  1022. hg update default
  1023. and then edit .hgtags as you would for a weekly.
  1024. """
  1025. c = repo[None]
  1026. if not releaseBranch:
  1027. return "no active release branches"
  1028. if c.branch() != releaseBranch:
  1029. if c.modified() or c.added() or c.removed():
  1030. raise util.Abort("uncommitted local changes - cannot switch branches")
  1031. err = hg.clean(repo, releaseBranch)
  1032. if err:
  1033. return err
  1034. try:
  1035. err = clpatch_or_undo(ui, repo, clname, opts, mode="backport")
  1036. if err:
  1037. raise util.Abort(err)
  1038. except Exception, e:
  1039. hg.clean(repo, "default")
  1040. raise e
  1041. return None
  1042. def rev2clname(rev):
  1043. # Extract CL name from revision description.
  1044. # The last line in the description that is a codereview URL is the real one.
  1045. # Earlier lines might be part of the user-written description.
  1046. all = re.findall('(?m)^http://codereview.appspot.com/([0-9]+)$', rev.description())
  1047. if len(all) > 0:
  1048. return all[-1]
  1049. return ""
  1050. undoHeader = """undo CL %s / %s
  1051. <enter reason for undo>
  1052. ««« original CL description
  1053. """
  1054. undoFooter = """
  1055. »»»
  1056. """
  1057. backportHeader = """[%s] %s
  1058. ««« CL %s / %s
  1059. """
  1060. backportFooter = """
  1061. »»»
  1062. """
  1063. # Implementation of clpatch/undo.
  1064. def clpatch_or_undo(ui, repo, clname, opts, mode):
  1065. if missing_codereview:
  1066. return missing_codereview
  1067. if mode == "undo" or mode == "backport":
  1068. if hgversion < '1.4':
  1069. # Don't have cmdutil.match (see implementation of sync command).
  1070. return "hg is too old to run hg %s - update to 1.4 or newer" % mode
  1071. # Find revision in Mercurial repository.
  1072. # Assume CL number is 7+ decimal digits.
  1073. # Otherwise is either change log sequence number (fewer decimal digits),
  1074. # hexadecimal hash, or tag name.
  1075. # Mercurial will fall over long before the change log
  1076. # sequence numbers get to be 7 digits long.
  1077. if re.match('^[0-9]{7,}$', clname):
  1078. found = False
  1079. matchfn = cmdutil.match(repo, [], {'rev': None})
  1080. def prep(ctx, fns):
  1081. pass
  1082. for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep):
  1083. rev = repo[ctx.rev()]
  1084. # Last line with a code review URL is the actual review URL.
  1085. # Earlier ones might be part of the CL description.
  1086. n = rev2clname(rev)
  1087. if n == clname:
  1088. found = True
  1089. break
  1090. if not found:
  1091. return "cannot find CL %s in local repository" % clname
  1092. else:
  1093. rev = repo[clname]
  1094. if not rev:
  1095. return "unknown revision %s" % clname
  1096. clname = rev2clname(rev)
  1097. if clname == "":
  1098. return "cannot find CL name in revision description"
  1099. # Create fresh CL and start with patch that would reverse the change.
  1100. vers = short(rev.node())
  1101. cl = CL("new")
  1102. desc = rev.description()
  1103. if mode == "undo":
  1104. cl.desc = (undoHeader % (clname, vers)) + desc + undoFooter
  1105. else:
  1106. cl.desc = (backportHeader % (releaseBranch, line1(desc), clname, vers)) + desc + undoFooter
  1107. v1 = vers
  1108. v0 = short(rev.parents()[0].node())
  1109. if mode == "undo":
  1110. arg = v1 + ":" + v0
  1111. else:
  1112. vers = v0
  1113. arg = v0 + ":" + v1
  1114. patch = RunShell(["hg", "diff", "--git", "-r", arg])
  1115. else: # clpatch
  1116. cl, vers, patch, err = DownloadCL(ui, repo, clname)
  1117. if err != "":
  1118. return err
  1119. if patch == emptydiff:
  1120. return "codereview issue %s has no diff" % clname
  1121. # find current hg version (hg identify)
  1122. ctx = repo[None]
  1123. parents = ctx.parents()
  1124. id = '+'.join([short(p.node()) for p in parents])
  1125. # if version does not match the patch version,
  1126. # try to update the patch line numbers.
  1127. if vers != "" and id != vers:
  1128. # "vers in repo" gives the wrong answer
  1129. # on some versions of Mercurial. Instead, do the actual
  1130. # lookup and catch the exception.
  1131. try:
  1132. repo[vers].description()
  1133. except:
  1134. return "local repository is out of date; sync to get %s" % (vers)
  1135. patch, err = portPatch(repo, patch, vers, id)
  1136. if err != "":
  1137. return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id)
  1138. argv = ["hgpatch"]
  1139. if opts["no_incoming"] or mode == "backport":
  1140. argv += ["--checksync=false"]
  1141. try:
  1142. cmd = subprocess.Popen(argv, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, close_fds=sys.platform != "win32")
  1143. except:
  1144. return "hgpatch: " + ExceptionDetail()
  1145. out, err = cmd.communicate(patch)
  1146. if cmd.returncode != 0 and not opts["ignore_hgpatch_failure"]:
  1147. return "hgpatch failed"
  1148. cl.local = True
  1149. cl.files = out.strip().split()
  1150. if not cl.files:
  1151. return "codereview issue %s has no changed files" % clname
  1152. files = ChangedFiles(ui, repo, [], opts)
  1153. extra = Sub(cl.files, files)
  1154. if extra:
  1155. ui.warn("warning: these files were listed in the patch but not changed:\n\t" + "\n\t".join(extra) + "\n")
  1156. cl.Flush(ui, repo)
  1157. if mode == "undo":
  1158. err = EditCL(ui, repo, cl)
  1159. if err != "":
  1160. return "CL created, but error editing: " + err
  1161. cl.Flush(ui, repo)
  1162. else:
  1163. ui.write(cl.PendingText() + "\n")
  1164. # portPatch rewrites patch from being a patch against
  1165. # oldver to being a patch against newver.
  1166. def portPatch(repo, patch, oldver, newver):
  1167. lines = patch.splitlines(True) # True = keep \n
  1168. delta = None
  1169. for i in range(len(lines)):
  1170. line = lines[i]
  1171. if line.startswith('--- a/'):
  1172. file = line[6:-1]
  1173. delta = fileDeltas(repo, file, oldver, newver)
  1174. if not delta or not line.startswith('@@ '):
  1175. continue
  1176. # @@ -x,y +z,w @@ means the patch chunk replaces
  1177. # the original file's line numbers x up to x+y with the
  1178. # line numbers z up to z+w in the new file.
  1179. # Find the delta from x in the original to the same
  1180. # line in the current version and add that delta to both
  1181. # x and z.
  1182. m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line)
  1183. if not m:
  1184. return None, "error parsing patch line numbers"
  1185. n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
  1186. d, err = lineDelta(delta, n1, len1)
  1187. if err != "":
  1188. return "", err
  1189. n1 += d
  1190. n2 += d
  1191. lines[i] = "@@ -%d,%d +%d,%d @@\n" % (n1, len1, n2, len2)
  1192. newpatch = ''.join(lines)
  1193. return newpatch, ""
  1194. # fileDelta returns the line number deltas for the given file's
  1195. # changes from oldver to newver.
  1196. # The deltas are a list of (n, len, newdelta) triples that say
  1197. # lines [n, n+len) were modified, and after that range the
  1198. # line numbers are +newdelta from what they were before.
  1199. def fileDeltas(repo, file, oldver, newver):
  1200. cmd = ["hg", "diff", "--git", "-r", oldver + ":" + newver, "path:" + file]
  1201. data = RunShell(cmd, silent_ok=True)
  1202. deltas = []
  1203. for line in data.splitlines():
  1204. m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line)
  1205. if not m:
  1206. continue
  1207. n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
  1208. deltas.append((n1, len1, n2+len2-(n1+len1)))
  1209. return deltas
  1210. # lineDelta finds the appropriate line number delta to apply to the lines [n, n+len).
  1211. # It returns an error if those lines were rewritten by the patch.
  1212. def lineDelta(deltas, n, len):
  1213. d = 0
  1214. for (old, oldlen, newdelta) in deltas:
  1215. if old >= n+len:
  1216. break
  1217. if old+len > n:
  1218. return 0, "patch and recent changes conflict"
  1219. d = newdelta
  1220. return d, ""
  1221. def download(ui, repo, clname, **opts):
  1222. """download a change from the code review server
  1223. Download prints a description of the given change list
  1224. followed by its diff, downloaded from the code review server.
  1225. """
  1226. if missing_codereview:
  1227. return missing_codereview
  1228. cl, vers, patch, err = DownloadCL(ui, repo, clname)
  1229. if err != "":
  1230. return err
  1231. ui.write(cl.EditorText() + "\n")
  1232. ui.write(patch + "\n")
  1233. return
  1234. def file(ui, repo, clname, pat, *pats, **opts):
  1235. """assign files to or remove files from a change list
  1236. Assign files to or (with -d) remove files from a change list.
  1237. The -d option only removes files from the change list.
  1238. It does not edit them or remove them from the repository.
  1239. """
  1240. if missing_codereview:
  1241. return missing_codereview
  1242. pats = tuple([pat] + list(pats))
  1243. if not GoodCLName(clname):
  1244. return "invalid CL name " + clname
  1245. dirty = {}
  1246. cl, err = LoadCL(ui, repo, clname, web=False)
  1247. if err != '':
  1248. return err
  1249. if not cl.local:
  1250. return "cannot change non-local CL " + clname
  1251. files = ChangedFiles(ui, repo, pats, opts)
  1252. if opts["delete"]:
  1253. oldfiles = Intersect(files, cl.files)
  1254. if oldfiles:
  1255. if not ui.quiet:
  1256. ui.status("# Removing files from CL. To undo:\n")
  1257. ui.status("# cd %s\n" % (repo.root))
  1258. for f in oldfiles:
  1259. ui.status("# hg file %s %s\n" % (cl.name, f))
  1260. cl.files = Sub(cl.files, oldfiles)
  1261. cl.Flush(ui, repo)
  1262. else:
  1263. ui.status("no such files in CL")
  1264. return
  1265. if not files:
  1266. return "no such modified files"
  1267. files = Sub(files, cl.files)
  1268. taken = Taken(ui, repo)
  1269. warned = False
  1270. for f in files:
  1271. if f in taken:
  1272. if not warned and not ui.quiet:
  1273. ui.status("# Taking files from other CLs. To undo:\n")
  1274. ui.status("# cd %s\n" % (repo.root))
  1275. warned = True
  1276. ocl = taken[f]
  1277. if not ui.quiet:
  1278. ui.status("# hg file %s %s\n" % (ocl.name, f))
  1279. if ocl not in dirty:
  1280. ocl.files = Sub(ocl.files, files)
  1281. dirty[ocl] = True
  1282. cl.files = Add(cl.files, files)
  1283. dirty[cl] = True
  1284. for d, _ in dirty.items():
  1285. d.Flush(ui, repo)
  1286. return
  1287. def gofmt(ui, repo, *pats, **opts):
  1288. """apply gofmt to modified files
  1289. Applies gofmt to the modified files in the repository that match
  1290. the given patterns.
  1291. """
  1292. if missing_codereview:
  1293. return missing_codereview
  1294. files = ChangedExistingFiles(ui, repo, pats, opts)
  1295. files = [f for f in files if f.endswith(".go")]
  1296. if not files:
  1297. return "no modified go files"
  1298. cwd = os.getcwd()
  1299. files = [RelativePath(repo.root + '/' + f, cwd) for f in files]
  1300. try:
  1301. cmd = ["gofmt", "-l"]
  1302. if not opts["list"]:
  1303. cmd += ["-w"]
  1304. if os.spawnvp(os.P_WAIT, "gofmt", cmd + files) != 0:
  1305. raise util.Abort("gofmt did not exit cleanly")
  1306. except error.Abort, e:
  1307. raise
  1308. except:
  1309. raise util.Abort("gofmt: " + ExceptionDetail())
  1310. return
  1311. def mail(ui, repo, *pats, **opts):
  1312. """mail a change for review
  1313. Uploads a patch to the code review server and then sends mail
  1314. to the reviewer and CC list asking for a review.
  1315. """
  1316. if missing_codereview:
  1317. return missing_codereview
  1318. cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc)
  1319. if err != "":
  1320. return err
  1321. cl.Upload(ui, repo, gofmt_just_warn=True)
  1322. if not cl.reviewer:
  1323. # If no reviewer is listed, assign the review to defaultcc.
  1324. # This makes sure that it appears in the
  1325. # codereview.appspot.com/user/defaultcc
  1326. # page, so that it doesn't get dropped on the floor.
  1327. if not defaultcc:
  1328. return "no reviewers listed in CL"
  1329. cl.cc = Sub(cl.cc, defaultcc)
  1330. cl.reviewer = defaultcc
  1331. cl.Flush(ui, repo)
  1332. if cl.files == []:
  1333. return "no changed files, not sending mail"
  1334. cl.Mail(ui, repo)
  1335. def pending(ui, repo, *pats, **opts):
  1336. """show pending changes
  1337. Lists pending changes followed by a list of unassigned but modified files.
  1338. """
  1339. if missing_codereview:
  1340. return missing_codereview
  1341. m = LoadAllCL(ui, repo, web=True)
  1342. names = m.keys()
  1343. names.sort()
  1344. for name in names:
  1345. cl = m[name]
  1346. ui.write(cl.PendingText() + "\n")
  1347. files = DefaultFiles(ui, repo, [], opts)
  1348. if len(files) > 0:
  1349. s = "Changed files not in any CL:\n"
  1350. for f in files:
  1351. s += "\t" + f + "\n"
  1352. ui.write(s)
  1353. def reposetup(ui, repo):
  1354. global original_match
  1355. if original_match is None:
  1356. start_status_thread()
  1357. original_match = cmdutil.match
  1358. cmdutil.match = ReplacementForCmdutilMatch
  1359. RietveldSetup(ui, repo)
  1360. def CheckContributor(ui, repo, user=None):
  1361. set_status("checking CONTRIBUTORS file")
  1362. user, userline = FindContributor(ui, repo, user, warn=False)
  1363. if not userline:
  1364. raise util.Abort("cannot find %s in CONTRIBUTORS" % (user,))
  1365. return userline
  1366. def FindContributor(ui, repo, user=None, warn=True):
  1367. if not user:
  1368. user = ui.config("ui", "username")
  1369. if not user:
  1370. raise util.Abort("[ui] username is not configured in .hgrc")
  1371. user = user.lower()
  1372. m = re.match(r".*<(.*)>", user)
  1373. if m:
  1374. user = m.group(1)
  1375. if user not in contributors:
  1376. if warn:
  1377. ui.warn("warning: cannot find %s in CONTRIBUTORS\n" % (user,))
  1378. return user, None
  1379. user, email = contributors[user]
  1380. return email, "%s <%s>" % (user, email)
  1381. def submit(ui, repo, *pats, **opts):
  1382. """submit change to remote repository
  1383. Submits change to remote repository.
  1384. Bails out if the local repository is not in sync with the remote one.
  1385. """
  1386. if missing_codereview:
  1387. return missing_codereview
  1388. # We already called this on startup but sometimes Mercurial forgets.
  1389. set_mercurial_encoding_to_utf8()
  1390. repo.ui.quiet = True
  1391. if not opts["no_incoming"] and Incoming(ui, repo, opts):
  1392. return "local repository out of date; must sync before submit"
  1393. cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc)
  1394. if err != "":
  1395. return err
  1396. user = None
  1397. if cl.copied_from:
  1398. user = cl.copied_from
  1399. userline = CheckContributor(ui, repo, user)
  1400. typecheck(userline, str)
  1401. about = ""
  1402. if cl.reviewer:
  1403. about += "R=" + JoinComma([CutDomain(s) for s in cl.reviewer]) + "\n"
  1404. if opts.get('tbr'):
  1405. tbr = SplitCommaSpace(opts.get('tbr'))
  1406. cl.reviewer = Add(cl.reviewer, tbr)
  1407. about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n"
  1408. if cl.cc:
  1409. about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n"
  1410. if not cl.reviewer:
  1411. return "no reviewers listed in CL"
  1412. if not cl.local:
  1413. return "cannot submit non-local CL"
  1414. # upload, to sync current patch and also get change number if CL is new.
  1415. if not cl.copied_from:
  1416. cl.Upload(ui, repo, gofmt_just_warn=True)
  1417. cl.Flush(ui, repo)
  1418. about += "%s%s\n" % (server_url_base, cl.name)
  1419. if cl.copied_from:
  1420. about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n"
  1421. typecheck(about, str)
  1422. if not cl.mailed and not cl.copied_from: # in case this is TBR
  1423. cl.Mail(ui, repo)
  1424. # submit changes locally
  1425. date = opts.get('date')
  1426. if date:
  1427. opts['date'] = util.parsedate(date)
  1428. typecheck(opts['date'], str)
  1429. opts['message'] = cl.desc.rstrip() + "\n\n" + about
  1430. typecheck(opts['message'], str)
  1431. if opts['dryrun']:
  1432. print "NOT SUBMITTING:"
  1433. print "User: ", userline
  1434. print "Message:"
  1435. print Indent(opts['message'], "\t")
  1436. print "Files:"
  1437. print Indent('\n'.join(cl.files), "\t")
  1438. return "dry run; not submitted"
  1439. m = match.exact(repo.root, repo.getcwd(), cl.files)
  1440. node = repo.commit(ustr(opts['message']), ustr(userline), opts.get('date'), m)
  1441. if not node:
  1442. return "nothing changed"
  1443. # push to remote; if it fails for any reason, roll back
  1444. try:
  1445. log = repo.changelog
  1446. rev = log.rev(node)
  1447. parents = log.parentrevs(rev)
  1448. if (rev-1 not in parents and
  1449. (parents == (nullrev, nullrev) or
  1450. len(log.heads(log.node(parents[0]))) > 1 and
  1451. (parents[1] == nullrev or len(log.heads(log.node(parents[1]))) > 1))):
  1452. # created new head
  1453. raise util.Abort("local repository out of date; must sync before submit")
  1454. # push changes to remote.
  1455. # if it works, we're committed.
  1456. # if not, roll back
  1457. other = getremote(ui, repo, opts)
  1458. r = repo.push(other, False, None)
  1459. if r == 0:
  1460. raise util.Abort("local repository out of date; must sync before submit")
  1461. except:
  1462. real_rollback()
  1463. raise
  1464. # we're committed. upload final patch, close review, add commit message
  1465. changeURL = short(node)
  1466. url = other.url()
  1467. m = re.match("^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?", url)
  1468. if m:
  1469. changeURL = "http://code.google.com/p/%s/source/detail?r=%s" % (m.group(2), changeURL)
  1470. else:
  1471. print >>sys.stderr, "URL: ", url
  1472. pmsg = "*** Submitted as " + changeURL + " ***\n\n" + opts['message']
  1473. # When posting, move reviewers to CC line,
  1474. # so that the issue stops showing up in their "My Issues" page.
  1475. PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc))
  1476. if not cl.copied_from:
  1477. EditDesc(cl.name, closed=True, private=cl.private)
  1478. cl.Delete(ui, repo)
  1479. c = repo[None]
  1480. if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed():
  1481. ui.write("switching from %s to default branch.\n" % releaseBranch)
  1482. err = hg.clean(repo, "default")
  1483. if err:
  1484. return err
  1485. return None
  1486. def sync(ui, repo, **opts):
  1487. """synchronize with remote repository
  1488. Incorporates recent changes from the remote repository
  1489. into the local repository.
  1490. """
  1491. if missing_codereview:
  1492. return missing_codereview
  1493. if not opts["local"]:
  1494. ui.status = sync_note
  1495. ui.note = sync_note
  1496. other = getremote(ui, repo, opts)
  1497. modheads = repo.pull(other)
  1498. err = commands.postincoming(ui, repo, modheads, True, "tip")
  1499. if err:
  1500. return err
  1501. commands.update(ui, repo)
  1502. sync_changes(ui, repo)
  1503. def sync_note(msg):
  1504. # we run sync (pull -u) in verbose mode to get the
  1505. # list of files being updated, but that drags along
  1506. # a bunch of messages we don't care about.
  1507. # omit them.
  1508. if msg == 'resolving manifests\n':
  1509. return
  1510. if msg == 'searching for changes\n':
  1511. return
  1512. if msg == "couldn't find merge tool hgmerge\n":
  1513. return
  1514. sys.stdout.write(msg)
  1515. def sync_changes(ui, repo):
  1516. # Look through recent change log descriptions to find
  1517. # potential references to http://.*/our-CL-number.
  1518. # Double-check them by looking at the Rietveld log.
  1519. def Rev(rev):
  1520. desc = repo[rev].description().strip()
  1521. for clname in re.findall('(?m)^http://(?:[^\n]+)/([0-9]+)$', desc):
  1522. if IsLocalCL(ui, repo, clname) and IsRietveldSubmitted(ui, clname, repo[rev].hex()):
  1523. ui.warn("CL %s submitted as %s; closing\n" % (clname, repo[rev]))
  1524. cl, err = LoadCL(ui, repo, clname, web=False)
  1525. if err != "":
  1526. ui.warn("loading CL %s: %s\n" % (clname, err))
  1527. continue
  1528. if not cl.copied_from:
  1529. EditDesc(cl.name, closed=True, private=cl.private)
  1530. cl.Delete(ui, repo)
  1531. if hgversion < '1.4':
  1532. get = util.cachefunc(lambda r: repo[r].changeset())
  1533. changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, [], get, {'rev': None})
  1534. n = 0
  1535. for st, rev, fns in changeiter:
  1536. if st != 'iter':
  1537. continue
  1538. n += 1
  1539. if n > 100:
  1540. break
  1541. Rev(rev)
  1542. else:
  1543. matchfn = cmdutil.match(repo, [], {'rev': None})
  1544. def prep(ctx, fns):
  1545. pass
  1546. for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep):
  1547. Rev(ctx.rev())
  1548. # Remove files that are not modified from the CLs in which they appear.
  1549. all = LoadAllCL(ui, repo, web=False)
  1550. changed = ChangedFiles(ui, repo, [], {})
  1551. for _, cl in all.items():
  1552. extra = Sub(cl.files, changed)
  1553. if extra:
  1554. ui.warn("Removing unmodified files from CL %s:\n" % (cl.name,))
  1555. for f in extra:
  1556. ui.warn("\t%s\n" % (f,))
  1557. cl.files = Sub(cl.files, extra)
  1558. cl.Flush(ui, repo)
  1559. if not cl.files:
  1560. if not cl.copied_from:
  1561. ui.warn("CL %s has no files; delete with hg change -d %s\n" % (cl.name, cl.name))
  1562. else:
  1563. ui.warn("CL %s has no files; delete locally with hg change -D %s\n" % (cl.name, cl.name))
  1564. return
  1565. def upload(ui, repo, name, **opts):
  1566. """upload diffs to the code review server
  1567. Uploads the current modifications for a given change to the server.
  1568. """
  1569. if missing_codereview:
  1570. return missing_codereview
  1571. repo.ui.quiet = True
  1572. cl, err = LoadCL(ui, repo, name, web=True)
  1573. if err != "":
  1574. return err
  1575. if not cl.local:
  1576. return "cannot upload non-local change"
  1577. cl.Upload(ui, repo)
  1578. print "%s%s\n" % (server_url_base, cl.name)
  1579. return
  1580. review_opts = [
  1581. ('r', 'reviewer', '', 'add reviewer'),
  1582. ('', 'cc', '', 'add cc'),
  1583. ('', 'tbr', '', 'add future reviewer'),
  1584. ('m', 'message', '', 'change description (for new change)'),
  1585. ]
  1586. cmdtable = {
  1587. # The ^ means to show this command in the help text that
  1588. # is printed when running hg with no arguments.
  1589. "^change": (
  1590. change,
  1591. [
  1592. ('d', 'delete', None, 'delete existing change list'),
  1593. ('D', 'deletelocal', None, 'delete locally, but do not change CL on server'),
  1594. ('i', 'stdin', None, 'read change list from standard input'),
  1595. ('o', 'stdout', None, 'print change list to standard output'),
  1596. ('p', 'pending', None, 'print pending summary to standard output'),
  1597. ],
  1598. "[-d | -D] [-i] [-o] change# or FILE ..."
  1599. ),
  1600. "^clpatch": (
  1601. clpatch,
  1602. [
  1603. ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'),
  1604. ('', 'no_incoming', None, 'disable check for incoming changes'),
  1605. ],
  1606. "change#"
  1607. ),
  1608. # Would prefer to call this codereview-login, but then
  1609. # hg help codereview prints the help for this command
  1610. # instead of the help for the extension.
  1611. "code-login": (
  1612. code_login,
  1613. [],
  1614. "",
  1615. ),
  1616. "^download": (
  1617. download,
  1618. [],
  1619. "change#"
  1620. ),
  1621. "^file": (
  1622. file,
  1623. [
  1624. ('d', 'delete', None, 'delete files from change list (but not repository)'),
  1625. ],
  1626. "[-d] change# FILE ..."
  1627. ),
  1628. "^gofmt": (
  1629. gofmt,
  1630. [
  1631. ('l', 'list', None, 'list files that would change, but do not edit them'),
  1632. ],
  1633. "FILE ..."
  1634. ),
  1635. "^pending|p": (
  1636. pending,
  1637. [],
  1638. "[FILE ...]"
  1639. ),
  1640. "^mail": (
  1641. mail,
  1642. review_opts + [
  1643. ] + commands.walkopts,
  1644. "[-r reviewer] [--cc cc] [change# | file ...]"
  1645. ),
  1646. "^release-apply": (
  1647. release_apply,
  1648. [
  1649. ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'),
  1650. ('', 'no_incoming', None, 'disable check for incoming changes'),
  1651. ],
  1652. "change#"
  1653. ),
  1654. # TODO: release-start, release-tag, weekly-tag
  1655. "^submit": (
  1656. submit,
  1657. review_opts + [
  1658. ('', 'no_incoming', None, 'disable initial incoming check (for testing)'),
  1659. ('n', 'dryrun', None, 'make change only locally (for testing)'),
  1660. ] + commands.walkopts + commands.commitopts + commands.commitopts2,
  1661. "[-r reviewer] [--cc cc] [change# | file ...]"
  1662. ),
  1663. "^sync": (
  1664. sync,
  1665. [
  1666. ('', 'local', None, 'do not pull changes from remote repository')
  1667. ],
  1668. "[--local]",
  1669. ),
  1670. "^undo": (
  1671. undo,
  1672. [
  1673. ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'),
  1674. ('', 'no_incoming', None, 'disable check for incoming changes'),
  1675. ],
  1676. "change#"
  1677. ),
  1678. "^upload": (
  1679. upload,
  1680. [],
  1681. "change#"
  1682. ),
  1683. }
  1684. #######################################################################
  1685. # Wrappers around upload.py for interacting with Rietveld
  1686. # HTML form parser
  1687. class FormParser(HTMLParser):
  1688. def __init__(self):
  1689. self.map = {}
  1690. self.curtag = None
  1691. self.curdata = None
  1692. HTMLParser.__init__(self)
  1693. def handle_starttag(self, tag, attrs):
  1694. if tag == "input":
  1695. key = None
  1696. value = ''
  1697. for a in attrs:
  1698. if a[0] == 'name':
  1699. key = a[1]
  1700. if a[0] == 'value':
  1701. value = a[1]
  1702. if key is not None:
  1703. self.map[key] = value
  1704. if tag == "textarea":
  1705. key = None
  1706. for a in attrs:
  1707. if a[0] == 'name':
  1708. key = a[1]
  1709. if key is not None:
  1710. self.curtag = key
  1711. self.curdata = ''
  1712. def handle_endtag(self, tag):
  1713. if tag == "textarea" and self.curtag is not None:
  1714. self.map[self.curtag] = self.curdata
  1715. self.curtag = None
  1716. self.curdata = None
  1717. def handle_charref(self, name):
  1718. self.handle_data(unichr(int(name)))
  1719. def handle_entityref(self, name):
  1720. import htmlentitydefs
  1721. if name in htmlentitydefs.entitydefs:
  1722. self.handle_data(htmlentitydefs.entitydefs[name])
  1723. else:
  1724. self.handle_data("&" + name + ";")
  1725. def handle_data(self, data):
  1726. if self.curdata is not None:
  1727. self.curdata += data
  1728. def JSONGet(ui, path):
  1729. try:
  1730. data = MySend(path, force_auth=False)
  1731. typecheck(data, str)
  1732. d = fix_json(json.loads(data))
  1733. except:
  1734. ui.warn("JSONGet %s: %s\n" % (path, ExceptionDetail()))
  1735. return None
  1736. return d
  1737. # Clean up json parser output to match our expectations:
  1738. # * all strings are UTF-8-encoded str, not unicode.
  1739. # * missing fields are missing, not None,
  1740. # so that d.get("foo", defaultvalue) works.
  1741. def fix_json(x):
  1742. if type(x) in [str, int, float, bool, type(None)]:
  1743. pass
  1744. elif type(x) is unicode:
  1745. x = x.encode("utf-8")
  1746. elif type(x) is list:
  1747. for i in range(len(x)):
  1748. x[i] = fix_json(x[i])
  1749. elif type(x) is dict:
  1750. todel = []
  1751. for k in x:
  1752. if x[k] is None:
  1753. todel.append(k)
  1754. else:
  1755. x[k] = fix_json(x[k])
  1756. for k in todel:
  1757. del x[k]
  1758. else:
  1759. raise util.Abort("unknown type " + str(type(x)) + " in fix_json")
  1760. if type(x) is str:
  1761. x = x.replace('\r\n', '\n')
  1762. return x
  1763. def IsRietveldSubmitted(ui, clname, hex):
  1764. dict = JSONGet(ui, "/api/" + clname + "?messages=true")
  1765. if dict is None:
  1766. return False
  1767. for msg in dict.get("messages", []):
  1768. text = msg.get("text", "")
  1769. m = re.match('\*\*\* Submitted as [^*]*?([0-9a-f]+) \*\*\*', text)
  1770. if m is not None and len(m.group(1)) >= 8 and hex.startswith(m.group(1)):
  1771. return True
  1772. return False
  1773. def IsRietveldMailed(cl):
  1774. for msg in cl.dict.get("messages", []):
  1775. if msg.get("text", "").find("I'd like you to review this change") >= 0:
  1776. return True
  1777. return False
  1778. def DownloadCL(ui, repo, clname):
  1779. set_status("downloading CL " + clname)
  1780. cl, err = LoadCL(ui, repo, clname, web=True)
  1781. if err != "":
  1782. return None, None, None, "error loading CL %s: %s" % (clname, err)
  1783. # Find most recent diff
  1784. diffs = cl.dict.get("patchsets", [])
  1785. if not diffs:
  1786. return None, None, None, "CL has no patch sets"
  1787. patchid = diffs[-1]
  1788. patchset = JSONGet(ui, "/api/" + clname + "/" + str(patchid))
  1789. if patchset is None:
  1790. return None, None, None, "error loading CL patchset %s/%d" % (clname, patchid)
  1791. if patchset.get("patchset", 0) != patchid:
  1792. return None, None, None, "malformed patchset information"
  1793. vers = ""
  1794. msg = patchset.get("message", "").split()
  1795. if len(msg) >= 3 and msg[0] == "diff" and msg[1] == "-r":
  1796. vers = msg[2]
  1797. diff = "/download/issue" + clname + "_" + str(patchid) + ".diff"
  1798. diffdata = MySend(diff, force_auth=False)
  1799. # Print warning if email is not in CONTRIBUTORS file.
  1800. email = cl.dict.get("owner_email", "")
  1801. if not email:
  1802. return None, None, None, "cannot find owner for %s" % (clname)
  1803. him = FindContributor(ui, repo, email)
  1804. me = FindContributor(ui, repo, None)
  1805. if him == me:
  1806. cl.mailed = IsRietveldMailed(cl)
  1807. else:
  1808. cl.copied_from = email
  1809. return cl, vers, diffdata, ""
  1810. def MySend(request_path, payload=None,
  1811. content_type="application/octet-stream",
  1812. timeout=None, force_auth=True,
  1813. **kwargs):
  1814. """Run MySend1 maybe twice, because Rietveld is unreliable."""
  1815. try:
  1816. return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
  1817. except Exception, e:
  1818. if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error
  1819. raise
  1820. print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds."
  1821. time.sleep(2)
  1822. return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
  1823. # Like upload.py Send but only authenticates when the
  1824. # redirect is to www.google.com/accounts. This keeps
  1825. # unnecessary redirects from happening during testing.
  1826. def MySend1(request_path, payload=None,
  1827. content_type="application/octet-stream",
  1828. timeout=None, force_auth=True,
  1829. **kwargs):
  1830. """Sends an RPC and returns the response.
  1831. Args:
  1832. request_path: The path to send the request to, eg /api/appversion/create.
  1833. payload: The body of the request, or None to send an empty request.
  1834. content_type: The Content-Type header to use.
  1835. timeout: timeout in seconds; default None i.e. no timeout.
  1836. (Note: for large requests on OS X, the timeout doesn't work right.)
  1837. kwargs: Any keyword arguments are converted into query string parameters.
  1838. Returns:
  1839. The response body, as a string.
  1840. """
  1841. # TODO: Don't require authentication. Let the server say
  1842. # whether it is necessary.
  1843. global rpc
  1844. if rpc == None:
  1845. rpc = GetRpcServer(upload_options)
  1846. self = rpc
  1847. if not self.authenticated and force_auth:
  1848. self._Authenticate()
  1849. if request_path is None:
  1850. return
  1851. old_timeout = socket.getdefaulttimeout()
  1852. socket.setdefaulttimeout(timeout)
  1853. try:
  1854. tries = 0
  1855. while True:
  1856. tries += 1
  1857. args = dict(kwargs)
  1858. url = "http://%s%s" % (self.host, request_path)
  1859. if args:
  1860. url += "?" + urllib.urlencode(args)
  1861. req = self._CreateRequest(url=url, data=payload)
  1862. req.add_header("Content-Type", content_type)
  1863. try:
  1864. f = self.opener.open(req)
  1865. response = f.read()
  1866. f.close()
  1867. # Translate \r\n into \n, because Rietveld doesn't.
  1868. response = response.replace('\r\n', '\n')
  1869. # who knows what urllib will give us
  1870. if type(response) == unicode:
  1871. response = response.encode("utf-8")
  1872. typecheck(response, str)
  1873. return response
  1874. except urllib2.HTTPError, e:
  1875. if tries > 3:
  1876. raise
  1877. elif e.code == 401:
  1878. self._Authenticate()
  1879. elif e.code == 302:
  1880. loc = e.info()["location"]
  1881. if not loc.startswith('https://www.google.com/a') or loc.find('/ServiceLogin') < 0:
  1882. return ''
  1883. self._Authenticate()
  1884. else:
  1885. raise
  1886. finally:
  1887. socket.setdefaulttimeout(old_timeout)
  1888. def GetForm(url):
  1889. f = FormParser()
  1890. f.feed(ustr(MySend(url))) # f.feed wants unicode
  1891. f.close()
  1892. # convert back to utf-8 to restore sanity
  1893. m = {}
  1894. for k,v in f.map.items():
  1895. m[k.encode("utf-8")] = v.replace("\r\n", "\n").encode("utf-8")
  1896. return m
  1897. def EditDesc(issue, subject=None, desc=None, reviewers=None, cc=None, closed=False, private=False):
  1898. set_status("uploading change to description")
  1899. form_fields = GetForm("/" + issue + "/edit")
  1900. if subject is not None:
  1901. form_fields['subject'] = subject
  1902. if desc is not None:
  1903. form_fields['description'] = desc
  1904. if reviewers is not None:
  1905. form_fields['reviewers'] = reviewers
  1906. if cc is not None:
  1907. form_fields['cc'] = cc
  1908. if closed:
  1909. form_fields['closed'] = "checked"
  1910. if private:
  1911. form_fields['private'] = "checked"
  1912. ctype, body = EncodeMultipartFormData(form_fields.items(), [])
  1913. response = MySend("/" + issue + "/edit", body, content_type=ctype)
  1914. if response != "":
  1915. print >>sys.stderr, "Error editing description:\n" + "Sent form: \n", form_fields, "\n", response
  1916. sys.exit(2)
  1917. def PostMessage(ui, issue, message, reviewers=None, cc=None, send_mail=True, subject=None):
  1918. set_status("uploading message")
  1919. form_fields = GetForm("/" + issue + "/publish")
  1920. if reviewers is not None:
  1921. form_fields['reviewers'] = reviewers
  1922. if cc is not None:
  1923. form_fields['cc'] = cc
  1924. if send_mail:
  1925. form_fields['send_mail'] = "checked"
  1926. else:
  1927. del form_fields['send_mail']
  1928. if subject is not None:
  1929. form_fields['subject'] = subject
  1930. form_fields['message'] = message
  1931. form_fields['message_only'] = '1' # Don't include draft comments
  1932. if reviewers is not None or cc is not None:
  1933. form_fields['message_only'] = '' # Must set '' in order to override cc/reviewer
  1934. ctype = "applications/x-www-form-urlencoded"
  1935. body = urllib.urlencode(form_fields)
  1936. response = MySend("/" + issue + "/publish", body, content_type=ctype)
  1937. if response != "":
  1938. print response
  1939. sys.exit(2)
  1940. class opt(object):
  1941. pass
  1942. def nocommit(*pats, **opts):
  1943. """(disabled when using this extension)"""
  1944. raise util.Abort("codereview extension enabled; use mail, upload, or submit instead of commit")
  1945. def nobackout(*pats, **opts):
  1946. """(disabled when using this extension)"""
  1947. raise util.Abort("codereview extension enabled; use undo instead of backout")
  1948. def norollback(*pats, **opts):
  1949. """(disabled when using this extension)"""
  1950. raise util.Abort("codereview extension enabled; use undo instead of rollback")
  1951. def RietveldSetup(ui, repo):
  1952. global defaultcc, upload_options, rpc, server, server_url_base, force_google_account, verbosity, contributors
  1953. global missing_codereview
  1954. repo_config_path = ''
  1955. # Read repository-specific options from utils/lib/codereview/codereview.cfg
  1956. try:
  1957. repo_config_path = repo.root + '/utils/lib/codereview/codereview.cfg'
  1958. f = open(repo_config_path)
  1959. for line in f:
  1960. if line.startswith('defaultcc: '):
  1961. defaultcc = SplitCommaSpace(line[10:])
  1962. except:
  1963. # If there are no options, chances are good this is not
  1964. # a code review repository; stop now before we foul
  1965. # things up even worse. Might also be that repo doesn't
  1966. # even have a root. See issue 959.
  1967. if repo_config_path == '':
  1968. missing_codereview = 'codereview disabled: repository has no root'
  1969. else:
  1970. missing_codereview = 'codereview disabled: cannot open ' + repo_config_path
  1971. return
  1972. # Should only modify repository with hg submit.
  1973. # Disable the built-in Mercurial commands that might
  1974. # trip things up.
  1975. cmdutil.commit = nocommit
  1976. global real_rollback
  1977. real_rollback = repo.rollback
  1978. repo.rollback = norollback
  1979. # would install nobackout if we could; oh well
  1980. try:
  1981. f = open(repo.root + '/CONTRIBUTORS', 'r')
  1982. except:
  1983. raise util.Abort("cannot open %s: %s" % (repo.root+'/CONTRIBUTORS', ExceptionDetail()))
  1984. for line in f:
  1985. # CONTRIBUTORS is a list of lines like:
  1986. # Person <email>
  1987. # Person <email> <alt-email>
  1988. # The first email address is the one used in commit logs.
  1989. if line.startswith('#'):
  1990. continue
  1991. m = re.match(r"([^<>]+\S)\s+(<[^<>\s]+>)((\s+<[^<>\s]+>)*)\s*$", line)
  1992. if m:
  1993. name = m.group(1)
  1994. email = m.group(2)[1:-1]
  1995. contributors[email.lower()] = (name, email)
  1996. for extra in m.group(3).split():
  1997. contributors[extra[1:-1].lower()] = (name, email)
  1998. if not ui.verbose:
  1999. verbosity = 0
  2000. # Config options.
  2001. x = ui.config("codereview", "server")
  2002. if x is not None:
  2003. server = x
  2004. # TODO(rsc): Take from ui.username?
  2005. email = None
  2006. x = ui.config("codereview", "email")
  2007. if x is not None:
  2008. email = x
  2009. server_url_base = "http://" + server + "/"
  2010. testing = ui.config("codereview", "testing")
  2011. force_google_account = ui.configbool("codereview", "force_google_account", False)
  2012. upload_options = opt()
  2013. upload_options.email = email
  2014. upload_options.host = None
  2015. upload_options.verbose = 0
  2016. upload_options.description = None
  2017. upload_options.description_file = None
  2018. upload_options.reviewers = None
  2019. upload_options.cc = None
  2020. upload_options.message = None
  2021. upload_options.issue = None
  2022. upload_options.download_base = False
  2023. upload_options.revision = None
  2024. upload_options.send_mail = False
  2025. upload_options.vcs = None
  2026. upload_options.server = server
  2027. upload_options.save_cookies = True
  2028. if testing:
  2029. upload_options.save_cookies = False
  2030. upload_options.email = "test@example.com"
  2031. rpc = None
  2032. global releaseBranch
  2033. tags = repo.branchtags().keys()
  2034. if 'release-branch.r100' in tags:
  2035. # NOTE(rsc): This tags.sort is going to get the wrong
  2036. # answer when comparing release-branch.r99 with
  2037. # release-branch.r100. If we do ten releases a year
  2038. # that gives us 4 years before we have to worry about this.
  2039. raise util.Abort('tags.sort needs to be fixed for release-branch.r100')
  2040. tags.sort()
  2041. for t in tags:
  2042. if t.startswith('release-branch.'):
  2043. releaseBranch = t
  2044. #######################################################################
  2045. # http://codereview.appspot.com/static/upload.py, heavily edited.
  2046. #!/usr/bin/env python
  2047. #
  2048. # Copyright 2007 Google Inc.
  2049. #
  2050. # Licensed under the Apache License, Version 2.0 (the "License");
  2051. # you may not use this file except in compliance with the License.
  2052. # You may obtain a copy of the License at
  2053. #
  2054. # http://www.apache.org/licenses/LICENSE-2.0
  2055. #
  2056. # Unless required by applicable law or agreed to in writing, software
  2057. # distributed under the License is distributed on an "AS IS" BASIS,
  2058. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2059. # See the License for the specific language governing permissions and
  2060. # limitations under the License.
  2061. """Tool for uploading diffs from a version control system to the codereview app.
  2062. Usage summary: upload.py [options] [-- diff_options]
  2063. Diff options are passed to the diff command of the underlying system.
  2064. Supported version control systems:
  2065. Git
  2066. Mercurial
  2067. Subversion
  2068. It is important for Git/Mercurial users to specify a tree/node/branch to diff
  2069. against by using the '--rev' option.
  2070. """
  2071. # This code is derived from appcfg.py in the App Engine SDK (open source),
  2072. # and from ASPN recipe #146306.
  2073. import cookielib
  2074. import getpass
  2075. import logging
  2076. import mimetypes
  2077. import optparse
  2078. import os
  2079. import re
  2080. import socket
  2081. import subprocess
  2082. import sys
  2083. import urllib
  2084. import urllib2
  2085. import urlparse
  2086. # The md5 module was deprecated in Python 2.5.
  2087. try:
  2088. from hashlib import md5
  2089. except ImportError:
  2090. from md5 import md5
  2091. try:
  2092. import readline
  2093. except ImportError:
  2094. pass
  2095. # The logging verbosity:
  2096. # 0: Errors only.
  2097. # 1: Status messages.
  2098. # 2: Info logs.
  2099. # 3: Debug logs.
  2100. verbosity = 1
  2101. # Max size of patch or base file.
  2102. MAX_UPLOAD_SIZE = 900 * 1024
  2103. # whitelist for non-binary filetypes which do not start with "text/"
  2104. # .mm (Objective-C) shows up as application/x-freemind on my Linux box.
  2105. TEXT_MIMETYPES = [
  2106. 'application/javascript',
  2107. 'application/x-javascript',
  2108. 'application/x-freemind'
  2109. ]
  2110. def GetEmail(prompt):
  2111. """Prompts the user for their email address and returns it.
  2112. The last used email address is saved to a file and offered up as a suggestion
  2113. to the user. If the user presses enter without typing in anything the last
  2114. used email address is used. If the user enters a new address, it is saved
  2115. for next time we prompt.
  2116. """
  2117. last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
  2118. last_email = ""
  2119. if os.path.exists(last_email_file_name):
  2120. try:
  2121. last_email_file = open(last_email_file_name, "r")
  2122. last_email = last_email_file.readline().strip("\n")
  2123. last_email_file.close()
  2124. prompt += " [%s]" % last_email
  2125. except IOError, e:
  2126. pass
  2127. email = raw_input(prompt + ": ").strip()
  2128. if email:
  2129. try:
  2130. last_email_file = open(last_email_file_name, "w")
  2131. last_email_file.write(email)
  2132. last_email_file.close()
  2133. except IOError, e:
  2134. pass
  2135. else:
  2136. email = last_email
  2137. return email
  2138. def StatusUpdate(msg):
  2139. """Print a status message to stdout.
  2140. If 'verbosity' is greater than 0, print the message.
  2141. Args:
  2142. msg: The string to print.
  2143. """
  2144. if verbosity > 0:
  2145. print msg
  2146. def ErrorExit(msg):
  2147. """Print an error message to stderr and exit."""
  2148. print >>sys.stderr, msg
  2149. sys.exit(1)
  2150. class ClientLoginError(urllib2.HTTPError):
  2151. """Raised to indicate there was an error authenticating with ClientLogin."""
  2152. def __init__(self, url, code, msg, headers, args):
  2153. urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  2154. self.args = args
  2155. self.reason = args["Error"]
  2156. class AbstractRpcServer(object):
  2157. """Provides a common interface for a simple RPC server."""
  2158. def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False):
  2159. """Creates a new HttpRpcServer.
  2160. Args:
  2161. host: The host to send requests to.
  2162. auth_function: A function that takes no arguments and returns an
  2163. (email, password) tuple when called. Will be called if authentication
  2164. is required.
  2165. host_override: The host header to send to the server (defaults to host).
  2166. extra_headers: A dict of extra headers to append to every request.
  2167. save_cookies: If True, save the authentication cookies to local disk.
  2168. If False, use an in-memory cookiejar instead. Subclasses must
  2169. implement this functionality. Defaults to False.
  2170. """
  2171. self.host = host
  2172. self.host_override = host_override
  2173. self.auth_function = auth_function
  2174. self.authenticated = False
  2175. self.extra_headers = extra_headers
  2176. self.save_cookies = save_cookies
  2177. self.opener = self._GetOpener()
  2178. if self.host_override:
  2179. logging.info("Server: %s; Host: %s", self.host, self.host_override)
  2180. else:
  2181. logging.info("Server: %s", self.host)
  2182. def _GetOpener(self):
  2183. """Returns an OpenerDirector for making HTTP requests.
  2184. Returns:
  2185. A urllib2.OpenerDirector object.
  2186. """
  2187. raise NotImplementedError()
  2188. def _CreateRequest(self, url, data=None):
  2189. """Creates a new urllib request."""
  2190. logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
  2191. req = urllib2.Request(url, data=data)
  2192. if self.host_override:
  2193. req.add_header("Host", self.host_override)
  2194. for key, value in self.extra_headers.iteritems():
  2195. req.add_header(key, value)
  2196. return req
  2197. def _GetAuthToken(self, email, password):
  2198. """Uses ClientLogin to authenticate the user, returning an auth token.
  2199. Args:
  2200. email: The user's email address
  2201. password: The user's password
  2202. Raises:
  2203. ClientLoginError: If there was an error authenticating with ClientLogin.
  2204. HTTPError: If there was some other form of HTTP error.
  2205. Returns:
  2206. The authentication token returned by ClientLogin.
  2207. """
  2208. account_type = "GOOGLE"
  2209. if self.host.endswith(".google.com") and not force_google_account:
  2210. # Needed for use inside Google.
  2211. account_type = "HOSTED"
  2212. req = self._CreateRequest(
  2213. url="https://www.google.com/accounts/ClientLogin",
  2214. data=urllib.urlencode({
  2215. "Email": email,
  2216. "Passwd": password,
  2217. "service": "ah",
  2218. "source": "rietveld-codereview-upload",
  2219. "accountType": account_type,
  2220. }),
  2221. )
  2222. try:
  2223. response = self.opener.open(req)
  2224. response_body = response.read()
  2225. response_dict = dict(x.split("=") for x in response_body.split("\n") if x)
  2226. return response_dict["Auth"]
  2227. except urllib2.HTTPError, e:
  2228. if e.code == 403:
  2229. body = e.read()
  2230. response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  2231. raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict)
  2232. else:
  2233. raise
  2234. def _GetAuthCookie(self, auth_token):
  2235. """Fetches authentication cookies for an authentication token.
  2236. Args:
  2237. auth_token: The authentication token returned by ClientLogin.
  2238. Raises:
  2239. HTTPError: If there was an error fetching the authentication cookies.
  2240. """
  2241. # This is a dummy value to allow us to identify when we're successful.
  2242. continue_location = "http://localhost/"
  2243. args = {"continue": continue_location, "auth": auth_token}
  2244. req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args)))
  2245. try:
  2246. response = self.opener.open(req)
  2247. except urllib2.HTTPError, e:
  2248. response = e
  2249. if (response.code != 302 or
  2250. response.info()["location"] != continue_location):
  2251. raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp)
  2252. self.authenticated = True
  2253. def _Authenticate(self):
  2254. """Authenticates the user.
  2255. The authentication process works as follows:
  2256. 1) We get a username and password from the user
  2257. 2) We use ClientLogin to obtain an AUTH token for the user
  2258. (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
  2259. 3) We pass the auth token to /_ah/login on the server to obtain an
  2260. authentication cookie. If login was successful, it tries to redirect
  2261. us to the URL we provided.
  2262. If we attempt to access the upload API without first obtaining an
  2263. authentication cookie, it returns a 401 response (or a 302) and
  2264. directs us to authenticate ourselves with ClientLogin.
  2265. """
  2266. for i in range(3):
  2267. credentials = self.auth_function()
  2268. try:
  2269. auth_token = self._GetAuthToken(credentials[0], credentials[1])
  2270. except ClientLoginError, e:
  2271. if e.reason == "BadAuthentication":
  2272. print >>sys.stderr, "Invalid username or password."
  2273. continue
  2274. if e.reason == "CaptchaRequired":
  2275. print >>sys.stderr, (
  2276. "Please go to\n"
  2277. "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  2278. "and verify you are a human. Then try again.")
  2279. break
  2280. if e.reason == "NotVerified":
  2281. print >>sys.stderr, "Account not verified."
  2282. break
  2283. if e.reason == "TermsNotAgreed":
  2284. print >>sys.stderr, "User has not agreed to TOS."
  2285. break
  2286. if e.reason == "AccountDeleted":
  2287. print >>sys.stderr, "The user account has been deleted."
  2288. break
  2289. if e.reason == "AccountDisabled":
  2290. print >>sys.stderr, "The user account has been disabled."
  2291. break
  2292. if e.reason == "ServiceDisabled":
  2293. print >>sys.stderr, "The user's access to the service has been disabled."
  2294. break
  2295. if e.reason == "ServiceUnavailable":
  2296. print >>sys.stderr, "The service is not available; try again later."
  2297. break
  2298. raise
  2299. self._GetAuthCookie(auth_token)
  2300. return
  2301. def Send(self, request_path, payload=None,
  2302. content_type="application/octet-stream",
  2303. timeout=None,
  2304. **kwargs):
  2305. """Sends an RPC and returns the response.
  2306. Args:
  2307. request_path: The path to send the request to, eg /api/appversion/create.
  2308. payload: The body of the request, or None to send an empty request.
  2309. content_type: The Content-Type header to use.
  2310. timeout: timeout in seconds; default None i.e. no timeout.
  2311. (Note: for large requests on OS X, the timeout doesn't work right.)
  2312. kwargs: Any keyword arguments are converted into query string parameters.
  2313. Returns:
  2314. The response body, as a string.
  2315. """
  2316. # TODO: Don't require authentication. Let the server say
  2317. # whether it is necessary.
  2318. if not self.authenticated:
  2319. self._Authenticate()
  2320. old_timeout = socket.getdefaulttimeout()
  2321. socket.setdefaulttimeout(timeout)
  2322. try:
  2323. tries = 0
  2324. while True:
  2325. tries += 1
  2326. args = dict(kwargs)
  2327. url = "http://%s%s" % (self.host, request_path)
  2328. if args:
  2329. url += "?" + urllib.urlencode(args)
  2330. req = self._CreateRequest(url=url, data=payload)
  2331. req.add_header("Content-Type", content_type)
  2332. try:
  2333. f = self.opener.open(req)
  2334. response = f.read()
  2335. f.close()
  2336. return response
  2337. except urllib2.HTTPError, e:
  2338. if tries > 3:
  2339. raise
  2340. elif e.code == 401 or e.code == 302:
  2341. self._Authenticate()
  2342. else:
  2343. raise
  2344. finally:
  2345. socket.setdefaulttimeout(old_timeout)
  2346. class HttpRpcServer(AbstractRpcServer):
  2347. """Provides a simplified RPC-style interface for HTTP requests."""
  2348. def _Authenticate(self):
  2349. """Save the cookie jar after authentication."""
  2350. super(HttpRpcServer, self)._Authenticate()
  2351. if self.save_cookies:
  2352. StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
  2353. self.cookie_jar.save()
  2354. def _GetOpener(self):
  2355. """Returns an OpenerDirector that supports cookies and ignores redirects.
  2356. Returns:
  2357. A urllib2.OpenerDirector object.
  2358. """
  2359. opener = urllib2.OpenerDirector()
  2360. opener.add_handler(urllib2.ProxyHandler())
  2361. opener.add_handler(urllib2.UnknownHandler())
  2362. opener.add_handler(urllib2.HTTPHandler())
  2363. opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  2364. opener.add_handler(urllib2.HTTPSHandler())
  2365. opener.add_handler(urllib2.HTTPErrorProcessor())
  2366. if self.save_cookies:
  2367. self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server)
  2368. self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
  2369. if os.path.exists(self.cookie_file):
  2370. try:
  2371. self.cookie_jar.load()
  2372. self.authenticated = True
  2373. StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file)
  2374. except (cookielib.LoadError, IOError):
  2375. # Failed to load cookies - just ignore them.
  2376. pass
  2377. else:
  2378. # Create an empty cookie file with mode 600
  2379. fd = os.open(self.cookie_file, os.O_CREAT, 0600)
  2380. os.close(fd)
  2381. # Always chmod the cookie file
  2382. os.chmod(self.cookie_file, 0600)
  2383. else:
  2384. # Don't save cookies across runs of update.py.
  2385. self.cookie_jar = cookielib.CookieJar()
  2386. opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
  2387. return opener
  2388. def GetRpcServer(options):
  2389. """Returns an instance of an AbstractRpcServer.
  2390. Returns:
  2391. A new AbstractRpcServer, on which RPC calls can be made.
  2392. """
  2393. rpc_server_class = HttpRpcServer
  2394. def GetUserCredentials():
  2395. """Prompts the user for a username and password."""
  2396. # Disable status prints so they don't obscure the password prompt.
  2397. global global_status
  2398. st = global_status
  2399. global_status = None
  2400. email = options.email
  2401. if email is None:
  2402. email = GetEmail("Email (login for uploading to %s)" % options.server)
  2403. password = getpass.getpass("Password for %s: " % email)
  2404. # Put status back.
  2405. global_status = st
  2406. return (email, password)
  2407. # If this is the dev_appserver, use fake authentication.
  2408. host = (options.host or options.server).lower()
  2409. if host == "localhost" or host.startswith("localhost:"):
  2410. email = options.email
  2411. if email is None:
  2412. email = "test@example.com"
  2413. logging.info("Using debug user %s. Override with --email" % email)
  2414. server = rpc_server_class(
  2415. options.server,
  2416. lambda: (email, "password"),
  2417. host_override=options.host,
  2418. extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email},
  2419. save_cookies=options.save_cookies)
  2420. # Don't try to talk to ClientLogin.
  2421. server.authenticated = True
  2422. return server
  2423. return rpc_server_class(options.server, GetUserCredentials,
  2424. host_override=options.host, save_cookies=options.save_cookies)
  2425. def EncodeMultipartFormData(fields, files):
  2426. """Encode form fields for multipart/form-data.
  2427. Args:
  2428. fields: A sequence of (name, value) elements for regular form fields.
  2429. files: A sequence of (name, filename, value) elements for data to be
  2430. uploaded as files.
  2431. Returns:
  2432. (content_type, body) ready for httplib.HTTP instance.
  2433. Source:
  2434. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  2435. """
  2436. BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
  2437. CRLF = '\r\n'
  2438. lines = []
  2439. for (key, value) in fields:
  2440. typecheck(key, str)
  2441. typecheck(value, str)
  2442. lines.append('--' + BOUNDARY)
  2443. lines.append('Content-Disposition: form-data; name="%s"' % key)
  2444. lines.append('')
  2445. lines.append(value)
  2446. for (key, filename, value) in files:
  2447. typecheck(key, str)
  2448. typecheck(filename, str)
  2449. typecheck(value, str)
  2450. lines.append('--' + BOUNDARY)
  2451. lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
  2452. lines.append('Content-Type: %s' % GetContentType(filename))
  2453. lines.append('')
  2454. lines.append(value)
  2455. lines.append('--' + BOUNDARY + '--')
  2456. lines.append('')
  2457. body = CRLF.join(lines)
  2458. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  2459. return content_type, body
  2460. def GetContentType(filename):
  2461. """Helper to guess the content-type from the filename."""
  2462. return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  2463. # Use a shell for subcommands on Windows to get a PATH search.
  2464. use_shell = sys.platform.startswith("win")
  2465. def RunShellWithReturnCode(command, print_output=False,
  2466. universal_newlines=True, env=os.environ):
  2467. """Executes a command and returns the output from stdout and the return code.
  2468. Args:
  2469. command: Command to execute.
  2470. print_output: If True, the output is printed to stdout.
  2471. If False, both stdout and stderr are ignored.
  2472. universal_newlines: Use universal_newlines flag (default: True).
  2473. Returns:
  2474. Tuple (output, return code)
  2475. """
  2476. logging.info("Running %s", command)
  2477. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2478. shell=use_shell, universal_newlines=universal_newlines, env=env)
  2479. if print_output:
  2480. output_array = []
  2481. while True:
  2482. line = p.stdout.readline()
  2483. if not line:
  2484. break
  2485. print line.strip("\n")
  2486. output_array.append(line)
  2487. output = "".join(output_array)
  2488. else:
  2489. output = p.stdout.read()
  2490. p.wait()
  2491. errout = p.stderr.read()
  2492. if print_output and errout:
  2493. print >>sys.stderr, errout
  2494. p.stdout.close()
  2495. p.stderr.close()
  2496. return output, p.returncode
  2497. def RunShell(command, silent_ok=False, universal_newlines=True,
  2498. print_output=False, env=os.environ):
  2499. data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines, env)
  2500. if retcode:
  2501. ErrorExit("Got error status from %s:\n%s" % (command, data))
  2502. if not silent_ok and not data:
  2503. ErrorExit("No output from %s" % command)
  2504. return data
  2505. class VersionControlSystem(object):
  2506. """Abstract base class providing an interface to the VCS."""
  2507. def __init__(self, options):
  2508. """Constructor.
  2509. Args:
  2510. options: Command line options.
  2511. """
  2512. self.options = options
  2513. def GenerateDiff(self, args):
  2514. """Return the current diff as a string.
  2515. Args:
  2516. args: Extra arguments to pass to the diff command.
  2517. """
  2518. raise NotImplementedError(
  2519. "abstract method -- subclass %s must override" % self.__class__)
  2520. def GetUnknownFiles(self):
  2521. """Return a list of files unknown to the VCS."""
  2522. raise NotImplementedError(
  2523. "abstract method -- subclass %s must override" % self.__class__)
  2524. def CheckForUnknownFiles(self):
  2525. """Show an "are you sure?" prompt if there are unknown files."""
  2526. unknown_files = self.GetUnknownFiles()
  2527. if unknown_files:
  2528. print "The following files are not added to version control:"
  2529. for line in unknown_files:
  2530. print line
  2531. prompt = "Are you sure to continue?(y/N) "
  2532. answer = raw_input(prompt).strip()
  2533. if answer != "y":
  2534. ErrorExit("User aborted")
  2535. def GetBaseFile(self, filename):
  2536. """Get the content of the upstream version of a file.
  2537. Returns:
  2538. A tuple (base_content, new_content, is_binary, status)
  2539. base_content: The contents of the base file.
  2540. new_content: For text files, this is empty. For binary files, this is
  2541. the contents of the new file, since the diff output won't contain
  2542. information to reconstruct the current file.
  2543. is_binary: True iff the file is binary.
  2544. status: The status of the file.
  2545. """
  2546. raise NotImplementedError(
  2547. "abstract method -- subclass %s must override" % self.__class__)
  2548. def GetBaseFiles(self, diff):
  2549. """Helper that calls GetBase file for each file in the patch.
  2550. Returns:
  2551. A dictionary that maps from filename to GetBaseFile's tuple. Filenames
  2552. are retrieved based on lines that start with "Index:" or
  2553. "Property changes on:".
  2554. """
  2555. files = {}
  2556. for line in diff.splitlines(True):
  2557. if line.startswith('Index:') or line.startswith('Property changes on:'):
  2558. unused, filename = line.split(':', 1)
  2559. # On Windows if a file has property changes its filename uses '\'
  2560. # instead of '/'.
  2561. filename = filename.strip().replace('\\', '/')
  2562. files[filename] = self.GetBaseFile(filename)
  2563. return files
  2564. def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
  2565. files):
  2566. """Uploads the base files (and if necessary, the current ones as well)."""
  2567. def UploadFile(filename, file_id, content, is_binary, status, is_base):
  2568. """Uploads a file to the server."""
  2569. set_status("uploading " + filename)
  2570. file_too_large = False
  2571. if is_base:
  2572. type = "base"
  2573. else:
  2574. type = "current"
  2575. if len(content) > MAX_UPLOAD_SIZE:
  2576. print ("Not uploading the %s file for %s because it's too large." %
  2577. (type, filename))
  2578. file_too_large = True
  2579. content = ""
  2580. checksum = md5(content).hexdigest()
  2581. if options.verbose > 0 and not file_too_large:
  2582. print "Uploading %s file for %s" % (type, filename)
  2583. url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
  2584. form_fields = [
  2585. ("filename", filename),
  2586. ("status", status),
  2587. ("checksum", checksum),
  2588. ("is_binary", str(is_binary)),
  2589. ("is_current", str(not is_base)),
  2590. ]
  2591. if file_too_large:
  2592. form_fields.append(("file_too_large", "1"))
  2593. if options.email:
  2594. form_fields.append(("user", options.email))
  2595. ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)])
  2596. response_body = rpc_server.Send(url, body, content_type=ctype)
  2597. if not response_body.startswith("OK"):
  2598. StatusUpdate(" --> %s" % response_body)
  2599. sys.exit(1)
  2600. # Don't want to spawn too many threads, nor do we want to
  2601. # hit Rietveld too hard, or it will start serving 500 errors.
  2602. # When 8 works, it's no better than 4, and sometimes 8 is
  2603. # too many for Rietveld to handle.
  2604. MAX_PARALLEL_UPLOADS = 4
  2605. sema = threading.BoundedSemaphore(MAX_PARALLEL_UPLOADS)
  2606. upload_threads = []
  2607. finished_upload_threads = []
  2608. class UploadFileThread(threading.Thread):
  2609. def __init__(self, args):
  2610. threading.Thread.__init__(self)
  2611. self.args = args
  2612. def run(self):
  2613. UploadFile(*self.args)
  2614. finished_upload_threads.append(self)
  2615. sema.release()
  2616. def StartUploadFile(*args):
  2617. sema.acquire()
  2618. while len(finished_upload_threads) > 0:
  2619. t = finished_upload_threads.pop()
  2620. upload_threads.remove(t)
  2621. t.join()
  2622. t = UploadFileThread(args)
  2623. upload_threads.append(t)
  2624. t.start()
  2625. def WaitForUploads():
  2626. for t in upload_threads:
  2627. t.join()
  2628. patches = dict()
  2629. [patches.setdefault(v, k) for k, v in patch_list]
  2630. for filename in patches.keys():
  2631. base_content, new_content, is_binary, status = files[filename]
  2632. file_id_str = patches.get(filename)
  2633. if file_id_str.find("nobase") != -1:
  2634. base_content = None
  2635. file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
  2636. file_id = int(file_id_str)
  2637. if base_content != None:
  2638. StartUploadFile(filename, file_id, base_content, is_binary, status, True)
  2639. if new_content != None:
  2640. StartUploadFile(filename, file_id, new_content, is_binary, status, False)
  2641. WaitForUploads()
  2642. def IsImage(self, filename):
  2643. """Returns true if the filename has an image extension."""
  2644. mimetype = mimetypes.guess_type(filename)[0]
  2645. if not mimetype:
  2646. return False
  2647. return mimetype.startswith("image/")
  2648. def IsBinary(self, filename):
  2649. """Returns true if the guessed mimetyped isnt't in text group."""
  2650. mimetype = mimetypes.guess_type(filename)[0]
  2651. if not mimetype:
  2652. return False # e.g. README, "real" binaries usually have an extension
  2653. # special case for text files which don't start with text/
  2654. if mimetype in TEXT_MIMETYPES:
  2655. return False
  2656. return not mimetype.startswith("text/")
  2657. class FakeMercurialUI(object):
  2658. def __init__(self):
  2659. self.quiet = True
  2660. self.output = ''
  2661. def write(self, *args, **opts):
  2662. self.output += ' '.join(args)
  2663. use_hg_shell = False # set to True to shell out to hg always; slower
  2664. class MercurialVCS(VersionControlSystem):
  2665. """Implementation of the VersionControlSystem interface for Mercurial."""
  2666. def __init__(self, options, ui, repo):
  2667. super(MercurialVCS, self).__init__(options)
  2668. self.ui = ui
  2669. self.repo = repo
  2670. # Absolute path to repository (we can be in a subdir)
  2671. self.repo_dir = os.path.normpath(repo.root)
  2672. # Compute the subdir
  2673. cwd = os.path.normpath(os.getcwd())
  2674. assert cwd.startswith(self.repo_dir)
  2675. self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
  2676. if self.options.revision:
  2677. self.base_rev = self.options.revision
  2678. else:
  2679. mqparent, err = RunShellWithReturnCode(['hg', 'log', '--rev', 'qparent', '--template={node}'])
  2680. if not err and mqparent != "":
  2681. self.base_rev = mqparent
  2682. else:
  2683. self.base_rev = RunShell(["hg", "parents", "-q"]).split(':')[1].strip()
  2684. def _GetRelPath(self, filename):
  2685. """Get relative path of a file according to the current directory,
  2686. given its logical path in the repo."""
  2687. assert filename.startswith(self.subdir), (filename, self.subdir)
  2688. return filename[len(self.subdir):].lstrip(r"\/")
  2689. def GenerateDiff(self, extra_args):
  2690. # If no file specified, restrict to the current subdir
  2691. extra_args = extra_args or ["."]
  2692. cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
  2693. data = RunShell(cmd, silent_ok=True)
  2694. svndiff = []
  2695. filecount = 0
  2696. for line in data.splitlines():
  2697. m = re.match("diff --git a/(\S+) b/(\S+)", line)
  2698. if m:
  2699. # Modify line to make it look like as it comes from svn diff.
  2700. # With this modification no changes on the server side are required
  2701. # to make upload.py work with Mercurial repos.
  2702. # NOTE: for proper handling of moved/copied files, we have to use
  2703. # the second filename.
  2704. filename = m.group(2)
  2705. svndiff.append("Index: %s" % filename)
  2706. svndiff.append("=" * 67)
  2707. filecount += 1
  2708. logging.info(line)
  2709. else:
  2710. svndiff.append(line)
  2711. if not filecount:
  2712. ErrorExit("No valid patches found in output from hg diff")
  2713. return "\n".join(svndiff) + "\n"
  2714. def GetUnknownFiles(self):
  2715. """Return a list of files unknown to the VCS."""
  2716. args = []
  2717. status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
  2718. silent_ok=True)
  2719. unknown_files = []
  2720. for line in status.splitlines():
  2721. st, fn = line.split(" ", 1)
  2722. if st == "?":
  2723. unknown_files.append(fn)
  2724. return unknown_files
  2725. def GetBaseFile(self, filename):
  2726. set_status("inspecting " + filename)
  2727. # "hg status" and "hg cat" both take a path relative to the current subdir
  2728. # rather than to the repo root, but "hg diff" has given us the full path
  2729. # to the repo root.
  2730. base_content = ""
  2731. new_content = None
  2732. is_binary = False
  2733. oldrelpath = relpath = self._GetRelPath(filename)
  2734. # "hg status -C" returns two lines for moved/copied files, one otherwise
  2735. if use_hg_shell:
  2736. out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
  2737. else:
  2738. fui = FakeMercurialUI()
  2739. ret = commands.status(fui, self.repo, *[relpath], **{'rev': [self.base_rev], 'copies': True})
  2740. if ret:
  2741. raise util.Abort(ret)
  2742. out = fui.output
  2743. out = out.splitlines()
  2744. # HACK: strip error message about missing file/directory if it isn't in
  2745. # the working copy
  2746. if out[0].startswith('%s: ' % relpath):
  2747. out = out[1:]
  2748. status, what = out[0].split(' ', 1)
  2749. if len(out) > 1 and status == "A" and what == relpath:
  2750. oldrelpath = out[1].strip()
  2751. status = "M"
  2752. if ":" in self.base_rev:
  2753. base_rev = self.base_rev.split(":", 1)[0]
  2754. else:
  2755. base_rev = self.base_rev
  2756. if status != "A":
  2757. if use_hg_shell:
  2758. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True)
  2759. else:
  2760. base_content = str(self.repo[base_rev][oldrelpath].data())
  2761. is_binary = "\0" in base_content # Mercurial's heuristic
  2762. if status != "R":
  2763. new_content = open(relpath, "rb").read()
  2764. is_binary = is_binary or "\0" in new_content
  2765. if is_binary and base_content and use_hg_shell:
  2766. # Fetch again without converting newlines
  2767. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
  2768. silent_ok=True, universal_newlines=False)
  2769. if not is_binary or not self.IsImage(relpath):
  2770. new_content = None
  2771. return base_content, new_content, is_binary, status
  2772. # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
  2773. def SplitPatch(data):
  2774. """Splits a patch into separate pieces for each file.
  2775. Args:
  2776. data: A string containing the output of svn diff.
  2777. Returns:
  2778. A list of 2-tuple (filename, text) where text is the svn diff output
  2779. pertaining to filename.
  2780. """
  2781. patches = []
  2782. filename = None
  2783. diff = []
  2784. for line in data.splitlines(True):
  2785. new_filename = None
  2786. if line.startswith('Index:'):
  2787. unused, new_filename = line.split(':', 1)
  2788. new_filename = new_filename.strip()
  2789. elif line.startswith('Property changes on:'):
  2790. unused, temp_filename = line.split(':', 1)
  2791. # When a file is modified, paths use '/' between directories, however
  2792. # when a property is modified '\' is used on Windows. Make them the same
  2793. # otherwise the file shows up twice.
  2794. temp_filename = temp_filename.strip().replace('\\', '/')
  2795. if temp_filename != filename:
  2796. # File has property changes but no modifications, create a new diff.
  2797. new_filename = temp_filename
  2798. if new_filename:
  2799. if filename and diff:
  2800. patches.append((filename, ''.join(diff)))
  2801. filename = new_filename
  2802. diff = [line]
  2803. continue
  2804. if diff is not None:
  2805. diff.append(line)
  2806. if filename and diff:
  2807. patches.append((filename, ''.join(diff)))
  2808. return patches
  2809. def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
  2810. """Uploads a separate patch for each file in the diff output.
  2811. Returns a list of [patch_key, filename] for each file.
  2812. """
  2813. patches = SplitPatch(data)
  2814. rv = []
  2815. for patch in patches:
  2816. set_status("uploading patch for " + patch[0])
  2817. if len(patch[1]) > MAX_UPLOAD_SIZE:
  2818. print ("Not uploading the patch for " + patch[0] +
  2819. " because the file is too large.")
  2820. continue
  2821. form_fields = [("filename", patch[0])]
  2822. if not options.download_base:
  2823. form_fields.append(("content_upload", "1"))
  2824. files = [("data", "data.diff", patch[1])]
  2825. ctype, body = EncodeMultipartFormData(form_fields, files)
  2826. url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
  2827. print "Uploading patch for " + patch[0]
  2828. response_body = rpc_server.Send(url, body, content_type=ctype)
  2829. lines = response_body.splitlines()
  2830. if not lines or lines[0] != "OK":
  2831. StatusUpdate(" --> %s" % response_body)
  2832. sys.exit(1)
  2833. rv.append([lines[1], patch[0]])
  2834. return rv