Skip to content

Instantly share code, notes, and snippets.

@ducaale
Last active September 10, 2020 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducaale/b3be400d3c3b8eb7cff80793166e1e5e to your computer and use it in GitHub Desktop.
Save ducaale/b3be400d3c3b8eb7cff80793166e1e5e to your computer and use it in GitHub Desktop.
WIP: A convenience wrapper for opam. Inspired by https://khady.info/opam-npm.html
# inspired by https://khady.info/opam-npm.html
USAGE="A convenience wrapper for opam
USAGE:
opamx [options] [command]
OPTIONS:
-h, --help Print help information
AVAILABLE COMMANDS:
new Create a new opam project at <path>
add Add a new dependency to .opam file
remove Remove dependency from .opam file
build alias for dune build
exec alias for dune exec
fmt Format code using ocamlformat
"
OPAM_FILE='opam-version: "2.0"
name: "$name"
maintainer: "$maintainer"
version: "0.1.0"
build: [
[ "dune" "subst" ] {pinned}
[ "dune" "build" "-p" name "-j" jobs ]
]
depends: [
"dune" {build}
"opam-lock" {dev}
]
'
man_pages() {
echo "$USAGE"
}
new_project() {
if [ "$#" -eq 1 ]; then
eval "mkdir $1 && opam switch create $1 4.10.0 --deps-only"
name="$(basename $1)"
maintainer="$(git config user.name) <$(git config user.email)>"
opam_file="$1/$name.opam"
echo "$OPAM_FILE" | name="$name" maintainer="$maintainer" envsubst > "$opam_file"
else
echo "Usage: opamx new <path>"
fi
}
# TODO: check if .opam file has been created and there is a local switch i.e _opam
add() {
# usage: opamx install [packages]...
if [ "$#" -gt 0 ]; then
echo "opam install --restore --yes $@ && opam lock"
# some magic for manipulating .opam file
cat *.opam | awk '/depends/,/]/' | grep -q "$1"
if [ $? -eq 0 ]; then
echo 'package is already installed'
sed -i "/depends/,/]/ s/\"$1\" {[^}]*}\|\"$1\"/\"case\" {>0.5}/" *.opam
else
echo 'installing the package'
# for list spanning multiple lines
sed -i "/depends/,/^]/ s/]/ \"$1\" {>0.5}\n]/" *.opam
# for single line list
sed -i "/depends.*]/ s/]/\"$1\" {>0.5} ]/" *.opam
fi
else
echo "opam install . --deps-only"
fi
}
remove() {
if [ "$#" -gt 0 ]; then
echo "opam uninstall --auto-remove --yes $@ && opam lock"
else
echo "Usage: opamx uninstall [packages]..."
fi
}
# TODO: check if opam is installed and is initialized
if [ "$#" -eq 0 ]; then
man_pages
else
case $1 in
new)
shift
new_project $@
;;
add)
shift
add $@
;;
remove)
shift
remove $@
;;
*)
echo "The command \"$1\" is not defined"
esac
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment