Created
August 30, 2020 16:14
-
-
Save juanmanuelramallo/d64767bdf8ab4950ae67c280d1a18a03 to your computer and use it in GitHub Desktop.
Github styled markdown preview
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/ruby | |
# Place this file in /usr/local/bin/ | |
# It uses Github API to generate the HTML from the Markdown | |
# It includes the Primer CSS stylesheet | |
# It adds the body class needed and some spacing for the body | |
# It opens Chrome with the HTML generated | |
# It deletes the file when you interrupt the process | |
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'httparty' | |
end | |
require 'tempfile' | |
require 'json' | |
if ARGV[0] == '-h' | |
puts "Github styled markdown preview.\n\tUsage: `md-preview PATH`.\n\tExample: `md-preview ./README.md`.\nSend a system interrupt CTRL + C to delete the preview file." | |
return | |
end | |
raise 'Missing file path argument. Usage: `md-preview PATH`' unless ARGV[0] | |
text = File.read(ARGV[0]) | |
options = { | |
headers: { | |
'Accept' => 'application/vnd.github.v3+json', | |
'User-Agent' => 'HTTParty' | |
}, | |
body: { text: text }.to_json | |
} | |
response = HTTParty.post('https://api.github.com/markdown', options) | |
raise response.body if response.code != 200 | |
body = ['<body class="markdown-body" style="width:980px;padding:45px;margin:auto;">', response.body, '</body>'].join | |
html = ['<head><link href="https://unpkg.com/@primer/css/dist/primer.css" rel="stylesheet"></head>', body].join | |
Tempfile.open(['readme', '.html']) do |file| | |
file.write(html) | |
file.rewind | |
`open -a 'Google Chrome' #{file.path}` | |
loop do | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment