Created
October 22, 2024 06:56
-
-
Save apainintheneck/17e2d86171265d37b17778d8ccfecc6d to your computer and use it in GitHub Desktop.
An experiment to create a wiki cli app. The results are not promising.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require "net/http" | |
require "json" | |
require "bundler/inline" | |
gemfile do | |
source 'https://rubygems.org' | |
gem "addressable" | |
gem "tty-prompt" | |
gem "reverse_markdown" | |
gem "tty-markdown" | |
gem "tty-pager" | |
gem "ruby-readability", :require => 'readability' | |
end | |
URL_TEMPLATE = Addressable::Template | |
.new("https://{lang}.wikipedia.org/w/api.php{?action,search,limit,format}") | |
.partial_expand(lang: "en", action: "opensearch", limit: 25, format: "json") | |
.freeze | |
search = ARGV.map(&:strip).join(" ") | |
if search.empty? | |
puts "usage: wiki-cli [SEARCH TERM]" | |
exit(1) | |
end | |
search_url = URL_TEMPLATE | |
.expand(search: search) | |
.then { URI(_1) } | |
response_body = Net::HTTP.get(search_url) | |
search_results = JSON | |
.parse(response_body) | |
.then { |json| json[1].zip(json[3]) } | |
.to_h | |
.freeze | |
choice = TTY::Prompt | |
.new( | |
quiet: true, | |
track_history: false, | |
interrupt: :exit, | |
symbols: { marker: ">" }, | |
enable_color: !ENV["NO_COLOR"] | |
) | |
.select("Choose a wikipedia article to read:", search_results.keys) | |
content_url = search_results | |
.fetch(choice) | |
.then { URI(_1) } | |
content_html = Net::HTTP.get(content_url) | |
article_html = Readability::Document | |
.new( | |
content_html, | |
tags: %w[div p h1 h2 h3 h4 h5 h6 a ul li table tbody tr td], | |
remove_empty_nodes: true, | |
blacklist: 'h2#References, ol.references, figcaption' | |
).content | |
markdown = ReverseMarkdown.convert(article_html) | |
pretty_markdown = TTY::Markdown.parse(markdown) | |
TTY::Pager.page(pretty_markdown, width: 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment