Catch Functionality
- Dominant language
- Rust
- Stars
- 35.8k
- Forks
- 846
- Avg merge
- 27m
- Merged PRs (30d)
- 3
Description
There is no current way in standard Just to run additional commands if the execution of a recipe fails to allow clean-up. This is available in other languages with keywords like `catch`. This type of feature is useful when you have a multistage process that produces an output like building and running a container or server.
The current best method is to use the `trap` shell command which forces you to make your recipe a shell script.
```
test-in-container:
#!/usr/bin/env sh
trap 'docker rm -f test-container' EXIT
docker run -d --name test-container test-image
docker exec test-container run-tests
```
Another current solution is using an `||`:
```
test-in-container:
docker run -d --name test-container test-image
docker exec test-container run-tests || (docker rm -f test-container && exit 1)
docker rm -f test-container
```
However, this only works on a single line and gets repetitive for longer recipes.
Below I've thought of some possible ways this could be implemented in Just while maintaining backwards compatibility:
Using an attribute:
```
[catch: docker rm -f test-container]
test-in-container:
docker run -d --name test-container test-image
docker exec test-container run-tests
```
Where the command after `catch:` would run if the recipe errored.
Using a keyword:
```
test-in-container:
docker run -d --name test-container test-image
docker exec test-container run-tests
::catch::
docker rm -f test-container
```
Where all the commands after `::catch::` would run if the recipe errored.
Extend the dependency system:
```
test-in-container-cleanup:
docker rm -f test-container
test-in-container: !& test-in-container-cleanup
docker run -d --name test-container test-image
docker exec test-container run-tests
```
Where recipes after the`!&` would run if the recipe errored.
The attribute method would likely be the most straightforward to implement, while extending the dependency system with `!&` does seem more elegant. However, I can think of some potential complications already, which might be tricky to solve.
This could also be extended with a `finally` type feature that would run at the end of a recipe error or not.
While I acknowledge this functionality is already available through other methods, and adding it might introduce unnecessary complexity, I believe it would be a useful addition that could help keep more recipes within the standard Just framework.
I'm curious about everyone's opinions on this, and if there's interest, I'd be willing to attempt to create an implementation.
Contributor guide
Assessment
This issue has not been assessed yet.