-
Notifications
You must be signed in to change notification settings - Fork 1
/
Rakefile
579 lines (489 loc) · 17.8 KB
/
Rakefile
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
require "rubygems"
require 'rake'
require 'yaml'
require 'time'
SOURCE = "."
CONFIG = {
'version' => "0.3.0",
'themes' => File.join(SOURCE, "_includes", "themes"),
'layouts' => File.join(SOURCE, "_layouts"),
'posts' => File.join(SOURCE, "_posts"),
'post_ext' => "md",
'theme_package_version' => "0.1.0"
}
# Path configuration helper
module JB
class Path
SOURCE = "."
Paths = {
:layouts => "_layouts",
:themes => "_includes/themes",
:theme_assets => "assets/themes",
:theme_packages => "_theme_packages",
:posts => "_posts"
}
def self.base
SOURCE
end
# build a path relative to configured path settings.
def self.build(path, opts = {})
opts[:root] ||= SOURCE
path = "#{opts[:root]}/#{Paths[path.to_sym]}/#{opts[:node]}".split("/")
path.compact!
File.__send__ :join, path
end
end #Path
end #JB
# Usage: rake post title="A Title" [date="2012-02-09"] [tags=[tag1, tag2]]
desc "Begin a new post in #{CONFIG['posts']}"
task :post do
abort("rake aborted: '#{CONFIG['posts']}' directory not found.") unless FileTest.directory?(CONFIG['posts'])
title = ENV["title"] || "new-post"
tags = ENV["tags"] || "[]"
slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
begin
date = (ENV['date'] ? Time.parse(ENV['date']) : Time.now).strftime('%Y-%m-%d')
rescue Exception => e
puts "Error - date format must be YYYY-MM-DD, please check you typed it correctly!"
exit -1
end
filename = File.join(CONFIG['posts'], "#{date}-#{slug}.#{CONFIG['post_ext']}")
if File.exist?(filename)
abort("rake aborted!") if ask("#{filename} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
end
puts "Creating new post: #{filename}"
open(filename, 'w') do |post|
post.puts "---"
post.puts "layout: post"
post.puts "title: \"#{title.gsub(/-/,' ')}\""
post.puts 'description: ""'
post.puts "category: "
post.puts "tags: []"
post.puts "---"
post.puts "{% include JB/setup %}"
end
end # task :post
# Usage: rake page name="about.html"
# You can also specify a sub-directory path.
# If you don't specify a file extention we create an index.html at the path specified
desc "Create a new page."
task :page do
name = ENV["name"] || "new-page.md"
filename = File.join(SOURCE, "#{name}")
filename = File.join(filename, "index.html") if File.extname(filename) == ""
title = File.basename(filename, File.extname(filename)).gsub(/[\W\_]/, " ").gsub(/\b\w/){$&.upcase}
if File.exist?(filename)
abort("rake aborted!") if ask("#{filename} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
end
mkdir_p File.dirname(filename)
puts "Creating new page: #{filename}"
open(filename, 'w') do |post|
post.puts "---"
post.puts "layout: page"
post.puts "title: \"#{title}\""
post.puts 'description: ""'
post.puts "---"
post.puts "{% include JB/setup %}"
end
end # task :page
desc "Launch preview environment"
task :preview do
system "jekyll --auto --server"
end # task :preview
# Public: Alias - Maintains backwards compatability for theme switching.
task :switch_theme => "theme:switch"
namespace :theme do
# Public: Switch from one theme to another for your blog.
#
# name - String, Required. name of the theme you want to switch to.
# The theme must be installed into your JB framework.
#
# Examples
#
# rake theme:switch name="the-program"
#
# Returns Success/failure messages.
desc "Switch between Jekyll-bootstrap themes."
task :switch do
theme_name = ENV["name"].to_s
theme_path = File.join(CONFIG['themes'], theme_name)
settings_file = File.join(theme_path, "settings.yml")
non_layout_files = ["settings.yml"]
abort("rake aborted: name cannot be blank") if theme_name.empty?
abort("rake aborted: '#{theme_path}' directory not found.") unless FileTest.directory?(theme_path)
abort("rake aborted: '#{CONFIG['layouts']}' directory not found.") unless FileTest.directory?(CONFIG['layouts'])
Dir.glob("#{theme_path}/*") do |filename|
next if non_layout_files.include?(File.basename(filename).downcase)
puts "Generating '#{theme_name}' layout: #{File.basename(filename)}"
open(File.join(CONFIG['layouts'], File.basename(filename)), 'w') do |page|
if File.basename(filename, ".html").downcase == "default"
page.puts "---"
page.puts File.read(settings_file) if File.exist?(settings_file)
page.puts "---"
else
page.puts "---"
page.puts "layout: default"
page.puts "---"
end
page.puts "{% include JB/setup %}"
page.puts "{% include themes/#{theme_name}/#{File.basename(filename)} %}"
end
end
puts "=> Theme successfully switched!"
puts "=> Reload your web-page to check it out =)"
end # task :switch
# Public: Install a theme using the theme packager.
# Version 0.1.0 simple 1:1 file matching.
#
# git - String, Optional path to the git repository of the theme to be installed.
# name - String, Optional name of the theme you want to install.
# Passing name requires that the theme package already exist.
#
# Examples
#
# rake theme:install git="https://github.com/jekyllbootstrap/theme-twitter.git"
# rake theme:install name="cool-theme"
#
# Returns Success/failure messages.
desc "Install theme"
task :install do
if ENV["git"]
manifest = theme_from_git_url(ENV["git"])
name = manifest["name"]
else
name = ENV["name"].to_s.downcase
end
packaged_theme_path = JB::Path.build(:theme_packages, :node => name)
abort("rake aborted!
=> ERROR: 'name' cannot be blank") if name.empty?
abort("rake aborted!
=> ERROR: '#{packaged_theme_path}' directory not found.
=> Installable themes can be added via git. You can find some here: http://github.com/jekyllbootstrap
=> To download+install run: `rake theme:install git='[PUBLIC-CLONE-URL]'`
=> example : rake theme:install git='[email protected]:jekyllbootstrap/theme-the-program.git'
") unless FileTest.directory?(packaged_theme_path)
manifest = verify_manifest(packaged_theme_path)
# Get relative paths to packaged theme files
# Exclude directories as they'll be recursively created. Exclude meta-data files.
packaged_theme_files = []
FileUtils.cd(packaged_theme_path) {
Dir.glob("**/*.*") { |f|
next if ( FileTest.directory?(f) || f =~ /^(manifest|readme|packager)/i )
packaged_theme_files << f
}
}
# Mirror each file into the framework making sure to prompt if already exists.
packaged_theme_files.each do |filename|
file_install_path = File.join(JB::Path.base, filename)
if File.exist? file_install_path and ask("#{file_install_path} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
next
else
mkdir_p File.dirname(file_install_path)
cp_r File.join(packaged_theme_path, filename), file_install_path
end
end
puts "=> #{name} theme has been installed!"
puts "=> ---"
if ask("=> Want to switch themes now?", ['y', 'n']) == 'y'
system("rake switch_theme name='#{name}'")
end
end
# Public: Package a theme using the theme packager.
# The theme must be structured using valid JB API.
# In other words packaging is essentially the reverse of installing.
#
# name - String, Required name of the theme you want to package.
#
# Examples
#
# rake theme:package name="twitter"
#
# Returns Success/failure messages.
desc "Package theme"
task :package do
name = ENV["name"].to_s.downcase
theme_path = JB::Path.build(:themes, :node => name)
asset_path = JB::Path.build(:theme_assets, :node => name)
abort("rake aborted: name cannot be blank") if name.empty?
abort("rake aborted: '#{theme_path}' directory not found.") unless FileTest.directory?(theme_path)
abort("rake aborted: '#{asset_path}' directory not found.") unless FileTest.directory?(asset_path)
## Mirror theme's template directory (_includes)
packaged_theme_path = JB::Path.build(:themes, :root => JB::Path.build(:theme_packages, :node => name))
mkdir_p packaged_theme_path
cp_r theme_path, packaged_theme_path
## Mirror theme's asset directory
packaged_theme_assets_path = JB::Path.build(:theme_assets, :root => JB::Path.build(:theme_packages, :node => name))
mkdir_p packaged_theme_assets_path
cp_r asset_path, packaged_theme_assets_path
## Log packager version
packager = {"packager" => {"version" => CONFIG["theme_package_version"].to_s } }
open(JB::Path.build(:theme_packages, :node => "#{name}/packager.yml"), "w") do |page|
page.puts packager.to_yaml
end
puts "=> '#{name}' theme is packaged and available at: #{JB::Path.build(:theme_packages, :node => name)}"
end
end # end namespace :theme
# Internal: Download and process a theme from a git url.
# Notice we don't know the name of the theme until we look it up in the manifest.
# So we'll have to change the folder name once we get the name.
#
# url - String, Required url to git repository.
#
# Returns theme manifest hash
def theme_from_git_url(url)
tmp_path = JB::Path.build(:theme_packages, :node => "_tmp")
abort("rake aborted: system call to git clone failed") if !system("git clone #{url} #{tmp_path}")
manifest = verify_manifest(tmp_path)
new_path = JB::Path.build(:theme_packages, :node => manifest["name"])
if File.exist?(new_path) && ask("=> #{new_path} theme package already exists. Override?", ['y', 'n']) == 'n'
remove_dir(tmp_path)
abort("rake aborted: '#{manifest["name"]}' already exists as theme package.")
end
remove_dir(new_path) if File.exist?(new_path)
mv(tmp_path, new_path)
manifest
end
# Internal: Process theme package manifest file.
#
# theme_path - String, Required. File path to theme package.
#
# Returns theme manifest hash
def verify_manifest(theme_path)
manifest_path = File.join(theme_path, "manifest.yml")
manifest_file = File.open( manifest_path )
abort("rake aborted: repo must contain valid manifest.yml") unless File.exist? manifest_file
manifest = YAML.load( manifest_file )
manifest_file.close
manifest
end
def ask(message, valid_options)
if valid_options
answer = get_stdin("#{message} #{valid_options.to_s.gsub(/"/, '').gsub(/, /,'/')} ") while !valid_options.include?(answer)
else
answer = get_stdin(message)
end
answer
end
def get_stdin(message)
print message
STDIN.gets.chomp
end
#Load custom rake scripts
Dir['_rake/*.rake'].each { |r| load r }
# Testing tasks
require 'rake/testtask'
task :test => ['test:unit', 'test:acceptance']
namespace 'test' do
Rake::TestTask.new('unit') do |test|
test.libs << 'test'
test.test_files = FileList['test/test_*.rb']
test.verbose = true
end
desc 'Run acceptance tests'
task :acceptance do
if ENV['SITE_URL'] == nil
if ENV['REMOTE'] == 'true'
file = File.open("CNAME")
ENV['SITE_URL'] = "http://" + file.read.gsub(/\s+/, "")
file.close
else
ENV['SITE_URL'] = 'http://localhost:4000'
end
end
sh "mvn clean test -DsiteUrl=#{ENV['SITE_URL']}"
end
end
namespace 'travis' do
SOURCE_BRANCH = 'dev'
DEPLOY_BRANCH = 'master'
VERSION_URL = 'https://pages.github.com/versions.json'
# install 'json' gem to parse version of Jekyll from Github Pages
sh "gem install json --no-document"
desc 'Setup site on Travis'
task :setup do
require 'net/http'
require 'uri'
require 'json'
if ENV['TRAVIS_BRANCH'] == DEPLOY_BRANCH
ENV['REMOTE'] = 'true'
else
uri = URI.parse(VERSION_URL)
response = Net::HTTP.get_response(uri)
json = JSON.parse(response.body)
jekyllVersion = json["jekyll"]
kramdownVersion = json["kramdown"]
# uninstall all versions of Jekyll
sh "gem uninstall -ax jekyll"
# uninstall all versions of Kramdown
sh "gem uninstall -ax kramdown"
sh "gem install jekyll --version '=" + jekyllVersion + "' --no-document"
sh "gem install kramdown --version '=" + kramdownVersion + "' --no-document"
sh "jekyll -v"
sh "kramdown -v"
sh "jekyll serve --detach"
end
end
desc 'Execute tests on Travis'
task :test => ['test:unit', 'travis:setup', 'test:acceptance']
desc 'Publish site to GitHub Pages from Travis'
task :deploy do
if ENV['TRAVIS_TEST_RESULT'].to_i != 0
puts "Skipping deployment due to test failure"
next
end
if ENV['TRAVIS_PULL_REQUEST'] == "true" or ENV['TRAVIS_BRANCH'] != SOURCE_BRANCH
puts "Skipping deployment from #{ENV['TRAVIS_BRANCH']}"
next
end
repo = %x(git config remote.origin.url).gsub(/^git:/, 'https:')
system "git remote set-url --push origin #{repo}"
system 'git config credential.helper "store --file=.git/credentials"'
File.open('.git/credentials', 'w') do |f|
f.write("https://#{ENV['GH_TOKEN']}:[email protected]")
end
puts "Deploying from #{SOURCE_BRANCH} to #{DEPLOY_BRANCH}"
deployed = system "git push origin #{SOURCE_BRANCH}:#{DEPLOY_BRANCH}"
puts "Deployed: #{deployed}"
File.delete '.git/credentials'
if not deployed
exit 1
end
end
end
# Quick Edmunds API Endpoint generation.
#
# To generate new Endpoint use 'endpoint' rake task
#
# Example
#
# rake endpoint path=api-documentation/vehicle/spec_make/v2/04_test title="Test Endpoint" url=api/v2/vehicle/makes/test
#
# Will generate endpoint articles in <path>:
# api-description.md
# api-parameters.md
# api-response.md
# api-request.md
# with proper headers and template body.
module ApiDocumentation
class Spec
attr_reader :api, :link, :title, :version, :versionAmount
def initialize(api, link, title, version, versionAmount)
@api = api
@link = link
@title = title
@version = version
@versionAmount = versionAmount
end
def to_s
"#{@api} -- #{@link} -- #{@title} -- #{@version} (#{@versionAmount})"
end
end
class Endpoint
attr_reader :spec, :title, :link
def initialize(spec, title, link)
@spec = spec
@title = title
@link = link
end
def to_s
"#{@spec} -- #{@title} -- #{@link}"
end
end
class Article
attr_reader :file, :endpoint, :title, :level, :number, :body
def initialize(file, endpoint, title, level, number, body)
@file = file
@endpoint = endpoint
@title = title
@level = level
@number = number
@body = body
end
def header
"---
layout: api-documentation
title : '#{@endpoint.title}'
title_active_left_menu: '#{@endpoint.spec.title}'
title_parent: Api documentation
amount_version: #{@endpoint.spec.versionAmount}
title-endpoint: '#{@endpoint.title}'
spec: #{@endpoint.spec.link}
version: #{@endpoint.spec.version}
api: #{@endpoint.spec.api}
dropdown-link: '#{@endpoint.link}'
level: #{@level}
description_edpoint: '#{@endpoint.title}'
title_md : #{@title}
number: #{@number}
---
"
end
def to_s
header + @body
end
end
def ApiDocumentation.findSpec(path)
path = File.join(path, 'index.md')
if File.exist? path
file = File.open(path)
content = file.read
file.close
api = /^api\s*:\s*(.+)\n/.match(content)[1]
link = /^spec\s*:\s*(.+)\n/.match(content)[1]
title = /^title\s*:\s*'(.+)'\n/.match(content)[1]
version = /^version\s*:\s*(.+)\n/.match(content)[1]
versionAmount = /^amount_version\s*:\s*(\d+)\n/.match(content)[1]
Spec.new(api, link, title, version, versionAmount)
else
raise "Spec is not found: #{path}"
end
end
def ApiDocumentation.generateEndpoint(path, title, link)
if Dir[File.join(path, '*')].size > 0
raise "Endpoint already exists: #{path}"
end
pathParts = /^(.*)\/(.*)$/.match(path)
spec = findSpec(pathParts[1])
endpoint = Endpoint.new(spec, title, link)
description = Article.new('api-description.md', endpoint, 'Description', 3, 1, "
### Description
### URL
### Code Example
")
parameters = Article.new('api-parameters.md', endpoint, 'Parameters', 4, 2, "
###Parameters
| Parameter | Description | Possible Values | Default Value | Required |
|:-----------|:--------------------------------------|:----------------- |:------------- |:-------- |
| | | | | |
")
response = Article.new('api-response.md', endpoint, 'Response Format', 4, 3, "
###Response format
| Property | Description | Visibility |
|:--------------|:----------------------------------------------------------|:------------------------- |
| | | Edmunds, Partners, Public |
")
request = Article.new('api-request.md', endpoint, 'Sample Request', 4, 4, "
###Sample Request
### URL
### Response
")
if not Dir.exist? path
Dir.mkdir(path)
end
[description, parameters, response, request].each do |article|
file = File.new(File.join(path, article.file), "w+")
file.write article
file.close
end
end
end
desc 'Quick Edmunds API Endpoint generation. Usage: rake endpoint path=<path> title=<title> url=<url>'
task :endpoint do
['path', 'title', 'url'].each do |param|
if not ENV[param] or ENV[param] == ''
puts "The parameter '#{param}' is not defined"
exit 1
end
end
ApiDocumentation.generateEndpoint(ENV['path'], ENV['title'], ENV['url'])
end