pw 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. #!/usr/bin/env python
  2. #
  3. # Patchwork command line client
  4. # Copyright (C) 2008, 2013 Nate Case <ncase@xes-inc.com>
  5. #
  6. # This file is part of the Patchwork package.
  7. #
  8. # Patchwork is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # Patchwork is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Patchwork; if not, write to the Free Software
  20. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. import os
  22. import sys
  23. import xmlrpclib
  24. import getopt
  25. import string
  26. import tempfile
  27. import subprocess
  28. import base64
  29. import ConfigParser
  30. import datetime
  31. import smtplib
  32. import urllib
  33. import re
  34. from email.mime.text import MIMEText
  35. notify_on_state_change = {
  36. 'accepted': 'emacs-orgmode@gnu.org',
  37. 'rejected': 'emacs-orgmode@gnu.org',
  38. 'changes requested': 'emacs-orgmode@gnu.org',
  39. 'rfc': 'emacs-orgmode@gnu.org'
  40. }
  41. # Default Patchwork remote XML-RPC server URL
  42. # This script will check the PW_XMLRPC_URL environment variable
  43. # for the URL to access. If that is unspecified, it will fallback to
  44. # the hardcoded default value specified here.
  45. DEFAULT_URL = "http://patchwork.newartisans.com/xmlrpc/"
  46. CONFIG_FILES = [os.path.expanduser('~/.pwclientrc')]
  47. class Filter:
  48. """Filter for selecting patches."""
  49. def __init__(self):
  50. # These fields refer to specific objects, so they are special
  51. # because we have to resolve them to IDs before passing the
  52. # filter to the server
  53. self.state = ""
  54. self.project = ""
  55. # The dictionary that gets passed to via XML-RPC
  56. self.d = {}
  57. def add(self, field, value):
  58. if field == 'state':
  59. self.state = value
  60. elif field == 'project':
  61. self.project = value
  62. else:
  63. # OK to add directly
  64. self.d[field] = value
  65. def resolve_ids(self, rpc):
  66. """Resolve State, Project, and Person IDs based on filter strings."""
  67. if self.state != "":
  68. id = state_id_by_name(rpc, self.state)
  69. if id == 0:
  70. sys.stderr.write("Note: No State found matching %s*, " \
  71. "ignoring filter\n" % self.state)
  72. else:
  73. self.d['state_id'] = id
  74. if self.project != "":
  75. id = project_id_by_name(rpc, self.project)
  76. if id == 0:
  77. sys.stderr.write("Note: No Project found matching %s, " \
  78. "ignoring filter\n" % self.project)
  79. else:
  80. self.d['project_id'] = id
  81. def __str__(self):
  82. """Return human-readable description of the filter."""
  83. return str(self.d)
  84. class BasicHTTPAuthTransport(xmlrpclib.SafeTransport):
  85. def __init__(self, username = None, password = None, use_https = False):
  86. self.username = username
  87. self.password = password
  88. self.use_https = use_https
  89. xmlrpclib.SafeTransport.__init__(self)
  90. def authenticated(self):
  91. return self.username != None and self.password != None
  92. def send_host(self, connection, host):
  93. xmlrpclib.Transport.send_host(self, connection, host)
  94. if not self.authenticated():
  95. return
  96. credentials = '%s:%s' % (self.username, self.password)
  97. auth = 'Basic ' + base64.encodestring(credentials).strip()
  98. connection.putheader('Authorization', auth)
  99. def make_connection(self, host):
  100. if self.use_https:
  101. fn = xmlrpclib.SafeTransport.make_connection
  102. else:
  103. fn = xmlrpclib.Transport.make_connection
  104. return fn(self, host)
  105. def usage():
  106. sys.stderr.write("Usage: %s <action> [options]\n\n" % \
  107. (os.path.basename(sys.argv[0])))
  108. sys.stderr.write("Where <action> is one of:\n")
  109. sys.stderr.write(
  110. """ apply <ID> : Apply a patch (in the current dir, using -p1)
  111. get <ID> : Download a patch and save it locally
  112. projects : List all projects
  113. states : Show list of potential patch states
  114. list [str] : List patches, using the optional filters specified
  115. below and an optional substring to search for patches
  116. by name
  117. search [str] : Same as 'list'
  118. view <ID> : View a patch
  119. show <ID> : Same as view
  120. update [-s state] [-c commit-ref] [-m email-comment] <ID>
  121. : Update patch, send mail to mailing list if appropriate
  122. branch <ID> : Create a topic branch t/patchNNN for this patch
  123. : and update it to the current master
  124. merge [-m email-comment] <ID>
  125. : Merge the t/patchNNN topic branch into master
  126. \n""")
  127. sys.stderr.write("""\nFilter options for 'list' and 'search':
  128. -s <state> : Filter by patch state (e.g., 'New', 'Accepted', etc.)
  129. -p <project> : Filter by project name (see 'projects' for list)
  130. -w <who> : Filter by submitter (name, e-mail substring search)
  131. -d <who> : Filter by delegate (name, e-mail substring search)
  132. -n <max #> : Restrict number of results\n""")
  133. sys.stderr.write("""\nActions that take an ID argument can also be \
  134. invoked with:
  135. -h <hash> : Lookup by patch hash\n""")
  136. sys.exit(1)
  137. def project_id_by_name(rpc, linkname):
  138. """Given a project short name, look up the Project ID."""
  139. if len(linkname) == 0:
  140. return 0
  141. projects = rpc.project_list(linkname, 0)
  142. for project in projects:
  143. if project['linkname'] == linkname:
  144. return project['id']
  145. return 0
  146. def state_id_by_name(rpc, name):
  147. """Given a partial state name, look up the state ID."""
  148. if len(name) == 0:
  149. return 0
  150. states = rpc.state_list(name, 0)
  151. for state in states:
  152. if state['name'].lower().startswith(name.lower()):
  153. return state['id']
  154. return 0
  155. def person_ids_by_name(rpc, name):
  156. """Given a partial name or email address, return a list of the
  157. person IDs that match."""
  158. if len(name) == 0:
  159. return []
  160. people = rpc.person_list(name, 0)
  161. return map(lambda x: x['id'], people)
  162. def list_patches(patches):
  163. """Dump a list of patches to stdout."""
  164. print("%-5s %-12s %s" % ("ID", "State", "Name"))
  165. print("%-5s %-12s %s" % ("--", "-----", "----"))
  166. for patch in patches:
  167. print("%-5d %-12s %s" % (patch['id'], patch['state'], patch['name']))
  168. def action_list(rpc, filter, submitter_str, delegate_str):
  169. filter.resolve_ids(rpc)
  170. if submitter_str != "":
  171. ids = person_ids_by_name(rpc, submitter_str)
  172. if len(ids) == 0:
  173. sys.stderr.write("Note: Nobody found matching *%s*\n", \
  174. submitter_str)
  175. else:
  176. for id in ids:
  177. person = rpc.person_get(id)
  178. print "Patches submitted by %s <%s>:" % \
  179. (person['name'], person['email'])
  180. f = filter
  181. f.add("submitter_id", id)
  182. patches = rpc.patch_list(f.d)
  183. list_patches(patches)
  184. return
  185. if delegate_str != "":
  186. ids = person_ids_by_name(rpc, delegate_str)
  187. if len(ids) == 0:
  188. sys.stderr.write("Note: Nobody found matching *%s*\n", \
  189. delegate_str)
  190. else:
  191. for id in ids:
  192. person = rpc.person_get(id)
  193. print "Patches delegated to %s <%s>:" % \
  194. (person['name'], person['email'])
  195. f = filter
  196. f.add("delegate_id", id)
  197. patches = rpc.patch_list(f.d)
  198. list_patches(patches)
  199. return
  200. patches = rpc.patch_list(filter.d)
  201. list_patches(patches)
  202. def action_projects(rpc):
  203. projects = rpc.project_list("", 0)
  204. print("%-5s %-24s %s" % ("ID", "Name", "Description"))
  205. print("%-5s %-24s %s" % ("--", "----", "-----------"))
  206. for project in projects:
  207. print("%-5d %-24s %s" % (project['id'], \
  208. project['linkname'], \
  209. project['name']))
  210. def action_states(rpc):
  211. states = rpc.state_list("", 0)
  212. print("%-5s %s" % ("ID", "Name"))
  213. print("%-5s %s" % ("--", "----"))
  214. for state in states:
  215. print("%-5d %s" % (state['id'], state['name']))
  216. def action_get(rpc, patch_id):
  217. patch = rpc.patch_get(patch_id)
  218. s = rpc.patch_get_mbox(patch_id)
  219. if patch == {} or len(s) == 0:
  220. sys.stderr.write("Unable to get patch %d\n" % patch_id)
  221. sys.exit(1)
  222. base_fname = fname = os.path.basename(patch['filename'])
  223. i = 0
  224. while os.path.exists(fname):
  225. fname = "%s.%d" % (base_fname, i)
  226. i += 1
  227. try:
  228. f = open(fname, "w")
  229. except:
  230. sys.stderr.write("Unable to open %s for writing\n" % fname)
  231. sys.exit(1)
  232. try:
  233. f.write(unicode(s).encode("utf-8"))
  234. f.close()
  235. print "Saved patch to %s" % fname
  236. except:
  237. sys.stderr.write("Failed to write to %s\n" % fname)
  238. sys.exit(1)
  239. def action_apply(rpc, patch_id):
  240. patch = rpc.patch_get(patch_id)
  241. if patch == {}:
  242. sys.stderr.write("Error getting information on patch ID %d\n" % \
  243. patch_id)
  244. sys.exit(1)
  245. print "Applying patch #%d to current directory" % patch_id
  246. print "Description: %s" % patch['name']
  247. s = rpc.patch_get_mbox(patch_id)
  248. if len(s) > 0:
  249. proc = subprocess.Popen(['patch', '-p1'], stdin = subprocess.PIPE)
  250. proc.communicate(s)
  251. else:
  252. sys.stderr.write("Error: No patch content found\n")
  253. sys.exit(1)
  254. def action_update_patch(rpc, patch_id, state = None, commit = None,
  255. delegate_str = "", comment_str = "None",
  256. archived = False):
  257. patch = rpc.patch_get(patch_id)
  258. if patch == {}:
  259. sys.stderr.write("Error getting information on patch ID %d\n" % \
  260. patch_id)
  261. sys.exit(1)
  262. params = {}
  263. delegate_id = None
  264. if delegate_str != "":
  265. params['delegate'] = delegate_str
  266. ids = person_ids_by_name(rpc, delegate_str)
  267. if len(ids) == 0:
  268. sys.stderr.write("Note: Nobody found matching *%s*\n"% \
  269. delegate_str)
  270. else:
  271. delegate_id = ids[0]
  272. if state:
  273. state_id = state_id_by_name(rpc, state)
  274. if state_id == 0:
  275. sys.stderr.write("Error: No State found matching %s*\n" % state)
  276. sys.exit(1)
  277. params['state'] = state_id
  278. if state.lower() in notify_on_state_change:
  279. if not delegate_id:
  280. sys.stderr.write("Error: Delegate (-d) required for this update\n")
  281. sys.exit(1)
  282. person = rpc.person_get(delegate_id)
  283. submitter = rpc.person_get(patch['submitter_id'])
  284. from_addr = '%s <%s>' % (person['name'], person['email'])
  285. cc_addr = '%s <%s>' % (submitter['name'], submitter['email'])
  286. to_addr = notify_on_state_change[state.lower()]
  287. orig_mail = rpc.patch_get_mbox(patch_id)
  288. orig_mail = '> ' + orig_mail.replace('\n','\n> ')
  289. longdesc = '''Patch %s (http://patchwork.newartisans.com/patch/%s/) is now "%s".
  290. Maintainer comment: %s
  291. This relates to the following submission:
  292. http://mid.gmane.org/%s
  293. Here is the original message containing the patch:
  294. %s''' % \
  295. (patch['id'], patch['id'], state, comment_str, urllib.quote(patch['msgid']), orig_mail)
  296. shortdesc = '[%s] %s' % (state, patch['name'])
  297. msg = MIMEText(longdesc)
  298. msg['Subject'] = shortdesc
  299. msg['From'] = from_addr
  300. msg['To'] = to_addr
  301. #msg['Cc'] = cc_addr
  302. msg['References'] = patch['msgid']
  303. # Send the message via our own SMTP server, but don't include
  304. # the envelope header.
  305. try:
  306. s = smtplib.SMTP('localhost')
  307. print "Sending e-mail to: %s, %s" % (to_addr, cc_addr)
  308. s.sendmail(from_addr, [to_addr, cc_addr], msg.as_string())
  309. s.quit()
  310. except:
  311. sys.stderr.write("Warning: Failed to send e-mail " +
  312. "(no SMTP server listening at localhost?)\n")
  313. if commit:
  314. params['commit_ref'] = commit
  315. if archived:
  316. params['archived'] = archived
  317. success = False
  318. try:
  319. print "Updating patch %d to state '%s', delegate %s" % \
  320. (patch_id, state, delegate_str)
  321. success = rpc.patch_set(patch_id, params)
  322. except xmlrpclib.Fault, f:
  323. sys.stderr.write("Error updating patch: %s\n" % f.faultString)
  324. if not success:
  325. sys.stderr.write("Patch not updated\n")
  326. def patch_id_from_hash(rpc, project, hash):
  327. try:
  328. patch = rpc.patch_get_by_project_hash(project, hash)
  329. except xmlrpclib.Fault:
  330. # the server may not have the newer patch_get_by_project_hash function,
  331. # so fall back to hash-only.
  332. patch = rpc.patch_get_by_hash(hash)
  333. if patch == {}:
  334. return None
  335. return patch['id']
  336. def branch_with(patch_id, rpc, delegate_str):
  337. s = rpc.patch_get_mbox(patch_id)
  338. if len(s) > 0:
  339. print unicode(s).encode("utf-8")
  340. patch = rpc.patch_get(patch_id)
  341. # Find the latest commit from the day before the patch
  342. proc = subprocess.Popen(['git', 'log', '--until=' + patch['date'],
  343. '-1', '--format=%H', 'master'],
  344. stdout = subprocess.PIPE)
  345. sha = proc.stdout.read()[:-1]
  346. # Create a topic branch named after this commit
  347. proc = subprocess.Popen(['git', 'checkout', '-b', 't/patch%s' %
  348. patch_id, sha])
  349. sts = os.waitpid(proc.pid, 0)
  350. if sts[1] != 0:
  351. sys.stderr.write("Could not create branch for patch\n")
  352. return
  353. # Apply the patch to the branch
  354. fname = '/tmp/patch'
  355. try:
  356. f = open(fname, "w")
  357. except:
  358. sys.stderr.write("Unable to open %s for writing\n" % fname)
  359. sys.exit(1)
  360. try:
  361. f.write(unicode(s).encode("utf-8"))
  362. f.close()
  363. print "Saved patch to %s" % fname
  364. except:
  365. sys.stderr.write("Failed to write to %s\n" % fname)
  366. sys.exit(1)
  367. proc = subprocess.Popen(['git', 'am', '/tmp/patch'])
  368. sts = os.waitpid(proc.pid, 0)
  369. if sts[1] != 0:
  370. sys.stderr.write("Failed to apply patch to branch\n")
  371. proc = subprocess.Popen(['git', 'checkout', 'master'])
  372. os.waitpid(proc.pid, 0)
  373. proc = subprocess.Popen(['git', 'branch', '-D', 't/patch%s' %
  374. patch_id, sha])
  375. os.waitpid(proc.pid, 0)
  376. return
  377. # If it succeeded this far, mark the patch as "Under Review" by the
  378. # invoking user.
  379. action_update_patch(rpc, patch_id, state = 'Under Review',
  380. delegate_str = delegate_str)
  381. proc = subprocess.Popen(['git', 'rebase', 'master'])
  382. sts = os.waitpid(proc.pid, 0)
  383. print sha
  384. def merge_with(patch_id, rpc, delegate_str, comment_str):
  385. s = rpc.patch_get_mbox(patch_id)
  386. if len(s) > 0:
  387. print unicode(s).encode("utf-8")
  388. proc = subprocess.Popen(['git', 'checkout', 'master'])
  389. sts = os.waitpid(proc.pid, 0)
  390. if sts[1] != 0:
  391. sys.stderr.write("Failed to checkout master branch\n")
  392. return
  393. proc = subprocess.Popen(['git', 'merge', '--ff', 't/patch%s' % patch_id])
  394. sts = os.waitpid(proc.pid, 0)
  395. if sts[1] != 0:
  396. sys.stderr.write("Failed to merge t/patch%s into master\n" % patch_id)
  397. return
  398. proc = subprocess.Popen(['git', 'rev-parse', 'master'],
  399. stdout = subprocess.PIPE)
  400. sha = proc.stdout.read()[:-1]
  401. # If it succeeded this far, mark the patch as "Accepted" by the invoking
  402. # user.
  403. action_update_patch(rpc, patch_id, state = 'Accepted', commit = sha,
  404. delegate_str = delegate_str, comment_str = comment_str,
  405. archived = True)
  406. print sha
  407. auth_actions = ['update', 'branch', 'merge']
  408. def main():
  409. try:
  410. opts, args = getopt.getopt(sys.argv[2:], 's:p:w:d:n:c:h:m:')
  411. except getopt.GetoptError, err:
  412. print str(err)
  413. usage()
  414. if len(sys.argv) < 2:
  415. usage()
  416. action = sys.argv[1].lower()
  417. # set defaults
  418. filt = Filter()
  419. submitter_str = ""
  420. delegate_str = ""
  421. project_str = ""
  422. commit_str = ""
  423. state_str = "New"
  424. hash_str = ""
  425. url = DEFAULT_URL
  426. config = ConfigParser.ConfigParser()
  427. config.read(CONFIG_FILES)
  428. # grab settings from config files
  429. if config.has_option('base', 'url'):
  430. url = config.get('base', 'url')
  431. if config.has_option('base', 'project'):
  432. project_str = config.get('base', 'project')
  433. comment_str = "none"
  434. for name, value in opts:
  435. if name == '-s':
  436. state_str = value
  437. elif name == '-p':
  438. project_str = value
  439. elif name == '-w':
  440. submitter_str = value
  441. elif name == '-d':
  442. delegate_str = value
  443. elif name == '-c':
  444. commit_str = value
  445. elif name == '-h':
  446. hash_str = value
  447. elif name == '-m':
  448. comment_str = value
  449. elif name == '-n':
  450. try:
  451. filt.add("max_count", int(value))
  452. except:
  453. sys.stderr.write("Invalid maximum count '%s'\n" % value)
  454. usage()
  455. else:
  456. sys.stderr.write("Unknown option '%s'\n" % name)
  457. usage()
  458. if len(args) > 1:
  459. sys.stderr.write("Too many arguments specified\n")
  460. usage()
  461. (username, password) = (None, None)
  462. transport = None
  463. if action in auth_actions:
  464. if config.has_option('auth', 'username') and \
  465. config.has_option('auth', 'password'):
  466. use_https = url.startswith('https')
  467. transport = BasicHTTPAuthTransport( \
  468. config.get('auth', 'username'),
  469. config.get('auth', 'password'),
  470. use_https)
  471. else:
  472. sys.stderr.write(("The %s action requires authentication, "
  473. "but no username or password\nis configured\n") % action)
  474. sys.exit(1)
  475. if project_str:
  476. filt.add("project", project_str)
  477. if state_str:
  478. filt.add("state", state_str)
  479. try:
  480. rpc = xmlrpclib.Server(url, transport = transport)
  481. except:
  482. sys.stderr.write("Unable to connect to %s\n" % url)
  483. sys.exit(1)
  484. patch_id = None
  485. if hash_str:
  486. patch_id = patch_id_from_hash(rpc, project_str, hash_str)
  487. if patch_id is None:
  488. sys.stderr.write("No patch has the hash provided\n")
  489. sys.exit(1)
  490. if action == 'list' or action == 'search':
  491. if len(args) > 0:
  492. filt.add("name__icontains", args[0])
  493. action_list(rpc, filt, submitter_str, delegate_str)
  494. elif action.startswith('project'):
  495. action_projects(rpc)
  496. elif action.startswith('state'):
  497. action_states(rpc)
  498. elif action == 'branch':
  499. try:
  500. patch_id = patch_id or int(args[0])
  501. except:
  502. sys.stderr.write("Invalid patch ID given\n")
  503. sys.exit(1)
  504. branch_with(patch_id, rpc, config.get('auth', 'username'))
  505. elif action == 'merge':
  506. try:
  507. patch_id = patch_id or int(args[0])
  508. except:
  509. sys.stderr.write("Invalid patch ID given\n")
  510. sys.exit(1)
  511. merge_with(patch_id, rpc, config.get('auth', 'username'), comment_str)
  512. elif action == 'test':
  513. patch_id = patch_id or int(args[0])
  514. patch = rpc.patch_get(patch_id)
  515. s = rpc.patch_get_mbox(patch_id)
  516. print "xxx %s xxx"
  517. print "xxx %s xxx" % patch['name']
  518. print "xxx %s xxx" % rpc.patch_get_mbox(patch_id)
  519. elif action == 'view' or action == 'show':
  520. try:
  521. patch_id = patch_id or int(args[0])
  522. except:
  523. sys.stderr.write("Invalid patch ID given\n")
  524. sys.exit(1)
  525. s = rpc.patch_get_mbox(patch_id)
  526. if len(s) > 0:
  527. print unicode(s).encode("utf-8")
  528. elif action == 'get' or action == 'save':
  529. try:
  530. patch_id = patch_id or int(args[0])
  531. except:
  532. sys.stderr.write("Invalid patch ID given\n")
  533. sys.exit(1)
  534. action_get(rpc, patch_id)
  535. elif action == 'apply':
  536. try:
  537. patch_id = patch_id or int(args[0])
  538. except:
  539. sys.stderr.write("Invalid patch ID given\n")
  540. sys.exit(1)
  541. action_apply(rpc, patch_id)
  542. elif action == 'update':
  543. try:
  544. patch_id = patch_id or int(args[0])
  545. except:
  546. sys.stderr.write("Invalid patch ID given\n")
  547. sys.exit(1)
  548. action_update_patch(rpc, patch_id, state = state_str,
  549. commit = commit_str, delegate_str = delegate_str, comment_str = comment_str)
  550. else:
  551. sys.stderr.write("Unknown action '%s'\n" % action)
  552. usage()
  553. if __name__ == "__main__":
  554. main()