all repos — markup @ ddaffd382a5bc9782ca36557f70c72b9179e4c1c

The code we use to render README.your_favorite_markup

lib/github/markup.rb (view raw)

 1begin
 2  require 'open3_detach'
 3rescue LoadError
 4  require 'open3'
 5end
 6
 7module GitHub
 8  module Markup
 9    extend self
10    @@markups = {}
11
12    def render(filename, content = nil)
13      content ||= File.read(filename)
14
15      if proc = renderer(filename)
16        proc[content]
17      else
18        content
19      end
20    end
21
22    def markup(file, pattern, &block)
23      require file.to_s
24      add_markup(pattern, &block)
25      true
26    rescue LoadError
27      false
28    end
29
30    def command(command, regexp, &block)
31      command = command.to_s
32
33      if File.exists?(file = File.dirname(__FILE__) + "/commands/#{command}")
34        command = file
35      end
36
37      add_markup(regexp) do |content|
38        rendered = execute(command, content)
39        rendered = rendered.to_s.empty? ? content : rendered
40
41        if block && block.arity == 2
42          # If the block takes two arguments, pass new content and old
43          # content.
44          block.call(rendered, content)
45        elsif block
46          # One argument is just the new content.
47          block.call(rendered)
48        else
49          # No block? No problem!
50          rendered
51        end
52      end
53    end
54
55    def add_markup(regexp, &block)
56      @@markups[regexp] = block
57    end
58
59    def can_render?(filename)
60      !!renderer(filename)
61    end
62
63    def renderer(filename)
64      @@markups.each do |key, value|
65        if Regexp.compile("\\.(#{key})$") =~ filename
66          return value
67        end
68      end
69      nil
70    end
71
72    def execute(command, target)
73      out = ''
74      Open3.popen3(command) do |stdin, stdout, _|
75        stdin.puts target
76        stdin.close
77        out = stdout.read
78      end
79      out.gsub("\r", '')
80    rescue Errno::EPIPE
81      ""
82    end
83
84    # Define markups
85    instance_eval File.read(File.dirname(__FILE__) + '/markups.rb')
86  end
87end