take -o - as stdout

getopt-long reads a lone `-' as an option, so -o - died there asking
for a value, and --output=- got through only to create a file named
`-'.

Fixes #43.
This commit is contained in:
2026-10-09 17:34:02 +03:00
parent b019da3fb3
commit 7abb125932
2 changed files with 28 additions and 4 deletions

View File

@@ -59,7 +59,8 @@
(value #f)
(single-char #\m))
(output ,(fmt #f "Write output to file. Default file name is a.out." nl
(pad padding) "If -E or -m options are provided, defaults to stdout")
(pad padding) "If -C or -m options are provided, defaults to stdout;" nl
(pad padding) "`-' is stdout too")
(required #f)
(value #t)
(single-char #\o))
@@ -100,6 +101,17 @@
(list)
(cdr tail))))
;;; getopt-long reads a lone `-' as an option, so `-o -' died there as
;;; one missing its value. `--output=-' is the spelling it takes
(define (spell-stdout-output argv)
(let loop ((as argv) (acc (list)))
(cond ((null? as) (reverse acc))
((and (member (car as) '("-o" "--output"))
(pair? (cdr as))
(string=? (cadr as) "-"))
(loop (cddr as) (cons "--output=-" acc)))
(else (loop (cdr as) (cons (car as) acc))))))
(define (get-rest-args args)
(cdr (assoc '@ args)))
@@ -126,7 +138,7 @@
(car rest-args))))
(define (write-to-file-or-stdout output what)
(if (eq? output 'default)
(if (or (eq? output 'default) (equal? output "-"))
(what)
(with-output-to-file output
(fn (what)))))
@@ -196,7 +208,7 @@ status, which is ours to pass on."
(let* ((argv (command-line-arguments))
(raw-args (args-before-separator argv))
(cc-args (args-after-separator argv))
(args (getopt-long raw-args
(args (getopt-long (spell-stdout-output raw-args)
opts-grammar))
(output (get-arg args 'output 'default))
(help (help-arg? args))

View File

@@ -52,4 +52,16 @@
(test "an empty command line is handled"
'()
(args-before-separator '())))
(args-before-separator '()))
;; getopt-long reads a lone `-' as an option and refused `-o -', so
;; it is handed the one spelling it takes a dash in
(test "-o - reaches getopt-long as a value"
'("x.sex" "--output=-" "-C")
(spell-stdout-output '("x.sex" "-o" "-" "-C")))
(test "and so does --output -"
'("--output=-")
(spell-stdout-output '("--output" "-")))
(test "any other output is left alone"
'("-o" "out" "-")
(spell-stdout-output '("-o" "out" "-"))))