Create a gist now

Instantly share code, notes, and snippets.

@Zettt /packagizer.sh
Last active Oct 24, 2016

What would you like to do?
TextBundle Packagizer -- This is a script that helps to create bundled folders of Markdown files. It downloads online-linked images to an assets directory, as well as copies local files to it. It's not finished yet.
#!/bin/sh
function usage {
echo "This script creates a folder containing all linked ![images]()"
echo "of a Markdown file -- even linked ones from the Internet."
echo ""
echo "It takes one argument: the file it should process."
echo
echo "When a file argument is present, it creates a new folder for:"
echo "a) the Markdown file"
echo "b) and an \"assets\" folder for images"
echo
echo "Everything referenced is packaged into one folder."
return
}
function localize() {
if [[ $i == *"http"* ]]; then
echo "Downloading: $fileurl"
# download file into assets with original name
cd "$packageName/assets"
curl -OJ --silent $fileurl
cd - &>/dev/null
newname=$(curl --write-out %{filename_effective} --silent --remote-name $fileurl)
else [[ -e $i ]]
echo "Copying: $fileurl"
# copy file into assets
cd "$packageName/assets"
cp $fileurl .
cd - &>/dev/null
newname=$(basename $fileurl)
fi
# replace old with new location
sed -i "" "s~$fileurl~assets/$newname~" "$packageName/$inFile"
}
### Setup
if [[ -e "$1" ]]; then
#packageName=$(basename $1)
packageName="${1%%.*}"
#Use this to make text bundles:
#packageName="${1%%.*}.textbundle"
inFile=$1
elif [[ "$1" == "--help" || "$1" == "-h" ]]; then
usage
exit
else
usage
echo
echo "Error: No file input present."
exit 1
fi
### Create Package Dir
echo "packageName: $packageName"
echo "inFile: $1"
mkdir "$packageName"
mkdir "$packageName/assets"
cp "$inFile" "$packageName"
### Localize files
# catch inline links
targets=($(grep "!\[\](" $inFile))
echo
echo "Processing inline links: ${targets[@]}"
for i in "${targets[@]}"; do
fileurl=$(echo $i | sed -e "s~\!\[\](\(.*\))~\1~")
#echo $i
#echo "fileurl: $fileurl"
localize $i
done
# catch reference links
targets=($(grep "!\[\]\[" $inFile))
echo
echo "Processing reference links: ${targets[@]}"
#search for reference tags and replace them
for i in "${targets[@]}"; do
filetag=$(echo $i | sed -e "s~\!\[\]\[\(.*\)\]~\1~")
fileurl=$(grep "\[$filetag\]:" $inFile | sed -e "s~\[$filetag\]:.\(.*\)~\1~")
#echo $i
#echo "fileurl: $fileurl"
localize $i
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment