+def HaskellOptToOptParse(opts, kind):
+ """Converts a Haskell options to Python cli_options.
+
+ @type opts: string
+ @param opts: comma-separated string with short and long options
+ @type kind: string
+ @param kind: type generated by Common.hs/complToText; needs to be
+ kept in sync
+
+ """
+ # pylint: disable=W0142
+ # since we pass *opts in a number of places
+ opts = opts.split(",")
+ if kind == "none":
+ return cli.cli_option(*opts, action="store_true")
+ elif kind in ["file", "string", "host", "dir", "inetaddr"]:
+ return cli.cli_option(*opts, type="string")
+ elif kind == "integer":
+ return cli.cli_option(*opts, type="int")
+ elif kind == "float":
+ return cli.cli_option(*opts, type="float")
+ elif kind == "onegroup":
+ return cli.cli_option(*opts, type="string",
+ completion_suggest=cli.OPT_COMPL_ONE_NODEGROUP)
+ elif kind == "onenode":
+ return cli.cli_option(*opts, type="string",
+ completion_suggest=cli.OPT_COMPL_ONE_NODE)
+ elif kind == "manyinstances":
+ # FIXME: no support for many instances
+ return cli.cli_option(*opts, type="string")
+ elif kind.startswith("choices="):
+ choices = kind[len("choices="):].split(",")
+ return cli.cli_option(*opts, type="choice", choices=choices)
+ else:
+ # FIXME: there are many other currently unused completion types,
+ # should be added on an as-needed basis
+ raise Exception("Unhandled option kind '%s'" % kind)
+
+
+#: serialised kind to arg type
+_ARG_MAP = {
+ "choices": cli.ArgChoice,
+ "command": cli.ArgCommand,
+ "file": cli.ArgFile,
+ "host": cli.ArgHost,
+ "jobid": cli.ArgJobId,
+ "onegroup": cli.ArgGroup,
+ "oneinstance": cli.ArgInstance,
+ "onenode": cli.ArgNode,
+ "oneos": cli.ArgOs,
+ "string": cli.ArgUnknown,
+ "suggests": cli.ArgSuggest,
+ }
+
+
+def HaskellArgToCliArg(kind, min_cnt, max_cnt):
+ """Converts a Haskell options to Python _Argument.
+
+ @type kind: string
+ @param kind: type generated by Common.hs/argComplToText; needs to be
+ kept in sync
+
+ """
+ min_cnt = int(min_cnt)
+ if max_cnt == "none":
+ max_cnt = None
+ else:
+ max_cnt = int(max_cnt)
+ # pylint: disable=W0142
+ # since we pass **kwargs
+ kwargs = {"min": min_cnt, "max": max_cnt}
+
+ if kind.startswith("choices=") or kind.startswith("suggest="):
+ (kind, choices) = kind.split("=", 1)
+ kwargs["choices"] = choices.split(",")
+
+ if kind not in _ARG_MAP:
+ raise Exception("Unhandled argument kind '%s'" % kind)
+ else:
+ return _ARG_MAP[kind](**kwargs)
+
+
+def ParseHaskellOptsArgs(script, output):
+ """Computes list of options/arguments from help-completion output.
+
+ """
+ cli_opts = []
+ cli_args = []
+ for line in output.splitlines():
+ v = line.split(None)
+ exc = lambda msg: Exception("Invalid %s output from %s: %s" %
+ (msg, script, v))
+ if len(v) < 2:
+ raise exc("help completion")
+ if v[0].startswith("-"):
+ if len(v) != 2:
+ raise exc("option format")
+ (opts, kind) = v
+ cli_opts.append(HaskellOptToOptParse(opts, kind))
+ else:
+ if len(v) != 3:
+ raise exc("argument format")
+ (kind, min_cnt, max_cnt) = v
+ cli_args.append(HaskellArgToCliArg(kind, min_cnt, max_cnt))
+ return (cli_opts, cli_args)
+
+
+def WriteHaskellCompletion(sw, script, htools=True, debug=True):
+ """Generates completion information for a Haskell program.
+
+ This converts completion info from a Haskell program into 'fake'
+ cli_opts and then builds completion for them.
+
+ """
+ if htools:
+ cmd = "./src/htools"
+ env = {"HTOOLS": script}
+ script_name = script
+ func_name = "htools_%s" % script
+ else:
+ cmd = "./" + script
+ env = {}
+ script_name = os.path.basename(script)
+ func_name = script_name
+ func_name = GetFunctionName(func_name)
+ output = utils.RunCmd([cmd, "--help-completion"], env=env, cwd=".").output
+ (opts, args) = ParseHaskellOptsArgs(script_name, output)
+ WriteCompletion(sw, script_name, func_name, debug, opts=opts, args=args)
+
+
+def WriteHaskellCmdCompletion(sw, script, debug=True):
+ """Generates completion information for a Haskell multi-command program.
+
+ This gathers the list of commands from a Haskell program and
+ computes the list of commands available, then builds the sub-command
+ list of options/arguments for each command, using that for building
+ a unified help output.
+
+ """
+ cmd = "./" + script
+ script_name = os.path.basename(script)
+ func_name = script_name
+ func_name = GetFunctionName(func_name)
+ output = utils.RunCmd([cmd, "--help-completion"], cwd=".").output
+ commands = {}
+ lines = output.splitlines()
+ if len(lines) != 1:
+ raise Exception("Invalid lines in multi-command mode: %s" % str(lines))
+ v = lines[0].split(None)
+ exc = lambda msg: Exception("Invalid %s output from %s: %s" %
+ (msg, script, v))
+ if len(v) != 3:
+ raise exc("help completion in multi-command mode")
+ if not v[0].startswith("choices="):
+ raise exc("invalid format in multi-command mode '%s'" % v[0])
+ for subcmd in v[0][len("choices="):].split(","):
+ output = utils.RunCmd([cmd, subcmd, "--help-completion"], cwd=".").output
+ (opts, args) = ParseHaskellOptsArgs(script, output)
+ commands[subcmd] = (None, args, opts, None, None)
+ WriteCompletion(sw, script_name, func_name, debug, commands=commands)
+
+