all repos — markup @ f9028e34d5cd1e360c83a322ce57eef75cba7a4b

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 renderer_name(filename)
73      @@markups.each do |key, value|
74        if Regexp.compile("\\.(#{key})$") =~ filename
75          return key
76        end
77      end
78      nil
79    end
80
81    def execute(command, target)
82      out = ''
83      Open3.popen3(command) do |stdin, stdout, _|
84        stdin.puts target
85        stdin.close
86        out = stdout.read
87      end
88      out.gsub("\r", '')
89    rescue Errno::EPIPE
90      ""
91    end
92
93    # Define markups
94    instance_eval File.read(File.dirname(__FILE__) + '/markups.rb')
95  end
96end