Skip to content

Instantly share code, notes, and snippets.

@BartMassey
Created March 15, 2022 21:50
Show Gist options
  • Save BartMassey/5e68dc0f68bc39985b382531ee6b195f to your computer and use it in GitHub Desktop.
Save BartMassey/5e68dc0f68bc39985b382531ee6b195f to your computer and use it in GitHub Desktop.
Local "Rust Playground" script
#!/bin/sh
# Local "Rust Playground"
# Bart Massey 2021
# Requires `cargo-add` and this additional shell function:
# function rpl {
# DIR="`$HOME/bin/mi/rpl \"$@\"`" &&
# echo "dir '$DIR'" >&2 &&
# pushd $DIR &&
# if [ -f src/main.rs ]
# then
# emacs -nw +2 src/main.rs
# elif [ -f src/lib.rs ]
# then
# emacs -nw src/lib.rs
# else
# emacs -nw *.rs
# fi
# }
USAGE="usage: rpl <--bin|--lib> <crate-name> [<dep-crate> ...]"
if [ $# -eq 0 ]
then
echo "$USAGE" >&2
exit 1
fi
CRATE_TYPE=""
MINI=true
while [ $# -gt 1 ]
do
case "$1" in
"--lib"|"--bin") CRATE_TYPE="$1"; shift ;;
"--mini") MINI=true; shift ;;
"--std") MINI=false; shift ;;
"-*") echo "$USAGE" >&2; exit 1;;
*) break ;;
esac
done
if [ "$CRATE_TYPE" = "" ]
then
echo "must specify crate type" >&2
exit 1
fi
CRATE_NAME="$1"; shift
CRATE_DIR="$HOME/.rpl/$CRATE_NAME"
if [ -s "$CRATE_DIR/Cargo.toml" ]
then
echo "$CRATE_DIR"
exit 0
fi
mkdir -p "$CRATE_DIR" &&
cd "$CRATE_DIR" &&
if $MINI
then
# Was a workaround for https://github.com/rust-lang/cargo/issues/9333
# but keeping it because convenience.
case "$CRATE_TYPE" in
"--lib") touch "$CRATE_NAME".rs ;;
"--bin")
cat >"$CRATE_NAME".rs <<'EOF'
fn main() {
}
EOF
;;
*) echo "unknown crate type $CRATE_TYPE" >&2; exit 1 ;;
esac
fi &&
cargo init -q --vcs=none "$CRATE_TYPE" &&
for DEP in "$@"
do
cargo add -q "$DEP"
if [ $? -ne 0 ]
then
exit 1
fi
done &&
echo "$CRATE_DIR"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment