PageRenderTime 39ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/codereview/codereview.py

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