g.extension.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: g.extension
  5. # AUTHOR(S): Markus Neteler
  6. # Pythonized by Martin Landa
  7. # PURPOSE: Tool to download and install extensions from GRASS Addons SVN into
  8. # local GRASS installation
  9. # COPYRIGHT: (C) 2009-2011 by Markus Neteler, and the GRASS Development Team
  10. #
  11. # This program is free software under the GNU General
  12. # Public License (>=v2). Read the file COPYING that
  13. # comes with GRASS for details.
  14. #
  15. # TODO: add sudo support where needed (i.e. check first permission to write into
  16. # $GISBASE directory)
  17. #############################################################################
  18. #%module
  19. #% label: Tool to maintain the extensions in local GRASS installation.
  20. #% description: Downloads, installs extensions from GRASS Addons SVN repository into local GRASS installation or removes installed extensions.
  21. #% keywords: general
  22. #% keywords: installation
  23. #% keywords: extensions
  24. #%end
  25. #%option
  26. #% key: extension
  27. #% type: string
  28. #% key_desc: name
  29. #% description: Name of extension to install/remove
  30. #% required: yes
  31. #%end
  32. #%option
  33. #% key: operation
  34. #% type: string
  35. #% description: Operation to be performed
  36. #% required: yes
  37. #% options: add,remove
  38. #% answer: add
  39. #%end
  40. #%option
  41. #% key: svnurl
  42. #% type: string
  43. #% key_desc: url
  44. #% description: SVN Addons repository URL
  45. #% required: yes
  46. #% answer: http://svn.osgeo.org/grass/grass-addons/grass7
  47. #%end
  48. #%option
  49. #% key: prefix
  50. #% type: string
  51. #% key_desc: path
  52. #% description: Prefix where to install extension (ignored when flag -s is given)
  53. #% answer: $GRASS_ADDON_PATH
  54. #% required: no
  55. #%end
  56. #%flag
  57. #% key: l
  58. #% description: List available modules in the GRASS Addons SVN repository
  59. #% guisection: Print
  60. #% suppress_required: yes
  61. #%end
  62. #%flag
  63. #% key: c
  64. #% description: List available modules in the GRASS Addons SVN repository including module description
  65. #% guisection: Print
  66. #% suppress_required: yes
  67. #%end
  68. #%flag
  69. #% key: g
  70. #% description: List available modules in the GRASS Addons SVN repository (shell script style)
  71. #% guisection: Print
  72. #% suppress_required: yes
  73. #%end
  74. #%flag
  75. #% key: s
  76. #% description: Install system-wide (may need system administrator rights)
  77. #%end
  78. #%flag
  79. #% key: d
  80. #% description: Download source code and exit
  81. #%end
  82. #%flag
  83. #% key: i
  84. #% description: Don't install new extension, just compile it
  85. #%end
  86. import os
  87. import sys
  88. import re
  89. import atexit
  90. import shutil
  91. import glob
  92. from urllib2 import urlopen, HTTPError
  93. try:
  94. import xml.etree.ElementTree as etree
  95. except ImportError:
  96. import elementtree.ElementTree as etree # Python <= 2.4
  97. from grass.script import core as grass
  98. # temp dir
  99. remove_tmpdir = True
  100. def check():
  101. for prog in ('svn', 'make', 'gcc'):
  102. if not grass.find_program(prog, ['--help']):
  103. grass.fatal(_("'%s' required. Please install '%s' first.") % (prog, prog))
  104. def expand_module_class_name(c):
  105. name = { 'd' : 'display',
  106. 'db' : 'database',
  107. 'g' : 'general',
  108. 'i' : 'imagery',
  109. 'm' : 'misc',
  110. 'ps' : 'postscript',
  111. 'p' : 'paint',
  112. 'r' : 'raster',
  113. 'r3' : 'raster3d',
  114. 's' : 'sites',
  115. 'v' : 'vector',
  116. 'gui' : 'gui/wxpython' }
  117. if name.has_key(c):
  118. return name[c]
  119. return c
  120. def list_available_modules():
  121. mlist = list()
  122. # try to download XML metadata file first
  123. url = "http://grass.osgeo.org/addons/grass%s.xml" % grass.version()['version'].split('.')[0]
  124. try:
  125. f = urlopen(url)
  126. tree = etree.fromstring(f.read())
  127. for mnode in tree.findall('task'):
  128. name = mnode.get('name')
  129. if flags['c'] or flags['g']:
  130. desc = mnode.find('description').text
  131. if not desc:
  132. desc = ''
  133. keyw = mnode.find('keywords').text
  134. if not keyw:
  135. keyw = ''
  136. if flags['g']:
  137. print 'name=' + name
  138. print 'description=' + desc
  139. print 'keywords=' + keyw
  140. elif flags['c']:
  141. print name + ' - ' + desc
  142. else:
  143. print name
  144. except HTTPError:
  145. return list_available_modules_svn()
  146. return mlist
  147. def list_available_modules_svn():
  148. mlist = list()
  149. grass.message(_('Fetching list of modules from GRASS-Addons SVN (be patient)...'))
  150. pattern = re.compile(r'(<li><a href=".+">)(.+)(</a></li>)', re.IGNORECASE)
  151. i = 0
  152. prefix = ['d', 'db', 'g', 'i', 'm', 'ps',
  153. 'p', 'r', 'r3', 's', 'v']
  154. nprefix = len(prefix)
  155. for d in prefix:
  156. if flags['g']:
  157. grass.percent(i, nprefix, 1)
  158. i += 1
  159. modclass = expand_module_class_name(d)
  160. grass.verbose(_("Checking for '%s' modules...") % modclass)
  161. url = '%s/%s' % (options['svnurl'], modclass)
  162. grass.debug("url = %s" % url, debug = 2)
  163. try:
  164. f = urlopen(url)
  165. except HTTPError:
  166. grass.debug(_("Unable to fetch '%s'") % url, debug = 1)
  167. continue
  168. for line in f.readlines():
  169. # list modules
  170. sline = pattern.search(line)
  171. if not sline:
  172. continue
  173. name = sline.group(2).rstrip('/')
  174. if name.split('.', 1)[0] == d:
  175. print_module_desc(name, url)
  176. mlist.append(name)
  177. mlist += list_wxgui_extensions()
  178. if flags['g']:
  179. grass.percent(1, 1, 1)
  180. return mlist
  181. def list_wxgui_extensions(print_module = True):
  182. mlist = list()
  183. grass.debug('Fetching list of wxGUI extensions from GRASS-Addons SVN (be patient)...')
  184. pattern = re.compile(r'(<li><a href=".+">)(.+)(</a></li>)', re.IGNORECASE)
  185. grass.verbose(_("Checking for '%s' modules...") % 'gui/wxpython')
  186. url = '%s/%s' % (options['svnurl'], 'gui/wxpython')
  187. grass.debug("url = %s" % url, debug = 2)
  188. f = urlopen(url)
  189. if not f:
  190. grass.warning(_("Unable to fetch '%s'") % url)
  191. return
  192. for line in f.readlines():
  193. # list modules
  194. sline = pattern.search(line)
  195. if not sline:
  196. continue
  197. name = sline.group(2).rstrip('/')
  198. if name not in ('..', 'Makefile'):
  199. if print_module:
  200. print_module_desc(name, url)
  201. mlist.append(name)
  202. return mlist
  203. def print_module_desc(name, url):
  204. if not flags['c'] and not flags['g']:
  205. print name
  206. return
  207. if flags['g']:
  208. print 'name=' + name
  209. # check main.c first
  210. desc = get_module_desc(url + '/' + name + '/' + name)
  211. if not desc:
  212. desc = get_module_desc(url + '/' + name + '/main.c', script = False)
  213. if not desc:
  214. if not flags['g']:
  215. print name + ' - '
  216. return
  217. if flags['g']:
  218. print 'description=' + desc.get('description', '')
  219. print 'keywords=' + ','.join(desc.get('keywords', list()))
  220. else:
  221. print name + ' - ' + desc.get('description', '')
  222. def get_module_desc(url, script = True):
  223. grass.debug('url=%s' % url)
  224. try:
  225. f = urlopen(url)
  226. except HTTPError:
  227. return {}
  228. if script:
  229. ret = get_module_script(f)
  230. else:
  231. ret = get_module_main(f)
  232. return ret
  233. def get_module_main(f):
  234. if not f:
  235. return dict()
  236. ret = { 'keyword' : list() }
  237. pattern = re.compile(r'(module.*->)(.+)(=)(.*)', re.IGNORECASE)
  238. keyword = re.compile(r'(G_add_keyword\()(.+)(\);)', re.IGNORECASE)
  239. key = ''
  240. value = ''
  241. for line in f.readlines():
  242. line = line.strip()
  243. find = pattern.search(line)
  244. if find:
  245. key = find.group(2).strip()
  246. line = find.group(4).strip()
  247. else:
  248. find = keyword.search(line)
  249. if find:
  250. ret['keyword'].append(find.group(2).replace('"', '').replace('_(', '').replace(')', ''))
  251. if key:
  252. value += line
  253. if line[-2:] == ');':
  254. value = value.replace('"', '').replace('_(', '').replace(');', '')
  255. if key == 'keywords':
  256. ret[key] = map(lambda x: x.strip(), value.split(','))
  257. else:
  258. ret[key] = value
  259. key = value = ''
  260. return ret
  261. def get_module_script(f):
  262. ret = dict()
  263. if not f:
  264. return ret
  265. begin = re.compile(r'#%.*module', re.IGNORECASE)
  266. end = re.compile(r'#%.*end', re.IGNORECASE)
  267. mline = None
  268. for line in f.readlines():
  269. if not mline:
  270. mline = begin.search(line)
  271. if mline:
  272. if end.search(line):
  273. break
  274. try:
  275. key, value = line.split(':', 1)
  276. key = key.replace('#%', '').strip()
  277. value = value.strip()
  278. if key == 'keywords':
  279. ret[key] = map(lambda x: x.strip(), value.split(','))
  280. else:
  281. ret[key] = value
  282. except ValueError:
  283. pass
  284. return ret
  285. def cleanup():
  286. if remove_tmpdir:
  287. grass.try_rmdir(tmpdir)
  288. else:
  289. grass.message(_("Path to the source code:"))
  290. sys.stderr.write('%s\n' % os.path.join(tmpdir, options['extension']))
  291. def install_extension_win():
  292. ### TODO: do not use hardcoded url
  293. version = grass.version()['version'].split('.')
  294. url = "http://wingrass.fsv.cvut.cz/grass%s%s/addons" % (version[0], version[1])
  295. success = False
  296. grass.message(_("Downloading precompiled GRASS Addons <%s>...") % options['extension'])
  297. for comp, ext in [(('bin', ), 'exe'),
  298. (('docs', 'html'), 'html'),
  299. (('man', 'man1'), None),
  300. (('scripts', ), 'py')]:
  301. name = options['extension']
  302. if ext:
  303. name += '.' + ext
  304. try:
  305. f = urlopen(url + '/' + '/'.join(comp) + '/' + name)
  306. fo = open(os.path.join(options['prefix'], os.path.sep.join(comp), name), 'wb')
  307. fo.write(f.read())
  308. fo.close()
  309. if comp[0] in ('bin', 'scripts'):
  310. success = True
  311. except HTTPError:
  312. pass
  313. if not success:
  314. grass.fatal(_("GRASS Addons <%s> not found") % options['extension'])
  315. def install_extension():
  316. gisbase = os.getenv('GISBASE')
  317. if not gisbase:
  318. grass.fatal(_('$GISBASE not defined'))
  319. if grass.find_program(options['extension'], ['--help']):
  320. grass.warning(_("Extension <%s> already installed. Will be updated...") % options['extension'])
  321. gui_list = list_wxgui_extensions(print_module = False)
  322. if options['extension'] not in gui_list:
  323. classchar = options['extension'].split('.', 1)[0]
  324. moduleclass = expand_module_class_name(classchar)
  325. url = options['svnurl'] + '/' + moduleclass + '/' + options['extension']
  326. else:
  327. url = options['svnurl'] + '/gui/wxpython/' + options['extension']
  328. if not flags['s']:
  329. grass.fatal(_("Installation of wxGUI extension requires -%s flag.") % 's')
  330. grass.message(_("Fetching '%s' from GRASS-Addons SVN (be patient)...") % options['extension'])
  331. os.chdir(tmpdir)
  332. if grass.verbosity() == 0:
  333. outdev = open(os.devnull, 'w')
  334. else:
  335. outdev = sys.stdout
  336. if grass.call(['svn', 'checkout',
  337. url], stdout = outdev) != 0:
  338. grass.fatal(_("GRASS Addons <%s> not found") % options['extension'])
  339. dirs = { 'bin' : os.path.join(tmpdir, options['extension'], 'bin'),
  340. 'docs' : os.path.join(tmpdir, options['extension'], 'docs'),
  341. 'html' : os.path.join(tmpdir, options['extension'], 'docs', 'html'),
  342. 'man' : os.path.join(tmpdir, options['extension'], 'man'),
  343. 'man1' : os.path.join(tmpdir, options['extension'], 'man', 'man1'),
  344. 'scripts' : os.path.join(tmpdir, options['extension'], 'scripts'),
  345. 'etc' : os.path.join(tmpdir, options['extension'], 'etc'),
  346. }
  347. makeCmd = ['make',
  348. 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ '),
  349. 'BIN=%s' % dirs['bin'],
  350. 'HTMLDIR=%s' % dirs['html'],
  351. 'MANDIR=%s' % dirs['man1'],
  352. 'SCRIPTDIR=%s' % dirs['scripts'],
  353. 'ETC=%s' % os.path.join(dirs['etc'],options['extension'])
  354. ]
  355. installCmd = ['make',
  356. 'MODULE_TOPDIR=%s' % gisbase,
  357. 'ARCH_DISTDIR=%s' % os.path.join(tmpdir, options['extension']),
  358. 'INST_DIR=%s' % options['prefix'],
  359. 'install'
  360. ]
  361. if flags['d']:
  362. grass.message(_("To compile run:"))
  363. sys.stderr.write(' '.join(makeCmd) + '\n')
  364. grass.message(_("To install run:\n\n"))
  365. sys.stderr.write(' '.join(installCmd) + '\n')
  366. return
  367. os.chdir(os.path.join(tmpdir, options['extension']))
  368. grass.message(_("Compiling '%s'...") % options['extension'])
  369. if options['extension'] not in gui_list:
  370. ret = grass.call(makeCmd,
  371. stdout = outdev)
  372. else:
  373. ret = grass.call(['make',
  374. 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ ')],
  375. stdout = outdev)
  376. if ret != 0:
  377. grass.fatal(_('Compilation failed, sorry. Please check above error messages.'))
  378. if flags['i'] or options['extension'] in gui_list:
  379. return
  380. grass.message(_("Installing '%s'...") % options['extension'])
  381. ret = grass.call(installCmd,
  382. stdout = outdev)
  383. if ret != 0:
  384. grass.warning(_('Installation failed, sorry. Please check above error messages.'))
  385. else:
  386. grass.message(_("Installation of '%s' successfully finished.") % options['extension'])
  387. # manual page: fix href
  388. if os.getenv('GRASS_ADDON_PATH'):
  389. html_man = os.path.join(os.getenv('GRASS_ADDON_PATH'), 'docs', 'html', options['extension'] + '.html')
  390. if os.path.exists(html_man):
  391. fd = open(html_man)
  392. html_str = '\n'.join(fd.readlines())
  393. fd.close()
  394. for rep in ('grassdocs.css', 'grass_logo.png'):
  395. patt = re.compile(rep, re.IGNORECASE)
  396. html_str = patt.sub(os.path.join(gisbase, 'docs', 'html', rep),
  397. html_str)
  398. patt = re.compile(r'(<a href=")(d|db|g|i|m|p|ps|r|r3|s|v|wxGUI)(\.)(.+)(.html">)', re.IGNORECASE)
  399. while True:
  400. m = patt.search(html_str)
  401. if not m:
  402. break
  403. html_str = patt.sub(m.group(1) + os.path.join(gisbase, 'docs', 'html',
  404. m.group(2) + m.group(3) + m.group(4)) + m.group(5),
  405. html_str, count = 1)
  406. fd = open(html_man, "w")
  407. fd.write(html_str)
  408. fd.close()
  409. if not os.environ.has_key('GRASS_ADDON_PATH') or \
  410. not os.environ['GRASS_ADDON_PATH']:
  411. grass.warning(_('This add-on module will not function until you set the '
  412. 'GRASS_ADDON_PATH environment variable (see "g.manual variables")'))
  413. def remove_extension():
  414. # try to download XML metadata file first
  415. url = "http://grass.osgeo.org/addons/grass%s.xml" % grass.version()['version'].split('.')[0]
  416. name = options['extension']
  417. try:
  418. f = urlopen(url)
  419. tree = etree.fromstring(f.read())
  420. flist = []
  421. for task in tree.findall('task'):
  422. if name == task.get('name', default = '') and \
  423. task.find('binary') is not None:
  424. for f in task.find('binary').findall('file'):
  425. fname = f.text
  426. if fname:
  427. fpath = fname.split('/')
  428. if sys.platform == 'win32':
  429. if fpath[0] == 'bin':
  430. fpath[-1] += '.exe'
  431. if fpath[0] == 'scripts':
  432. fpath[-1] += '.py'
  433. flist.append(fpath)
  434. if flist:
  435. removed = False
  436. err = list()
  437. for f in flist:
  438. fpath = os.path.join(options['prefix'], os.path.sep.join(f))
  439. try:
  440. os.remove(fpath)
  441. removed = True
  442. except OSError:
  443. err.append((_("Unable to remove file '%s'") % fpath))
  444. if not removed:
  445. grass.fatal(_("Extension <%s> not found") % options['extension'])
  446. if err:
  447. for e in err:
  448. grass.error(e)
  449. else:
  450. remove_extension_std()
  451. except HTTPError:
  452. remove_extension_std()
  453. grass.message(_("Extension <%s> successfully uninstalled.") % options['extension'])
  454. def remove_extension_std():
  455. # is module available?
  456. if not os.path.exists(os.path.join(options['prefix'], 'bin', options['extension'])):
  457. grass.fatal(_("Extension <%s> not found") % options['extension'])
  458. for file in [os.path.join(options['prefix'], 'bin', options['extension']),
  459. os.path.join(options['prefix'], 'scripts', options['extension']),
  460. os.path.join(options['prefix'], 'docs', 'html', options['extension'] + '.html')]:
  461. if os.path.isfile(file):
  462. os.remove(file)
  463. def create_dir(path):
  464. if os.path.isdir(path):
  465. return
  466. try:
  467. os.makedirs(path)
  468. except OSError, e:
  469. grass.fatal(_("Unable to create '%s': %s") % (path, e))
  470. grass.debug("'%s' created" % path)
  471. def check_style_files(fil):
  472. #check the links to grassdocs.css/grass_logo.png to a correct manual page of addons
  473. dist_file = os.path.join(os.getenv('GISBASE'),'docs','html',fil)
  474. addons_file = os.path.join(options['prefix'],'docs','html',fil)
  475. #check if file already exists in the grass addons docs html path
  476. if os.path.isfile(addons_file):
  477. return
  478. #otherwise copy the file from $GISBASE/docs/html, it doesn't use link
  479. #because os.symlink it work only in Linux
  480. else:
  481. try:
  482. shutil.copyfile(dist_file,addons_file)
  483. except OSError, e:
  484. grass.fatal(_("Unable to create '%s': %s") % (addons_file, e))
  485. def check_dirs():
  486. create_dir(os.path.join(options['prefix'], 'bin'))
  487. create_dir(os.path.join(options['prefix'], 'docs', 'html'))
  488. check_style_files('grass_logo.png')
  489. check_style_files('grassdocs.css')
  490. create_dir(os.path.join(options['prefix'], 'man', 'man1'))
  491. create_dir(os.path.join(options['prefix'], 'scripts'))
  492. def main():
  493. # check dependecies
  494. if sys.platform != "win32":
  495. check()
  496. # list available modules
  497. if flags['l'] or flags['c'] or flags['g']:
  498. list_available_modules()
  499. return 0
  500. else:
  501. if not options['extension']:
  502. grass.fatal(_('You need to define an extension name or use -l'))
  503. # define path
  504. if flags['s']:
  505. options['prefix'] = os.environ['GISBASE']
  506. if options['prefix'] == '$GRASS_ADDON_PATH':
  507. if not os.environ.has_key('GRASS_ADDON_PATH') or \
  508. not os.environ['GRASS_ADDON_PATH']:
  509. major_version = int(grass.version()['version'].split('.', 1)[0])
  510. grass.warning(_("GRASS_ADDON_PATH is not defined, "
  511. "installing to ~/.grass%d/addons/") % major_version)
  512. options['prefix'] = os.path.join(os.environ['HOME'], '.grass%d' % major_version, 'addons')
  513. else:
  514. path_list = os.environ['GRASS_ADDON_PATH'].split(os.pathsep)
  515. if len(path_list) < 1:
  516. grass.fatal(_("Invalid GRASS_ADDON_PATH value - '%s'") % os.environ['GRASS_ADDON_PATH'])
  517. if len(path_list) > 1:
  518. grass.warning(_("GRASS_ADDON_PATH has more items, using first defined - '%s'") % path_list[0])
  519. options['prefix'] = path_list[0]
  520. # check dirs
  521. check_dirs()
  522. if flags['d']:
  523. if options['operation'] != 'add':
  524. grass.warning(_("Flag 'd' is relevant only to 'operation=add'. Ignoring this flag."))
  525. else:
  526. global remove_tmpdir
  527. remove_tmpdir = False
  528. if options['operation'] == 'add':
  529. if sys.platform == "win32":
  530. install_extension_win()
  531. else:
  532. install_extension()
  533. else: # remove
  534. remove_extension()
  535. return 0
  536. if __name__ == "__main__":
  537. options, flags = grass.parser()
  538. global tmpdir
  539. tmpdir = grass.tempdir()
  540. atexit.register(cleanup)
  541. sys.exit(main())