Created
April 10, 2017 16:37
-
-
Save acidprime/f071f8e29a2d826edde5132c87dd59b6 to your computer and use it in GitHub Desktop.
Build shell scripts out of markdown code fences
This file contains 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 | |
DEBUG = false | |
require 'kramdown' | |
@markdown_file = ARGV[0] | |
text = File.read(@markdown_file) | |
doc = Kramdown::Document.new(text, input: 'GFM') | |
def p(element) | |
case element.type | |
when :codeblock | |
# puts element.value | |
when :codespan | |
# puts element.value | |
end | |
end | |
def shbang(lang) | |
case lang.to_sym | |
when :puppet | |
"#!/opt/puppetlabs/puppet/bin/puppet apply\n" | |
when :shell | |
"#!/bin/bash\n" | |
end | |
end | |
def read_file(file,line_number) | |
IO.readlines(file)[line_number] | |
end | |
@scripts = Hash.new | |
doc.root.children.each do |section| | |
puts "#{section.type}: #{section.value}" if DEBUG | |
case section.type | |
when :codeblock | |
markdown_comment = read_file( | |
@markdown_file, | |
section.options[:location] - 3, | |
) | |
match = markdown_comment.match( | |
/^\[\/\/\]\:\s#\s\((?<filename>\S*\.\w+)\)$/ | |
) | |
filename = match['filename'] | |
# Add the shbang to the top of the file | |
(@scripts[filename] ||= [])[0] = shbang( | |
section.options[:lang] | |
) | |
@scripts[filename] << section.value | |
when :p | |
p(section) | |
end | |
end | |
@scripts.each do |filename,lines| | |
unless File.exist?(filename) | |
# TODO: write these files based on the lines array | |
puts filename.inspect | |
puts lines.inspect | |
else | |
puts "File: #{filename} already exists, will not overwrite." | |
end | |
end |
Author
acidprime
commented
Apr 10, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment