forked from sr/git-wiki
-
Notifications
You must be signed in to change notification settings - Fork 6
/
git-wiki.rb
executable file
·115 lines (100 loc) · 2.67 KB
/
git-wiki.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env ruby
require 'sinatra'
require 'haml'
require 'grit'
require 'rdiscount'
require 'time'
module GitWiki
class << self
attr_accessor :wiki_path, :root_page, :extension, :link_pattern
attr_reader :wiki_name, :repo
def wiki_path=(path)
@wiki_name = File.basename(path)
@repo = Grit::Repo.new(path)
end
def all_page_blobs
@repo.head.commit.tree.contents.select do |obj|
obj.kind_of?(Grit::Blob) && obj.name.end_with?(@extension)
end
end
def create_blob(path)
Grit::Blob.create(@repo, :name => path)
end
def file_path(name)
(name.empty? ? @root_page : name) + @extension
end
def url(page=nil, params=nil)
'/' + (page && page.name != @root_page ? page.name : '') + (params ? "?#{Rack::Utils.build_query(params)}" : '')
end
def expand_links(html)
html.gsub(@link_pattern) do
link_text = $1
page = Page.find_or_create(link_text.gsub(/[^\w\s]/, '').split.join('-').downcase)
"<a class='page #{'new' unless page.exists?}' href='#{url(page)}'>#{link_text}</a>"
end
end
end
end
class Page
def self.find_all
GitWiki.all_page_blobs.map {|blob| new(blob) }
end
def self.find_or_create(name, rev=nil)
path = GitWiki.file_path(name)
commit = rev ? GitWiki.repo.commit(rev) : GitWiki.repo.head.commit
blob = commit.tree/path
new(blob || GitWiki.create_blob(path))
end
def initialize(blob)
@blob = blob
end
def name
@blob.name.sub(/#{GitWiki.extension}$/, '')
end
def exists?
end
def content
@blob.data
end
def to_html
GitWiki.expand_links(RDiscount.new(content).to_html)
end
def log
head = GitWiki.repo.head.name
GitWiki.repo.log(head, @blob.name).map {|commit| commit.to_hash }
end
def save!(data, msg)
msg = "web commit: #{name}" if msg.empty?
Dir.chdir(GitWiki.repo.working_dir) do
File.open(@blob.name, 'w') {|f| f.puts(data.gsub("\r\n", "\n")) }
GitWiki.repo.add(@blob.name)
GitWiki.repo.commit_index(msg)
end
end
end
set :haml, :format => :html5, :attr_wrapper => '"'
get '/*' do
if params[:view] == 'tree'
@pages = Page.find_all
haml :list
else
@page = Page.find_or_create(*params[:splat], params[:rev])
case params[:view]
when 'log'; haml :log
when 'edit'; haml :edit
else haml @page.exists? ? :show : :edit
end
end
end
post '/*' do
@page = Page.find_or_create(*params[:splat])
@page.save!(params[:content], params[:msg])
redirect GitWiki.url(@page), 303
end
configure do
GitWiki.wiki_path = Dir.pwd
GitWiki.root_page = 'index'
GitWiki.extension = '.md'
GitWiki.link_pattern = /\[\[(.*?)\]\]/
end