问题描述
在AdaCore Gem #138 : Master the Commandline之后,我试图创建一个仅接受两个选项的命令行程序。
我将一个字符串传递给getopt,该字符串指出哪些选项有效:
Getopt ("-project= -help")
这意味着可以给出“ --project foo”,也可以给出“ --help”而不带参数。我要非常严格-项目需要一个参数,并且帮助不应带有参数。但是,只要没有以减号开头的参数,上面的内容似乎就会愉快地接受(并忽略)命令行中给出的其他参数:
$ ./getopt_invalid_option.exe --project foo these options are all invalid
Project := foo
$ ./getopt_invalid_option.exe things
Project :=
$ ./getopt_invalid_option.exe --switch
raised GNAT.COMMAND_LINE.INVALID_SWITCH : Unrecognized option '--switch'
$ ./getopt_invalid_option.exe -sss
raised GNAT.COMMAND_LINE.INVALID_SWITCH : Unrecognized option '-s'
如何禁止上面的前两个示例?
由于我有一个小节,在这之后应该允许所有 的情况使我的情况有些复杂。通过阅读GNAT.Command_Line
的规范,我认为可以通过转到相应的章节后调用Getopt("*")
来实现,该章节可以正常工作,但是无论有没有章节,我都无法捕获无效的开关(除非它们以“-”开头)。
在下面的代码中,我对与本节相关的部分进行了注释;但关键是,还需要与该部分配合使用完整的解决方案。
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Command_Line; use GNAT.Command_Line;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Main is
Project : Unbounded_String;
begin
-- Initialize_Option_Scan (Section_Delimiters => "anything");
-- Goto_Section ("");
loop
case Getopt ("-project= -help") is
when '-' =>
if Full_Switch = "-project" then
Project := To_Unbounded_String (Parameter);
elsif Full_Switch = "-help" then
Put_Line ("Usage: etc... ");
return;
end if;
when ASCII.Nul =>
exit;
when others =>
Put_Line ("Error: unrecognized switch " & Full_Switch);
return;
end case;
end loop;
-- Goto_Section ("anything");
-- loop
-- exit when Getopt ("*") = ASCII.Nul;
-- Put_Line ("Accepted: " & Full_Switch);
-- end loop;
Put_Line ("Project := " & To_String (Project));
end Main;
我尝试将第一个Getopt更改为:
case Getopt ("-project= -help *") is
这根本不会改变行为!还尝试过:
case Getopt ("*") is
奇怪的是,哪一个都不允许。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)