Search code examples
filenamessmalltalkgnu-smalltalk

How do I get the current module/script/file name in GNU Smalltalk?


GNU Smalltalk omits the script name in argv.

#!/usr/bin/env gst -f

| argv program |

argv := Smalltalk arguments.

(argv size) > 0 ifTrue: [
    program := argv at: 1.

    Transcript show: 'Program: ', program; cr.
] ifFalse: [
    Transcript show: 'argv = {}'; cr.
]

$ ./scriptname.st
argv = {}

I see two ways to get the script name:

  • Track down some Smalltalk method which returns the script name akin to Perl's variable $0.
  • Track down syntax for a multiline shebang and force GST to supply the scriptname as the first member of argv. Here's an example in Common Lisp.

Solution

  • It seems the best that can be done is use shebangs to force the script name to ARGV, then check whether Smalltalk getArgv: 1 ends with a hardcoded string.

    Posted here and on Rosetta Code.

    "exec" "gst" "-f" "$0" "$0" "$@"
    "exit"
    
    Object subclass: ScriptedMain [
        ScriptedMain class >> meaningOfLife [ ^42 ]
    ]
    
    | main |
    
    main := [
        Transcript show: 'Main: The meaning of life is ', ((ScriptedMain meaningOfLife) printString); cr.
    ].
    
    (((Smalltalk getArgc) > 0) and: [ ((Smalltalk getArgv: 1) endsWith: 'scriptedmain.st') ]) ifTrue: [
        main value.
    ]