Setup.jl/src/cmdpuns.jl

72 lines
1.3 KiB
Julia

import Base.!, Base.~
"""
~(cmd::AbstractCmd)
Run `cmd` and return the output as a string.
```julia-repl
julia> ~ `ls /home`
"doe"
```
"""
function ~(c::Base.AbstractCmd)
strip(read(c, String), '\n')
end
"""
!(cmd::AbstractCmd)
Run `cmd` and print the output to stdout.
```julia-repl
julia> ! `ls /home`
doe
```
This can also be combined with `~ cmd` to print and return
the output by using `!~ cmd`.
```julia-repl
julia> !~ `ls /home`
doe
"doe"
```
"""
function !(c::Base.AbstractCmd)
println(~c)
end
function !(o::SubString{String})
println(o)
o
end
struct PipeCmds <: Base.AbstractCmd
cmds::Vector{<:Base.AbstractCmd}
PipeCmds(left::Base.AbstractCmd, right::Base.AbstractCmd) = new([left, right])
PipeCmds(left::PipeCmds, right::Base.AbstractCmd) = new([left.cmds; right])
PipeCmds(left::Base.AbstractCmd, right::PipeCmds) = new([left; right.cmds])
end
import Base.|
"""
cmd1::AbstractCmd | cmd2::AbstractCmd
Create a pipleine from `cmd1` to `cmd2`.
```julia-repl
julia> `cat .zshenv` | `wc -l`
PipeCmds(Cmd[`cat .zshenv`, `wc -l`])
When `PipeCmds` are passed to `!` or `~`, the commands contained are
expanded inside a `pipeline` call.
```
"""
function (|)(left::Base.AbstractCmd, right::Base.AbstractCmd)
PipeCmds(left, right)
end
function ~(c::PipeCmds)
strip(read(pipeline(c.cmds...), String), '\n')
end