;;; Chickadee Game Toolkit ;;; Copyright © 2021 David Thompson ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (define-module (chickadee cli) #:use-module (chickadee) #:use-module (chickadee config) #:use-module (ice-9 format) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:use-module (srfi srfi-37) #:export (launch-chickadee display-version-and-exit leave simple-args-fold operands)) (define (display-version-and-exit) (format #t "Chickadee ~a Copyright (C) 2021 David Thompson and Chickadee contributors License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.~%" %chickadee-version) (exit 0)) (define (display-help-and-exit) (format #t "Usage: chickadee SUBCOMMAND ARGS ...~% Run SUBCOMMAND with ARGS Valid subcommands: * bundle * play~%") (exit 1)) (define (leave format-string . args) "Display error message and exist." (apply format (current-error-port) format-string args) (newline) (exit 1)) (define (simple-args-fold args options defaults) (args-fold args options (lambda (opt name arg result) (leave "unrecognized option: ~A" name)) (lambda (arg result) (alist-cons 'operand arg result)) defaults)) (define (operands opts) (filter-map (match-lambda (('operand . arg) arg) (_ #f)) opts)) (define (run-chickadee-command command . args) (define (invalid-command) (format (current-error-port) "invalid subcommand: ~a~%~%" command) (display-help-and-exit)) (let* ((module (catch 'misc-error (lambda () (resolve-interface `(chickadee cli ,command))) (lambda args (invalid-command)))) (proc-name (symbol-append 'chickadee- command)) (command-proc (false-if-exception (module-ref module proc-name)))) (if (procedure? command-proc) (apply command-proc args) (invalid-command)))) (define (subcommand? arg) (not (string-prefix? "-" arg))) (define (launch-chickadee . args) (match args ((program (or "--verison" "-v")) (display-version-and-exit)) ((or (program) (program (or "--help" "-h"))) (display-help-and-exit)) ((program (? subcommand? subcommand) . args*) (apply run-chickadee-command (string->symbol subcommand) args*)) ((program invalid-subcommand . args*) (leave "invalid subcommand: ~A" invalid-subcommand))))