-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnix.rb
executable file
·193 lines (158 loc) · 5.31 KB
/
nix.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'date', '~> 3.4.0', require: true
gem 'optparse', '~> 0.4.0', require: true
gem 'open-uri', '~> 0.4.1', require: true
gem 'kramdown', '~> 2.4.0', require: true
gem 'kramdown-parser-gfm', '~> 1.1.0', require: true
gem 'rouge', '~> 4.4.0', require: true
end
class Site
attr_reader :pages, :layouts
def initialize(layouts = [])
@layouts = layouts.to_h { |layout| [layout.name, layout] }
@pages = []
end
def add(new_pages)
@pages += new_pages
self
end
def compile(variables:)
@pages.map do |page|
page.compile(layouts:, ctx: { pages:, variables: })
end.flatten.uniq(&:path)
end
end
class Document
attr_reader :path, :name, :data
def initialize(path, data = nil, name = nil)
@path = Pathname.new path.to_s
@name = name ||= @path.parent.basename.to_s
@data = data
end
def self.from(reader) = ->(path) { new(Pathname.new(path), reader[path]) }
end
class Layout < Document
def initialize(path, html)
super(path, html, path.basename(path.extname).to_s)
end
def to_s = @data
end
class HTMLPage < Document
def initialize(path:, title:)
super(path)
@title = title || @path.basename.to_s
end
def compile(layouts:, ctx:)
type = self.class.to_s.downcase
name = @path.basename(@path.extname).to_s
html = <<~BODY
#{layouts['header']}
<main class="#{type} #{name}">#{render(ctx)}</main>
#{layouts['footer']}
BODY
@data = replace(html, ctx[:variables].merge({ root_url: root_url }))
self
end
def root_url(basename = '')
File.join(path.each_filename.to_a.drop(1).map { '../' }
.join(''), basename).delete_prefix('/')
end
def render(*) = ''
private def bytesize(html) = html.gsub(/\s+/, '').bytesize.to_s
private def replace(html, variables)
{ **variables, 'title' => @title, 'bytes' => bytesize(html) }
.reduce(html) do |replaced, (variable, value)|
replaced.gsub("{{#{variable}}}", value.to_s)
end
end
end
class MarkdownPage < HTMLPage
attr_reader :title
def initialize(path, markdown, title = nil)
super(path:, title: title || markdown.lines.first[2..].strip)
@markdown = markdown
end
def render(ctx)
super + Kramdown::Document.new(@markdown, { input: 'GFM' }).to_html
end
end
class Page < MarkdownPage
def initialize(path, markdown)
super("/#{path.basename(path.extname)}/index.html", markdown)
end
end
class Post < MarkdownPage
attr_reader :date
def initialize(path, markdown)
super("/posts/#{path.basename(path.extname)}/index.html", markdown)
@date = Date.parse(markdown.lines[2]&.strip || '')
end
def render(ctx)
"#{super}<link rel=\"stylesheet\" href=\"#{root_url}highlight.css\">
<link>"
end
end
def config = YAML.load_file('_config.yml', symbolize_names: true)
class Index < MarkdownPage
def initialize(_path, markdown)
super('/index.html', markdown, 'Home')
end
def post? = ->(page) { page.is_a?Post }
def posts(ctx) = ctx[:pages].filter(&post?).sort_by(&:date).reverse
def render(ctx)
"%s <ul class=\"list\">%s</ul>" % [super, posts(ctx).reduce(+'') do
|list, p| list << "<li>
<a href=\"%<link>s\"><h3>%<head>s</h3><small>%<year>s</small></a>
</li>" % {
head: p.title,
link: root_url("posts/#{p.name}"),
year: p.date.strftime('%b, %Y'),
name: p.name
}
end]
end
end
def between(str, a, b) = str[/#{Regexp.escape(a)}(.*?)#{Regexp.escape(b)}/m, 1]
def color(name, colors = { 'red': 31, 'yellow': 33, 'green': 32, blue: 34 })
ENV['NO_COLOR'] || !STDOUT.tty? ? '' : "\e[0;#{colors[name.downcase.to_sym]}m"
end
def writefile(dest, force: false) =
lambda do |page|
FileUtils.mkdir_p(File.dirname(File.join(dest, page.path)))
if File.exist?(page.path) && !force
return
end
File.write(File.join(dest, page.path), page.data)
end
def build(dest:, **variables)
FileUtils.rm_rf(File.join(dest, '/'))
Site
.new(Dir['_layouts/*.html'].map(&Layout.from(File.method(:read))))
.add(Dir['posts/*.md'].map(&Post.from(File.method(:read))))
.add(Dir['pages/*[^index]*.md'].map(&Page.from(File.method(:read))))
.add(Dir['pages/index.md'].map(&Index.from(File.method(:read))))
.compile(variables:).each(&writefile(dest, force: true))
FileUtils.cp_r('public/.', dest)
puts color(:green), 'build: ok', color(:reset)
end
def serve(port:, dest:, **)
exec "ruby -run -e httpd -- #{dest.tr('./', '')} -p #{port ||= 8000} ||= '0'}"
end
def init(url: 'https://raw.github.com/nicholaswmin/nix/main/README.md')
path = File.exist?(File.basename(url)) ? File.basename(url) : URI(url).open
text = between(path.is_a?(URI) ? path.read : File.read(path), '<!---d', '-->')
hash = YAML.load(text).inject(:merge)
hash.keys.map(&Document.from(hash)).each(&writefile('./', force: true))
puts color(:green), "init ok: #{Dir.pwd}", color(:reset)
end
op = OptionParser.new(nil, 25, 'ruby nix.rb') do |o|
o.on '--init [url]', 'create sample blog' do _1 ? init(_1) : init() end
o.on '--build', 'build static HTML' do |v| build(**config) end
o.on '--serve [port]', 'serve locally' do serve(**{ port: _1, **config }) end
end
puts ARGV.empty? ? "\n#{op}\ndocs: https://github.com/nicholaswmin/nix\n\n" : ''
op.parse!