foo: unrecognized option `--bar' bar: file: No such file or directoryHere is suggested a simple gnuerr command to print error messages, similar to the GNU C Library error function. Of course, it's only useful in applications which aren't interactive (or which support non-interactive mode at least.) That is, in CLI applications.
- Variable
- program-short-name
file tail $::argv0It's put before the error message itself by the following procedures.
- Procedure
- gnuerr ?-exit returnCode? formatString ?arg arg ...?
- parse errorCode (if requested) and print POSIX error message after the message printed;
- something like error_at_line could be useful as well.
### gnuerr.tcl -*- Tcl -*-
## The following code is in public domain.
### Code:
namespace eval ::gnuerr {
variable program-short-name \
[ expr { [ info exists ::argv0 ]
? [ file tail $::argv0 ]
: "" } ]
namespace export gnuerr
}
proc ::gnuerr::prefix-lines { prefix text } {
set result ""
## .
append result \
$prefix [ string map [ list "\n" "\n${prefix}" ] $text ]
}
proc ::gnuerr::msg { formatString args } {
variable program-short-name
set s [ uplevel \#0 [ list ::format $formatString ] $args ]
puts stderr [ prefix-lines "${program-short-name}: " $s ]
}
proc ::gnuerr::gnuerr { args } {
if { [ llength $args ] < 1 } {
error [ format "wrong # args: should be \"gnuerr %s\"" \
"?-exit returnCode? formatString ?arg arg ...?" ]
} elseif { ! [ string equal "-exit" [ lindex $args 0 ] ] } {
set exit 0
} elseif { [ llength $args ] < 2 } {
error "expected argument after \"-exit\""
} elseif { [ set exit [ lindex $args 1 ]
catch { incr exit 0 } ] } {
error "expected integer but got \"$exit\""
} else {
set args [ lrange $args 2 end ]
}
eval msg $args
## .
if { $exit } {
exit $exit
}
}
package provide gnuerr 0.1
### gnuerr.tcl ends hereCategory Package

