dnaeon / clingon

Command-line options parser system for Common Lisp
Other
122 stars 7 forks source link

[Question] Having a subcommand that doesn't take any arguments or options #1

Closed alecStewart1 closed 2 years ago

alecStewart1 commented 2 years ago

Hello there!

Firstly, I'd like say this package is great.

Secondly, I'm curious as to how I could specify a subcommand that doesn't take any arguments. So in the intro example, there's clingon-intro echo foo bar baz, but I'm wanting to do my-cmd subcmd; where subcmd does something by itself.

I imagine it would be something like in the demo example with print-doc:

:handler (lambda (cmd) 
                () ; but what do we do with `cmd`?
dnaeon commented 2 years ago

Hey @alecStewart1 ,

In case your sub-command doesn't take any arguments, you simply ignore the cmd parameter of the handler itself, since you don't need anything from it's environment. Here's a full example.

(in-package :cl-user)
(defpackage clingon/issue-1
  (:use :cl)
  (:import-from :clingon)
  (:export main))
(in-package :clingon/issue-1)

(defun bar/command ()
  "Returns the `bar' command"
  (clingon:make-command
   :name "bar"
   :description "the bar command"
   :handler (lambda (cmd)
          (declare (ignore cmd))
          (format t "Running bar command ..."))))

(defun foo/command ()
  "Returns the `foo' command"
  (clingon:make-command
   :name "foo"
   :description "the foo command"
   :sub-commands (list (bar/command))
   :handler (lambda (cmd)
          (declare (ignore cmd))
          (format t "Running foo command ..."))))

(defun main ()
  (let ((app (foo/command)))
    (clingon:run app)))

You can find a similar example in the clingon-demo logging commands.

If your handlers are large enough, you could define them as separate functions, but for small enough handlers having them defined as lambdas within the command itself is fine as well.

Hope this helps!

alecStewart1 commented 2 years ago

Awesome! Thank you!