DannyBen/datamix

View on GitHub
examples.runfile

Summary

Maintainability
Test Coverage
require "filewatcher"
require "pry"
require 'datamix'
require 'byebug'

summary "Generate example"

usage 'generate [EXAMPLE]'
help  'Generate output file for a given example'
action :generate do |args|
  if args['EXAMPLE']
    generate_example "examples/#{args['EXAMPLE']}"
  else
    generate_all_examples
  end
end

help 'Watch example files and rerun them on change'
action :watch do |args|
  glob = "examples/**/*.rb"
  
  say "g`watch`: #{glob}"

  Filewatcher.new(glob).watch do |files|
    files.each do |filename, event|
      say "g`#{event}`: #{filename}"
      next if event == :delete
      dir = File.dirname filename
      generate_example dir
    end
  end
end

helpers do
  def generate_all_examples
    glob = Dir['examples/*/'].reject { |dir| dir =~ /\/_/ }
    glob.each { |dir| generate_example dir }
    generate_examples_index
  end

  def generate_examples_index
    glob = Dir['examples/*/'].reject { |dir| dir =~ /\/_/ }

    content = ["# Examples Index\n\nExample | Description\n---|---"]
    glob.each do |dir|
      example = File.basename dir
      description = File.read("#{dir}info.md").strip.split("\n").first
      link = "https://github.com/DannyBen/datamix/tree/master/examples/#{example}##{example}"
      content << "[#{example}](#{link}) | #{description}"
    end

    content = content.join "\n"

    say 'g`generate`: examples/README.md'
    File.write "examples/README.md", content
  end

  def generate_example(dir)
    dir = "#{dir}/" unless dir[-1] == '/'
    generate_example_output dir
    generate_example_readme dir
  end

  def generate_example_output(dir)
    say "g`generate`: #{dir}output.txt"
    Dir.chdir dir do
      output = `ruby example.rb`
      File.write "output.txt", output
    end
  end

  def generate_example_readme(dir)
    source_file = 'example.rb'
    output_file = 'output.txt'
    info_file   = 'info.md'
    readme_file = 'README.md'

    say "g`generate`: #{dir}#{readme_file}"
    
    Dir.chdir dir do
      source = File.read(source_file).strip
      output = File.exist?(output_file) ? File.read(output_file).strip : false
      info   = File.exist?(info_file) ? File.read(info_file).strip : false
      title  = File.basename dir

      File.open(readme_file, 'w') do |f|
        f.puts "# #{title}\n\n"
        f.puts "#{info}\n\n" if info
        f.puts "```ruby\n"
        f.puts "#{source}\n\n"
        f.puts "```\n\n"
        f.puts "# Output\n\n```\n#{output}\n```\n" unless output.empty?
      end
    end
  end
end