tildelog/lib/write_entry.sh

103 lines
3.4 KiB
Bash

#!/usr/bin/env bash
# Manages the creation of the text file and the parsing to html file
# also the drafts
write_entry() {
declare template_tags_line_header
declare global_url
declare convert_filename
declare save_markdown
test_markdown && fmt=md || fmt=html
f=$2
[[ $2 == -html ]] && fmt=html && f=$3
if [[ -n $f ]]; then
TMPFILE=$f
if [[ ! -f $TMPFILE ]]; then
echo "The file doesn't exist"
delete_includes
exit
fi
# guess format from TMPFILE
extension=${TMPFILE##*.}
[[ $extension == md || $extension == html ]] && fmt=$extension
# but let user override it (`bb.sh post -html file.md`)
[[ $2 == -html ]] && fmt=html
# Test if Markdown is working before re-posting a .md file
if [[ $extension == md ]]; then
if test_markdown; then
echo "Markdown is not working, please edit HTML file directly."
exit
fi
fi
else
TMPFILE=.entry-$RANDOM.$fmt
echo -e "Title on this line\n" >> "$TMPFILE"
[[ $fmt == html ]] && cat << EOF >> "$TMPFILE"
<p>The rest of the text file is an <b>html</b> blog post. The process will continue as soon
as you exit your editor.</p>
<p>$template_tags_line_header keep-this-tag-format, tags-are-optional, example</p>
EOF
[[ $fmt == md ]] && cat << EOF >> "$TMPFILE"
The rest of the text file is a **Markdown** blog post. The process will continue
as soon as you exit your editor.
$template_tags_line_header keep-this-tag-format, tags-are-optional, beware-with-underscores-in-markdown, example
EOF
fi
chmod 600 "$TMPFILE"
post_status="E"
filename=""
while [[ $post_status != "p" && $post_status != "P" ]]; do
[[ -n $filename ]] && rm "$filename" # Delete the generated html file, if any
$EDITOR "$TMPFILE"
if [[ $fmt == md ]]; then
html_from_md=$(mrkdwn "$TMPFILE")
parse_file "$html_from_md"
rm "$html_from_md"
else
parse_file "$TMPFILE" # this command sets $filename as the html processed file
fi
chmod 644 "$filename"
[[ -n $preview_url ]] || preview_url=$global_url
echo "To preview the entry, open $preview_url/$filename in your browser"
echo -n "[P]ost this entry, [E]dit again, [D]raft for later? (p/E/d) "
read -r post_status
if [[ $post_status == d || $post_status == D ]]; then
mkdir -p "drafts/"
chmod 700 "drafts/"
title=$(head -n 1 $TMPFILE)
[[ -n $convert_filename ]] && title=$(echo "$title" | eval "$convert_filename")
[[ -n $title ]] || title=$RANDOM
draft=drafts/$title.$fmt
mv "$TMPFILE" "$draft"
chmod 600 "$draft"
rm "$filename"
delete_includes
echo "Saved your draft as '$draft'"
exit
fi
done
if [[ $fmt == md && -n $save_markdown ]]; then
mv "$TMPFILE" "${filename%%.*}.md"
else
rm "$TMPFILE"
fi
chmod 644 "$filename"
echo "Posted $filename"
relevant_tags=$(tags_in_post "$filename")
if [[ -n $relevant_tags ]]; then
# shellcheck disable=SC2086 # Intended splitting of $relevant_tags
relevant_posts="$(posts_with_tags $relevant_tags) $filename"
rebuild_tags "$relevant_posts" "$relevant_tags"
fi
}