Swift has already supported running a single source file directly in the CLI. However, it can be hard to use it together with third party packages. I think the simplicity of Swift syntax make it one of the nice choices for scripting and filling this gap of working with packages might be useful. So, I tried to implement SwiftScript, which is a CLI tools that help using Swift for scripting while allowing third party packages.
There are already some similar work available, one of them is swift-sh. It is a great project, but personally, I prefer managing packages with styles similar to tools like pip3
instead of declaring the packages in the script using comments.
About SwiftScript
The installation guidance and usage instructions can be found in the README in the repository, here I'll just give a brief introduction.
SwiftScript is implemented as an SPM wrapper that will build your script together with all the packages with a SPM project.
The subcommands and their abstracts are listed in the screenshot above.
Run a script
swiftscript /path/to/script <additional_args>
Search for a package
SwiftScript will try to find the package identity in Swift Package Index and print out some useful information
swiftscript search <package_identity>
Install a package
Packages to install can be specified with identity or url
Version of the package to install can be specified using Version Requirement, which is the same as the one used in Package.swift
in SPM project.
--exact \<version\>
--branch \<branch\>
--from \<version\>
(up to next major)--up-to-next-minor-from \<version\>
--to \<version\>
(upper bound version)
swiftscript install <package_identity> <version_requirement>
swiftscript install <package_url> <version_requirement>
Edit a script
Editing a Swift source file can be done in any editor, but auto-completion will not work for packages installed through SwiftScript. For such case, use the edit
subcommand.
swiftscript edit /path/to/script
It will create a temporary SPM project with all the dependencies already configured. By default it will try to find VSCode in the environment (i.e.: the code
command), but the editor used can be configured using swiftscript config set editor
command.
Any editor should be OK as long as:
- It is able to open a folder
- It can be configured to NOT return before the editor window is closed
Known Limitations
- No directly installable binary available yet
- Testing fail to run on ARM Windows
- Cannot build in Release Mode on ARM Windows for some reason
- Does not support Module Alias yet
- Script building might be slow, so it can take sometime before starting to execute the script.
- Maybe more ...
Finally
I'm not sure whether people are interested in using Swift as script since there aren't many relative discussions. Please feel free to discuss whether such tools are really useful.