tildelog/lib/edit.sh

68 lines
2.6 KiB
Bash

#!/usr/bin/env bash
# Edit an existing, published .html file while keeping its original timestamp
# Please note that this function does not automatically republish anything, as
# it is usually called from 'main'.
#
# Note that it edits HTML file, even if you wrote the post as markdown originally
# Note that if you edit title then filename might also change
#
# $1 the file to edit
# $2 (optional) edit mode:
# "keep" to keep old filename
# "full" to edit full HTML, and not only text part (keeps old filename)
# leave empty for default behavior (edit only text part and change name)
declare date_format_full
declare date_format_timestamp
declare template_tags_line_header
declare prefix_tags
edit() {
[[ ! -f "${1%%.*}.html" ]] && \
printf "Can't edit post \"%s.html\", did you mean to use \"bb.sh post <draft_file>\"?\\n" "${1%%.*}" && exit 1
# Original post timestamp
edit_timestamp=$(LC_ALL=C date -r "${1%%.*}.html" +"$date_format_full")
touch_timestamp=$(LC_ALL=C date -r "${1%%.*}.html" +"$date_format_timestamp")
tags_before=$(tags_in_post "${1%%.*}.html")
if [[ $2 == full ]]; then
$EDITOR "$1"
filename=$1
else
if [[ ${1##*.} == md ]]; then
# editing markdown file
$EDITOR "$1"
TMPFILE=$(make_html "$1")
filename=${1%%.*}.html
else
# Create the content file
TMPFILE=$(basename "$1").$RANDOM.html
# Title
get_post_title "$1" >"$TMPFILE"
# Post text with plaintext tags
get_html_file_content 'text' 'text' <"$1" | sed "/^<p>$template_tags_line_header/s|<a href='$prefix_tags\([^']*\).html'>\\1</a>|\\1|g" >>"$TMPFILE"
$EDITOR "$TMPFILE"
filename=$1
fi
rm "$filename"
if [[ $2 == keep ]]; then
parse_file "$TMPFILE" "$edit_timestamp" "$filename"
else
parse_file "$TMPFILE" "$edit_timestamp" # this command sets $filename as the html processed file
[[ ${1##*.} == md ]] && mv "$1" "${filename%%.*}.md" 2>/dev/null
fi
rm "$TMPFILE"
fi
touch -t "$touch_timestamp" "$filename"
touch -t "$touch_timestamp" "$1"
chmod 644 "$filename"
echo "Posted $filename"
tags_after=$(tags_in_post "$filename")
relevant_tags=$(echo "$tags_before $tags_after" | tr ',' ' ' | tr ' ' '\n' | sort -u | tr '\n' ' ')
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
}