Skip to content

Instantly share code, notes, and snippets.

@blockloop
Last active November 25, 2022 03:27
Show Gist options
  • Save blockloop/8fffbd1bc9c1323368a4c1983b3b655e to your computer and use it in GitHub Desktop.
Save blockloop/8fffbd1bc9c1323368a4c1983b3b655e to your computer and use it in GitHub Desktop.
browse top hacker news articles from the command line
#!/usr/bin/env bash
#
# Author: blockloop
#
# Purpose: browse top hacker news articles from the command line
#
# Requirements:
# jq fzf curl
set -ueo pipefail
base_url=https://hacker-news.firebaseio.com/v0
topstories_url=/topstories.json
cache_dir="/tmp/.hn-cache"
mkdir -p "${cache_dir}"
main() {
find "${cache_dir}" \
-type f \
-iname topstories.json \
-mmin +10 \
-exec rm {} \;
local item_urls; item_urls=$(request ${topstories_url} \
| jq -r '.[:30] | @csv' \
| tr ',' '\n')
get_titles "${item_urls}" \
| FZF_DEFAULT_OPTS="" fzf -m \
| xargs -r -d '\n' -I% \
grep -irl '"%"' "${cache_dir}" \
| xargs -r cat \
| jq -r '.url' \
| xargs -r -n1 xdg-open 2> /dev/null
}
get_titles() {
urls="${1}"
for item_id in ${urls}; do
local url; url=$(item_url "${item_id}")
request "${url}" \
| jq -r '.title' &
done
}
request() {
local uri=${1}
local url="${base_url}${uri}"
local cache_file_dir; cache_file_dir="${cache_dir}/$(dirname "${url//https:\/\//}")"
local cache_file="${cache_dir}/${url//https:\/\//}"
if [ -z "${NOCACHE:-}" ] && [ -f "${cache_file}" ]; then
cat "${cache_file}"
else
mkdir -p "${cache_file_dir}" > /dev/null
curl -LSLs "${url}" | tee "${cache_file}"
fi
}
item_url() {
local item="${1}"
echo "/item/${item}.json"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment