The*_*off 6 haskell optparse-applicative
我正在构建一个脑残编译器。可执行文件接受两个命令$ brainfuck compile ...
和$ brainfuck run
。我希望可执行文件在按 Tab 时自动完成。例如,写入$ brainfuck com
然后按 Tab 应该生成$ brainfuck compile
.
data Command = Compile CompileArgs | Run RunArgs
deriving (Show)
main :: IO ()
main = execute =<< execParser opts
where
opts = info (helper <*> argsParser) fullDesc
execute :: Command -> IO ()
execute (Compile args) = compile args
execute (Run args) = run args
argsParser :: Parser Command
argsParser = subparser (compileCommand <> runCommand)
where
compileCommand = command "compile" $ info compileOptions $ progDesc "Compile brainfuck to an executable"
runCommand = command "run" $ info runOptions $ progDesc "Execute brainfuck code"
Run Code Online (Sandbox Code Playgroud)
optparse 的 github 页面上有一个部分,但我不太明白。
该功能看起来与我已经使用的completeWith :: Options.Applicative.Builder.Internal.HasCompleter f => [String] -> Mod f a
非常相似。command :: String -> ParserInfo a -> Mod CommandFields a
所以我想我可以使用它并将它们与 结合起来,<>
但事实证明这CommandFields
不是 的实例HasCompleter
。
您应该如何让自动完成功能发挥作用?
经过 RTFM 的研究,我发现了如何配置自动完成功能。
completeWith
在为各个参数构造解析器时应用。就像这样:
data CompileArgs = CompileArgs
{
debug :: Bool,
optimizations :: OptimizationLevel,
file :: String
}
deriving (Show, Read)
compileArgsParser :: Parser CompileArgs
compileArgsParser = CompileArgs
<$> switch (
long "debug" <>
help "Outputs object and assembly files")
<*> option auto (
long "optimization-level" <>
value All <>
metavar "LEVEL" <>
help "all | none, default: all" <>
completeWith ["all", "none"])
<*> argument str (
metavar "FILE" <>
help "brainfuck source code" <>
action "file")
<**> helper
Run Code Online (Sandbox Code Playgroud)
action
是关于 bash 如何自动完成的指令。"file"
意味着自动完成任何文件或目录。请参阅此页面了解更多信息。
为了启动这些自动完成功能,您需要生成一个脚本并确保该脚本是来源的。/etc/bash_completion.d/
按照惯例,使用 bash 时它被放在下面。
brainfuck --bash-completion-script `which brainfuck` | sudo tee /etc/bash_completion.d/brainfuck
Run Code Online (Sandbox Code Playgroud)
在我的例子中,我的程序被称为brainfuck
.
归档时间: |
|
查看次数: |
348 次 |
最近记录: |