Skip to content

Instantly share code, notes, and snippets.

@jmetzz
Created February 12, 2019 14:39
Show Gist options
  • Save jmetzz/97570513580e5f5cdb80da105f74b34e to your computer and use it in GitHub Desktop.
Save jmetzz/97570513580e5f5cdb80da105f74b34e to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
function usage {
echo "$0 [options] <conda environment file>"
echo
echo " Options:"
echo " -h shows this message"
echo
echo
}
function error {
echo "$2" >&2
usage
exit $1
}
if [[ $# -ne 1 ]]; then
error 1 "Missing required argument: <conda environment file>"
fi
INPUT_FILE="$1"
echo "$INPUT_FILE"
if [[ ! -f "$INPUT_FILE" ]]; then
error 2 "Conda environment file not found"
fi
# create an empty the requirements file
echo "" > requirements.txt
CONDA_BLOCK=0
PIP_BLOCK=0
CONDA_BLOCK_PATTERN="^dependencies:$"
PIP_BLOCK_PATTERN="^- pip:$"
# read every non-empty line
while IFS="" read -r line || [ -n "$line" ]; do
# trim string
entry=$(echo "${line}" | sed -e 's/^[ \t]*//')
[[ $entry =~ $CONDA_BLOCK_PATTERN ]] && echo "Conda dependencies block found " && CONDA_BLOCK=1
[[ $CONDA_BLOCK == 0 ]] && continue
# Skip non dependency lines
[[ $entry != -* ]] && echo "skipping '$line' line" && continue
if [[ $entry =~ $PIP_BLOCK_PATTERN ]]; then
PIP_BLOCK=1
echo "pip dependencies block found"
continue
fi
if [[ $PIP_BLOCK == 1 ]]; then
entry=$(echo "${entry}" | sed -e 's/^[ -]*//')
echo "${entry}" >> requirements.txt
else
# remove the '-' and space before the package name
entry=$(echo "${entry}" | sed -e 's/^[ -]*//')
regex="^([ -]*)([a-zA-Z_-]*)(=.*)?"
if [[ $entry =~ $regex ]]; then
package="${BASH_REMATCH[2]}"
version="${BASH_REMATCH[3]}"
# echo correct structure to requirements file
if [[ ! -z "${version}" ]]; then
echo "${package}=${version}" >> requirements.txt
else
echo "${package}" >> requirements.txt
fi
fi
fi
done <<< "$(cat $INPUT_FILE)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment