My Technical Notes

Friday, 2 June 2017

Adding an `.rb` shell wrapper for an executable

(CLI means command line interface in this article.)

This article continues on from a similar one, Adding a `.cmd` shell wrapper for an executable, but uses Ruby instead of CMD.

On Windows, to make an `.exe` visible on the command line, the standard way is to append the `.exe`'s location to the `PATH` environment variable. An alternative method is to create an `.rb` shell wrapper for the `.exe` in a folder that is in `PATH`. On my computer, I created a specific folder, `C:\ShellWrappers`, to store shell wrappers, and added its location to `PATH`.

An example shell wrapper, `git.rb`, is shown below.

exec '"C:/Program Files/Git/bin/git.exe"', *ARGV

`exec` executes a process. The executable path passed to it must have forward slashes instead of backslashes, which is the string escape character in Ruby. `*` is the splat operator and separates an array into its elements and is used here to pass the arguments to `exec`. If the app path contains spaces, put an additional set of double quotes around its path.

You can invoke `git.rb` as simply `git`:

git status

The `PATHEXT` environment variable lists extensions of executable files that can be executed without their file extension:


CLI vs GUI Applications

`exec` is used for wrapping a CLI application because it executes the application synchronously in the current terminal. For GUI applications, `exec` is unsuitable because it would block the terminal, and only after closing the application could you continue using the terminal. Instead of `exec`, use `spawn` for GUI applications, which sends you back to the prompt immediately and allows closing the terminal without closing the launched application. Below is an example, `vs2015.rb`, that launches Visual Studio 2015:

spawn '"C:/Program Files (x86)/Microsoft Visual Studio 14.0/Common7/IDE/devenv.exe"', *ARGV


No comments: