g.extension.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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: no
  31. #%end
  32. #%option
  33. #% key: operation
  34. #% type: string
  35. #% description: Operation to be performed
  36. #% required: no
  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: https://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: yes
  55. #%end
  56. #%flag
  57. #% key: l
  58. #% description: List available modules in the GRASS Addons SVN repository
  59. #% guisection: Print
  60. #%end
  61. #%flag
  62. #% key: f
  63. #% description: List available modules in the GRASS Addons SVN repository including modules description
  64. #% guisection: Print
  65. #%end
  66. #%flag
  67. #% key: g
  68. #% description: List available modules in the GRASS Addons SVN repository (shell script style)
  69. #% guisection: Print
  70. #%end
  71. #%flag
  72. #% key: s
  73. #% description: Install system-wide (may need system administrator rights)
  74. #%end
  75. #%flag
  76. #% key: d
  77. #% description: Download source code and exit
  78. #%end
  79. #%flag
  80. #% key: i
  81. #% description: Don't install new extension, just compile it
  82. #%end
  83. import os
  84. import sys
  85. import re
  86. import atexit
  87. import urllib
  88. from grass.script import core as grass
  89. # temp dir
  90. remove_tmpdir = True
  91. tmpdir = grass.tempdir()
  92. def check():
  93. for prog in ('svn', 'make', 'install', 'gcc'):
  94. if not grass.find_program(prog, ['--help']):
  95. grass.fatal(_("%s required. Please install '%s' first.") % (prog, prog))
  96. def expand_module_class_name(c):
  97. name = { 'd' : 'display',
  98. 'db' : 'database',
  99. 'g' : 'general',
  100. 'i' : 'imagery',
  101. 'm' : 'misc',
  102. 'ps' : 'postscript',
  103. 'p' : 'paint',
  104. 'r' : 'raster',
  105. 'r3' : 'raster3D',
  106. 's' : 'sites',
  107. 'v' : 'vector',
  108. 'gui' : 'gui/wxpython' }
  109. if name.has_key(c):
  110. return name[c]
  111. return c
  112. def list_available_modules():
  113. mlist = list()
  114. grass.message(_('Fetching list of modules from GRASS-Addons SVN (be patient)...'))
  115. pattern = re.compile(r'(<li><a href=".+">)(.+)(</a></li>)', re.IGNORECASE)
  116. i = 0
  117. prefix = ['d', 'db', 'g', 'i', 'm', 'ps',
  118. 'p', 'r', 'r3', 's', 'v']
  119. nprefix = len(prefix)
  120. for d in prefix:
  121. if flags['g']:
  122. grass.percent(i, nprefix, 1)
  123. i += 1
  124. modclass = expand_module_class_name(d)
  125. grass.verbose(_("Checking for '%s' modules...") % modclass)
  126. url = '%s/%s' % (options['svnurl'], modclass)
  127. grass.debug("url = %s" % url, debug = 2)
  128. f = urllib.urlopen(url)
  129. if not f:
  130. grass.warning(_("Unable to fetch '%s'") % url)
  131. continue
  132. for line in f.readlines():
  133. # list modules
  134. sline = pattern.search(line)
  135. if not sline:
  136. continue
  137. name = sline.group(2).rstrip('/')
  138. if name.split('.', 1)[0] == d:
  139. print_module_desc(name, url)
  140. mlist.append(name)
  141. mlist += list_wxgui_extensions()
  142. if flags['g']:
  143. grass.percent(1, 1, 1)
  144. return mlist
  145. def list_wxgui_extensions(print_module = True):
  146. mlist = list()
  147. grass.debug('Fetching list of wxGUI extensions from GRASS-Addons SVN (be patient)...')
  148. pattern = re.compile(r'(<li><a href=".+">)(.+)(</a></li>)', re.IGNORECASE)
  149. grass.verbose(_("Checking for '%s' modules...") % 'gui/wxpython')
  150. url = '%s/%s' % (options['svnurl'], 'gui/wxpython')
  151. grass.debug("url = %s" % url, debug = 2)
  152. f = urllib.urlopen(url)
  153. if not f:
  154. grass.warning(_("Unable to fetch '%s'") % url)
  155. return
  156. for line in f.readlines():
  157. # list modules
  158. sline = pattern.search(line)
  159. if not sline:
  160. continue
  161. name = sline.group(2).rstrip('/')
  162. if name not in ('..', 'Makefile'):
  163. if print_module:
  164. print_module_desc(name, url)
  165. mlist.append(name)
  166. return mlist
  167. def print_module_desc(name, url):
  168. if not flags['f'] and not flags['g']:
  169. print name
  170. return
  171. if flags['g']:
  172. print 'name=' + name
  173. # check main.c first
  174. desc = get_module_desc(url + '/' + name + '/' + name)
  175. if not desc:
  176. desc = get_module_desc(url + '/' + name + '/main.c', script = False)
  177. if not desc:
  178. if not flags['g']:
  179. print name + '-'
  180. return
  181. if flags['g']:
  182. print 'description=' + desc.get('description', '')
  183. print 'keywords=' + ','.join(desc.get('keywords', list()))
  184. else:
  185. print name + ' - ' + desc.get('description', '')
  186. def get_module_desc(url, script = True):
  187. grass.debug('url=%s' % url)
  188. f = urllib.urlopen(url)
  189. if script:
  190. ret = get_module_script(f)
  191. else:
  192. ret = get_module_main(f)
  193. return ret
  194. def get_module_main(f):
  195. if not f:
  196. return dict()
  197. ret = { 'keyword' : list() }
  198. pattern = re.compile(r'(module.*->)(.+)(=)(.*)', re.IGNORECASE)
  199. keyword = re.compile(r'(G_add_keyword\()(.+)(\);)', re.IGNORECASE)
  200. key = ''
  201. value = ''
  202. for line in f.readlines():
  203. line = line.strip()
  204. find = pattern.search(line)
  205. if find:
  206. key = find.group(2).strip()
  207. line = find.group(4).strip()
  208. else:
  209. find = keyword.search(line)
  210. if find:
  211. ret['keyword'].append(find.group(2).replace('"', '').replace('_(', '').replace(')', ''))
  212. if key:
  213. value += line
  214. if line[-2:] == ');':
  215. value = value.replace('"', '').replace('_(', '').replace(');', '')
  216. if key == 'keywords':
  217. ret[key] = map(lambda x: x.strip(), value.split(','))
  218. else:
  219. ret[key] = value
  220. key = value = ''
  221. return ret
  222. def get_module_script(f):
  223. ret = dict()
  224. if not f:
  225. return ret
  226. begin = re.compile(r'#%.*module', re.IGNORECASE)
  227. end = re.compile(r'#%.*end', re.IGNORECASE)
  228. mline = None
  229. for line in f.readlines():
  230. if not mline:
  231. mline = begin.search(line)
  232. if mline:
  233. if end.search(line):
  234. break
  235. try:
  236. key, value = line.split(':', 1)
  237. key = key.replace('#%', '').strip()
  238. value = value.strip()
  239. if key == 'keywords':
  240. ret[key] = map(lambda x: x.strip(), value.split(','))
  241. else:
  242. ret[key] = value
  243. except ValueError:
  244. pass
  245. return ret
  246. def cleanup():
  247. global tmpdir, remove_tmpdir
  248. if remove_tmpdir:
  249. grass.try_rmdir(tmpdir)
  250. else:
  251. grass.info(_("Path to the source code: '%s'") % tmpdir)
  252. def install_extension():
  253. gisbase = os.getenv('GISBASE')
  254. if not gisbase:
  255. grass.fatal(_('$GISBASE not defined'))
  256. if grass.find_program(options['extension']):
  257. grass.warning(_("Extension '%s' already installed. Will be updated...") % options['extension'])
  258. gui_list = list_wxgui_extensions(print_module = False)
  259. if options['extension'] not in gui_list:
  260. classchar = options['extension'].split('.', 1)[0]
  261. moduleclass = expand_module_class_name(classchar)
  262. url = options['svnurl'] + '/' + moduleclass + '/' + options['extension']
  263. else:
  264. url = options['svnurl'] + '/gui/wxpython/' + options['extension']
  265. if not flags['s']:
  266. grass.fatal(_("Installation of wxGUI extension requires -%s flag.") % 's')
  267. grass.message(_("Fetching '%s' from GRASS-Addons SVN (be patient)...") % options['extension'])
  268. global tmpdir
  269. os.chdir(tmpdir)
  270. if grass.verbosity() == 0:
  271. outdev = open(os.devnull, 'w')
  272. else:
  273. outdev = sys.stdout
  274. if grass.call(['svn', 'checkout',
  275. url], stdout = outdev) != 0:
  276. grass.fatal(_("GRASS Addons '%s' not found in repository") % options['extension'])
  277. if flags['d']:
  278. return
  279. os.chdir(os.path.join(tmpdir, options['extension']))
  280. grass.message(_("Compiling '%s'...") % options['extension'])
  281. if options['extension'] not in gui_list:
  282. bin_dir = os.path.join(tmpdir, options['extension'], 'bin')
  283. docs_dir = os.path.join(tmpdir, options['extension'], 'docs')
  284. html_dir = os.path.join(docs_dir, 'html')
  285. man_dir = os.path.join(tmpdir, options['extension'], 'man')
  286. man1_dir = os.path.join(man_dir, 'man1')
  287. script_dir = os.path.join(tmpdir, options['extension'], 'scripts')
  288. for d in (bin_dir, docs_dir, html_dir, man_dir, man1_dir, script_dir):
  289. os.mkdir(d)
  290. ret = grass.call(['make',
  291. 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ '),
  292. 'BIN=%s' % bin_dir,
  293. 'HTMLDIR=%s' % html_dir,
  294. 'MANDIR=%s' % man1_dir,
  295. 'SCRIPTDIR=%s' % script_dir],
  296. stdout = outdev)
  297. else:
  298. ret = grass.call(['make',
  299. 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ ')],
  300. stdout = outdev)
  301. if ret != 0:
  302. grass.fatal(_('Compilation failed, sorry. Please check above error messages.'))
  303. if flags['i'] or options['extension'] in gui_list:
  304. return
  305. grass.message(_("Installing '%s'...") % options['extension'])
  306. ret = grass.call(['make',
  307. 'MODULE_TOPDIR=%s' % gisbase,
  308. 'ARCH_DISTDIR=%s' % os.path.join(tmpdir, options['extension']),
  309. 'INST_DIR=%s' % options['prefix'],
  310. 'install'],
  311. stdout = outdev)
  312. if ret != 0:
  313. grass.warning(_('Installation failed, sorry. Please check above error messages.'))
  314. else:
  315. grass.message(_("Installation of '%s' successfully finished.") % options['extension'])
  316. def remove_extension():
  317. # is module available?
  318. if not os.path.exists(os.path.join(options['prefix'], 'bin', options['extension'])):
  319. grass.fatal(_("Module '%s' not found") % options['extension'])
  320. for file in [os.path.join(options['prefix'], 'bin', options['extension']),
  321. os.path.join(options['prefix'], 'scripts', options['extension']),
  322. os.path.join(options['prefix'], 'docs', 'html', options['extension'] + '.html')]:
  323. if os.path.isfile(file):
  324. os.remove(file)
  325. grass.message(_("'%s' successfully uninstalled.") % options['extension'])
  326. def create_dir(path):
  327. if os.path.isdir(path):
  328. return
  329. try:
  330. os.makedirs(path)
  331. except OSError, e:
  332. grass.fatal(_("Unable to create '%s': %s") % (path, e))
  333. grass.debug("'%s' created" % path)
  334. def check_dirs():
  335. create_dir(os.path.join(options['prefix'], 'bin'))
  336. create_dir(os.path.join(options['prefix'], 'docs', 'html'))
  337. create_dir(os.path.join(options['prefix'], 'man', 'man1'))
  338. create_dir(os.path.join(options['prefix'], 'scripts'))
  339. def main():
  340. # check dependecies
  341. check()
  342. # list available modules
  343. if flags['l'] or flags['f'] or flags['g']:
  344. list_available_modules()
  345. return 0
  346. else:
  347. if not options['extension']:
  348. grass.fatal(_('You need to define an extension name or use -l'))
  349. # define path
  350. if flags['s']:
  351. options['prefix'] = os.environ['GISBASE']
  352. if options['prefix'] == '$GRASS_ADDON_PATH':
  353. if not os.environ.has_key('GRASS_ADDON_PATH') or \
  354. not os.environ['GRASS_ADDON_PATH']:
  355. major_version = int(grass.version()['version'].split('.', 1)[0])
  356. grass.warning(_("GRASS_ADDON_PATH is not defined, "
  357. "installing to ~/.grass%d/addons/") % major_version)
  358. options['prefix'] = os.path.join(os.environ['HOME'], '.grass%d' % major_version, 'addons')
  359. else:
  360. path_list = os.environ['GRASS_ADDON_PATH'].split(os.pathsep)
  361. if len(path_list) < 1:
  362. grass.fatal(_("Invalid GRASS_ADDON_PATH value - '%s'") % os.environ['GRASS_ADDON_PATH'])
  363. if len(path_list) > 1:
  364. grass.warning(_("GRASS_ADDON_PATH has more items, using first defined - '%s'") % path_list[0])
  365. options['prefix'] = path_list[0]
  366. # check dirs
  367. check_dirs()
  368. if flags['d']:
  369. if options['operation'] != 'add':
  370. grass.warning(_("Flag 'd' is relevant only to 'operation=add'. Ignoring this flag."))
  371. else:
  372. global remove_tmpdir
  373. remove_tmpdir = False
  374. if options['operation'] == 'add':
  375. install_extension()
  376. else: # remove
  377. remove_extension()
  378. return 0
  379. if __name__ == "__main__":
  380. options, flags = grass.parser()
  381. atexit.register(cleanup)
  382. sys.exit(main())