Questions about OptionParser

Hello, actually I’m programmin a package manager for my Linux Distribution with crystal.

I have some questions about OptionParser. Are there anyway to catch option but without any “–” or “-” ? This is very annoying because a lot of command line interface don’t use that. For example the command “apt install” don’t use “apt --install”.

One other question is, I seen you have an option parser.banner. Very good idea honestly ! But my question is: how I can specify with “OptionParser.parse do |parser|” when the user input nothing ? I didn’t see any method for that.

Check the example about Subcommands here

Adding an example specific to your usecase(apt.cr)

require "option_parser"

install = false
install_yes = false
pos_args = [] of String

parser = OptionParser.new do |parser|
  parser.banner = "Usage: apt [subcommand] [arguments]"
  parser.on("install", "Install packages") do
    install = true
    parser.banner = "Usage: apt install [arguments]"
    parser.on("-y", "--yes", "No Prompt") { install_auto = true }
  end

  parser.unknown_args do |args|
    pos_args = args
  end

  parser.invalid_option do |flag|
    STDERR.puts "Invalid Option: #{flag}"
    exit 1
  end

  parser.missing_option do |flag|
    STDERR.puts "Missing Option: #{flag}"
    exit 1
  end
end

parser.parse

if install
  if pos_args.size == 0
    STDERR.puts "No packages specified for install"
    exit 1
  end

  puts "Installing #{pos_args.join(", ")}"
else
  puts parser
  exit 1
end
crystal build apt.cr
./apt install abcd efgh
2 Likes

Thanks you very much for you reply ! One other question. I had a problem when I tried to use the parser and when I use colourised string ( with colorize).

How can I colour the output without problem ? I mean after the parser do his job, how for example can I colour the banner ?

There are also some shards that make building CLIs a bit easier if you need more robust functionality: GitHub - veelenga/awesome-crystal: A collection of awesome Crystal libraries, tools, frameworks and software.

if you’re feeling adventurous, Athena’s Console component is also usable atm, but technically isn’t released so would need to pin via commit hash. I’d be happy to help with setup/usage if you go that route.