ipso icon indicating copy to clipboard operation
ipso copied to clipboard

Shell scripting examples

Open LightAndLight opened this issue 4 years ago • 0 comments

This issue tracks real-life scripts that I should port to ipso.

ipso golden tests script

Before:

#! /usr/bin/env bash            
                    
ipso-golden --bin $(which ipso) --dir examples "$@"

After:

#! /usr/bin/env -S ipso --script

bind path <- cmd.read `which ipso`
bind args <- env.args
cmd.run `ipso-golden --bin $path --dir examples $..args`

Docker cleanup script

Before:

#! /usr/bin/env bash

# remove containers
docker ps --all --format "{{.ID}}" | xargs docker rm

# remove images
docker images --format "{{.ID}}" | xargs docker rmi -f

# remove volumes
docker volume prune

# remove build cache
docker builder prune

After:

#! /usr/bin/env -S ipso --script

# remove containers
bind containerIds <- cmd.lines `docker ps --all --format "{{.ID}}"`
cmd.run `docker rm $..containerIds`

# remove images
bind imageIds <- cmd.lines `docker images --format "{{.ID}}"`
cmd.run `docker rmi -f $..imageIds`

# remove volumes
cmd.run `docker volume prune`

# remove build cache
cmd.run `docker builder prune`

Postgres local server

Before:

#! /usr/bin/env bash
set -euo pipefail

POSTGRES_DATA_DIR=".postgres-data"
POSTGRES_SOCKET_DIR="$PWD/$POSTGRES_DATA_DIR"

rm -rf "$POSTGRES_DATA_DIR"
initdb -D "$POSTGRES_DATA_DIR"
pg_ctl start -D "$POSTGRES_DATA_DIR" -l "$POSTGRES_DATA_DIR/log.txt" -o "-k $POSTGRES_SOCKET_DIR"
createdb -h "$POSTGRES_SOCKET_DIR" blog
psql -h "$POSTGRES_SOCKET_DIR" -d blog -c "CREATE ROLE blog WITH LOGIN"

After:

#! /usr/bin/env -S ipso --script

let POSTGRES_DATA_DIR = ".postgres-data"

bind currentDir <- env.currentDir
let POSTGRES_SOCKET_DIR = "$currentDir/$POSTGRES_DATA_DIR"

cmd.run `rm -rf $POSTGRES_DATA_DIR`
cmd.run `initdb -D $POSTGRES_DATA_DIR`
cmd.run `pg_ctl start -D $POSTGRES_DATA_DIR -l $POSTGRES_DATA_DIR/log.txt -o "-k $POSTGRES_SOCKET_DIR"`
cmd.run `createdb -h $POSTGRES_SOCKET_DIR blog`
cmd.run `psql -h $POSTGRES_SOCKET_DIR -d blog -c "CREATE ROLE blog WITH LOGIN"`

PID manipulation (draft)

There's a pattern where one script will spawn a process and save the PID to a file, so that another script can later read the PID and kill the process.

Does ipso have a the tools to do this nicely?

#! /usr/bin/env -S ipso --script

start : IO ()
start =
  comp
    bind process <- cmd.spawn `my_executable`
    file.write "process.pid" <| int.toString process.id

stop : IO ()
stop =
  comp
    bind pid <- file.read "process.pid"
    kill (int.fromString! pid) SigKill

main : IO ()
main =
  comp
    args <- env.args
    case args[1] of
      "start" -> start
      "stop" -> stop
      command -> eprintln "error: invalid command \"$command\""

LightAndLight avatar Dec 24 '21 04:12 LightAndLight