Browse Source

Switch from getopt to argparse

getopt is a low-level module for command line handling, and requires
manual boilerplate to work. Instead, migrate to argparse, which is more
high-level and provides a number of facilities:
- a single place to define each option
- streamlined help texts
- enforcing of mandatory options
- enforcing a value as certain type, or in a list of allowed values
pull/21/head
Pino Toscano 5 years ago
parent
commit
4a0483b46f
  1. 118
      src/xdgmenumaker

118
src/xdgmenumaker

@ -2,9 +2,9 @@
# coding: utf-8 # coding: utf-8
# vim:et:sta:sts=4:sw=4:ts=8:tw=79: # vim:et:sta:sts=4:sw=4:ts=8:tw=79:
import argparse
import os import os
import sys import sys
import getopt
import fnmatch import fnmatch
import xdg.DesktopEntry as dentry import xdg.DesktopEntry as dentry
import xdg.Exceptions as exc import xdg.Exceptions as exc
@ -153,7 +153,7 @@ if not terminal_app:
terminal_app = 'xterm' terminal_app = 'xterm'
def main(argv): def main():
global desktop global desktop
global seticon global seticon
global iconsize global iconsize
@ -162,37 +162,48 @@ def main(argv):
global pekwmdynamic global pekwmdynamic
global twmtitles global twmtitles
global max_icon_size global max_icon_size
try: parser = argparse.ArgumentParser(usage='%(prog)s -f FORMAT [OPTIONS]',
opts, args = getopt.getopt(argv, "hins:f:", ["help", "icons", formatter_class=argparse.RawDescriptionHelpFormatter,
"no-submenu", epilog='''\
"pekwm-dynamic",
"twm-titles", examples:
"max-icon-size", xdgmenumaker -f windowmaker
"no-svg", xdgmenumaker -i -f fluxbox
"size=", ''')
"format="]) parser.add_argument('-f', '--format', metavar='FORMAT', required=True,
except getopt.GetoptError: choices=['amiwm', 'blackbox', 'compizboxmenu',
usage() 'fluxbox', 'fvwm', 'icewm', 'jwm', 'pekwm',
sys.exit(2) 'twm', 'windowmaker'],
for opt, arg in opts: help='the output format to use. Valid options are '
if opt in ("-h", "--help"): '%(choices)s')
usage() parser.add_argument('-i', '--icons', action='store_true',
sys.exit(0) help='enable support for icons in the menus. Does '
elif opt in ("-i", "--icons"): 'not work with windowmaker or amiwm')
seticon = True parser.add_argument('--no-svg', action='store_false', dest='svg',
elif opt in ("-s", "--size"): help='Do not use SVG icons even for WMs that support '
try: 'it')
iconsize = int(arg) parser.add_argument('-s', '--size', type=int, default=16, dest='iconsize',
except ValueError: help='preferred icon size in pixels (default: '
usage() '%(default)s)')
sys.exit('ERROR: size must be a number') parser.add_argument('-n', '--no-submenu', action='store_false',
elif opt in ("-n", "--no-submenu"): dest='submenu',
submenu = False help='do not create a submenu. Does not work with '
elif opt in ("--pekwm-dynamic",): 'windowmaker')
pekwmdynamic = True parser.add_argument('--max-icon-size', action='store_true',
elif opt in ("--twm-titles",): help='restrict the icon sizes to the specified size')
twmtitles = True parser.add_argument('--pekwm-dynamic', action='store_true',
elif opt in ("--max-icon-size",): help='generate dynamic menus for pekwm')
parser.add_argument('--twm-titles', action='store_true',
help='show menu titles in twm menus')
args = parser.parse_args()
desktop = args.format
seticon = args.icons
iconsize = args.iconsize
nosvg = not args.svg
submenu = args.submenu
pekwmdynamic = args.pekwm_dynamic
twmtitles = args.twm_titles
if args.max_icon_size is True:
try: try:
# Pillow is optional and loaded only if we want to restrict the # Pillow is optional and loaded only if we want to restrict the
# icon sizes (useful for Fvwm). Yeah, I know it's not a good # icon sizes (useful for Fvwm). Yeah, I know it's not a good
@ -204,16 +215,8 @@ def main(argv):
from PIL import Image from PIL import Image
max_icon_size = True max_icon_size = True
except ImportError: except ImportError:
usage() parser.error('--max-icon-size requires Pillow')
sys.exit('ERROR: --max-icon-size requires Pillow') if desktop == "blackbox":
elif opt == "--no-svg":
nosvg = True
elif opt in ("-f", "--format"):
desktop = arg
if not desktop:
usage()
sys.exit('ERROR: You must specify the output format with -f')
elif desktop == "blackbox":
blackbox() blackbox()
elif desktop == "fluxbox": elif desktop == "fluxbox":
fluxbox() fluxbox()
@ -236,32 +239,7 @@ def main(argv):
seticon = False seticon = False
amiwm() amiwm()
else: else:
usage() parser.error('INTERNAL ERROR: unhandled format %s' % desktop)
sys.exit(2)
def usage():
print('USAGE:', os.path.basename(sys.argv[0]), '[OPTIONS]')
print()
print('OPTIONS:')
print(' -f, --format the output format to use.')
print(' Valid options are amiwm, blackbox, compizboxmenu,')
print(' fluxbox, fvwm, twm, icewm, jwm, windowmaker and pekwm')
print(' -i, --icons enable support for icons in the')
print(' menus. Does not work with windowmaker or amiwm')
print(' --no-svg Do not use SVG icons even for WMs that support it')
print(' -s, --size preferred icon size in pixels (default: 16)')
print(' -n, --no-submenu do not create a submenu. Does not work with')
print(' windowmaker')
print(' --max-icon-size restrict the icon sizes to the specified size')
print(' --pekwm-dynamic generate dynamic menus for pekwm')
print(' --twm-titles show menu titles in twm menus')
print(' -h, --help show this help message')
print(' You have to specify the output format using the -f switch.')
print()
print('EXAMPLES:')
print(' xdgmenumaker -f windowmaker')
print(' xdgmenumaker -i -f fluxbox')
def icon_strip(icon): def icon_strip(icon):
@ -887,4 +865,4 @@ def amiwm():
if __name__ == "__main__": if __name__ == "__main__":
main(sys.argv[1:]) main()

Loading…
Cancel
Save