Compare commits

..

1 Commits

Author SHA1 Message Date
Parker Moore
2db51e6464 Beginning work on class-based hooks. 2014-06-23 19:35:29 -04:00
393 changed files with 10033 additions and 21369 deletions

View File

@@ -1,29 +0,0 @@
engines:
rubocop: { enabled: true }
fixme: { enabled: false }
exclude_paths:
- .rubocop.yml
- .codeclimate.yml
- .travis.yml
- .gitignore
- .rspec
- Gemfile.lock
- CHANGELOG.{md,markdown,txt,textile}
- CONTRIBUTING.{md,markdown,txt,textile}
- readme.{md,markdown,txt,textile}
- README.{md,markdown,txt,textile}
- Readme.{md,markdown,txt,textile}
- ReadMe.{md,markdown,txt,textile}
- COPYING
- LICENSE
- site/**/*
- test/**/*
- vendor/**/*
- features/**/*
- script/**/*
- spec/**/*
ratings:
paths:
- lib/**/*.rb

View File

@@ -1,122 +0,0 @@
# Contributing to Jekyll
Hi there! Interested in contributing to Jekyll? We'd love your help. Jekyll is an open source project, built one contribution at a time by users like you.
## Where to get help or report a problem
* If you have a question about using Jekyll, start a discussion on [Jekyll Talk](https://talk.jekyllrb.com).
* If you think you've found a bug within a Jekyll plugin, open an issue in that plugin's repository.
* If you think you've found a bug within Jekyll itself, [open an issue](https://github.com/jekyll/jekyll/issues/new).
* More resources are listed on our [Help page](https://jekyllrb.com/help/).
## Ways to contribute
Whether you're a developer, a designer, or just a Jekyll devotee, there are lots of ways to contribute. Here's a few ideas:
* [Install Jekyll on your computer](https://jekyllrb.com/docs/installation/) and kick the tires. Does it work? Does it do what you'd expect? If not, [open an issue](https://github.com/jekyll/jekyll/issues/new) and let us know.
* Comment on some of the project's [open issues](https://github.com/jekyll/jekyll/issues). Have you experienced the same problem? Know a work around? Do you have a suggestion for how the feature could be better?
* Read through [the documentation](https://jekyllrb.com/docs/home/), and click the "improve this page" button, any time you see something confusing, or have a suggestion for something that could be improved.
* Browse through [the Jekyll discussion forum](https://talk.jekyllrb.com/), and lend a hand answering questions. There's a good chance you've already experienced what another user is experiencing.
* Find [an open issue](https://github.com/jekyll/jekyll/issues) (especially [those labeled `help-wanted`](https://github.com/jekyll/jekyll/issues?q=is%3Aopen+is%3Aissue+label%3Ahelp-wanted)), and submit a proposed fix. If it's your first pull request, we promise we won't bite, and are glad to answer any questions.
* Help evaluate [open pull requests](https://github.com/jekyll/jekyll/pulls), by testing the changes locally and reviewing what's proposed.
## Submitting a pull request
### Pull requests generally
* The smaller the proposed change, the better. If you'd like to propose two unrelated changes, submit two pull requests.
* The more information, the better. Make judicious use of the pull request body. Describe what changes were made, why you made them, and what impact they will have for users.
* Pull request are easy and fun. If this is your first pull request, it may help to [understand GitHub Flow](https://guides.github.com/introduction/flow/).
* If you're submitting a code contribution, be sure to read the [code contributions](#code-contributions) section below.
### Submitting a pull request via github.com
Many small changes can be made entirely through the github.com web interface.
1. Navigate to the file within [`jekyll/jekyll`](https://github.com/jekyll/jekyll) that you'd like to edit.
2. Click the pencil icon in the top right corner to edit the file
3. Make your proposed changes
4. Click "Propose file change"
5. Click "Create pull request"
6. Add a descriptive title and detailed description for your proposed change. The more information the better.
7. Click "Create pull request"
That's it! You'll be automatically subscribed to receive updates as others review your proposed change and provide feedback.
### Submitting a pull request via Git command line
1. Fork the project by clicking "Fork" in the top right corner of [`jekyll/jekyll`](https://github.com/jekyll/jekyll).
2. Clone the repository lcoally `git clone https://github.com/<you-username>/jekyll`.
3. Create a new, descriptively named branch to contain your change ( `git checkout -b my-awesome-feature` ).
4. Hack away, add tests. Not necessarily in that order.
5. Make sure everything still passes by running `script/cibuild` (see [the tests section](#running-tests-locally) below)
6. Push the branch up ( `git push origin my-awesome-feature` ).
7. Create a pull request by visiting `https://github.com/<your-username>/jekyll` and following the instructions at the top of the screen.
## Proposing updates to the documentation
We want the Jekyll documentation to be the best it can be. We've open-sourced our docs and we welcome any pull requests if you find it lacking.
### How to submit changes
You can find the documentation for jekyllrb.com in the [site](https://github.com/jekyll/jekyll/tree/master/site) directory. See the section above, [submitting a pull request](#submitting-a-pull-request) for information on how to propose a change.
One gotcha, all pull requests should be directed at the `master` branch (the default branch).
### Adding plugins
If you want to add your plugin to the [list of plugins](https://jekyllrb.com/docs/plugins/#available-plugins), please submit a pull request modifying the [plugins page source file](site/_docs/plugins.md) by adding a link to your plugin under the proper subheading depending upon its type.
## Code Contributions
Interesting in submitting a pull request? Awesome. Read on. There's a few common gotchas that we'd love to help you avoid.
### Tests and documentation
Any time you propose a code change, you should also include updates to the documentation and tests within the same pull request.
#### Documentation
If your contribution changes any Jekyll behavior, make sure to update the documentation. Documentation lives in the `site/_docs` folder (spoiler alert: it's a Jekyll site!). If the docs are missing information, please feel free to add it in. Great docs make a great project. Include changes to the documentation within your pull request, and once merged, `jekyllrb.com` will be updated.
#### Tests
* If you're creating a small fix or patch to an existing feature, a simple test is more than enough. You can usually copy/paste from an existing example in the `tests` folder, but if you need you can find out about our tests suites [Shoulda](https://github.com/thoughtbot/shoulda/tree/master) and [RSpec-Mocks](https://github.com/rspec/rspec-mocks).
* If it's a brand new feature, create a new [Cucumber](https://github.com/cucumber/cucumber/) feature, reusing existing steps where appropriate.
### Code contributions generally
* Jekyll follows the [GitHub Ruby Styleguide](https://github.com/styleguide/ruby).
* Don't bump the Gem version in your pull request (if you don't know what that means, you probably didn't).
## Running tests locally
### Test Dependencies
To run the test suite and build the gem you'll need to install Jekyll's dependencies by running the following command:
<pre class="highlight"><code>$ script/bootstrap</code></pre>
Before you make any changes, run the tests and make sure that they pass (to confirm your environment is configured properly):
<pre class="highlight"><code>$ script/cibuild</code></pre>
If you are only updating a file in `test/`, you can use the command:
<pre class="highlight"><code>$ script/test test/blah_test.rb</code></pre>
If you are only updating a `.feature` file, you can use the command:
<pre class="highlight"><code>$ script/cucumber features/blah.feature</code></pre>
Both `script/test` and `script/cucumber` can be run without arguments to
run its entire respective suite.
## A thank you
Thanks! Hacking on Jekyll should be fun. If you find any of this hard to figure out, let us know so we can improve our process or documentation!

View File

@@ -1,20 +0,0 @@
###### What version of Jekyll are you using (`jekyll -v`)?
###### What operating system are you using?
###### What did you do?
(Please include the content causing the issue, any relevant configuration settings, and the command you ran)
###### What did you expect to see?
###### What did you see instead?

25
.gitignore vendored
View File

@@ -1,22 +1,15 @@
Gemfile.lock
test/dest
*.gem
pkg/
*.swp
*~
.DS_Store
.analysis
_site/
.bundle/
.byebug_history
.jekyll-metadata
.ruby-gemset
.DS_Store
bbin/
gh-pages/
site/_site/
coverage
.ruby-version
.sass-cache
/test/source/file_name.txt
/vendor
Gemfile.lock
_site/
bbin/
coverage
gh-pages/
pkg/
site/_site/
test/dest
tmp/*

View File

@@ -1,3 +0,0 @@
backtrace.mask=true
backtrace.color=true
backtrace.style=mri

View File

@@ -1,80 +0,0 @@
Metrics/MethodLength: { Max: 24 }
Metrics/ClassLength: { Max: 240 }
Metrics/ModuleLength: { Max: 240 }
Metrics/LineLength: { Max: 112 }
Metrics/CyclomaticComplexity: { Max: 8 }
Metrics/PerceivedComplexity: { Max: 8 }
Metrics/ParameterLists: { Max: 4 }
Metrics/MethodLength: { Max: 24 }
Metrics/AbcSize: { Max: 20 }
Style/IndentHash: { EnforcedStyle: consistent }
Style/HashSyntax: { EnforcedStyle: hash_rockets }
Style/SignalException: { EnforcedStyle: only_raise }
Style/AlignParameters: { EnforcedStyle: with_fixed_indentation }
Style/StringLiteralsInInterpolation: { EnforcedStyle: double_quotes }
Style/MultilineMethodCallIndentation: { EnforcedStyle: indented }
Style/MultilineOperationIndentation: { EnforcedStyle: indented }
Style/FirstParameterIndentation: { EnforcedStyle: consistent }
Style/StringLiterals: { EnforcedStyle: double_quotes }
Style/RegexpLiteral: { EnforcedStyle: slashes }
Style/IndentArray: { EnforcedStyle: consistent }
Style/ExtraSpacing: { AllowForAlignment: true }
Style/PercentLiteralDelimiters:
PreferredDelimiters:
'%q': '{}'
'%Q': '{}'
'%r': '!!'
'%s': '()'
'%w': '()'
'%W': '()'
'%x': '()'
Style/AlignArray: { Enabled: false }
Style/StringLiterals: { Enabled: false }
Style/Documentation: { Enabled: false }
Style/DoubleNegation: { Enabled: false }
Style/UnneededCapitalW: { Enabled: false }
Style/EmptyLinesAroundModuleBody: { Enabled: false }
Style/EmptyLinesAroundAccessModifier: { Enabled: false }
Style/BracesAroundHashParameters: { Enabled: false }
Style/SpaceInsideBrackets: { Enabled: false }
Style/IfUnlessModifier: { Enabled: false }
Style/ModuleFunction: { Enabled: false }
Style/RescueModifier: { Enabled: false }
Style/GuardClause: { Enabled: false }
Style/FileName: { Enabled: false }
Lint/UselessAccessModifier: { Enabled: false }
Style/SpaceAroundOperators: { Enabled: false }
Style/RedundantReturn: { Enabled: false }
Style/SingleLineMethods: { Enabled: false }
AllCops:
TargetRubyVersion: 2.0
Include:
- lib/**/*.rb
Exclude:
- .rubocop.yml
- .codeclimate.yml
- .travis.yml
- .gitignore
- .rspec
- Gemfile.lock
- CHANGELOG.{md,markdown,txt,textile}
- CONTRIBUTING.{md,markdown,txt,textile}
- readme.{md,markdown,txt,textile}
- README.{md,markdown,txt,textile}
- Readme.{md,markdown,txt,textile}
- ReadMe.{md,markdown,txt,textile}
- COPYING
- LICENSE
- site/**/*
- test/**/*
- vendor/**/*
- features/**/*
- script/**/*
- spec/**/*

View File

@@ -1,52 +1,27 @@
before_script: bundle update
bundler_args: --without benchmark:site:development
script: script/cibuild
cache: bundler
language: ruby
sudo: false
cache: bundler
install:
- script/rebund download
- travis_retry bundle install --path vendor/bundle
rvm:
- &ruby1 2.3.0
- &ruby2 2.2.4
- &ruby3 2.1.8
- &jruby jruby-9.0.4.0
- &rhead ruby-head
matrix:
fast_finish: true
allow_failures:
- rvm: *jruby
- rvm: *rhead
env:
matrix:
- TEST_SUITE=test
- TEST_SUITE=cucumber
branches:
only:
- master
- 2.1
- 2.0
- 1.9.3
script: script/cibuild
after_script:
- script/rebund upload
notifications:
irc:
template: "%{repository}#%{build_number} (%{branch}) %{message} %{build_url}"
channels: irc.freenode.org#jekyll
on_success: change
on_failure: change
channels:
- irc.freenode.org#jekyll
template:
- '%{repository}#%{build_number} (%{branch}) %{message} %{build_url}'
email:
recipients:
- jordon@envygeeks.io
slack:
secure: "\
dNdKk6nahNURIUbO3ULhA09/vTEQjK0fNbgjVjeYPEvROHgQBP1cIP3AJy8aWs8rl5Yyow4Y\
GEilNRzKPz18AsFptVXofpwyqcBxaCfmHP809NX5PHBaadydveLm+TNVao2XeLXSWu+HUNAY\
O1AanCUbJSEyJTju347xCBGzESU=\
"
addons:
code_climate:
repo_token:
secure: "\
mAuvDu+nrzB8dOaLqsublDGt423mGRyZYM3vsrXh4Tf1sT+L1PxsRzU4gLmcV27HtX2Oq9\
DA4vsRURfABU0fIhwYkQuZqEcA3d8TL36BZcGEshG6MQ2AmnYsmFiTcxqV5bmlElHEqQuT\
5SUFXLafgZPBnL0qDwujQcHukID41sE=\
"
on_success: never
on_failure: never
env:
global:
- secure: bt5nglPTdsc0N5fB1dOJz2WbM81dGpDuVD8PnhEsxgUfoo6xavhU4+pNrUADlSUqQ1aJrdU+MKW4x+JZ2ZnJS8vOpNzRymuMZSbFaljK4pgFGiKFgBdMKxVikvoYcxKCjLAl7NJZ11W6hUw+JtJScClDZwrJJAQB6I7Isp/LsdM=
- secure: Ym8nx7nbfGYGo47my92M+deJykaiMkdZdb615EO51liv/xy/0aQ919Jpfieugc9d3zVnm+zFGPbpv4YzRpsik6OlVBNa4lP+BnQ27ptf5YcLWD8Hksi7845WFLecXMoaTCoYer/TvYZsIWJb2nSDMH9qbfZhnd1YZKuvUpK0rEU=

View File

@@ -1,49 +0,0 @@
# Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by opening an issue or contacting a project maintainer. All complaints
will be reviewed and investigated and will result in a response that is deemed
necessary and appropriate to the circumstances. Maintainers are obligated to
maintain confidentiality with regard to the reporter of an incident.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/3/0/

91
CONTRIBUTING.markdown Normal file
View File

@@ -0,0 +1,91 @@
Contribute
==========
So you've got an awesome idea to throw into Jekyll. Great! Please keep the
following in mind:
* **Contributions will not be accepted without tests or necessary documentation updates.**
* If you're creating a small fix or patch to an existing feature, just a simple
test will do. Please stay in the confines of the current test suite and use
[Shoulda](https://github.com/thoughtbot/shoulda/tree/master) and
[RR](https://github.com/rr/rr).
* If it's a brand new feature, make sure to create a new
[Cucumber](https://github.com/cucumber/cucumber/) feature and reuse steps
where appropriate. Also, whipping up some documentation in your fork's `site`
would be appreciated, and once merged it will be transferred over to the main
`site`, jekyllrb.com.
* If your contribution changes any Jekyll behavior, make sure to update the
documentation. It lives in `site/docs`. If the docs are missing information,
please feel free to add it in. Great docs make a great project!
* Please follow the [GitHub Ruby Styleguide](https://github.com/styleguide/ruby)
when modifying Ruby code.
* Please do your best to submit **small pull requests**. The easier the proposed
change is to review, the more likely it will be merged.
* When submitting a pull request, please make judicious use of the pull request
body. A description of what changes were made, the motivations behind the
changes and [any tasks completed or left to complete](http://git.io/gfm-tasks)
will also speed up review time.
Test Dependencies
-----------------
To run the test suite and build the gem you'll need to install Jekyll's
dependencies. Jekyll uses Bundler, so a quick run of the bundle command and
you're all set!
$ bundle
Before you start, run the tests and make sure that they pass (to confirm your
environment is configured properly):
$ bundle exec rake test
$ bundle exec rake features
Workflow
--------
Here's the most direct way to get your work merged into the project:
* Fork the project.
* Clone down your fork ( `git clone git@github.com:<username>/jekyll.git` ).
* Create a topic branch to contain your change ( `git checkout -b my_awesome_feature` ).
* Hack away, add tests. Not necessarily in that order.
* Make sure everything still passes by running `rake`.
* If necessary, rebase your commits into logical chunks, without errors.
* Push the branch up ( `git push origin my_awesome_feature` ).
* Create a pull request against jekyll/jekyll and describe what your change
does and the why you think it should be merged.
Updating Documentation
----------------------
We want the Jekyll documentation to be the best it can be. We've
open-sourced our docs and we welcome any pull requests if you find it
lacking.
You can find the documentation for jekyllrb.com in the
[site](https://github.com/jekyll/jekyll/tree/master/site) directory of
Jekyll's repo on GitHub.com.
All documentation pull requests should be directed at `master`. Pull
requests directed at another branch will not be accepted.
The [Jekyll wiki](https://github.com/jekyll/jekyll/wiki) on GitHub
can be freely updated without a pull request as all GitHub users have access.
Gotchas
-------
* If you want to bump the gem version, please put that in a separate commit.
This way, the maintainers can control when the gem gets released.
* Try to keep your patch(es) based from the latest commit on jekyll/jekyll.
The easier it is to apply your work, the less work the maintainers have to do,
which is always a good thing.
* Please don't tag your GitHub issue with [fix], [feature], etc. The maintainers
actively read the issues and will label it once they come across it.
Finally...
----------
Thanks! Hacking on Jekyll should be fun. If you find any of this hard to figure
out, let us know so we can improve our process or documentation!

90
Gemfile
View File

@@ -1,88 +1,2 @@
source "https://rubygems.org"
gemspec :name => "jekyll"
gem "rake", "~> 11.0"
group :development do
gem "launchy", "~> 2.3"
gem "rubocop", :branch => :master, :github => "bbatsov/rubocop"
gem "pry"
unless RUBY_ENGINE == "jruby"
gem "pry-byebug"
end
end
#
group :test do
gem "cucumber", "~> 2.1"
gem "jekyll_test_plugin"
gem "jekyll_test_plugin_malicious"
gem "codeclimate-test-reporter"
gem "rspec-mocks"
gem "nokogiri"
gem "rspec"
end
#
group :test_legacy do
if RUBY_PLATFORM =~ /cygwin/ || RUBY_VERSION.start_with?("2.2")
gem 'test-unit'
end
gem "redgreen"
gem "simplecov"
gem "minitest-reporters"
gem "minitest-profile"
gem "minitest"
gem "shoulda"
end
#
group :benchmark do
if ENV["BENCHMARK"]
gem "ruby-prof"
gem "benchmark-ips"
gem "stackprof"
gem "rbtrace"
end
end
#
group :jekyll_optional_dependencies do
gem "toml", "~> 0.1.0"
gem "coderay", "~> 1.1.0"
gem "jekyll-docs", :path => '../docs' if Dir.exist?('../docs') && ENV['JEKYLL_VERSION']
gem "jekyll-gist", "~> 1.0"
gem "jekyll-feed", "~> 0.1.3"
gem "jekyll-coffeescript", "~> 1.0"
gem "jekyll-redirect-from", "~> 0.9.1"
gem "jekyll-paginate", "~> 1.0"
gem "mime-types", "~> 3.0"
gem "kramdown", "~> 1.9"
gem "rdoc", "~> 4.2"
platform :ruby, :mswin, :mingw do
gem "rdiscount", "~> 2.0"
gem "pygments.rb", "~> 0.6.0"
gem "redcarpet", "~> 3.2", ">= 3.2.3"
gem "classifier-reborn", "~> 2.0"
gem "liquid-c", "~> 3.0"
end
end
#
group :site do
if ENV["PROOF"]
gem "html-proofer", "~> 2.0"
end
gem "jemoji", "0.5.1"
gem "jekyll-sitemap"
gem "jekyll-seo-tag", "~> 1.1"
gem "jekyll-avatar"
end
source 'https://rubygems.org'
gemspec

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,9 @@
The MIT License (MIT)
(The MIT License)
Copyright (c) 2008-2016 Tom Preston-Werner
Copyright (c) 2008-2014 Tom Preston-Werner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
@@ -12,7 +12,7 @@ furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

View File

@@ -1,58 +1,35 @@
# [Jekyll](https://jekyllrb.com/)
# [Jekyll](http://jekyllrb.com/)
[![Gem Version](https://img.shields.io/gem/v/jekyll.svg)][ruby-gems]
[![Build Status](https://travis-ci.org/jekyll/jekyll.svg?branch=master)][travis]
[![Test Coverage](https://codeclimate.com/github/jekyll/jekyll/badges/coverage.svg)][coverage]
[![Code Climate](https://codeclimate.com/github/jekyll/jekyll/badges/gpa.svg)][codeclimate]
[![Dependency Status](https://gemnasium.com/jekyll/jekyll.svg)][gemnasium]
[![Security](https://hakiri.io/github/jekyll/jekyll/master.svg)][hakiri]
[![Gem Version](https://badge.fury.io/rb/jekyll.svg)](https://rubygems.org/gems/jekyll)
[![Build Status](https://secure.travis-ci.org/jekyll/jekyll.svg?branch=master)](https://travis-ci.org/jekyll/jekyll)
[![Code Climate](http://img.shields.io/codeclimate/github/jekyll/jekyll.svg)](https://codeclimate.com/github/jekyll/jekyll)
[![Dependency Status](https://gemnasium.com/jekyll/jekyll.svg)](https://gemnasium.com/jekyll/jekyll)
[ruby-gems]: https://rubygems.org/gems/jekyll
[gemnasium]: https://gemnasium.com/jekyll/jekyll
[codeclimate]: https://codeclimate.com/github/jekyll/jekyll
[coverage]: https://codeclimate.com/github/jekyll/jekyll/coverage
[hakiri]: https://hakiri.io/github/jekyll/jekyll/master
[travis]: https://travis-ci.org/jekyll/jekyll
By Tom Preston-Werner, Nick Quaranto, and many [awesome contributors](https://github.com/jekyll/jekyll/graphs/contributors)!
Jekyll is a simple, blog-aware, static site generator perfect for personal, project, or organization sites. Think of it like a file-based CMS, without all the complexity. Jekyll takes your content, renders Markdown and Liquid templates, and spits out a complete, static website ready to be served by Apache, Nginx or another web server. Jekyll is the engine behind [GitHub Pages](https://pages.github.com), which you can use to host sites right from your GitHub repositories.
Jekyll is a simple, blog-aware, static site generator perfect for personal, project, or organization sites. Think of it like a file-based CMS, without all the complexity. Jekyll takes your content, renders Markdown and Liquid templates, and spits out a complete, static website ready to be served by Apache, Nginx or another web server. Jekyll is the engine behind [GitHub Pages](http://pages.github.com), which you can use to host sites right from your GitHub repositories.
## Philosophy
Jekyll does what you tell it to do — no more, no less. It doesn't try to outsmart users by making bold assumptions, nor does it burden them with needless complexity and configuration. Put simply, Jekyll gets out of your way and allows you to concentrate on what truly matters: your content.
## Having trouble with OS X El Capitan?
See: https://jekyllrb.com/docs/troubleshooting/#jekyll-amp-mac-os-x-1011
## Getting Started
* [Install](https://jekyllrb.com/docs/installation/) the gem
* Read up about its [Usage](https://jekyllrb.com/docs/usage/) and [Configuration](https://jekyllrb.com/docs/configuration/)
* [Install](http://jekyllrb.com/docs/installation/) the gem
* Read up about its [Usage](http://jekyllrb.com/docs/usage/) and [Configuration](http://jekyllrb.com/docs/configuration/)
* Take a gander at some existing [Sites](https://wiki.github.com/jekyll/jekyll/sites)
* [Fork](https://github.com/jekyll/jekyll/fork) and [Contribute](https://jekyllrb.com/docs/contributing/) your own modifications
* Have questions? Check out our official forum community [Jekyll Talk](https://talk.jekyllrb.com/) or [`#jekyll` on irc.freenode.net](https://botbot.me/freenode/jekyll/)
## Code of Conduct
In order to have a more open and welcoming community, Jekyll adheres to a
[code of conduct](CONDUCT.markdown) adapted from the Ruby on Rails code of
conduct.
Please adhere to this code of conduct in any interactions you have in the
Jekyll community. It is strictly enforced on all official Jekyll
repositories, websites, and resources. If you encounter someone violating
these terms, please let a maintainer ([@parkr](https://github.com/parkr), [@envygeeks](https://github.com/envygeeks), or [@mattr-](https://github.com/mattr-)) know
and we will address it as soon as possible.
* Fork and [Contribute](http://jekyllrb.com/docs/contributing/) your own modifications
* Have questions? Check out [`#jekyll` on irc.freenode.net](https://botbot.me/freenode/jekyll/).
## Diving In
* [Migrate](http://import.jekyllrb.com/docs/home/) from your previous system
* Learn how the [YAML Front Matter](https://jekyllrb.com/docs/frontmatter/) works
* Put information on your site with [Variables](https://jekyllrb.com/docs/variables/)
* Customize the [Permalinks](https://jekyllrb.com/docs/permalinks/) your posts are generated with
* Use the built-in [Liquid Extensions](https://jekyllrb.com/docs/templates/) to make your life easier
* Use custom [Plugins](https://jekyllrb.com/docs/plugins/) to generate content specific to your site
* Learn how the [YAML Front Matter](http://jekyllrb.com/docs/frontmatter/) works
* Put information on your site with [Variables](http://jekyllrb.com/docs/variables/)
* Customize the [Permalinks](http://jekyllrb.com/docs/permalinks/) your posts are generated with
* Use the built-in [Liquid Extensions](http://jekyllrb.com/docs/templates/) to make your life easier
* Use custom [Plugins](http://jekyllrb.com/docs/plugins/) to generate content specific to your site
## License
See the [LICENSE](https://github.com/jekyll/jekyll/blob/master/LICENSE) file.
See [LICENSE](https://github.com/jekyll/jekyll/blob/master/LICENSE).

203
Rakefile
View File

@@ -7,8 +7,6 @@ require 'yaml'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), *%w[lib]))
require 'jekyll/version'
Dir.glob('rake/**.rake').each { |f| import f }
#############################################################################
#
# Helper functions
@@ -16,23 +14,19 @@ Dir.glob('rake/**.rake').each { |f| import f }
#############################################################################
def name
"jekyll"
@name ||= Dir['*.gemspec'].first.split('.').first
end
def version
Jekyll::VERSION
end
def docs_name
"#{name}-docs"
end
def gemspec_file
"#{name}.gemspec"
end
def gem_file
"#{name}-#{Gem::Version.new(version).to_s}.gem"
"#{name}-#{version}.gem"
end
def normalize_bullets(markdown)
@@ -59,60 +53,13 @@ def liquid_escape(markdown)
markdown.gsub(/(`{[{%].+[}%]}`)/, "{% raw %}\\1{% endraw %}")
end
def custom_release_header_anchors(markdown)
header_regexp = /^(\d{1,2})\.(\d{1,2})\.(\d{1,2}) \/ \d{4}-\d{2}-\d{2}/
section_regexp = /^### \w+ \w+$/
markdown.split(/^##\s/).map do |release_notes|
_, major, minor, patch = *release_notes.match(header_regexp)
release_notes
.gsub(header_regexp, "\\0\n{: #v\\1-\\2-\\3}")
.gsub(section_regexp) { |section| "#{section}\n{: ##{sluffigy(section)}-v#{major}-#{minor}-#{patch}}" }
end.join("\n## ")
end
def sluffigy(header)
header.gsub(/#/, '').strip.downcase.gsub(/\s+/, '-')
end
def remove_head_from_history(markdown)
index = markdown =~ /^##\s+\d+\.\d+\.\d+/
markdown[index..-1]
end
def converted_history(markdown)
remove_head_from_history(
custom_release_header_anchors(
liquid_escape(
linkify(
normalize_bullets(markdown)))))
end
def siteify_file(file, overrides_front_matter = {})
abort "You seem to have misplaced your #{file} file. I can haz?" unless File.exists?(file)
title = begin
File.read(file).match(/\A# (.*)$/)[1]
rescue
File.basename(file, ".*").downcase.capitalize
end
slug = File.basename(file, ".markdown").downcase
front_matter = {
"title" => title,
"layout" => "docs",
"permalink" => "/docs/#{slug}/",
"note" => "This file is autogenerated. Edit /#{file} instead."
}.merge(overrides_front_matter)
contents = "#{front_matter.to_yaml}---\n\n#{content_for(file)}"
File.write("site/_docs/#{slug}.md", contents)
end
def content_for(file)
contents = File.read(file)
case file
when "History.markdown"
converted_history(contents)
else
contents.gsub(/\A# .*\n\n?/, "")
end
remove_head_from_history(liquid_escape(linkify(normalize_bullets(markdown))))
end
#############################################################################
@@ -121,9 +68,8 @@ end
#
#############################################################################
multitask :default => [:test, :features]
task :default => [:test, :features]
task :spec => :test
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
@@ -158,3 +104,144 @@ desc "Open an irb session preloaded with this library"
task :console do
sh "irb -rubygems -r ./lib/#{name}.rb"
end
#############################################################################
#
# Site tasks - http://jekyllrb.com
#
#############################################################################
namespace :site do
desc "Generate and view the site locally"
task :preview do
require "launchy"
# Yep, it's a hack! Wait a few seconds for the Jekyll site to generate and
# then open it in a browser. Someday we can do better than this, I hope.
Thread.new do
sleep 4
puts "Opening in browser..."
Launchy.open("http://localhost:4000")
end
# Generate the site in server mode.
puts "Running Jekyll..."
Dir.chdir("site") do
sh "#{File.expand_path('bin/jekyll', File.dirname(__FILE__))} serve --watch"
end
end
desc "Update normalize.css library to the latest version and minify"
task :update_normalize_css do
Dir.chdir("site/_includes/css") do
sh 'curl "http://necolas.github.io/normalize.css/latest/normalize.css" -o "normalize.scss"'
sh 'sass "normalize.scss":"normalize.css" --style compressed'
sh 'rm "normalize.scss"'
end
end
desc "Commit the local site to the gh-pages branch and publish to GitHub Pages"
task :publish => [:history] do
# Ensure the gh-pages dir exists so we can generate into it.
puts "Checking for gh-pages dir..."
unless File.exist?("./gh-pages")
puts "No gh-pages directory found. Run the following commands first:"
puts " `git clone git@github.com:jekyll/jekyll gh-pages"
puts " `cd gh-pages"
puts " `git checkout gh-pages`"
exit(1)
end
# Ensure gh-pages branch is up to date.
Dir.chdir('gh-pages') do
sh "git pull origin gh-pages"
end
# Copy to gh-pages dir.
puts "Copying site to gh-pages branch..."
Dir.glob("site/*") do |path|
next if path.include? "_site"
sh "cp -R #{path} gh-pages/"
end
# Commit and push.
puts "Committing and pushing to GitHub Pages..."
sha = `git log`.match(/[a-z0-9]{40}/)[0]
Dir.chdir('gh-pages') do
sh "git add ."
sh "git commit --allow-empty -m 'Updating to #{sha}.'"
sh "git push origin gh-pages"
end
puts 'Done.'
end
desc "Create a nicely formatted history page for the jekyll site based on the repo history."
task :history do
if File.exist?("History.markdown")
history_file = File.read("History.markdown")
front_matter = {
"layout" => "docs",
"title" => "History",
"permalink" => "/docs/history/",
"prev_section" => "contributing"
}
Dir.chdir('site/docs/') do
File.open("history.md", "w") do |file|
file.write("#{front_matter.to_yaml}---\n\n")
file.write(converted_history(history_file))
end
end
else
abort "You seem to have misplaced your History.markdown file. I can haz?"
end
end
namespace :releases do
desc "Create new release post"
task :new, :version do |t, args|
raise "Specify a version: rake site:releases:new['1.2.3']" unless args.version
today = Time.new.strftime('%Y-%m-%d')
release = args.version.to_s
filename = "site/_posts/#{today}-jekyll-#{release.split('.').join('-')}-released.markdown"
File.open(filename, "wb") do |post|
post.puts("---")
post.puts("layout: news_item")
post.puts("title: 'Jekyll #{release} Released'")
post.puts("date: #{Time.new.strftime('%Y-%m-%d %H:%M:%S %z')}")
post.puts("author: ")
post.puts("version: #{release}")
post.puts("categories: [release]")
post.puts("---")
post.puts
post.puts
end
puts "Created #{filename}"
end
end
end
#############################################################################
#
# Packaging tasks
#
#############################################################################
task :release => :build do
unless `git branch` =~ /^\* master$/
puts "You must be on the master branch to release!"
exit!
end
sh "git commit --allow-empty -m 'Release #{version}'"
sh "git tag v#{version}"
sh "git push origin master"
sh "git push origin v#{version}"
sh "gem push pkg/#{name}-#{version}.gem"
end
task :build do
mkdir_p "pkg"
sh "gem build #{gemspec_file}"
sh "mv #{gem_file} pkg"
end

View File

@@ -1,15 +0,0 @@
require 'benchmark/ips'
Benchmark.ips do |x|
path_without_ending_slash = '/some/very/very/long/path/to/a/file/i/like'
x.report('no slash regexp') { path_without_ending_slash =~ /\/$/ }
x.report('no slash end_with?') { path_without_ending_slash.end_with?("/") }
x.report('no slash [-1, 1]') { path_without_ending_slash[-1, 1] == "/" }
end
Benchmark.ips do |x|
path_with_ending_slash = '/some/very/very/long/path/to/a/file/i/like/'
x.report('slash regexp') { path_with_ending_slash =~ /\/$/ }
x.report('slash end_with?') { path_with_ending_slash.end_with?("/") }
x.report('slash [-1, 1]') { path_with_ending_slash[-1, 1] == "/" }
end

View File

@@ -1,54 +0,0 @@
#!/usr/bin/env ruby
require 'benchmark/ips'
# For this pull request, which changes Page#dir
# https://github.com/jekyll/jekyll/pull/4403
FORWARD_SLASH = '/'.freeze
def pre_pr(url)
url[-1, 1] == FORWARD_SLASH ? url : File.dirname(url)
end
def pr(url)
if url.end_with?(FORWARD_SLASH)
url
else
url_dir = File.dirname(url)
url_dir.end_with?(FORWARD_SLASH) ? url_dir : "#{url_dir}/"
end
end
def envygeeks(url)
return url if url.end_with?(FORWARD_SLASH) || url == FORWARD_SLASH
url = File.dirname(url)
url == FORWARD_SLASH ? url : "#{url}/"
end
# Just a slash
Benchmark.ips do |x|
path = '/'
x.report("pre_pr:#{path}") { pre_pr(path) }
x.report("pr:#{path}") { pr(path) }
x.report("envygeeks:#{path}") { pr(path) }
x.compare!
end
# No trailing slash
Benchmark.ips do |x|
path = '/some/very/very/long/path/to/a/file/i/like'
x.report("pre_pr:#{path}") { pre_pr(path) }
x.report("pr:#{path}") { pr(path) }
x.report("envygeeks:#{path}") { pr(path) }
x.compare!
end
# No trailing slash
Benchmark.ips do |x|
path = '/some/very/very/long/path/to/a/file/i/like/'
x.report("pre_pr:#{path}") { pre_pr(path) }
x.report("pr:#{path}") { pr(path) }
x.report("envygeeks:#{path}") { pr(path) }
x.compare!
end

View File

@@ -1,16 +0,0 @@
require 'benchmark/ips'
enum = (0..50).to_a
nested = enum.map { |i| [i] }
def do_thing(blah)
blah * 1
end
Benchmark.ips do |x|
x.report('.map.flatten with nested arrays') { nested.map { |i| do_thing(i) }.flatten(1) }
x.report('.flat_map with nested arrays') { nested.flat_map { |i| do_thing(i) } }
x.report('.map.flatten with no nested arrays') { enum.map { |i| do_thing(i) }.flatten(1) }
x.report('.flat_map with no nested arrays') { enum.flat_map { |i| do_thing(i) } }
end

View File

@@ -1,9 +0,0 @@
require 'benchmark/ips'
h = {:bar => 'uco'}
Benchmark.ips do |x|
x.report('fetch with no block') { h.fetch(:bar, (0..9).to_a) }
x.report('fetch with a block') { h.fetch(:bar) { (0..9).to_a } }
x.report('brackets with an ||') { h[:bar] || (0..9).to_a }
end

View File

@@ -1,46 +0,0 @@
#!/usr/bin/env ruby
require_relative '../lib/jekyll'
require 'benchmark/ips'
base_directory = Dir.pwd
Benchmark.ips do |x|
#
# Does not include the base_directory
#
x.report('with no questionable path') do
Jekyll.sanitized_path(base_directory, '')
end
x.report('with a single-part questionable path') do
Jekyll.sanitized_path(base_directory, 'thingy')
end
x.report('with a multi-part questionable path') do
Jekyll.sanitized_path(base_directory, 'thingy/in/my/soup')
end
x.report('with a single-part traversal path') do
Jekyll.sanitized_path(base_directory, '../thingy')
end
x.report('with a multi-part traversal path') do
Jekyll.sanitized_path(base_directory, '../thingy/in/my/../../soup')
end
#
# Including the base_directory
#
x.report('with the exact same paths') do
Jekyll.sanitized_path(base_directory, base_directory)
end
x.report('with a single-part absolute path including the base_directory') do
Jekyll.sanitized_path(base_directory, File.join(base_directory, 'thingy'))
end
x.report('with a multi-part absolute path including the base_directory') do
Jekyll.sanitized_path(base_directory, File.join(base_directory, 'thingy/in/my/soup'))
end
x.report('with a single-part traversal path including the base_directory') do
Jekyll.sanitized_path(base_directory, File.join(base_directory, 'thingy/..'))
end
x.report('with a multi-part traversal path including the base_directory') do
Jekyll.sanitized_path(base_directory, File.join('thingy/in/my/../../soup'))
end
end

View File

@@ -1,14 +0,0 @@
require 'benchmark/ips'
def fast
yield
end
def slow(&block)
block.call
end
Benchmark.ips do |x|
x.report('yield') { fast { (0..9).to_a } }
x.report('block.call') { slow { (0..9).to_a } }
end

View File

@@ -1,51 +0,0 @@
#!/usr/bin/env ruby
require 'benchmark/ips'
# For this pull request, which changes Page#dir
# https://github.com/jekyll/jekyll/pull/4403
CONTENT_CONTAINING = <<-HTML.freeze
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Jemoji</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="/css/screen.css">
</head>
<body class="wrap">
<p><img class="emoji" title=":+1:" alt=":+1:" src="https://assets.github.com/images/icons/emoji/unicode/1f44d.png" height="20" width="20" align="absmiddle"></p>
</body>
</html>
HTML
CONTENT_NOT_CONTAINING = <<-HTML.freeze
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Jemoji</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="/css/screen.css">
</head>
<body class="wrap">
<p><img class="emoji" title=":+1:" alt=":+1:" src="https://assets.github.com/images/icons/emoji/unicode/1f44d.png" height="20" width="20" align="absmiddle"></p>
</body>
</html>
HTML
Benchmark.ips do |x|
x.report("no body include?") { CONTENT_NOT_CONTAINING.include?('<body') }
x.report("no body regexp") { CONTENT_NOT_CONTAINING =~ /<\s*body/ }
x.compare!
end
# No trailing slash
Benchmark.ips do |x|
x.report("with body include?") { CONTENT_CONTAINING.include?('<body') }
x.report("with body regexp") { CONTENT_CONTAINING =~ /<\s*body/ }
x.compare!
end

View File

@@ -1,11 +0,0 @@
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('parallel assignment') do
a, b = 1, 2
end
x.report('multi-line assignment') do
a = 1
b = 2
end
end

View File

@@ -1,8 +0,0 @@
require 'benchmark/ips'
url = "http://jekyllrb.com"
Benchmark.ips do |x|
x.report('+=') { url += '/' }
x.report('<<') { url << '/' }
end

View File

@@ -1,13 +0,0 @@
require 'benchmark/ips'
def str
'http://baruco.org/2014/some-talk-with-some-amount-of-value'
end
Benchmark.ips do |x|
x.report('#tr') { str.tr('some', 'a') }
x.report('#gsub') { str.gsub('some', 'a') }
x.report('#gsub!') { str.gsub!('some', 'a') }
x.report('#sub') { str.sub('some', 'a') }
x.report('#sub!') { str.sub!('some', 'a') }
end

View File

@@ -1,6 +0,0 @@
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('block') { (1..100).map { |i| i.to_s } }
x.report('&:to_s') { (1..100).map(&:to_s) }
end

View File

@@ -1,12 +1,17 @@
#!/usr/bin/env ruby
STDOUT.sync = true
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), *%w( .. lib ))
$:.unshift File.join(File.dirname(__FILE__), *%w{ .. lib })
require 'jekyll'
require 'mercenary'
Jekyll::PluginManager.require_from_bundler
%w[jekyll-import].each do |blessed_gem|
begin
require blessed_gem
rescue LoadError
end
end
Jekyll::Deprecator.process(ARGV)
@@ -18,33 +23,17 @@ Mercenary.program(:jekyll) do |p|
p.option 'source', '-s', '--source [DIR]', 'Source directory (defaults to ./)'
p.option 'destination', '-d', '--destination [DIR]', 'Destination directory (defaults to ./_site)'
p.option 'safe', '--safe', 'Safe mode (defaults to false)'
p.option 'plugins_dir', '-p', '--plugins PLUGINS_DIR1[,PLUGINS_DIR2[,...]]', Array, 'Plugins directory (defaults to ./_plugins)'
p.option 'layouts_dir', '--layouts DIR', String, 'Layouts directory (defaults to ./_layouts)'
p.option 'profile', '--profile', 'Generate a Liquid rendering profile'
Jekyll::External.require_if_present(Jekyll::External.blessed_gems) do |g|
cmd = g.split('-').last
p.command(cmd.to_sym) do |c|
c.syntax cmd
c.action do
Jekyll.logger.abort_with "You must install the '#{g}' gem to use the 'jekyll #{cmd}' command."
end
end
end
p.option 'plugins', '-p', '--plugins PLUGINS_DIR1[,PLUGINS_DIR2[,...]]', Array, 'Plugins directory (defaults to ./_plugins)'
p.option 'layouts', '--layouts DIR', String, 'Layouts directory (defaults to ./_layouts)'
Jekyll::Command.subclasses.each { |c| c.init_with_program(p) }
p.action do |args, _|
p.action do |args, options|
if args.empty?
Jekyll.logger.error "A subcommand is required."
puts p
abort
else
subcommand = args.first
unless p.has_command? subcommand
Jekyll.logger.abort_with "fatal: 'jekyll #{args.first}' could not" \
" be found. You may need to install the jekyll-#{args.first} gem" \
" or a related gem to be able to use this subcommand."
unless p.has_command?(args.first)
Jekyll.logger.abort_with "Invalid command. Use --help for more information"
end
end
end

3
cucumber.yml Normal file
View File

@@ -0,0 +1,3 @@
default: --format pretty
travis: --format progress
html_report: --format progress --format html --out=features_report.html

View File

@@ -0,0 +1,93 @@
コントリビュート
==========
あなたは Jekyll に投じるすばらしいアイディアを持っています。
すばらしいことです!次の事柄を心に留めてください。
* **テストなしではコントリビュートはできません。**
* もし、既存の機能への小さな修正やパッチを作成したなら、シンプルなテストを行います。
現在のテストスイートの範囲にとどまり、そして
[Shoulda](https://github.com/thoughtbot/shoulda/tree/master) や
[RR](https://github.com/btakita/rr/tree/master) を使用してください。
* もし、それが新しい機能の場合は、必ず新しい
[Cucumber](https://github.com/cucumber/cucumber/) の機能を作成し、
必要に応じて手順を再利用します。
また、あなたがフォークした `site`
急ぎいくつかのドキュメントを用意し、一度マージを行い
メイン `site` の jekyllrb.com に転送していただければ幸いです。
* あなたのコントリビュートによって Jekyll の振る舞いが変わった場合、ドキュメントを更新すべきです。
それは `site/docs` にあります。
もし、 docs に情報の誤りがあった場合、遠慮なく追加してください。
すばらしいドキュメントはすばらしいプロジェクトを作ります!
* Ruby のコードを変更するときは、 [GitHub Ruby Styleguide](https://github.com/styleguide/ruby)
に従ってください。
* **小さなプルリクエスト** に最善を尽くしてください。
簡単に提案された変更はレビューされ、マージされる可能性が高いです。
* プルリクエストを送信するとき、プルリクエストのボディを賢明に使用してください。
変更されたかどうかの記述、変更の背後にある動機、 [完了したかどうかのタスクリスト](http://git.io/gfm-tasks)
もレビュー時間を早めます。
テストの依存関係
-----------------
テストスイートの実行や gem のビルドのために、
Jekyll の依存ツールをインストールする必要があります。
Jekyll は Bundler を使用しており、 `bundle` コマンドを実行すると全ての設定が迅速に行われます!
$ bundle
はじめる前に、テストを実行し、必ずテストが通ることを
確認してください(あなたの環境が適切に設定されているかを確認するために):
$ bundle exec rake test
$ bundle exec rake features
ワークフロー
--------
これは、あなたの作業がプロジェクトにマージされるもっとも直接的な方法です:
* プロジェクトをフォークします。
* あなたのフォークプロジェクトをクローンします ( `git clone git@github.com:<username>/jekyll.git` )。
* トピックブランチを作成し、あなたの変更を含んでください ( `git checkout -b my_awesome_feature` )。
* ハックし、テストを追加します。必ずしもこの順番でなくてかまいません
* `rake` を実行し、テストが必ず全て通ることを確認してください
* 必要に応じて、エラーがないようにコミットを論理的な塊にリベースしてください
* ブランチをプッシュしてください ( `git push origin my_awesome_feature` ).
* jekyll/jekyll プロジェクトの master ブランチに対してプルリクエストを作成し、
あなたの変更内容と、なぜそれをマージすべきかを記述してください
ドキュメントの更新
----------------------
私たちは Jekyll のドキュメントについて最善を尽くしたいです。
私たちはドキュメントをオープンソース化しました、そして
あなたが Jekyll に欠けているものを見つけた場合、私たちはプルリクエストを歓迎しています。
あなたは、 GitHub.com 上の Jekyll リポジトリの [site]({{ site.repository }}/tree/master/site) で
jekyllrb.comのドキュメントを見つけることができます。
全てのドキュメントのプルリクエストは `master` に向けられる必要があります。
他のブランチに向けたプルリクエストは受け入れられません。
GitHub の [Jekyll wiki](https://github.com/jekyll/jekyll/wiki) は、
自由に更新することができるように、プルリクエストなしで
全ての GitHub ユーザがアクセス権を持つことができます。
落とし穴
-------
* もし、 gem のバージョンがかちあった場合、コミットを分けてください。
この方法だと、メンテナが gem をリリースするときに制御できます。
* jekyll/jekyll の最新コミットに基づいて(複数の)パッチを維持してください。
それは適用するためのあなたの仕事で、メンテナがしなければならないことを少なくするのは
とてもよいことです。
* あなたの GitHub issue で [fix], [feature] などのタグをつけないでください。
メンテナは積極的に issue を読み、彼らが問題に出くわしたらラベルをつけるでしょう。
最後に…
----------
ありがとう! Jekyll のハックは楽しいものでなければなりません。
もし、あなたがこのハードを理解するための何かを発見した場合、知らせてください。
我々のプロセスやドキュメントを改善することができます!

View File

@@ -0,0 +1,68 @@
# [Jekyll](http://jekyllrb.com/)
[![Gem Version](https://badge.fury.io/rb/jekyll.png)](http://badge.fury.io/rb/jekyll)
[![Build Status](https://secure.travis-ci.org/jekyll/jekyll.png?branch=master)](https://travis-ci.org/jekyll/jekyll)
[![Code Climate](https://codeclimate.com/github/jekyll/jekyll.png)](https://codeclimate.com/github/jekyll/jekyll)
[![Dependency Status](https://gemnasium.com/jekyll/jekyll.png)](https://gemnasium.com/jekyll/jekyll)
Tom Preston-Werner, Nick Quaranto や多くの[素晴らしいコントリビュータ](https://github.com/jekyll/jekyll/graphs/contributors)によって作成されています!
Jekyll は個人プロジェクトや組織のサイトに最適な、シンプルで、ブログを意識した静的サイトジェネレータです。
複雑さを排除したファイルベースのCMSのようなものと考えてください。
Jekyll はコンテンツを受け取り、 Markdown や Liquid テンプレート をレンダリングし、
Apache や Nginx やその他の Web サーバに提供する準備ができた静的な Web サイトを完全に出力してくれます。
Jekyll は [GitHub Pages](http://pages.github.com) の背後にあるエンジンなので、
あなたの GitHub リポジトリからサイトをホストするために使用する事ができます。
## 原理
Jekyll あなたがするように伝えたことをします ― それ以上でもそれ以下でもありません。
それは、大胆な仮定によってユーザの裏をかこうとせず、
また、不必要な複雑さや設定をユーザに負担しません。
簡単に言えば、 Jekyll はあなたの道を開け、
真に重要なもの: コンテンツに集中することができます。
## 開始方法
* gem を[インストール](http://jekyllrb.com/docs/installation/)します
* [使用方法](http://jekyllrb.com/docs/usage/) と [設定方法](http://jekyllrb.com/docs/configuration/) を読みます
* 既存の [Jekyll で作られたサイト](https://wiki.github.com/jekyll/jekyll/sites) をチラッと見ます
* Fork し、あなたの変更を [コントリビュート](http://jekyllrb.com/docs/contributing/) します
* 質問があったら? irc.freenode.net の `#jekyll` チャンネルをチェックしてください
## より深く
* 以前のシステムからの[移行](http://jekyllrb.com/docs/migrations/)
* [YAML Front Matter](http://jekyllrb.com/docs/frontmatter/) がどのように働くかを学ぶ
* [変数](http://jekyllrb.com/docs/variables/)を使ってサイトに情報を表示する
* posts が生成される時の[パーマリンク](http://jekyllrb.com/docs/permalinks/)をカスタマイズ
* 人生を容易にするために、組み込みの [Liquid 拡張](http://jekyllrb.com/docs/templates/)を使用する
* あなたのサイト固有のコンテンツを生成するために、カスタム[プラグイン](http://jekyllrb.com/docs/plugins/)を使用する
## 実行時の依存関係
* Commander: コマンドラインインターフェース構築 (Ruby)
* Colorator: コマンドライン出力に色付け (Ruby)
* Classifier: posts の関連を生成 (Ruby)
* Directory Watcher: サイトの自動再生成 (Ruby)
* Kramdown: デフォルトの Markdown エンジン (Ruby)
* Liquid: テンプレートシステム (Ruby)
* Pygments.rb: シンタックスハイライト (Ruby/Python)
* RedCarpet: Markdown エンジン (Ruby)
* Safe YAML: セキュリティのために構築された YAML パーサ (Ruby)
## 開発時の依存関係
* Launchy: クロスプラットフォーム ファイルランチャ (Ruby)
* Maruku: Markdown スーパーセット インタプリタ (Ruby)
* RDiscount: Discount Markdown プロセッサ (Ruby)
* RedCloth: Textile サポート (Ruby)
* RedGreen: よりよいテスト出力 (Ruby)
* RR: モック (Ruby)
* Shoulda: テストフレームワーク (Ruby)
* SimpleCov: カバレッジフレームワーク (Ruby)
## ライセンス
[ライセンス](https://github.com/jekyll/jekyll/blob/master/LICENSE)を見てください。

View File

@@ -8,13 +8,13 @@ Feature: Collections
And I have fixture collections
And I have a configuration file with "collections" set to "['methods']"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Collections: <p>Use <code>Jekyll.configuration</code> to build a full configuration for use w/Jekyll.</p>\n\n<p>Whatever: foo.bar</p>\n<p><code>Jekyll.sanitized_path</code> is used to make sure your path is in your source.</p>\n<p>Run your generators! default</p>\n<p>Page without title.</p>\n<p>Run your generators! default</p>" in "_site/index.html"
And the "_site/methods/configuration.html" file should not exist
Scenario: Rendered collection
Given I have an "index.html" page that contains "Collections: output => {{ site.collections[0].output }} label => {{ site.collections[0].label }}"
And I have an "collection_metadata.html" page that contains "Methods metadata: {{ site.collections[0].foo }} {{ site.collections[0] }}"
Given I have an "index.html" page that contains "Collections: {{ site.collections }}"
And I have an "collection_metadata.html" page that contains "Methods metadata: {{ site.collections.methods.foo }} {{ site.collections.methods }}"
And I have fixture collections
And I have a "_config.yml" file with content:
"""
@@ -24,10 +24,8 @@ Feature: Collections
foo: bar
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Collections: output => true" in "_site/index.html"
And I should see "label => methods" in "_site/index.html"
Then the _site directory should exist
And I should see "Collections: {\"methods" in "_site/index.html"
And I should see "Methods metadata: bar" in "_site/collection_metadata.html"
And I should see "<p>Whatever: foo.bar</p>" in "_site/methods/configuration.html"
@@ -42,12 +40,11 @@ Feature: Collections
permalink: /:collection/:path/
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "<p>Whatever: foo.bar</p>" in "_site/methods/configuration/index.html"
Scenario: Rendered document in a layout
Given I have an "index.html" page that contains "Collections: output => {{ site.collections[0].output }} label => {{ site.collections[0].label }} foo => {{ site.collections[0].foo }}"
Given I have an "index.html" page that contains "Collections: {{ site.collections }}"
And I have a default layout that contains "<div class='title'>Tom Preston-Werner</div> {{content}}"
And I have fixture collections
And I have a "_config.yml" file with content:
@@ -58,11 +55,8 @@ Feature: Collections
foo: bar
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Collections: output => true" in "_site/index.html"
And I should see "label => methods" in "_site/index.html"
And I should see "foo => bar" in "_site/index.html"
Then the _site directory should exist
And I should see "Collections: {\"methods" in "_site/index.html"
And I should see "<p>Run your generators! default</p>" in "_site/methods/site/generate.html"
And I should see "<div class='title'>Tom Preston-Werner</div>" in "_site/methods/site/generate.html"
@@ -75,9 +69,8 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
Then the _site directory should exist
And I should see "Collections: _methods/collection/entries _methods/configuration.md _methods/escape-\+ #%20\[\].md _methods/sanitized_path.md _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md" in "_site/index.html"
And I should see "Collections: _methods/configuration.md _methods/sanitized_path.md _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md" in "_site/index.html"
Scenario: Collections specified as an hash
Given I have an "index.html" page that contains "Collections: {% for method in site.methods %}{{ method.relative_path }} {% endfor %}"
@@ -88,9 +81,8 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
Then the _site directory should exist
And I should see "Collections: _methods/collection/entries _methods/configuration.md _methods/escape-\+ #%20\[\].md _methods/sanitized_path.md _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md" in "_site/index.html"
And I should see "Collections: _methods/configuration.md _methods/sanitized_path.md _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md" in "_site/index.html"
Scenario: All the documents
Given I have an "index.html" page that contains "All documents: {% for doc in site.documents %}{{ doc.relative_path }} {% endfor %}"
@@ -101,12 +93,11 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
Then the _site directory should exist
And I should see "All documents: _methods/collection/entries _methods/configuration.md _methods/escape-\+ #%20\[\].md _methods/sanitized_path.md _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md" in "_site/index.html"
And I should see "All documents: _methods/configuration.md _methods/sanitized_path.md _methods/site/generate.md _methods/site/initialize.md _methods/um_hi.md" in "_site/index.html"
Scenario: Documents have an output attribute, which is the converted HTML
Given I have an "index.html" page that contains "Second document's output: {{ site.documents[1].output }}"
Given I have an "index.html" page that contains "First document's output: {{ site.documents.first.output }}"
And I have fixture collections
And I have a "_config.yml" file with content:
"""
@@ -114,9 +105,8 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
Then the _site directory should exist
And I should see "Second document's output: <p>Use <code class=\"highlighter-rouge\">Jekyll.configuration</code> to build a full configuration for use w/Jekyll.</p>\n\n<p>Whatever: foo.bar</p>" in "_site/index.html"
And I should see "First document's output: <p>Use <code>Jekyll.configuration</code> to build a full configuration for use w/Jekyll.</p>\n\n<p>Whatever: foo.bar</p>" in "_site/index.html"
Scenario: Filter documents by where
Given I have an "index.html" page that contains "{% assign items = site.methods | where: 'whatever','foo.bar' %}Item count: {{ items.size }}"
@@ -127,12 +117,11 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Item count: 2" in "_site/index.html"
Then the _site directory should exist
And I should see "Item count: 1" in "_site/index.html"
Scenario: Sort by title
Given I have an "index.html" page that contains "{% assign items = site.methods | sort: 'title' %}2. of {{ items.size }}: {{ items[1].output }}"
Given I have an "index.html" page that contains "{% assign items = site.methods | sort: 'title' %}1. of {{ items.size }}: {{ items.first.output }}"
And I have fixture collections
And I have a "_config.yml" file with content:
"""
@@ -140,12 +129,11 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "2. of 8: <p>Page without title.</p>" in "_site/index.html"
Then the _site directory should exist
And I should see "1. of 5: <p>Page without title.</p>" in "_site/index.html"
Scenario: Sort by relative_path
Given I have an "index.html" page that contains "Collections: {% assign methods = site.methods | sort: 'relative_path' %}{{ methods | map:"title" | join: ", " }}"
Given I have an "index.html" page that contains "Collections: {% assign methods = site.methods | sort: 'relative_path' %}{% for method in methods %}{{ method.title }}, {% endfor %}"
And I have fixture collections
And I have a "_config.yml" file with content:
"""
@@ -153,22 +141,5 @@ Feature: Collections
- methods
"""
When I run jekyll build
Then I should get a zero exit status
Then the _site directory should exist
And I should see "Collections: Collection#entries, Jekyll.configuration, Jekyll.escape, Jekyll.sanitized_path, Site#generate, Initialize, Site#generate," in "_site/index.html"
Scenario: Rendered collection with date/dateless filename
Given I have an "index.html" page that contains "Collections: {% for method in site.thanksgiving %}{{ method.title }} {% endfor %}"
And I have fixture collections
And I have a "_config.yml" file with content:
"""
collections:
thanksgiving:
output: true
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Thanksgiving Black Friday" in "_site/index.html"
And I should see "Happy Thanksgiving" in "_site/thanksgiving/2015-11-26-thanksgiving.html"
And I should see "Black Friday" in "_site/thanksgiving/black-friday.html"
And I should see "Collections: Jekyll.configuration, Jekyll.sanitized_path, Site#generate, , Site#generate," in "_site/index.html"

View File

@@ -13,8 +13,7 @@ Feature: Create sites
Scenario: Basic site
Given I have an "index.html" file that contains "Basic Site"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Basic Site" in "_site/index.html"
Scenario: Basic site with a post
@@ -23,8 +22,7 @@ Feature: Create sites
| title | date | content |
| Hackers | 2009-03-27 | My First Exploit |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "My First Exploit" in "_site/2009/03/27/hackers.html"
Scenario: Basic site with layout and a page
@@ -32,8 +30,7 @@ Feature: Create sites
And I have an "index.html" page with layout "default" that contains "Basic Site with Layout"
And I have a default layout that contains "Page Layout: {{ content }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page Layout: Basic Site with Layout" in "_site/index.html"
Scenario: Basic site with layout and a post
@@ -44,8 +41,7 @@ Feature: Create sites
| Wargames | 2009-03-27 | default | The only winning move is not to play. |
And I have a default layout that contains "Post Layout: {{ content }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post Layout: <p>The only winning move is not to play.</p>" in "_site/2009/03/27/wargames.html"
Scenario: Basic site with layout inside a subfolder and a post
@@ -56,8 +52,7 @@ Feature: Create sites
| Wargames | 2009-03-27 | post/simple | The only winning move is not to play. |
And I have a post/simple layout that contains "Post Layout: {{ content }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post Layout: <p>The only winning move is not to play.</p>" in "_site/2009/03/27/wargames.html"
Scenario: Basic site with layouts, pages, posts and files
@@ -80,8 +75,7 @@ Feature: Create sites
| entry3 | 2009-05-27 | post | content for entry3. |
| entry4 | 2009-06-27 | post | content for entry4. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page : Site contains 2 pages and 4 posts" in "_site/index.html"
And I should see "No replacement \{\{ site.posts.size \}\}" in "_site/about.html"
And I should see "" in "_site/another_file"
@@ -96,8 +90,7 @@ Feature: Create sites
And I have an "index.html" page that contains "Basic Site with include tag: {% include about.textile %}"
And I have an "_includes/about.textile" file that contains "Generated by Jekyll"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Basic Site with include tag: Generated by Jekyll" in "_site/index.html"
Scenario: Basic site with subdir include tag
@@ -106,8 +99,7 @@ Feature: Create sites
And I have an info directory
And I have an "info/index.html" page that contains "Basic Site with subdir include tag: {% include about.textile %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Basic Site with subdir include tag: Generated by Jekyll" in "_site/info/index.html"
Scenario: Basic site with nested include tag
@@ -116,35 +108,31 @@ Feature: Create sites
And I have an "_includes/jekyll.textile" file that contains "Jekyll"
And I have an "index.html" page that contains "Basic Site with include tag: {% include about.textile %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Basic Site with include tag: Generated by Jekyll" in "_site/index.html"
Scenario: Basic site with internal post linking
Given I have an "index.html" page that contains "URL: {% post_url 2008-01-01-entry2 %}"
Given I have an "index.html" page that contains "URL: {% post_url 2020-01-31-entry2 %}"
And I have a configuration file with "permalink" set to "pretty"
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2007-12-31 | post | content for entry1. |
| entry2 | 2008-01-01 | post | content for entry2. |
| entry2 | 2020-01-31 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "URL: /2008/01/01/entry2/" in "_site/index.html"
Then the _site directory should exist
And I should see "URL: /2020/01/31/entry2/" in "_site/index.html"
Scenario: Basic site with whitelisted dotfile
Given I have an ".htaccess" file that contains "SomeDirective"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "SomeDirective" in "_site/.htaccess"
Scenario: File was replaced by a directory
Given I have a "test" file that contains "some stuff"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
When I delete the file "test"
Given I have a test directory
And I have a "test/index.html" file that contains "some other stuff"
@@ -158,48 +146,13 @@ Feature: Create sites
And I have a "secret.html" page with published "false" that contains "Unpublished page"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the "_site/index.html" file should exist
And the "_site/public.html" file should exist
But the "_site/secret.html" file should not exist
When I run jekyll build --unpublished
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the "_site/index.html" file should exist
And the "_site/public.html" file should exist
And the "_site/secret.html" file should exist
Scenario: Basic site with page with future date
Given I have a _posts directory
And I have the following post:
| title | date | layout | content |
| entry1 | 2020-12-31 | post | content for entry1. |
| entry2 | 2007-12-31 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "content for entry2" in "_site/2007/12/31/entry2.html"
And the "_site/2020/12/31/entry1.html" file should not exist
When I run jekyll build --future
Then I should get a zero exit status
And the _site directory should exist
And the "_site/2020/12/31/entry1.html" file should exist
Scenario: Basic site with layouts, posts and related posts
Given I have a _layouts directory
And I have a page layout that contains "Page {{ page.title }}: {{ content }}"
And I have a post layout that contains "Post {{ page.title }}: {{ content }}Related posts: {{ site.related_posts | size }}"
And I have an "index.html" page with layout "page" that contains "Site contains {{ site.pages.size }} pages and {{ site.posts.size }} posts; Related posts: {{ site.related_posts | size }}"
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2009-03-27 | post | content for entry1. |
| entry2 | 2009-04-27 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Page : Site contains 1 pages and 2 posts; Related posts: 0" in "_site/index.html"
And I should see "Post entry1: <p>content for entry1.</p>\nRelated posts: 1" in "_site/2009/03/27/entry1.html"
And I should see "Post entry2: <p>content for entry2.</p>\nRelated posts: 1" in "_site/2009/04/27/entry2.html"

View File

@@ -45,20 +45,6 @@ Feature: Data
And I should see "Jack" in "_site/index.html"
And I should see "Leon" in "_site/index.html"
Scenario: autoload *.csv files in _data directory
Given I have a _data directory
And I have a "_data/members.csv" file with content:
"""
name,age
Jack,28
Leon,34
"""
And I have an "index.html" page that contains "{% for member in site.data.members %}{{member.name}}{% endfor %}"
When I run jekyll build
Then the "_site/index.html" file should exist
And I should see "Jack" in "_site/index.html"
And I should see "Leon" in "_site/index.html"
Scenario: autoload *.yml files in _data directory with space in file name
Given I have a _data directory
And I have a "_data/team members.yml" file with content:

View File

@@ -10,8 +10,7 @@ Feature: Draft Posts
| title | date | layout | content |
| Recipe | 2009-03-27 | default | Not baked yet. |
When I run jekyll build --drafts
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Not baked yet." in "_site/recipe.html"
Scenario: Don't preview a draft
@@ -22,8 +21,7 @@ Feature: Draft Posts
| title | date | layout | content |
| Recipe | 2009-03-27 | default | Not baked yet. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the "_site/recipe.html" file should not exist
Scenario: Don't preview a draft that is not published
@@ -34,8 +32,7 @@ Feature: Draft Posts
| title | date | layout | published | content |
| Recipe | 2009-03-27 | default | false | Not baked yet. |
When I run jekyll build --drafts
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the "_site/recipe.html" file should not exist
Scenario: Use page.path variable
@@ -45,6 +42,5 @@ Feature: Draft Posts
| title | date | layout | content |
| Recipe | 2009-03-27 | simple | Post path: {{ page.path }} |
When I run jekyll build --drafts
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post path: _drafts/recipe.markdown" in "_site/recipe.html"
Then the _site directory should exist
And I should see "Post path: _drafts/recipe.textile" in "_site/recipe.html"

View File

@@ -11,8 +11,7 @@ Feature: Embed filters
| Star Wars | 2009-03-27 | default | These aren't the droids you're looking for. |
And I have a default layout that contains "{{ site.time | date_to_xmlschema }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see today's date in "_site/2009/03/27/star-wars.html"
Scenario: Escape text for XML
@@ -21,10 +20,11 @@ Feature: Embed filters
And I have the following post:
| title | date | layout | content |
| Star & Wars | 2009-03-27 | default | These aren't the droids you're looking for. |
And I have a default layout that contains "{{ page.title | xml_escape }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Star &amp; Wars" in "_site/2009/03/27/star-wars.html"
Scenario: Calculate number of words
@@ -33,10 +33,9 @@ Feature: Embed filters
And I have the following post:
| title | date | layout | content |
| Star Wars | 2009-03-27 | default | These aren't the droids you're looking for. |
And I have a default layout that contains "{{ content | number_of_words }}"
And I have a default layout that contains "{{ content | xml_escape }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "7" in "_site/2009/03/27/star-wars.html"
Scenario: Convert an array into a sentence
@@ -47,20 +46,18 @@ Feature: Embed filters
| Star Wars | 2009-03-27 | default | [scifi, movies, force] | These aren't the droids you're looking for. |
And I have a default layout that contains "{{ page.tags | array_to_sentence_string }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "scifi, movies, and force" in "_site/2009/03/27/star-wars.html"
Scenario: Markdownify a given string
Scenario: Textilize a given string
Given I have a _posts directory
And I have a _layouts directory
And I have the following post:
| title | date | layout | content |
| Star Wars | 2009-03-27 | default | These aren't the droids you're looking for. |
And I have a default layout that contains "By {{ '_Obi-wan_' | markdownify }}"
And I have a default layout that contains "By {{ '_Obi-wan_' | textilize }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "By <p><em>Obi-wan</em></p>" in "_site/2009/03/27/star-wars.html"
Scenario: Sort by an arbitrary variable
@@ -73,37 +70,38 @@ Feature: Embed filters
| Page-2 | default | 6 | Something |
And I have a default layout that contains "{{ site.pages | sort:'value' | map:'title' | join:', ' }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see exactly "Page-2, Page-1" in "_site/page-1.html"
And I should see exactly "Page-2, Page-1" in "_site/page-2.html"
Scenario: Sort pages by the title
Given I have a _layouts directory
And I have the following pages:
| title | layout | content |
| Dog | default | Run |
| Bird | default | Fly |
And I have the following page:
| layout | content |
| default | Jump |
| title | layout | content |
| Dog | default | Run |
And I have the following page:
| title | layout | content |
| Bird | default | Fly |
And I have the following page:
| layout | content |
| default | Jump |
And I have a default layout that contains "{% assign sorted_pages = site.pages | sort: 'title' %}The rule of {{ sorted_pages.size }}: {% for p in sorted_pages %}{{ p.content | strip_html | strip_newlines }}, {% endfor %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see exactly "The rule of 3: Jump, Fly, Run," in "_site/bird.html"
Scenario: Sort pages by the title ordering pages without title last
Given I have a _layouts directory
And I have the following pages:
| title | layout | content |
| Dog | default | Run |
| Bird | default | Fly |
And I have the following page:
| layout | content |
| default | Jump |
| title | layout | content |
| Dog | default | Run |
And I have the following page:
| title | layout | content |
| Bird | default | Fly |
And I have the following page:
| layout | content |
| default | Jump |
And I have a default layout that contains "{% assign sorted_pages = site.pages | sort: 'title', 'last' %}The rule of {{ sorted_pages.size }}: {% for p in sorted_pages %}{{ p.content | strip_html | strip_newlines }}, {% endfor %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see exactly "The rule of 3: Fly, Run, Jump," in "_site/bird.html"

View File

@@ -12,8 +12,7 @@ Feature: frontmatter defaults
And I have a configuration file with "defaults" set to "[{scope: {path: ""}, values: {layout: "pretty"}}]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "THIS IS THE LAYOUT: <p>just some post</p>" in "_site/2013/09/11/default-layout.html"
And I should see "THIS IS THE LAYOUT: just some page" in "_site/index.html"
@@ -25,9 +24,8 @@ Feature: frontmatter defaults
And I have an "index.html" page that contains "just {{page.custom}} by {{page.author}}"
And I have a configuration file with "defaults" set to "[{scope: {path: ""}, values: {custom: "some special data", author: "Ben"}}]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "<p>some special data</p>\n<div>Ben</div>" in "_site/2013/09/11/default-data.html"
Then the _site directory should exist
And I should see "<p>some special data</p><div>Ben</div>" in "_site/2013/09/11/default-data.html"
And I should see "just some special data by Ben" in "_site/index.html"
Scenario: Override frontmatter defaults by path
@@ -50,36 +48,12 @@ Feature: frontmatter defaults
And I have a configuration file with "defaults" set to "[{scope: {path: "special"}, values: {layout: "subfolder", description: "the special section"}}, {scope: {path: ""}, values: {layout: "root", description: "the webpage"}}]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "root: <p>info on the webpage</p>" in "_site/2013/10/14/about.html"
And I should see "subfolder: <p>info on the special section</p>" in "_site/special/2013/10/14/about.html"
And I should see "root: Overview for the webpage" in "_site/index.html"
And I should see "subfolder: Overview for the special section" in "_site/special/index.html"
Scenario: Use frontmatter variables by relative path
Given I have a _layouts directory
And I have a main layout that contains "main: {{ content }}"
And I have a _posts directory
And I have the following post:
| title | date | content |
| about | 2013-10-14 | content of site/2013/10/14/about.html |
And I have a special/_posts directory
And I have the following post in "special":
| title | date | path | content |
| about1 | 2013-10-14 | local | content of site/special/2013/10/14/about1.html |
| about2 | 2013-10-14 | local | content of site/special/2013/10/14/about2.html |
And I have a configuration file with "defaults" set to "[{scope: {path: "special"}, values: {layout: "main"}}, {scope: {path: "special/_posts"}, values: {layout: "main"}}, {scope: {path: "_posts"}, values: {layout: "main"}}]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "main: <p>content of site/2013/10/14/about.html</p>" in "_site/2013/10/14/about.html"
And I should see "main: <p>content of site/special/2013/10/14/about1.html</p>" in "_site/special/2013/10/14/about1.html"
And I should see "main: <p>content of site/special/2013/10/14/about2.html</p>" in "_site/special/2013/10/14/about2.html"
Scenario: Override frontmatter defaults by type
Given I have a _posts directory
And I have the following post:
@@ -104,22 +78,11 @@ Feature: frontmatter defaults
And I should see "nothing" in "_site/override.html"
But the "_site/perma.html" file should not exist
Scenario: Define permalink default for posts
Given I have a _posts directory
And I have the following post:
| title | date | category | content |
| testpost | 2013-10-14 | blog | blabla |
And I have a configuration file with "defaults" set to "[{scope: {path: "", type: "posts"}, values: {permalink: "/:categories/:title/"}}]"
When I run jekyll build
Then I should see "blabla" in "_site/blog/testpost/index.html"
Scenario: Use frontmatter defaults in collections
Given I have a _slides directory
And I have a "index.html" file that contains "nothing"
And I have a "_slides/slide1.html" file with content:
And I have a "_slides/slide1.html" file with content:
"""
---
---
Value: {{ page.myval }}
"""
And I have a "_config.yml" file with content:
@@ -136,14 +99,13 @@ Feature: frontmatter defaults
myval: "Test"
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Value: Test" in "_site/slides/slide1.html"
Scenario: Override frontmatter defaults inside a collection
Given I have a _slides directory
And I have a "index.html" file that contains "nothing"
And I have a "_slides/slide2.html" file with content:
And I have a "_slides/slide2.html" file with content:
"""
---
myval: Override
@@ -164,12 +126,5 @@ Feature: frontmatter defaults
myval: "Test"
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Value: Override" in "_site/slides/slide2.html"
Scenario: Deep merge frontmatter defaults
Given I have an "index.html" page with fruit "{orange: 1}" that contains "Fruits: {{ page.fruit.orange | plus: page.fruit.apple }}"
And I have a configuration file with "defaults" set to "[{scope: {path: ""}, values: {fruit: {apple: 2}}}]"
When I run jekyll build
Then I should see "Fruits: 3" in "_site/index.html"

View File

@@ -1,335 +0,0 @@
Feature: Hooks
As a plugin author
I want to be able to run code during various stages of the build process
Scenario: Run some code after site reset
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :site, :after_reset do |site|
pageklass = Class.new(Jekyll::Page) do
def initialize(site, base)
@site = site
@base = base
@data = {}
@dir = '/'
@name = 'foo.html'
@content = 'mytinypage'
self.process(@name)
end
end
site.pages << pageklass.new(site, site.source)
end
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "mytinypage" in "_site/foo.html"
Scenario: Modify the payload before rendering the site
Given I have a _plugins directory
And I have a "index.html" page that contains "{{ site.injected }}!"
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :site, :pre_render do |site, payload|
payload['site']['injected'] = 'myparam'
end
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "myparam!" in "_site/index.html"
Scenario: Modify the site contents after reading
Given I have a _plugins directory
And I have a "page1.html" page that contains "page1"
And I have a "page2.html" page that contains "page2"
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :site, :post_read do |site|
site.pages.delete_if { |p| p.name == 'page1.html' }
end
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And the "_site/page1.html" file should not exist
And I should see "page2" in "_site/page2.html"
Scenario: Work with the site files after they've been written to disk
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :site, :post_write do |site|
firstpage = site.pages.first
content = File.read firstpage.destination(site.dest)
File.write(File.join(site.dest, 'firstpage.html'), content)
end
"""
And I have a "page1.html" page that contains "page1"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "page1" in "_site/firstpage.html"
Scenario: Alter a page right after it is initialized
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :pages, :post_init do |page|
page.name = 'renamed.html'
page.process(page.name)
end
"""
And I have a "page1.html" page that contains "page1"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "page1" in "_site/renamed.html"
Scenario: Alter the payload for one page but not another
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :pages, :pre_render do |page, payload|
payload['page']['myparam'] = 'special' if page.name == 'page1.html'
end
"""
And I have a "page1.html" page that contains "{{ page.myparam }}"
And I have a "page2.html" page that contains "{{ page.myparam }}"
When I run jekyll build
Then I should see "special" in "_site/page1.html"
And I should not see "special" in "_site/page2.html"
Scenario: Modify page contents before writing to disk
Given I have a _plugins directory
And I have a "index.html" page that contains "WRAP ME"
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :pages, :post_render do |page|
page.output = "{{{{{ #{page.output.chomp} }}}}}"
end
"""
When I run jekyll build
Then I should see "{{{{{ WRAP ME }}}}}" in "_site/index.html"
Scenario: Work with a page after writing it to disk
Given I have a _plugins directory
And I have a "index.html" page that contains "HELLO FROM A PAGE"
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :pages, :post_write do |page|
require 'fileutils'
filename = page.destination(page.site.dest)
FileUtils.mv(filename, "#{filename}.moved")
end
"""
When I run jekyll build
Then I should see "HELLO FROM A PAGE" in "_site/index.html.moved"
Scenario: Alter a post right after it is initialized
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :posts, :post_init do |post|
post.data['harold'] = "content for entry1.".tr!('abcdefghijklmnopqrstuvwxyz',
'nopqrstuvwxyzabcdefghijklm')
end
"""
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2015-03-14 | nil | {{ page.harold }} |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "pbagrag sbe ragel1." in "_site/2015/03/14/entry1.html"
Scenario: Alter the payload for certain posts
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
# Add myvar = 'old' to posts before 2015-03-15, and myvar = 'new' for
# others
Jekyll::Hooks.register :posts, :pre_render do |post, payload|
if post.date < Time.new(2015, 3, 15)
payload['myvar'] = 'old'
else
payload['myvar'] = 'new'
end
end
"""
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2015-03-14 | nil | {{ myvar }} post |
| entry2 | 2015-03-15 | nil | {{ myvar }} post |
When I run jekyll build
Then I should see "old post" in "_site/2015/03/14/entry1.html"
And I should see "new post" in "_site/2015/03/15/entry2.html"
Scenario: Modify post contents before writing to disk
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
# Replace content after rendering
Jekyll::Hooks.register :posts, :post_render do |post|
post.output.gsub! /42/, 'the answer to life, the universe and everything'
end
"""
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2015-03-14 | nil | {{ 6 \| times: 7 }} |
| entry2 | 2015-03-15 | nil | {{ 6 \| times: 8 }} |
When I run jekyll build
Then I should see "the answer to life, the universe and everything" in "_site/2015/03/14/entry1.html"
And I should see "48" in "_site/2015/03/15/entry2.html"
Scenario: Work with a post after writing it to disk
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
# Log all post filesystem writes
Jekyll::Hooks.register :posts, :post_write do |post|
filename = post.destination(post.site.dest)
open('_site/post-build.log', 'a') do |f|
f.puts "Wrote #{filename} at #{Time.now}"
end
end
"""
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2015-03-14 | nil | entry one |
| entry2 | 2015-03-15 | nil | entry two |
When I run jekyll build
Then I should see "_site/2015/03/14/entry1.html at" in "_site/post-build.log"
Then I should see "_site/2015/03/15/entry2.html at" in "_site/post-build.log"
Scenario: Register a hook on multiple owners at the same time
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register [:pages, :posts], :post_render do |owner|
owner.output = "{{{{{ #{owner.output.chomp} }}}}}"
end
"""
And I have a "index.html" page that contains "WRAP ME"
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2015-03-14 | nil | entry one |
When I run jekyll build
Then I should see "{{{{{ WRAP ME }}}}}" in "_site/index.html"
And I should see "{{{{{ <p>entry one</p> }}}}}" in "_site/2015/03/14/entry1.html"
Scenario: Allow hooks to have a named priority
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :pages, :post_render, priority: :normal do |owner|
# first normal runs second
owner.output = "1 #{owner.output.chomp}"
end
Jekyll::Hooks.register :pages, :post_render, priority: :high do |owner|
# high runs last
owner.output = "2 #{owner.output.chomp}"
end
Jekyll::Hooks.register :pages, :post_render do |owner|
# second normal runs third (normal is default)
owner.output = "3 #{owner.output.chomp}"
end
Jekyll::Hooks.register :pages, :post_render, priority: :low do |owner|
# low runs first
owner.output = "4 #{owner.output.chomp}"
end
"""
And I have a "index.html" page that contains "WRAP ME"
When I run jekyll build
Then I should see "2 3 1 4 WRAP ME" in "_site/index.html"
Scenario: Alter a document right after it is initialized
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :documents, :pre_render do |doc, payload|
doc.data['text'] = doc.data['text'] << ' are belong to us'
end
"""
And I have a "_config.yml" file that contains "collections: [ memes ]"
And I have a _memes directory
And I have a "_memes/doc1.md" file with content:
"""
---
text: all your base
---
"""
And I have an "index.md" file with content:
"""
---
---
{{ site.memes.first.text }}
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "all your base are belong to us" in "_site/index.html"
Scenario: Update a document after rendering it, but before writing it to disk
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :documents, :post_render do |doc|
doc.output.gsub! /<p>/, '<p class="meme">'
end
"""
And I have a "_config.yml" file with content:
"""
collections:
memes:
output: true
"""
And I have a _memes directory
And I have a "_memes/doc1.md" file with content:
"""
---
text: all your base are belong to us
---
{{ page.text }}
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "<p class=\"meme\">all your base are belong to us" in "_site/memes/doc1.html"
Scenario: Perform an action after every document is written
Given I have a _plugins directory
And I have a "_plugins/ext.rb" file with content:
"""
Jekyll::Hooks.register :documents, :post_write do |doc|
open('_site/document-build.log', 'a') do |f|
f.puts "Wrote document #{doc.collection.docs.index doc} at #{Time.now}"
end
end
"""
And I have a "_config.yml" file with content:
"""
collections:
memes:
output: true
"""
And I have a _memes directory
And I have a "_memes/doc1.md" file with content:
"""
---
text: all your base are belong to us
---
{{ page.text }}
"""
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Wrote document 0" in "_site/document-build.log"

View File

@@ -9,18 +9,17 @@ Feature: Include tags
And I have an "_includes/params.html" file that contains "Parameters:<ul>{% for param in include %}<li>{{param[0]}} = {{param[1]}}</li>{% endfor %}</ul>"
And I have an "_includes/ignore.html" file that contains "<footer>My blog footer</footer>"
And I have a _posts directory
And I have the following posts:
| title | date | type | content |
| Include Files | 2013-03-21 | html | {% include header.html param="myparam" %} |
| Ignore params if unused | 2013-03-21 | html | {% include ignore.html date="today" %} |
| List multiple parameters | 2013-03-21 | html | {% include params.html date="today" start="tomorrow" %} |
| Dont keep parameters | 2013-03-21 | html | {% include ignore.html param="test" %}\n{% include header.html %} |
| Allow params with spaces and quotes | 2013-04-07 | html | {% include params.html cool="param with spaces" super="\\"quoted\\"" single='has "quotes"' escaped='\\'single\\' quotes' %} |
| Parameter syntax | 2013-04-12 | html | {% include params.html param1_or_2="value" %} |
| Pass a variable | 2013-06-22 | html | {% assign var = 'some text' %}{% include params.html local=var title=page.title %} |
And I have the following post:
| title | date | layout | content |
| Include Files | 2013-03-21 | default | {% include header.html param="myparam" %} |
| Ignore params if unused | 2013-03-21 | default | {% include ignore.html date="today" %} |
| List multiple parameters | 2013-03-21 | default | {% include params.html date="today" start="tomorrow" %} |
| Dont keep parameters | 2013-03-21 | default | {% include ignore.html param="test" %}\n{% include header.html %} |
| Allow params with spaces and quotes | 2013-04-07 | default | {% include params.html cool="param with spaces" super="\"quoted\"" single='has "quotes"' escaped='\'single\' quotes' %} |
| Parameter syntax | 2013-04-12 | default | {% include params.html param1_or_2="value" %} |
| Pass a variable | 2013-06-22 | default | {% assign var = 'some text' %}{% include params.html local=var layout=page.layout %} |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "<header>My awesome blog header: myparam</header>" in "_site/2013/03/21/include-files.html"
And I should not see "myparam" in "_site/2013/03/21/ignore-params-if-unused.html"
And I should see "<li>date = today</li>" in "_site/2013/03/21/list-multiple-parameters.html"
@@ -28,12 +27,12 @@ Feature: Include tags
And I should not see "<header>My awesome blog header: myparam</header>" in "_site/2013/03/21/dont-keep-parameters.html"
But I should see "<header>My awesome blog header: </header>" in "_site/2013/03/21/dont-keep-parameters.html"
And I should see "<li>cool = param with spaces</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>super = \"quoted\"</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>single = has \"quotes\"</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>escaped = 'single' quotes</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>super = &#8220;quoted&#8221;</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>single = has &#8220;quotes&#8221;</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>escaped = &#8216;single&#8217; quotes</li>" in "_site/2013/04/07/allow-params-with-spaces-and-quotes.html"
And I should see "<li>param1_or_2 = value</li>" in "_site/2013/04/12/parameter-syntax.html"
And I should see "<li>local = some text</li>" in "_site/2013/06/22/pass-a-variable.html"
And I should see "<li>title = Pass a variable</li>" in "_site/2013/06/22/pass-a-variable.html"
And I should see "<li>layout = default</li>" in "_site/2013/06/22/pass-a-variable.html"
Scenario: Include a file from a variable
Given I have an _includes directory
@@ -45,8 +44,7 @@ Feature: Include tags
| include_file2 | parametrized.html |
And I have an "index.html" page that contains "{% include {{site.include_file1}} %} that {% include {{site.include_file2}} what='parameters' %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "a snippet that works with parameters" in "_site/index.html"
Scenario: Include a variable file in a loop
@@ -55,8 +53,7 @@ Feature: Include tags
And I have an "_includes/two.html" file that contains "two"
And I have an "index.html" page with files "[one.html, two.html]" that contains "{% for file in page.files %}{% include {{file}} %} {% endfor %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "one two" in "_site/index.html"
Scenario: Include a file with variables and filters
@@ -67,40 +64,5 @@ Feature: Include tags
| include_file | one |
And I have an "index.html" page that contains "{% include {{ site.include_file | append: '.html' }} %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "one included" in "_site/index.html"
Scenario: Include a file with partial variables
Given I have an _includes directory
And I have an "_includes/one.html" file that contains "one included"
And I have a configuration file with:
| key | value |
| include_file | one |
And I have an "index.html" page that contains "{% include {{ site.include_file }}.html %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "one included" in "_site/index.html"
Scenario: Include a file and rebuild when include content is changed
Given I have an _includes directory
And I have an "_includes/one.html" file that contains "include"
And I have an "index.html" page that contains "{% include one.html %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "include" in "_site/index.html"
When I wait 1 second
Then I have an "_includes/one.html" file that contains "include content changed"
When I run jekyll build
Then I should see "include content changed" in "_site/index.html"
Scenario: Include a file with multiple variables
Given I have an _includes directory
And I have an "_includes/header-en.html" file that contains "include"
And I have an "index.html" page that contains "{% assign name = 'header' %}{% assign locale = 'en' %}{% include {{name}}-{{locale}}.html %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "include" in "_site/index.html"

View File

@@ -1,68 +0,0 @@
Feature: Incremental rebuild
As an impatient hacker who likes to blog
I want to be able to make a static site
Without waiting too long for it to build
Scenario: Produce correct output site
Given I have a _layouts directory
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| Wargames | 2009-03-27 | default | The only winning move is not to play. |
And I have a default layout that contains "Post Layout: {{ content }}"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post Layout: <p>The only winning move is not to play.</p>" in "_site/2009/03/27/wargames.html"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post Layout: <p>The only winning move is not to play.</p>" in "_site/2009/03/27/wargames.html"
Scenario: Generate a metadata file
Given I have an "index.html" file that contains "Basic Site"
When I run jekyll build -I
Then the ".jekyll-metadata" file should exist
Scenario: Rebuild when content is changed
Given I have an "index.html" file that contains "Basic Site"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Basic Site" in "_site/index.html"
When I wait 1 second
Then I have an "index.html" file that contains "Bacon Site"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Bacon Site" in "_site/index.html"
Scenario: Rebuild when layout is changed
Given I have a _layouts directory
And I have an "index.html" page with layout "default" that contains "Basic Site with Layout"
And I have a default layout that contains "Page Layout: {{ content }}"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Page Layout: Basic Site with Layout" in "_site/index.html"
When I wait 1 second
Then I have a default layout that contains "Page Layout Changed: {{ content }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Page Layout Changed: Basic Site with Layout" in "_site/index.html"
Scenario: Rebuild when an include is changed
Given I have a _includes directory
And I have an "index.html" page that contains "Basic Site with include tag: {% include about.textile %}"
And I have an "_includes/about.textile" file that contains "Generated by Jekyll"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Basic Site with include tag: Generated by Jekyll" in "_site/index.html"
When I wait 1 second
Then I have an "_includes/about.textile" file that contains "Regenerated by Jekyll"
When I run jekyll build -I
Then I should get a zero exit status
And the _site directory should exist
And I should see "Basic Site with include tag: Regenerated by Jekyll" in "_site/index.html"

View File

@@ -1,37 +0,0 @@
Feature: Layout data
As a hacker who likes to avoid repetition
I want to be able to embed data into my layouts
In order to make the layouts slightly dynamic
Scenario: Use custom layout data
Given I have a _layouts directory
And I have a "_layouts/custom.html" file with content:
"""
---
foo: my custom data
---
{{ content }} foo: {{ layout.foo }}
"""
And I have an "index.html" page with layout "custom" that contains "page content"
When I run jekyll build
Then the "_site/index.html" file should exist
And I should see "page content\n foo: my custom data" in "_site/index.html"
Scenario: Inherit custom layout data
Given I have a _layouts directory
And I have a "_layouts/custom.html" file with content:
"""
---
layout: base
foo: my custom data
---
{{ content }}
"""
And I have a "_layouts/base.html" file with content:
"""
{{ content }} foo: {{ layout.foo }}
"""
And I have an "index.html" page with layout "custom" that contains "page content"
When I run jekyll build
Then the "_site/index.html" file should exist
And I should see "page content\n foo: my custom data" in "_site/index.html"

View File

@@ -11,24 +11,57 @@ Feature: Markdown
| title | date | content | type |
| Hackers | 2009-03-27 | # My Title | markdown |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Index" in "_site/index.html"
And I should see "<h1 id=\"my-title\">My Title</h1>" in "_site/2009/03/27/hackers.html"
And I should see "<h1 id=\"my-title\">My Title</h1>" in "_site/index.html"
Scenario: Markdown in pagination on index
Given I have a configuration file with:
| key | value |
| paginate | 5 |
| gems | [jekyll-paginate] |
Given I have a configuration file with "paginate" set to "5"
And I have an "index.html" page that contains "Index - {% for post in paginator.posts %} {{ post.content }} {% endfor %}"
And I have a _posts directory
And I have the following post:
| title | date | content | type |
| Hackers | 2009-03-27 | # My Title | markdown |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Index" in "_site/index.html"
And I should see "<h1 id=\"my-title\">My Title</h1>" in "_site/index.html"
Scenario: Maruku fenced codeblocks
Given I have a configuration file with "markdown" set to "maruku"
And I have an "index.markdown" file with content:
"""
---
title: My title
---
# My title
```
My awesome code
```
"""
When I run jekyll build
Then the _site directory should exist
And I should see "My awesome code" in "_site/index.html"
And I should see "<pre><code>\nMy awesome code\n</code></pre>" in "_site/index.html"
Scenario: Maruku fenced codeblocks
Given I have a configuration file with "markdown" set to "maruku"
And I have an "index.markdown" file with content:
"""
---
title: My title
---
# My title
```ruby
puts "My awesome string"
```
"""
When I run jekyll build
Then the _site directory should exist
And I should see "My awesome string" in "_site/index.html"
And I should see "<pre class="ruby"><code class="ruby">\nputs &quot;My awesome string&quot;\n</code></pre>" in "_site/index.html"

View File

@@ -4,10 +4,7 @@ Feature: Site pagination
I want divide the posts in several pages
Scenario Outline: Paginate with N posts per page
Given I have a configuration file with:
| key | value |
| paginate | <num> |
| gems | [jekyll-paginate] |
Given I have a configuration file with "paginate" set to "<num>"
And I have a _layouts directory
And I have an "index.html" page that contains "{{ paginator.posts.size }}"
And I have a _posts directory
@@ -35,7 +32,6 @@ Feature: Site pagination
| paginate | 1 |
| paginate_path | /blog/page-:num |
| permalink | /blog/:year/:month/:day/:title |
| gems | [jekyll-paginate] |
And I have a blog directory
And I have an "blog/index.html" page that contains "{{ paginator.posts.size }}"
And I have a _posts directory
@@ -63,7 +59,6 @@ Feature: Site pagination
| paginate | 1 |
| paginate_path | /blog/page/:num |
| permalink | /blog/:year/:month/:day/:title |
| gems | [jekyll-paginate] |
And I have a blog directory
And I have an "blog/index.html" page that contains "{{ paginator.posts.size }}"
And I have an "index.html" page that contains "Don't pick me!"

View File

@@ -10,8 +10,7 @@ Feature: Fancy permalinks
| None Permalink Schema | 2009-03-27 | Totally nothing. |
And I have a configuration file with "permalink" set to "none"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Totally nothing." in "_site/none-permalink-schema.html"
Scenario: Use pretty permalink schema
@@ -21,8 +20,7 @@ Feature: Fancy permalinks
| Pretty Permalink Schema | 2009-03-27 | Totally wordpress. |
And I have a configuration file with "permalink" set to "pretty"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Totally wordpress." in "_site/2009/03/27/pretty-permalink-schema/index.html"
Scenario: Use pretty permalink schema for pages
@@ -31,8 +29,7 @@ Feature: Fancy permalinks
And I have an "sitemap.xml" page that contains "Totally uhm, sitemap"
And I have a configuration file with "permalink" set to "pretty"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Totally index" in "_site/index.html"
And I should see "Totally awesome" in "_site/awesome/index.html"
And I should see "Totally uhm, sitemap" in "_site/sitemap.xml"
@@ -42,10 +39,9 @@ Feature: Fancy permalinks
And I have the following post:
| title | category | date | content |
| Custom Permalink Schema | stuff | 2009-03-27 | Totally custom. |
And I have a configuration file with "permalink" set to "/blog/:year/:month/:day/:title/"
And I have a configuration file with "permalink" set to "/blog/:year/:month/:day/:title"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Totally custom." in "_site/blog/2009/03/27/custom-permalink-schema/index.html"
Scenario: Use custom permalink schema with category
@@ -55,8 +51,7 @@ Feature: Fancy permalinks
| Custom Permalink Schema | stuff | 2009-03-27 | Totally custom. |
And I have a configuration file with "permalink" set to "/:categories/:title.html"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Totally custom." in "_site/stuff/custom-permalink-schema.html"
Scenario: Use custom permalink schema with squished date
@@ -66,32 +61,16 @@ Feature: Fancy permalinks
| Custom Permalink Schema | stuff | 2009-03-27 | Totally custom. |
And I have a configuration file with "permalink" set to "/:month-:day-:year/:title.html"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Totally custom." in "_site/03-27-2009/custom-permalink-schema.html"
Scenario: Use custom permalink schema with date and time
Given I have a _posts directory
And I have the following post:
| title | category | date | content |
| Custom Permalink Schema | stuff | 2009-03-27 22:31:07 | Totally custom. |
And I have a configuration file with:
| key | value |
| permalink | "/:year:month:day:hour:minute:second.html" |
| timezone | UTC |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Totally custom." in "_site/20090327223107.html"
Scenario: Use per-post permalink
Given I have a _posts directory
And I have the following post:
| title | date | permalink | content |
| Some post | 2013-04-14 | /custom/posts/1/ | bla bla |
| Some post | 2013-04-14 | /custom/posts/1 | bla bla |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the _site/custom/posts/1 directory should exist
And I should see "bla bla" in "_site/custom/posts/1/index.html"
@@ -101,44 +80,6 @@ Feature: Fancy permalinks
| title | date | permalink | content |
| Some post | 2013-04-14 | /custom/posts/some.html | bla bla |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the _site/custom/posts directory should exist
And I should see "bla bla" in "_site/custom/posts/some.html"
Scenario: Use pretty permalink schema with cased file name
Given I have a _posts directory
And I have an "_posts/2009-03-27-Pretty-Permalink-Schema.md" page that contains "Totally wordpress"
And I have a configuration file with "permalink" set to "pretty"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Totally wordpress." in "_site/2009/03/27/Pretty-Permalink-Schema/index.html"
Scenario: Use custom permalink schema with cased file name
Given I have a _posts directory
And I have an "_posts/2009-03-27-Custom-Schema.md" page with title "Custom Schema" that contains "Totally awesome"
And I have a configuration file with "permalink" set to "/:year/:month/:day/:slug/"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Totally awesome" in "_site/2009/03/27/custom-schema/index.html"
Scenario: Use pretty permalink schema with title containing underscore
Given I have a _posts directory
And I have an "_posts/2009-03-27-Custom_Schema.md" page with title "Custom Schema" that contains "Totally awesome"
And I have a configuration file with "permalink" set to "pretty"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Totally awesome" in "_site/2009/03/27/Custom_Schema/index.html"
Scenario: Use a non-HTML file extension in the permalink
Given I have a _posts directory
And I have an "_posts/2016-01-18-i-am-php.md" page with permalink "/2016/i-am-php.php" that contains "I am PHP"
And I have a "i-am-also-php.md" page with permalink "/i-am-also-php.php" that contains "I am also PHP"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "I am PHP" in "_site/2016/i-am-php.php"
And I should see "I am also PHP" in "_site/i-am-also-php.php"

View File

@@ -1,37 +0,0 @@
Feature: Configuring and using plugins
As a hacker
I want to specify my own plugins that can modify Jekyll's behaviour
Scenario: Add a gem-based plugin
Given I have an "index.html" file that contains "Whatever"
And I have a configuration file with "gems" set to "[jekyll_test_plugin]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Whatever" in "_site/index.html"
And I should see "this is a test" in "_site/test.txt"
Scenario: Add an empty whitelist to restrict all gems
Given I have an "index.html" file that contains "Whatever"
And I have a configuration file with:
| key | value |
| gems | [jekyll_test_plugin] |
| whitelist | [] |
When I run jekyll build --safe
Then I should get a zero exit status
And the _site directory should exist
And I should see "Whatever" in "_site/index.html"
And the "_site/test.txt" file should not exist
Scenario: Add a whitelist to restrict some gems but allow others
Given I have an "index.html" file that contains "Whatever"
And I have a configuration file with:
| key | value |
| gems | [jekyll_test_plugin, jekyll_test_plugin_malicious] |
| whitelist | [jekyll_test_plugin] |
When I run jekyll build --safe
Then I should get a zero exit status
And the _site directory should exist
And I should see "Whatever" in "_site/index.html"
And the "_site/test.txt" file should exist
And I should see "this is a test" in "_site/test.txt"

View File

@@ -11,8 +11,7 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post title: {{ page.title }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post title: Star Wars" in "_site/2009/03/27/star-wars.html"
Scenario: Use post.url variable
@@ -23,8 +22,7 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post url: {{ page.url }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post url: /2009/03/27/star-wars.html" in "_site/2009/03/27/star-wars.html"
Scenario: Use post.date variable
@@ -35,24 +33,9 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post date: {{ page.date | date_to_string }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post date: 27 Mar 2009" in "_site/2009/03/27/star-wars.html"
Scenario: Use post.date variable with invalid
Given I have a _posts directory
And I have a "_posts/2016-01-01-test.md" page with date "tuesday" that contains "I have a bad date."
When I run jekyll build
Then the _site directory should not exist
And I should see "Document '_posts/2016-01-01-test.md' does not have a valid date in the YAML front matter." in the build output
Scenario: Invalid date in filename
Given I have a _posts directory
And I have a "_posts/2016-22-01-test.md" page that contains "I have a bad date."
When I run jekyll build
Then the _site directory should not exist
And I should see "Document '_posts/2016-22-01-test.md' does not have a valid date in the filename." in the build output
Scenario: Use post.id variable
Given I have a _posts directory
And I have a _layouts directory
@@ -61,8 +44,7 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post id: {{ page.id }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post id: /2009/03/27/star-wars" in "_site/2009/03/27/star-wars.html"
Scenario: Use post.content variable
@@ -73,8 +55,7 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post content: {{ content }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post content: <p>Luke, I am your father.</p>" in "_site/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when category is in a folder
@@ -86,48 +67,20 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when category is in a folder and has category in YAML
Given I have a movies directory
And I have a movies/_posts directory
And I have a _layouts directory
And I have the following post in "movies":
| title | date | layout | category | content |
| Star Wars | 2009-03-27 | simple | film | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post category: movies" in "_site/movies/film/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when category is in a folder and has categories in YAML
Given I have a movies directory
And I have a movies/_posts directory
And I have a _layouts directory
And I have the following post in "movies":
| title | date | layout | categories | content |
| Star Wars | 2009-03-27 | simple | [film, scifi] | Luke, I am your father. |
| title | date | layout | categories | content |
| Star Wars | 2009-03-27 | simple | [film] | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post category: movies" in "_site/movies/film/scifi/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when category is in a folder and duplicated category is in YAML
Given I have a movies directory
And I have a movies/_posts directory
And I have a _layouts directory
And I have the following post in "movies":
| title | date | layout | category | content |
| Star Wars | 2009-03-27 | simple | movies | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Then the _site directory should exist
And I should see "Post category: movies" in "_site/movies/film/2009/03/27/star-wars.html"
Scenario: Use post.tags variable
Given I have a _posts directory
@@ -137,8 +90,7 @@ Feature: Post data
| Star Wars | 2009-05-18 | simple | twist | Luke, I am your father. |
And I have a simple layout that contains "Post tags: {{ page.tags }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post tags: twist" in "_site/2009/05/18/star-wars.html"
Scenario: Use post.categories variable when categories are in folders
@@ -151,8 +103,7 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post categories: {{ page.categories | array_to_sentence_string }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post categories: scifi and movies" in "_site/scifi/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when categories are in folders with mixed case
@@ -165,9 +116,8 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Luke, I am your father. |
And I have a simple layout that contains "Post categories: {{ page.categories | array_to_sentence_string }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post categories: scifi and Movies" in "_site/scifi/movies/2009/03/27/star-wars.html"
Then the _site directory should exist
And I should see "Post categories: scifi and movies" in "_site/scifi/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when category is in YAML
Given I have a _posts directory
@@ -177,8 +127,7 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | movies | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when category is in YAML and is mixed-case
@@ -189,52 +138,18 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Movies | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post category: Movies" in "_site/movies/2009/03/27/star-wars.html"
Then the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when categories are in YAML
Scenario: Use post.categories variable when category is in YAML
Given I have a _posts directory
And I have a _layouts directory
And I have the following post:
| title | date | layout | categories | content |
| Star Wars | 2009-03-27 | simple | ['scifi', 'movies'] | Luke, I am your father. |
And I have a simple layout that contains "Post categories: {{ page.categories | array_to_sentence_string }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post categories: scifi and movies" in "_site/scifi/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when categories are in YAML and are duplicated
Given I have a _posts directory
And I have a _layouts directory
And I have the following post:
| title | date | layout | categories | content |
| Star Wars | 2009-03-27 | simple | ['movies', 'movies'] | Luke, I am your father. |
| title | date | layout | category | content |
| Star Wars | 2009-03-27 | simple | movies | Luke, I am your father. |
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Scenario: Superdirectories of _posts applied to post.categories
Given I have a movies/_posts directory
And I have a "movies/_posts/2009-03-27-star-wars.html" page with layout "simple" that contains "hi"
And I have a _layouts directory
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Scenario: Subdirectories of _posts not applied to post.categories
Given I have a movies/_posts/scifi directory
And I have a "movies/_posts/scifi/2009-03-27-star-wars.html" page with layout "simple" that contains "hi"
And I have a _layouts directory
And I have a simple layout that contains "Post category: {{ page.categories }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post category: movies" in "_site/movies/2009/03/27/star-wars.html"
Scenario: Use post.categories variable when categories are in YAML with mixed case
@@ -246,10 +161,9 @@ Feature: Post data
| Star Trek | 2013-03-17 | simple | ['SciFi', 'movies'] | Jean Luc, I am your father. |
And I have a simple layout that contains "Post categories: {{ page.categories | array_to_sentence_string }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Post categories: scifi and Movies" in "_site/scifi/movies/2009/03/27/star-wars.html"
And I should see "Post categories: SciFi and movies" in "_site/scifi/movies/2013/03/17/star-trek.html"
Then the _site directory should exist
And I should see "Post categories: scifi and movies" in "_site/scifi/movies/2009/03/27/star-wars.html"
And I should see "Post categories: scifi and movies" in "_site/scifi/movies/2013/03/17/star-trek.html"
Scenario Outline: Use page.path variable
Given I have a <dir>/_posts directory
@@ -257,8 +171,7 @@ Feature: Post data
| title | type | date | content |
| my-post | html | 2013-04-12 | Source path: {{ page.path }} |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Source path: <path_prefix>_posts/2013-04-12-my-post.html" in "_site/<dir>/2013/04/12/my-post.html"
Examples:
@@ -267,15 +180,14 @@ Feature: Post data
| dir | dir/ |
| dir/nested | dir/nested/ |
Scenario: Cannot override page.path variable
Scenario: Override page.path variable
Given I have a _posts directory
And I have the following post:
| title | date | path | content |
| override | 2013-04-12 | override-path.html | Non-custom path: {{ page.path }} |
| override | 2013-04-12 | override-path.html | Custom path: {{ page.path }} |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "Non-custom path: _posts/2013-04-12-override.markdown" in "_site/2013/04/12/override.html"
Then the _site directory should exist
And I should see "Custom path: override-path.html" in "_site/2013/04/12/override.html"
Scenario: Disable a post from being published
Given I have a _posts directory
@@ -284,8 +196,7 @@ Feature: Post data
| title | date | layout | published | content |
| Star Wars | 2009-03-27 | simple | false | Luke, I am your father. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the "_site/2009/03/27/star-wars.html" file should not exist
And I should see "Published!" in "_site/index.html"
@@ -297,22 +208,9 @@ Feature: Post data
| Star Wars | 2009-03-27 | simple | Darth Vader | Luke, I am your father. |
And I have a simple layout that contains "Post author: {{ page.author }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Post author: Darth Vader" in "_site/2009/03/27/star-wars.html"
Scenario: Use a variable which is a reserved keyword in Ruby
Given I have a _posts directory
And I have a _layouts directory
And I have the following post:
| title | date | layout | class | content |
| My post | 2016-01-21 | simple | kewl-post | Luke, I am your father. |
And I have a simple layout that contains "{{page.title}} has class {{page.class}}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "My post has class kewl-post" in "_site/2016/01/21/my-post.html"
Scenario: Previous and next posts title
Given I have a _posts directory
And I have a _layouts directory
@@ -323,7 +221,6 @@ Feature: Post data
| Terminator | 2009-05-27 | ordered | Arnold | Sayonara, baby |
And I have a ordered layout that contains "Previous post: {{ page.previous.title }} and next post: {{ page.next.title }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "next post: Some like it hot" in "_site/2009/03/27/star-wars.html"
And I should see "Previous post: Some like it hot" in "_site/2009/05/27/terminator.html"

View File

@@ -12,8 +12,7 @@ Feature: Post excerpts
| title | date | layout | content |
| entry1 | 2007-12-31 | post | content for entry1. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see exactly "<p>content for entry1.</p>" in "_site/index.html"
Scenario: An excerpt from a post with a layout
@@ -25,8 +24,7 @@ Feature: Post excerpts
| title | date | layout | content |
| entry1 | 2007-12-31 | post | content for entry1. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the _site/2007 directory should exist
And the _site/2007/12 directory should exist
And the _site/2007/12/31 directory should exist
@@ -43,11 +41,10 @@ Feature: Post excerpts
| title | date | layout | content |
| entry1 | 2007-12-31 | post | content for entry1. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the _site/2007 directory should exist
And the _site/2007/12 directory should exist
And the _site/2007/12/31 directory should exist
And the "_site/2007/12/31/entry1.html" file should exist
And I should see "<p>content for entry1.</p>" in "_site/index.html"
And I should see "<html><head></head><body><p>content for entry1.</p>\n</body></html>" in "_site/2007/12/31/entry1.html"
And I should see exactly "<p>content for entry1.</p>" in "_site/index.html"
And I should see exactly "<html><head></head><body><p>content for entry1.</p></body></html>" in "_site/2007/12/31/entry1.html"

View File

@@ -5,51 +5,30 @@ Feature: Rendering
But I want to make it as simply as possible
So render with Liquid and place in Layouts
Scenario: When receiving bad Liquid
Given I have a "index.html" page with layout "simple" that contains "{% include invalid.html %}"
And I have a simple layout that contains "{{ content }}"
When I run jekyll build
Then I should get a non-zero exit-status
And I should see "Liquid Exception" in the build output
Scenario: Render Liquid and place in layout
Given I have a "index.html" page with layout "simple" that contains "Hi there, Jekyll {{ jekyll.environment }}!"
And I have a simple layout that contains "{{ content }}Ahoy, indeed!"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Hi there, Jekyll development!\nAhoy, indeed" in "_site/index.html"
Scenario: Don't place asset files in layout
Given I have an "index.scss" page with layout "simple" that contains ".foo-bar { color:black; }"
And I have an "index.coffee" page with layout "simple" that contains "whatever()"
And I have a configuration file with "gems" set to "[jekyll-coffeescript]"
And I have a simple layout that contains "{{ content }}Ahoy, indeed!"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should not see "Ahoy, indeed!" in "_site/index.css"
And I should not see "Ahoy, indeed!" in "_site/index.js"
Scenario: Render liquid in Sass
Scenario: Don't render liquid in Sass
Given I have an "index.scss" page that contains ".foo-bar { color:{{site.color}}; }"
And I have a configuration file with "color" set to "red"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see ".foo-bar {\n color: red; }" in "_site/index.css"
Then the _site directory should not exist
And I should see "Invalid CSS after" in the build output
Scenario: Not render liquid in CoffeeScript without explicitly including jekyll-coffeescript
Given I have an "index.coffee" page with animal "cicada" that contains "hey='for {{page.animal}}'"
Scenario: Don't render liquid in CoffeeScript
Given I have an "index.coffee" page that contains "hey='for {{site.animal}}'"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And the "_site/index.js" file should not exist
Scenario: Render liquid in CoffeeScript with jekyll-coffeescript enabled
Given I have an "index.coffee" page with animal "cicada" that contains "hey='for {{page.animal}}'"
And I have a configuration file with "gems" set to "[jekyll-coffeescript]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "hey = 'for cicada';" in "_site/index.js"
Then the _site directory should exist
And I should see "hey = 'for {{site.animal}}';" in "_site/index.js"

View File

@@ -8,8 +8,7 @@ Feature: Site configuration
And I have an "_sourcedir/index.html" file that contains "Changing source directory"
And I have a configuration file with "source" set to "_sourcedir"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Changing source directory" in "_site/index.html"
Scenario: Change destination directory
@@ -67,31 +66,34 @@ Feature: Site configuration
Given I have an "index.markdown" page that contains "[Google](http://google.com)"
And I have a configuration file with "markdown" set to "rdiscount"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "<a href=\"http://google.com\">Google</a>" in "_site/index.html"
Scenario: Use Kramdown for markup
Given I have an "index.markdown" page that contains "[Google](http://google.com)"
And I have a configuration file with "markdown" set to "kramdown"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "<a href=\"http://google.com\">Google</a>" in "_site/index.html"
Scenario: Use Redcarpet for markup
Given I have an "index.markdown" page that contains "[Google](http://google.com)"
And I have a configuration file with "markdown" set to "redcarpet"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "<a href=\"http://google.com\">Google</a>" in "_site/index.html"
Scenario: Use Maruku for markup
Given I have an "index.markdown" page that contains "[Google](http://google.com)"
And I have a configuration file with "markdown" set to "maruku"
When I run jekyll build
Then the _site directory should exist
And I should see "<a href=\"http://google.com\">Google</a>" in "_site/index.html"
Scenario: Highlight code with pygments
Given I have an "index.html" page that contains "{% highlight ruby %} puts 'Hello world!' {% endhighlight %}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Hello world!" in "_site/index.html"
And I should see "class=\"highlight\"" in "_site/index.html"
@@ -99,8 +101,7 @@ Feature: Site configuration
Given I have an "index.html" page that contains "{% highlight ruby %} puts 'Hello world!' {% endhighlight %}"
And I have a configuration file with "highlighter" set to "rouge"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Hello world!" in "_site/index.html"
And I should see "class=\"highlight\"" in "_site/index.html"
@@ -128,8 +129,7 @@ Feature: Site configuration
| entry1 | 2007-12-31 | post | content for entry1. |
| entry2 | 2020-01-31 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page Layout: 1 on 2010-01-01" in "_site/index.html"
And I should see "Post Layout: <p>content for entry1.</p>" in "_site/2007/12/31/entry1.html"
And the "_site/2020/01/31/entry2.html" file should not exist
@@ -149,8 +149,7 @@ Feature: Site configuration
| entry1 | 2007-12-31 | post | content for entry1. |
| entry2 | 2020-01-31 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page Layout: 2 on 2010-01-01" in "_site/index.html"
And I should see "Post Layout: <p>content for entry1.</p>" in "_site/2007/12/31/entry1.html"
And I should see "Post Layout: <p>content for entry2.</p>" in "_site/2020/01/31/entry2.html"
@@ -169,11 +168,10 @@ Feature: Site configuration
| entry1 | 2013-04-09 23:22 -0400 | post | content for entry1. |
| entry2 | 2013-04-10 03:14 -0400 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page Layout: 2" in "_site/index.html"
And I should see "Post Layout: <p>content for entry1.</p>\n built at 2013-04-09T23:22:00-04:00" in "_site/2013/04/09/entry1.html"
And I should see "Post Layout: <p>content for entry2.</p>\n built at 2013-04-10T03:14:00-04:00" in "_site/2013/04/10/entry2.html"
And I should see "Post Layout: <p>content for entry1.</p> built at 2013-04-09T23:22:00-04:00" in "_site/2013/04/09/entry1.html"
And I should see "Post Layout: <p>content for entry2.</p> built at 2013-04-10T03:14:00-04:00" in "_site/2013/04/10/entry2.html"
Scenario: Generate proper dates with explicitly set timezone (different than posts' time)
Given I have a _layouts directory
@@ -182,20 +180,19 @@ Feature: Site configuration
And I have an "index.html" page with layout "page" that contains "site index page"
And I have a configuration file with:
| key | value |
| timezone | Pacific/Honolulu |
| timezone | Australia/Melbourne |
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2013-04-09 23:22 +0400 | post | content for entry1. |
| entry2 | 2013-04-10 03:14 +0400 | post | content for entry2. |
| entry1 | 2013-04-09 23:22 -0400 | post | content for entry1. |
| entry2 | 2013-04-10 03:14 -0400 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page Layout: 2" in "_site/index.html"
And the "_site/2013/04/09/entry1.html" file should exist
And the "_site/2013/04/09/entry2.html" file should exist
And I should see "Post Layout: <p>content for entry1.</p>\n built at 2013-04-09T09:22:00-10:00" in "_site/2013/04/09/entry1.html"
And I should see "Post Layout: <p>content for entry2.</p>\n built at 2013-04-09T13:14:00-10:00" in "_site/2013/04/09/entry2.html"
And the "_site/2013/04/10/entry1.html" file should exist
And the "_site/2013/04/10/entry2.html" file should exist
And I should see escaped "Post Layout: <p>content for entry1.</p> built at 2013-04-10T13:22:00+10:00" in "_site/2013/04/10/entry1.html"
And I should see escaped "Post Layout: <p>content for entry2.</p> built at 2013-04-10T17:14:00+10:00" in "_site/2013/04/10/entry2.html"
Scenario: Limit the number of posts generated by most recent date
Given I have a _posts directory
@@ -208,8 +205,7 @@ Feature: Site configuration
| Oranges | 2009-04-01 | An article about oranges |
| Bananas | 2009-04-05 | An article about bananas |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And the "_site/2009/04/05/bananas.html" file should exist
And the "_site/2009/04/01/oranges.html" file should exist
And the "_site/2009/03/27/apples.html" file should not exist
@@ -222,8 +218,7 @@ Feature: Site configuration
| .gitignore |
| .foo |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see ".DS_Store" in "_site/.gitignore"
And the "_site/.htaccess" file should not exist
@@ -236,24 +231,45 @@ Feature: Site configuration
| key | value |
| time | 2010-01-01 |
| future | true |
| layouts_dir | _theme |
| layouts | _theme |
And I have a _posts directory
And I have the following posts:
| title | date | layout | content |
| entry1 | 2007-12-31 | post | content for entry1. |
| entry2 | 2020-01-31 | post | content for entry2. |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Page Layout: 2 on 2010-01-01" in "_site/index.html"
And I should see "Post Layout: <p>content for entry1.</p>" in "_site/2007/12/31/entry1.html"
And I should see "Post Layout: <p>content for entry2.</p>" in "_site/2020/01/31/entry2.html"
Scenario: arbitrary file reads via layouts
Given I have an "index.html" page with layout "page" that contains "FOO"
And I have a "_config.yml" file that contains "layouts: '../../../../../../../../../../../../../../usr/include'"
Scenario: Add a gem-based plugin
Given I have an "index.html" file that contains "Whatever"
And I have a configuration file with "gems" set to "[jekyll_test_plugin]"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
And I should see "FOO" in "_site/index.html"
And I should not see " " in "_site/index.html"
Then the _site directory should exist
And I should see "Whatever" in "_site/index.html"
And I should see "this is a test" in "_site/test.txt"
Scenario: Add an empty whitelist to restrict all gems
Given I have an "index.html" file that contains "Whatever"
And I have a configuration file with:
| key | value |
| gems | [jekyll_test_plugin] |
| whitelist | [] |
When I run jekyll build --safe
Then the _site directory should exist
And I should see "Whatever" in "_site/index.html"
And the "_site/test.txt" file should not exist
Scenario: Add a whitelist to restrict some gems but allow others
Given I have an "index.html" file that contains "Whatever"
And I have a configuration file with:
| key | value |
| gems | [jekyll_test_plugin, jekyll_test_plugin_malicious] |
| whitelist | [jekyll_test_plugin] |
When I run jekyll build --safe
Then the _site directory should exist
And I should see "Whatever" in "_site/index.html"
And the "_site/test.txt" file should exist
And I should see "this is a test" in "_site/test.txt"

View File

@@ -6,16 +6,14 @@ Feature: Site data
Scenario: Use page variable in a page
Given I have an "contact.html" page with title "Contact" that contains "{{ page.title }}: email@example.com"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Contact: email@example.com" in "_site/contact.html"
Scenario Outline: Use page.path variable in a page
Given I have a <dir> directory
And I have a "<path>" page that contains "Source path: {{ page.path }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Source path: <path>" in "_site/<path>"
Examples:
@@ -27,15 +25,13 @@ Feature: Site data
Scenario: Override page.path
Given I have an "override.html" page with path "custom-override.html" that contains "Custom path: {{ page.path }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Custom path: custom-override.html" in "_site/override.html"
Scenario: Use site.time variable
Given I have an "index.html" page that contains "{{ site.time }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see today's time in "_site/index.html"
Scenario: Use site.posts variable for latest post
@@ -47,8 +43,7 @@ Feature: Site data
| Second Post | 2009-03-26 | My Second Post |
| Third Post | 2009-03-27 | My Third Post |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Third Post: /2009/03/27/third-post.html" in "_site/index.html"
Scenario: Use site.posts variable in a loop
@@ -60,8 +55,7 @@ Feature: Site data
| Second Post | 2009-03-26 | My Second Post |
| Third Post | 2009-03-27 | My Third Post |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Third Post Second Post First Post" in "_site/index.html"
Scenario: Use site.categories.code variable
@@ -72,8 +66,7 @@ Feature: Site data
| Awesome Hack | 2009-03-26 | code | puts 'Hello World' |
| Delicious Beer | 2009-03-26 | food | 1) Yuengling |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Awesome Hack" in "_site/index.html"
Scenario: Use site.tags variable
@@ -83,8 +76,7 @@ Feature: Site data
| title | date | tag | content |
| Delicious Beer | 2009-03-26 | beer | 1) Yuengling |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "Yuengling" in "_site/index.html"
Scenario: Order Posts by name when on the same date
@@ -98,21 +90,18 @@ Feature: Site data
| C | 2009-03-26 | C |
| last | 2009-04-26 | last |
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "last:C, C:B,last B:A,C A:first,B first:,A" in "_site/index.html"
Scenario: Use configuration date in site payload
Given I have an "index.html" page that contains "{{ site.url }}"
And I have a configuration file with "url" set to "http://example.com"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "http://example.com" in "_site/index.html"
Scenario: Access Jekyll version via jekyll.version
Given I have an "index.html" page that contains "{{ jekyll.version }}"
When I run jekyll build
Then I should get a zero exit status
And the _site directory should exist
Then the _site directory should exist
And I should see "\d+\.\d+\.\d+" in "_site/index.html"

View File

@@ -1,245 +0,0 @@
Before do
FileUtils.mkdir_p(Paths.test_dir) unless Paths.test_dir.directory?
Dir.chdir(Paths.test_dir)
end
#
After do
Paths.test_dir.rmtree if Paths.test_dir.exist?
Paths.output_file.delete if Paths.output_file.exist?
Paths.status_file.delete if Paths.status_file.exist?
Dir.chdir(Paths.test_dir.parent)
end
#
Given %r{^I have a blank site in "(.*)"$} do |path|
if !File.exist?(path)
then FileUtils.mkdir_p(path)
end
end
#
Given %r{^I do not have a "(.*)" directory$} do |path|
Paths.test_dir.join(path).directory?
end
#
Given %r{^I have an? "(.*)" page(?: with (.*) "(.*)")? that contains "(.*)"$} do |file, key, value, text|
File.write(file, Jekyll::Utils.strip_heredoc(<<-DATA))
---
#{key || 'layout'}: #{value || 'nil'}
---
#{text}
DATA
end
#
Given %r{^I have an? "(.*)" file that contains "(.*)"$} do |file, text|
File.write(file, text)
end
#
Given %r{^I have an? (.*) (layout|theme) that contains "(.*)"$} do |name, type, text|
folder = type == "layout" ? "_layouts" : "_theme"
destination_file = Pathname.new(File.join(folder, "#{name}.html"))
FileUtils.mkdir_p(destination_file.parent) unless destination_file.parent.directory?
File.write(destination_file, text)
end
#
Given %r{^I have an? "(.*)" file with content:$} do |file, text|
File.write(file, text)
end
#
Given %r{^I have an? (.*) directory$} do |dir|
if !File.directory?(dir)
then FileUtils.mkdir_p(dir)
end
end
#
Given %r{^I have the following (draft|page|post)s?(?: (in|under) "([^"]+)")?:$} do |status, direction, folder, table|
table.hashes.each do |input_hash|
title = slug(input_hash["title"])
ext = input_hash["type"] || "markdown"
filename = filename = "#{title}.#{ext}" if %w(draft page).include?(status)
before, after = location(folder, direction)
dest_folder = "_drafts" if status == "draft"
dest_folder = "_posts" if status == "post"
dest_folder = "" if status == "page"
if status == "post"
parsed_date = Time.xmlschema(input_hash['date']) rescue Time.parse(input_hash['date'])
filename = "#{parsed_date.strftime('%Y-%m-%d')}-#{title}.#{ext}"
end
path = File.join(before, dest_folder, after, filename)
File.write(path, file_content_from_hash(input_hash))
end
end
#
Given %r{^I have a configuration file with "(.*)" set to "(.*)"$} do |key, value|
config = if source_dir.join("_config.yml").exist?
SafeYAML.load_file(source_dir.join("_config.yml"))
else
{}
end
config[key] = YAML.load(value)
File.write("_config.yml", YAML.dump(config))
end
#
Given %r{^I have a configuration file with:$} do |table|
table.hashes.each do |row|
step %(I have a configuration file with "#{row["key"]}" set to "#{row["value"]}")
end
end
#
Given %r{^I have a configuration file with "([^\"]*)" set to:$} do |key, table|
File.open("_config.yml", "w") do |f|
f.write("#{key}:\n")
table.hashes.each do |row|
f.write("- #{row["value"]}\n")
end
end
end
#
Given %r{^I have fixture collections$} do
FileUtils.cp_r Paths.source_dir.join("test", "source", "_methods"), source_dir
FileUtils.cp_r Paths.source_dir.join("test", "source", "_thanksgiving"), source_dir
end
#
Given %r{^I wait (\d+) second(s?)$} do |time, plural|
sleep(time.to_f)
end
#
When %r{^I run jekyll(.*)$} do |args|
run_jekyll(args)
if args.include?("--verbose") || ENV["DEBUG"]
$stderr.puts "\n#{jekyll_run_output}\n"
end
end
#
When %r{^I run bundle(.*)$} do |args|
run_bundle(args)
if args.include?("--verbose") || ENV['DEBUG']
$stderr.puts "\n#{jekyll_run_output}\n"
end
end
#
When %r{^I change "(.*)" to contain "(.*)"$} do |file, text|
File.open(file, "a") do |f|
f.write(text)
end
end
#
When %r{^I delete the file "(.*)"$} do |file|
File.delete(file)
end
#
Then %r{^the (.*) directory should +(not )?exist$} do |dir, negative|
if negative.nil?
expect(Pathname.new(dir)).to exist
else
expect(Pathname.new(dir)).to_not exist
end
end
#
Then %r{^I should (not )?see "(.*)" in "(.*)"$} do |negative, text, file|
step %(the "#{file}" file should exist)
regexp = Regexp.new(text, Regexp::MULTILINE)
if negative.nil? || negative.empty?
expect(file_contents(file)).to match regexp
else
expect(file_contents(file)).not_to match regexp
end
end
#
Then %r{^I should see exactly "(.*)" in "(.*)"$} do |text, file|
step %(the "#{file}" file should exist)
expect(file_contents(file).strip).to eq text
end
#
Then %r{^I should see escaped "(.*)" in "(.*)"$} do |text, file|
step %(I should see "#{Regexp.escape(text)}" in "#{file}")
end
#
Then %r{^the "(.*)" file should +(not )?exist$} do |file, negative|
if negative.nil?
expect(Pathname.new(file)).to exist
else
expect(Pathname.new(file)).to_not exist
end
end
#
Then %r{^I should see today's time in "(.*)"$} do |file|
step %(I should see "#{seconds_agnostic_time(Time.now)}" in "#{file}")
end
#
Then %r{^I should see today's date in "(.*)"$} do |file|
step %(I should see "#{Date.today.to_s}" in "#{file}")
end
#
Then %r{^I should (not )?see "(.*)" in the build output$} do |negative, text|
if negative.nil? || negative.empty?
expect(jekyll_run_output).to match Regexp.new(text)
else
expect(jekyll_run_output).not_to match Regexp.new(text)
end
end
#
Then %r{^I should get a zero exit(?:\-| )status$} do
step %(I should see "EXIT STATUS: 0" in the build output)
end
#
Then %r{^I should get a non-zero exit(?:\-| )status$} do
step %(I should not see "EXIT STATUS: 0" in the build output)
end

View File

@@ -0,0 +1,201 @@
def file_content_from_hash(input_hash)
matter_hash = input_hash.reject { |k, v| k == "content" }
matter = matter_hash.map { |k, v| "#{k}: #{v}\n" }.join.chomp
content = if input_hash['input'] && input_hash['filter']
"{{ #{input_hash['input']} | #{input_hash['filter']} }}"
else
input_hash['content']
end
<<EOF
---
#{matter}
---
#{content}
EOF
end
Before do
FileUtils.mkdir_p(TEST_DIR) unless File.exist?(TEST_DIR)
Dir.chdir(TEST_DIR)
end
After do
FileUtils.rm_rf(TEST_DIR) if File.exists?(TEST_DIR)
FileUtils.rm(JEKYLL_COMMAND_OUTPUT_FILE) if File.exists?(JEKYLL_COMMAND_OUTPUT_FILE)
end
World(Test::Unit::Assertions)
Given /^I have a blank site in "(.*)"$/ do |path|
FileUtils.mkdir_p(path) unless File.exist?(path)
end
Given /^I do not have a "(.*)" directory$/ do |path|
File.directory?("#{TEST_DIR}/#{path}")
end
# Like "I have a foo file" but gives a yaml front matter so jekyll actually processes it
Given /^I have an? "(.*)" page(?: with (.*) "(.*)")? that contains "(.*)"$/ do |file, key, value, text|
File.open(file, 'w') do |f|
f.write <<EOF
---
#{key || 'layout'}: #{value || 'nil'}
---
#{text}
EOF
end
end
Given /^I have an? "(.*)" file that contains "(.*)"$/ do |file, text|
File.open(file, 'w') do |f|
f.write(text)
end
end
Given /^I have an? (.*) (layout|theme) that contains "(.*)"$/ do |name, type, text|
folder = if type == 'layout'
'_layouts'
else
'_theme'
end
destination_file = File.join(folder, name + '.html')
destination_path = File.dirname(destination_file)
unless File.exist?(destination_path)
FileUtils.mkdir_p(destination_path)
end
File.open(destination_file, 'w') do |f|
f.write(text)
end
end
Given /^I have an? "(.*)" file with content:$/ do |file, text|
File.open(file, 'w') do |f|
f.write(text)
end
end
Given /^I have an? (.*) directory$/ do |dir|
FileUtils.mkdir_p(dir)
end
Given /^I have the following (draft|page|post)s?(?: (in|under) "([^"]+)")?:$/ do |status, direction, folder, table|
table.hashes.each do |input_hash|
title = slug(input_hash['title'])
ext = input_hash['type'] || 'textile'
before, after = location(folder, direction)
case status
when "draft"
dest_folder = '_drafts'
filename = "#{title}.#{ext}"
when "page"
dest_folder = ''
filename = "#{title}.#{ext}"
when "post"
parsed_date = Time.xmlschema(input_hash['date']) rescue Time.parse(input_hash['date'])
dest_folder = '_posts'
filename = "#{parsed_date.strftime('%Y-%m-%d')}-#{title}.#{ext}"
end
path = File.join(before, dest_folder, after, filename)
File.open(path, 'w') do |f|
f.write file_content_from_hash(input_hash)
end
end
end
Given /^I have a configuration file with "(.*)" set to "(.*)"$/ do |key, value|
File.open('_config.yml', 'w') do |f|
f.write("#{key}: #{value}\n")
end
end
Given /^I have a configuration file with:$/ do |table|
File.open('_config.yml', 'w') do |f|
table.hashes.each do |row|
f.write("#{row["key"]}: #{row["value"]}\n")
end
end
end
Given /^I have a configuration file with "([^\"]*)" set to:$/ do |key, table|
File.open('_config.yml', 'w') do |f|
f.write("#{key}:\n")
table.hashes.each do |row|
f.write("- #{row["value"]}\n")
end
end
end
Given /^I have fixture collections$/ do
FileUtils.cp_r File.join(JEKYLL_SOURCE_DIR, "test", "source", "_methods"), source_dir
end
##################
#
# Changing stuff
#
##################
When /^I run jekyll(.*)$/ do |args|
status = run_jekyll(args)
if args.include?("--verbose") || ENV['DEBUG']
puts jekyll_run_output
end
end
When /^I change "(.*)" to contain "(.*)"$/ do |file, text|
File.open(file, 'a') do |f|
f.write(text)
end
end
When /^I delete the file "(.*)"$/ do |file|
File.delete(file)
end
Then /^the (.*) directory should +exist$/ do |dir|
assert File.directory?(dir), "The directory \"#{dir}\" does not exist"
end
Then /^the (.*) directory should not exist$/ do |dir|
assert !File.directory?(dir), "The directory \"#{dir}\" exists"
end
Then /^I should see "(.*)" in "(.*)"$/ do |text, file|
assert_match Regexp.new(text, Regexp::MULTILINE), file_contents(file)
end
Then /^I should see exactly "(.*)" in "(.*)"$/ do |text, file|
assert_equal text, file_contents(file).strip
end
Then /^I should not see "(.*)" in "(.*)"$/ do |text, file|
assert_no_match Regexp.new(text, Regexp::MULTILINE), file_contents(file)
end
Then /^I should see escaped "(.*)" in "(.*)"$/ do |text, file|
assert_match Regexp.new(Regexp.escape(text)), file_contents(file)
end
Then /^the "(.*)" file should +exist$/ do |file|
assert File.file?(file), "The file \"#{file}\" does not exist"
end
Then /^the "(.*)" file should not exist$/ do |file|
assert !File.exist?(file), "The file \"#{file}\" exists"
end
Then /^I should see today's time in "(.*)"$/ do |file|
assert_match Regexp.new(seconds_agnostic_time(Time.now)), file_contents(file)
end
Then /^I should see today's date in "(.*)"$/ do |file|
assert_match Regexp.new(Date.today.to_s), file_contents(file)
end
Then /^I should see "(.*)" in the build output$/ do |text|
assert_match Regexp.new(text), jekyll_run_output
end

65
features/support/env.rb Normal file
View File

@@ -0,0 +1,65 @@
require 'fileutils'
require 'rr'
require 'test/unit'
require 'time'
JEKYLL_SOURCE_DIR = File.dirname(File.dirname(File.dirname(__FILE__)))
TEST_DIR = File.expand_path(File.join('..', '..', 'tmp', 'jekyll'), File.dirname(__FILE__))
JEKYLL_PATH = File.join(File.dirname(__FILE__), '..', '..', 'bin', 'jekyll')
JEKYLL_COMMAND_OUTPUT_FILE = File.join(File.dirname(TEST_DIR), 'jekyll_output.txt')
def source_dir(*files)
File.join(TEST_DIR, *files)
end
def jekyll_output_file
JEKYLL_COMMAND_OUTPUT_FILE
end
def jekyll_run_output
File.read(jekyll_output_file)
end
def run_jekyll(args)
system "#{JEKYLL_PATH} #{args} --trace > #{jekyll_output_file} 2>&1"
end
def slug(title)
if title
title.downcase.gsub(/[^\w]/, " ").strip.gsub(/\s+/, '-')
else
Time.now.strftime("%s%9N") # nanoseconds since the Epoch
end
end
def location(folder, direction)
if folder
before = folder if direction == "in"
after = folder if direction == "under"
end
[before || '.', after || '.']
end
def file_contents(path)
File.open(path) do |file|
file.readlines.join # avoid differences with \n and \r\n line endings
end
end
def seconds_agnostic_datetime(datetime = Time.now)
date, time, zone = datetime.to_s.split(" ")
time = seconds_agnostic_time(time)
[
Regexp.escape(date),
"#{time}:\\d{2}",
Regexp.escape(zone)
].join("\\ ")
end
def seconds_agnostic_time(time)
if time.is_a? Time
time = time.strftime("%H:%M:%S")
end
hour, minutes, _ = time.split(":")
"#{hour}:#{minutes}"
end

View File

@@ -1,184 +0,0 @@
require 'fileutils'
require 'colorator'
require 'cucumber/formatter/console'
require 'cucumber/formatter/io'
module Jekyll
module Cucumber
class Formatter
attr_accessor :indent, :runtime
include ::Cucumber::Formatter::Console
include ::Cucumber::Formatter::Io
include FileUtils
CHARS = {
:failed => "\u2718".red,
:pending => "\u203D".yellow,
:undefined => "\u2718".red,
:passed => "\u2714".green,
:skipped => "\u203D".blue
}
#
def initialize(runtime, path_or_io, options)
@runtime = runtime
@snippets_input = []
@io = ensure_io(path_or_io)
@prefixes = options[:prefixes] || {}
@delayed_messages = []
@options = options
@exceptions = []
@indent = 0
end
#
def before_features(features)
print_profile_information
end
#
def after_features(features)
@io.puts
print_summary(features)
end
#
def before_feature(feature)
@exceptions = []
@indent = 0
end
#
def tag_name(tag_name); end
def comment_line(comment_line); end
def after_feature_element(feature_element); end
def after_tags(tags); end
#
def before_feature_element(feature_element)
@indent = 2
@scenario_indent = 2
end
#
def before_background(background)
@scenario_indent = 2
@in_background = true
@indent = 2
end
#
def after_background(background)
@in_background = nil
end
#
def background_name(keyword, name, source_line, indend)
print_feature_element_name(
keyword, name, source_line, indend
)
end
#
def scenario_name(keyword, name, source_line, indent)
print_feature_element_name(
keyword, name, source_line, indent
)
end
#
def before_step(step)
@current_step = step
end
#
def before_step_result(keyword, step_match, multiline_arg, status, exception, \
source_indent, background, file_colon_line)
@hide_this_step = false
if exception
if @exceptions.include?(exception)
@hide_this_step = true
return
end
@exceptions << exception
end
if status != :failed && @in_background ^ background
@hide_this_step = true
return
end
@status = status
end
#
def step_name(keyword, step_match, status, source_indent, background, file_colon_line)
@io.print CHARS[status]
@io.print " "
end
#
def exception(exception, status)
return if @hide_this_step
@io.puts
print_exception(exception, status, @indent)
@io.flush
end
#
def after_test_step(test_step, result)
collect_snippet_data(
test_step, result
)
end
#
private
def print_feature_element_name(keyword, name, source_line, indent)
@io.puts
names = name.empty? ? [name] : name.each_line.to_a
line = " #{keyword}: #{names[0]}"
@io.print(source_line) if @options[:source]
@io.print(line)
@io.print " "
@io.flush
end
#
def cell_prefix(status)
@prefixes[status]
end
#
def print_summary(features)
@io.puts
print_stats(features, @options)
print_snippets(@options)
print_passing_wip(@options)
end
end
end
end

View File

@@ -1,161 +0,0 @@
require "fileutils"
require "jekyll/utils"
require "open3"
require "time"
require "safe_yaml/load"
class Paths
SOURCE_DIR = Pathname.new(File.expand_path("../..", __dir__))
def self.test_dir; source_dir.join("tmp", "jekyll"); end
def self.output_file; test_dir.join("jekyll_output.txt"); end
def self.status_file; test_dir.join("jekyll_status.txt"); end
def self.jekyll_bin; source_dir.join("bin", "jekyll"); end
def self.source_dir; SOURCE_DIR; end
end
#
def file_content_from_hash(input_hash)
matter_hash = input_hash.reject { |k, v| k == "content" }
matter = matter_hash.map do |k, v| "#{k}: #{v}\n"
end
matter = matter.join.chomp
content = \
if !input_hash['input'] || !input_hash['filter']
then input_hash['content']
else "{{ #{input_hash['input']} | " \
"#{input_hash['filter']} }}"
end
Jekyll::Utils.strip_heredoc(<<-EOF)
---
#{matter.gsub(
/\n/, "\n "
)}
---
#{content}
EOF
end
#
def source_dir(*files)
return Paths.test_dir(*files)
end
#
def all_steps_to_path(path)
source = source_dir
dest = Pathname.new(path).expand_path
paths = []
dest.ascend do |f|
break if f == source
paths.unshift f.to_s
end
paths
end
#
def jekyll_run_output
if Paths.output_file.file?
then return Paths.output_file.read
end
end
#
def jekyll_run_status
if Paths.status_file.file?
then return Paths.status_file.read
end
end
#
def run_bundle(args)
run_in_shell("bundle", *args.strip.split(' '))
end
#
def run_jekyll(args)
args = args.strip.split(" ") # Shellwords?
process = run_in_shell(Paths.jekyll_bin.to_s, *args, "--trace")
process.exitstatus == 0
end
#
def run_in_shell(*args)
i, o, e, p = Open3.popen3(*args)
out = o.read.strip
err = e.read.strip
[i, o, e].each do |m|
m.close
end
File.write(Paths.status_file, p.value.exitstatus)
File.open(Paths.output_file, "wb") do |f|
f.puts "$ " << args.join(" ")
f.puts out
f.puts err
f.puts "EXIT STATUS: #{p.value.exitstatus}"
end
p.value
end
#
def slug(title = nil)
if !title
then Time.now.strftime("%s%9N") # nanoseconds since the Epoch
else title.downcase.gsub(/[^\w]/, " ").strip.gsub(/\s+/, '-')
end
end
#
def location(folder, direction)
if folder
before = folder if direction == "in"
after = folder if direction == "under"
end
[before || '.',
after || '.']
end
#
def file_contents(path)
return Pathname.new(path).read
end
#
def seconds_agnostic_datetime(datetime = Time.now)
date, time, zone = datetime.to_s.split(" ")
time = seconds_agnostic_time(time)
[
Regexp.escape(date),
"#{time}:\\d{2}",
Regexp.escape(zone)
] \
.join("\\ ")
end
#
def seconds_agnostic_time(time)
time = time.strftime("%H:%M:%S") if time.is_a?(Time)
hour, minutes, _ = time.split(":")
"#{hour}:#{minutes}"
end

View File

@@ -5,35 +5,59 @@ require 'jekyll/version'
Gem::Specification.new do |s|
s.specification_version = 2 if s.respond_to? :specification_version=
s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version=
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = '2.2.2'
s.required_ruby_version = '>= 2.0.0'
s.required_ruby_version = '>= 1.9.3'
s.name = 'jekyll'
s.version = Jekyll::VERSION
s.license = 'MIT'
s.name = 'jekyll'
s.version = Jekyll::VERSION
s.license = 'MIT'
s.summary = 'A simple, blog aware, static site generator.'
s.description = 'Jekyll is a simple, blog aware, static site generator.'
s.summary = "A simple, blog aware, static site generator."
s.description = "Jekyll is a simple, blog aware, static site generator."
s.authors = ['Tom Preston-Werner']
s.email = 'tom@mojombo.com'
s.homepage = 'https://github.com/jekyll/jekyll'
s.authors = ["Tom Preston-Werner"]
s.email = 'tom@mojombo.com'
s.homepage = 'https://github.com/jekyll/jekyll'
all_files = `git ls-files -z`.split("\x0")
s.files = all_files.grep(%r{^(bin|lib)/|^.rubocop.yml$})
s.executables = all_files.grep(%r{^bin/}) { |f| File.basename(f) }
s.require_paths = ['lib']
s.files = `git ls-files`.split($/)
s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ["lib"]
s.rdoc_options = ['--charset=UTF-8']
s.rdoc_options = ["--charset=UTF-8"]
s.extra_rdoc_files = %w[README.markdown LICENSE]
s.add_runtime_dependency('liquid', '~> 3.0')
s.add_runtime_dependency('kramdown', '~> 1.3')
s.add_runtime_dependency('mercenary', '~> 0.3.3')
s.add_runtime_dependency('safe_yaml', '~> 1.0')
s.add_runtime_dependency('colorator', '~> 0.1')
s.add_runtime_dependency('rouge', '~> 1.7')
s.add_runtime_dependency('liquid', "~> 2.6.1")
s.add_runtime_dependency('classifier', "~> 1.3")
s.add_runtime_dependency('listen', [">= 2.7.6", "< 3.0.0"])
s.add_runtime_dependency('kramdown', "~> 1.3")
s.add_runtime_dependency('pygments.rb', "~> 0.6.0")
s.add_runtime_dependency('mercenary', "~> 0.3.3")
s.add_runtime_dependency('safe_yaml', "~> 1.0")
s.add_runtime_dependency('colorator', "~> 0.1")
s.add_runtime_dependency('redcarpet', "~> 3.1")
s.add_runtime_dependency('toml', '~> 0.1.0')
s.add_runtime_dependency('jekyll-paginate', '~> 1.0')
s.add_runtime_dependency('jekyll-gist', '~> 1.0')
s.add_runtime_dependency('jekyll-coffeescript', '~> 1.0')
s.add_runtime_dependency('jekyll-sass-converter', '~> 1.0')
s.add_runtime_dependency('jekyll-watch', '~> 1.1')
s.add_development_dependency('rake', "~> 10.1")
s.add_development_dependency('rdoc', "~> 3.11")
s.add_development_dependency('redgreen', "~> 1.2")
s.add_development_dependency('shoulda', "~> 3.5")
s.add_development_dependency('rr', "~> 1.1")
s.add_development_dependency('cucumber', "1.3.11")
s.add_development_dependency('RedCloth', "~> 4.2")
s.add_development_dependency('maruku', "0.7.0")
s.add_development_dependency('rdiscount', "~> 1.6")
s.add_development_dependency('launchy', "~> 2.3")
s.add_development_dependency('simplecov', "~> 0.7")
s.add_development_dependency('simplecov-gem-adapter', "~> 1.0.1")
s.add_development_dependency('mime-types', "~> 1.5")
s.add_development_dependency('activesupport', '~> 3.2.13')
s.add_development_dependency('jekyll_test_plugin')
s.add_development_dependency('jekyll_test_plugin_malicious')
s.add_development_dependency('rouge', '~> 1.3')
end

View File

@@ -1,4 +1,4 @@
$LOAD_PATH.unshift File.dirname(__FILE__) # For use/testing when no gem is installed
$:.unshift File.dirname(__FILE__) # For use/testing when no gem is installed
# Require all of the Ruby files in the given directory.
#
@@ -16,165 +16,131 @@ end
require 'rubygems'
# stdlib
require 'forwardable'
require 'fileutils'
require 'time'
require 'safe_yaml/load'
require 'English'
require 'pathname'
require 'logger'
require 'set'
# 3rd party
require 'safe_yaml/load'
require 'liquid'
require 'kramdown'
require 'colorator'
require 'toml'
# internal requires
require 'jekyll/version'
require 'jekyll/utils'
require 'jekyll/hooks'
require 'jekyll/log_adapter'
require 'jekyll/stevenson'
require 'jekyll/deprecator'
require 'jekyll/configuration'
require 'jekyll/document'
require 'jekyll/collection'
require 'jekyll/plugin_manager'
require 'jekyll/frontmatter_defaults'
require 'jekyll/site'
require 'jekyll/convertible'
require 'jekyll/url'
require 'jekyll/layout'
require 'jekyll/page'
require 'jekyll/post'
require 'jekyll/excerpt'
require 'jekyll/draft'
require 'jekyll/filters'
require 'jekyll/static_file'
require 'jekyll/errors'
require 'jekyll/related_posts'
require 'jekyll/cleaner'
require 'jekyll/entry_filter'
require 'jekyll/layout_reader'
require 'jekyll/publisher'
require 'jekyll/renderer'
# extensions
require 'jekyll/plugin'
require 'jekyll/converter'
require 'jekyll/generator'
require 'jekyll/command'
require 'jekyll/liquid_extensions'
require_all 'jekyll/commands'
require_all 'jekyll/converters'
require_all 'jekyll/converters/markdown'
require_all 'jekyll/generators'
require_all 'jekyll/tags'
# plugins
require 'jekyll-coffeescript'
require 'jekyll-sass-converter'
require 'jekyll-paginate'
require 'jekyll-gist'
SafeYAML::OPTIONS[:suppress_warnings] = true
module Jekyll
# internal requires
autoload :Cleaner, 'jekyll/cleaner'
autoload :Collection, 'jekyll/collection'
autoload :Configuration, 'jekyll/configuration'
autoload :Convertible, 'jekyll/convertible'
autoload :Deprecator, 'jekyll/deprecator'
autoload :Document, 'jekyll/document'
autoload :Draft, 'jekyll/draft'
autoload :EntryFilter, 'jekyll/entry_filter'
autoload :Errors, 'jekyll/errors'
autoload :Excerpt, 'jekyll/excerpt'
autoload :External, 'jekyll/external'
autoload :Filters, 'jekyll/filters'
autoload :FrontmatterDefaults, 'jekyll/frontmatter_defaults'
autoload :Hooks, 'jekyll/hooks'
autoload :Layout, 'jekyll/layout'
autoload :CollectionReader, 'jekyll/readers/collection_reader'
autoload :DataReader, 'jekyll/readers/data_reader'
autoload :LayoutReader, 'jekyll/readers/layout_reader'
autoload :PostReader, 'jekyll/readers/post_reader'
autoload :PageReader, 'jekyll/readers/page_reader'
autoload :StaticFileReader, 'jekyll/readers/static_file_reader'
autoload :LogAdapter, 'jekyll/log_adapter'
autoload :Page, 'jekyll/page'
autoload :PluginManager, 'jekyll/plugin_manager'
autoload :Publisher, 'jekyll/publisher'
autoload :Reader, 'jekyll/reader'
autoload :Regenerator, 'jekyll/regenerator'
autoload :RelatedPosts, 'jekyll/related_posts'
autoload :Renderer, 'jekyll/renderer'
autoload :LiquidRenderer, 'jekyll/liquid_renderer'
autoload :Site, 'jekyll/site'
autoload :StaticFile, 'jekyll/static_file'
autoload :Stevenson, 'jekyll/stevenson'
autoload :URL, 'jekyll/url'
autoload :Utils, 'jekyll/utils'
autoload :VERSION, 'jekyll/version'
# extensions
require 'jekyll/plugin'
require 'jekyll/converter'
require 'jekyll/generator'
require 'jekyll/command'
require 'jekyll/liquid_extensions'
# Public: Tells you which Jekyll environment you are building in so you can skip tasks
# if you need to. This is useful when doing expensive compression tasks on css and
# images and allows you to skip that when working in development.
class << self
# Public: Tells you which Jekyll environment you are building in so you can skip tasks
# if you need to. This is useful when doing expensive compression tasks on css and
# images and allows you to skip that when working in development.
def self.env
ENV["JEKYLL_ENV"] || "development"
end
def env
ENV["JEKYLL_ENV"] || "development"
# Public: Generate a Jekyll configuration Hash by merging the default
# options with anything in _config.yml, and adding the given options on top.
#
# override - A Hash of config directives that override any options in both
# the defaults and the config file. See Jekyll::Configuration::DEFAULTS for a
# list of option names and their defaults.
#
# Returns the final configuration Hash.
def self.configuration(override)
config = Configuration[Configuration::DEFAULTS]
override = Configuration[override].stringify_keys
config = config.read_config_files(config.config_files(override))
# Merge DEFAULTS < _config.yml < override
config = Utils.deep_merge_hashes(config, override).stringify_keys
set_timezone(config['timezone']) if config['timezone']
config
end
# Static: Set the TZ environment variable to use the timezone specified
#
# timezone - the IANA Time Zone
#
# Returns nothing
def self.set_timezone(timezone)
ENV['TZ'] = timezone
end
def self.logger
@logger ||= LogAdapter.new(Stevenson.new)
end
def self.logger=(writer)
@logger = LogAdapter.new(writer)
end
# Public: File system root
#
# Returns the root of the filesystem as a Pathname
def self.fs_root
@fs_root ||= "/"
end
def self.sanitized_path(base_directory, questionable_path)
clean_path = File.expand_path(questionable_path, fs_root)
clean_path.gsub!(/\A\w\:\//, '/')
unless clean_path.start_with?(base_directory)
File.join(base_directory, clean_path)
else
clean_path
end
# Public: Generate a Jekyll configuration Hash by merging the default
# options with anything in _config.yml, and adding the given options on top.
#
# override - A Hash of config directives that override any options in both
# the defaults and the config file. See Jekyll::Configuration::DEFAULTS for a
# list of option names and their defaults.
#
# Returns the final configuration Hash.
def configuration(override = {})
config = Configuration[Configuration::DEFAULTS]
override = Configuration[override].stringify_keys
unless override.delete('skip_config_files')
config = config.read_config_files(config.config_files(override))
end
# Merge DEFAULTS < _config.yml < override
config = Utils.deep_merge_hashes(config, override).stringify_keys
set_timezone(config['timezone']) if config['timezone']
config
end
# Public: Set the TZ environment variable to use the timezone specified
#
# timezone - the IANA Time Zone
#
# Returns nothing
def set_timezone(timezone)
ENV['TZ'] = timezone
end
# Public: Fetch the logger instance for this Jekyll process.
#
# Returns the LogAdapter instance.
def logger
@logger ||= LogAdapter.new(Stevenson.new, (ENV["JEKYLL_LOG_LEVEL"] || :info).to_sym)
end
# Public: Set the log writer.
# New log writer must respond to the same methods
# as Ruby's interal Logger.
#
# writer - the new Logger-compatible log transport
#
# Returns the new logger.
def logger=(writer)
@logger = LogAdapter.new(writer, (ENV["JEKYLL_LOG_LEVEL"] || :info).to_sym)
end
# Public: An array of sites
#
# Returns the Jekyll sites created.
def sites
@sites ||= []
end
# Public: Ensures the questionable path is prefixed with the base directory
# and prepends the questionable path with the base directory if false.
#
# base_directory - the directory with which to prefix the questionable path
# questionable_path - the path we're unsure about, and want prefixed
#
# Returns the sanitized path.
def sanitized_path(base_directory, questionable_path)
return base_directory if base_directory.eql?(questionable_path)
questionable_path.insert(0, '/') if questionable_path.start_with?('~')
clean_path = File.expand_path(questionable_path, "/")
clean_path.sub!(/\A\w\:\//, '/')
if clean_path.start_with?(base_directory.sub(/\A\w\:\//, '/'))
clean_path
else
File.join(base_directory, clean_path)
end
end
# Conditional optimizations
Jekyll::External.require_if_present('liquid-c')
end
end
require "jekyll/drops/drop"
require_all 'jekyll/commands'
require_all 'jekyll/converters'
require_all 'jekyll/converters/markdown'
require_all 'jekyll/drops'
require_all 'jekyll/generators'
require_all 'jekyll/tags'
require 'jekyll-sass-converter'

View File

@@ -1,106 +1,95 @@
require 'set'
module Jekyll
# Handles the cleanup of a site's destination before it is built.
class Cleaner
HIDDEN_FILE_REGEX = /\/\.{1,2}$/
attr_reader :site
class Site
# Handles the cleanup of a site's destination before it is built.
class Cleaner
attr_reader :site
def initialize(site)
@site = site
end
# Cleans up the site's destination directory
def cleanup!
FileUtils.rm_rf(obsolete_files)
FileUtils.rm_rf(metadata_file) unless @site.incremental?
end
private
# Private: The list of files and directories to be deleted during cleanup process
#
# Returns an Array of the file and directory paths
def obsolete_files
(existing_files - new_files - new_dirs + replaced_files).to_a
end
# Private: The metadata file storing dependency tree and build history
#
# Returns an Array with the metdata file as the only item
def metadata_file
[site.regenerator.metadata_file]
end
# Private: The list of existing files, apart from those included in keep_files and hidden files.
#
# Returns a Set with the file paths
def existing_files
files = Set.new
regex = keep_file_regex
dirs = keep_dirs
Utils.safe_glob(site.in_dest_dir, ["**", "*"], File::FNM_DOTMATCH).each do |file|
next if file =~ HIDDEN_FILE_REGEX || file =~ regex || dirs.include?(file)
files << file
def initialize(site)
@site = site
end
files
end
# Private: The list of files to be created when site is built.
#
# Returns a Set with the file paths
def new_files
files = Set.new
site.each_site_file { |item| files << item.destination(site.dest) }
files
end
# Private: The list of directories to be created when site is built.
# These are the parent directories of the files in #new_files.
#
# Returns a Set with the directory paths
def new_dirs
new_files.map { |file| parent_dirs(file) }.flatten.to_set
end
# Private: The list of parent directories of a given file
#
# Returns an Array with the directory paths
def parent_dirs(file)
parent_dir = File.dirname(file)
if parent_dir == site.dest
[]
else
[parent_dir] + parent_dirs(parent_dir)
# Cleans up the site's destination directory
def cleanup!
FileUtils.rm_rf(obsolete_files)
end
end
# Private: The list of existing files that will be replaced by a directory during build
#
# Returns a Set with the file paths
def replaced_files
new_dirs.select { |dir| File.file?(dir) }.to_set
end
private
# Private: The list of directories that need to be kept because they are parent directories
# of files specified in keep_files
#
# Returns a Set with the directory paths
def keep_dirs
site.keep_files.map { |file| parent_dirs(site.in_dest_dir(file)) }.flatten.to_set
end
# Private: The list of files and directories to be deleted during cleanup process
#
# Returns an Array of the file and directory paths
def obsolete_files
(existing_files - new_files - new_dirs + replaced_files).to_a
end
# Private: Creates a regular expression from the config's keep_files array
#
# Examples
# ['.git','.svn'] with site.dest "/myblog/_site" creates
# the following regex: /\A\/myblog\/_site\/(\.git|\/.svn)/
#
# Returns the regular expression
def keep_file_regex
/\A#{Regexp.quote(site.dest)}\/(#{Regexp.union(site.keep_files).source})/
# Private: The list of existing files, apart from those included in keep_files and hidden files.
#
# Returns a Set with the file paths
def existing_files
files = Set.new
Dir.glob(File.join(site.dest, "**", "*"), File::FNM_DOTMATCH) do |file|
files << file unless file =~ /\/\.{1,2}$/ || file =~ keep_file_regex || keep_dirs.include?(file)
end
files
end
# Private: The list of files to be created when site is built.
#
# Returns a Set with the file paths
def new_files
files = Set.new
site.each_site_file { |item| files << item.destination(site.dest) }
files
end
# Private: The list of directories to be created when site is built.
# These are the parent directories of the files in #new_files.
#
# Returns a Set with the directory paths
def new_dirs
new_files.map { |file| parent_dirs(file) }.flatten.to_set
end
# Private: The list of parent directories of a given file
#
# Returns an Array with the directory paths
def parent_dirs(file)
parent_dir = File.dirname(file)
if parent_dir == site.dest
[]
else
[parent_dir] + parent_dirs(parent_dir)
end
end
# Private: The list of existing files that will be replaced by a directory during build
#
# Returns a Set with the file paths
def replaced_files
new_dirs.select { |dir| File.file?(dir) }.to_set
end
# Private: The list of directories that need to be kept because they are parent directories
# of files specified in keep_files
#
# Returns a Set with the directory paths
def keep_dirs
site.keep_files.map{|file| parent_dirs(File.join(site.dest, file))}.flatten.to_set
end
# Private: Creates a regular expression from the config's keep_files array
#
# Examples
# ['.git','.svn'] creates the following regex: /\/(\.git|\/.svn)/
#
# Returns the regular expression
def keep_file_regex
or_list = site.keep_files.join("|")
pattern = "\/(#{or_list.gsub(".", "\.")})"
Regexp.new pattern
end
end
end
end

View File

@@ -1,7 +1,6 @@
module Jekyll
class Collection
attr_reader :site, :label, :metadata
attr_writer :docs
# Create a new Collection.
#
@@ -23,50 +22,14 @@ module Jekyll
@docs ||= []
end
# Override of normal respond_to? to match method_missing's logic for
# looking in @data.
def respond_to?(method, include_private = false)
docs.respond_to?(method.to_sym, include_private) || super
end
# Override of method_missing to check in @data for the key.
def method_missing(method, *args, &blck)
if docs.respond_to?(method.to_sym)
Jekyll.logger.warn "Deprecation:", "#{label}.#{method} should be changed to #{label}.docs.#{method}."
Jekyll.logger.warn "", "Called by #{caller.first}."
docs.public_send(method.to_sym, *args, &blck)
else
super
end
end
# Fetch the static files in this collection.
# Defaults to an empty array if no static files have been read in.
#
# Returns an array of Jekyll::StaticFile objects.
def files
@files ||= []
end
# Read the allowed documents into the collection's array of docs.
#
# Returns the sorted array of docs.
def read
filtered_entries.each do |file_path|
full_path = collection_dir(file_path)
next if File.directory?(full_path)
if Utils.has_yaml_header? full_path
doc = Jekyll::Document.new(full_path, { :site => site, :collection => self })
doc.read
if site.publisher.publish?(doc) || !write?
docs << doc
else
Jekyll.logger.debug "Skipped From Publishing:", doc.relative_path
end
else
relative_dir = Jekyll.sanitized_path(relative_directory, File.dirname(file_path)).chomp("/.")
files << StaticFile.new(site, site.source, relative_dir, File.basename(full_path), self)
end
doc = Jekyll::Document.new(Jekyll.sanitized_path(directory, file_path), { site: site, collection: self })
doc.read
docs << doc
end
docs.sort!
end
@@ -76,12 +39,10 @@ module Jekyll
# Returns an Array of file paths to the documents in this collection
# relative to the collection's directory
def entries
return [] unless exists?
@entries ||=
Utils.safe_glob(collection_dir, ["**", "*"]).map do |entry|
entry["#{collection_dir}/"] = ''
entry
end
return Array.new unless exists?
Dir.glob(File.join(directory, "**", "*.*")).map do |entry|
entry[File.join(directory, "")] = ''; entry
end
end
# Filtered version of the entries in this collection.
@@ -89,14 +50,10 @@ module Jekyll
#
# Returns a list of filtered entry paths.
def filtered_entries
return [] unless exists?
@filtered_entries ||=
Dir.chdir(directory) do
entry_filter.filter(entries).reject do |f|
path = collection_dir(f)
File.directory?(path) || (File.symlink?(f) && site.safe)
end
end
return Array.new unless exists?
Dir.chdir(directory) do
entry_filter.filter(entries)
end
end
# The directory for this Collection, relative to the site source.
@@ -104,28 +61,15 @@ module Jekyll
# Returns a String containing the directory name where the collection
# is stored on the filesystem.
def relative_directory
@relative_directory ||= "_#{label}"
"_#{label}"
end
# The full path to the directory containing the collection.
# The full path to the directory containing the
#
# Returns a String containing th directory name where the collection
# is stored on the filesystem.
def directory
@directory ||= site.in_source_dir(relative_directory)
end
# The full path to the directory containing the collection, with
# optional subpaths.
#
# *files - (optional) any other path pieces relative to the
# directory to append to the path
#
# Returns a String containing th directory name where the collection
# is stored on the filesystem.
def collection_dir(*files)
return directory if files.empty?
site.in_source_dir(relative_directory, *files)
Jekyll.sanitized_path(site.source, relative_directory)
end
# Checks whether the directory "exists" for this collection.
@@ -161,7 +105,7 @@ module Jekyll
#
# Returns a sanitized version of the label.
def sanitize_label(label)
label.gsub(/[^a-z0-9_\-\.]/i, '')
label.gsub(/[^a-z0-9_\-]/i, '')
end
# Produce a representation of this Collection for use in Liquid.
@@ -171,7 +115,13 @@ module Jekyll
#
# Returns a representation of this collection for use in Liquid.
def to_liquid
Drops::CollectionDrop.new self
metadata.merge({
"label" => label,
"docs" => docs,
"directory" => directory,
"output" => write?,
"relative_directory" => relative_directory
})
end
# Whether the collection's documents ought to be written as individual
@@ -179,16 +129,14 @@ module Jekyll
#
# Returns true if the 'write' metadata is true, false otherwise.
def write?
!!metadata.fetch('output', false)
!!metadata['output']
end
# The URL template to render collection's documents at.
#
# Returns the URL template to render collection's documents at.
def url_template
@url_template ||= metadata.fetch('permalink') do
Utils.add_permalink_suffix("/:collection/:path", site.permalink_style)
end
metadata.fetch('permalink', "/:collection/:path:output_ext")
end
# Extract options for this collection from the site configuration.
@@ -196,10 +144,11 @@ module Jekyll
# Returns the metadata for this collection
def extract_metadata
if site.config['collections'].is_a?(Hash)
site.config['collections'][label] || {}
site.config['collections'][label] || Hash.new
else
{}
end
end
end
end

View File

@@ -1,6 +1,8 @@
module Jekyll
class Command
class << self
# A list of subclasses of Jekyll::Command
def subclasses
@subclasses ||= []
@@ -17,6 +19,31 @@ module Jekyll
super(base)
end
# Paths to ignore for the watch option
#
# options - A Hash of options passed to the command
#
# Returns a list of relative paths from source that should be ignored
def ignore_paths(options)
source = options['source']
destination = options['destination']
config_files = Configuration[options].config_files(options)
paths = config_files + Array(destination)
ignored = []
source_abs = Pathname.new(source).expand_path
paths.each do |p|
path_abs = Pathname.new(p).expand_path
begin
rel_path = path_abs.relative_path_from(source_abs).to_s
ignored << Regexp.new(Regexp.escape(rel_path)) unless rel_path.start_with?('../')
rescue ArgumentError
# Could not find a relative path
end
end
ignored
end
# Run Site#process and catch errors
#
# site - the Jekyll::Site object
@@ -24,7 +51,7 @@ module Jekyll
# Returns nothing
def process_site(site)
site.process
rescue Jekyll::Errors::FatalException => e
rescue Jekyll::FatalException => e
Jekyll.logger.error "ERROR:", "YOUR SITE COULD NOT BE BUILT:"
Jekyll.logger.error "", "------------------------------------"
Jekyll.logger.error "", e.message
@@ -47,19 +74,18 @@ module Jekyll
# Returns nothing
def add_build_options(c)
c.option 'config', '--config CONFIG_FILE[,CONFIG_FILE2,...]', Array, 'Custom configuration file'
c.option 'destination', '-d', '--destination DESTINATION', 'The current folder will be generated into DESTINATION'
c.option 'source', '-s', '--source SOURCE', 'Custom source directory'
c.option 'future', '--future', 'Publishes posts with a future date'
c.option 'limit_posts', '--limit_posts MAX_POSTS', Integer, 'Limits the number of posts to parse and publish'
c.option 'watch', '-w', '--[no-]watch', 'Watch for changes and rebuild'
c.option 'watch', '-w', '--watch', 'Watch for changes and rebuild'
c.option 'force_polling', '--force_polling', 'Force watch to use polling'
c.option 'lsi', '--lsi', 'Use LSI for improved related posts'
c.option 'show_drafts', '-D', '--drafts', 'Render posts in the _drafts folder'
c.option 'unpublished', '--unpublished', 'Render posts that were marked as unpublished'
c.option 'quiet', '-q', '--quiet', 'Silence output.'
c.option 'verbose', '-V', '--verbose', 'Print verbose output.'
c.option 'incremental', '-I', '--incremental', 'Enable incremental rebuild.'
end
end
end
end

View File

@@ -1,17 +1,18 @@
module Jekyll
module Commands
class Build < Command
class << self
# Create the Mercenary command for the Jekyll CLI for this Command
def init_with_program(prog)
prog.command(:build) do |c|
c.syntax 'build [options]'
c.description 'Build your site'
c.alias :b
add_build_options(c)
c.action do |_, options|
c.action do |args, options|
options["serving"] = false
Jekyll::Commands::Build.process(options)
end
@@ -21,8 +22,7 @@ module Jekyll
# Build your jekyll site
# Continuously watch if `watch` is set to true in the config.
def process(options)
# Adjust verbosity quickly
Jekyll.logger.adjust_verbosity(options)
Jekyll.logger.log_level = :error if options['quiet']
options = configuration_from_options(options)
site = Jekyll::Site.new(options)
@@ -32,33 +32,23 @@ module Jekyll
else
build(site, options)
end
if options.fetch('detach', false)
Jekyll.logger.info "Auto-regeneration:", "disabled when running server detached."
elsif options.fetch('watch', false)
watch(site, options)
else
Jekyll.logger.info "Auto-regeneration:", "disabled. Use --watch to enable."
end
watch(site, options) if options['watch']
end
# Build your Jekyll site.
#
# site - the Jekyll::Site instance to build
# options - A Hash of options passed to the command
# options - the
#
# Returns nothing.
def build(site, options)
t = Time.now
source = options['source']
destination = options['destination']
incremental = options['incremental']
Jekyll.logger.info "Source:", source
Jekyll.logger.info "Destination:", destination
Jekyll.logger.info "Incremental build:", (incremental ? "enabled" : "disabled. Enable with --incremental")
Jekyll.logger.info "Generating..."
process_site(site)
Jekyll.logger.info "", "done in #{(Time.now - t).round(3)} seconds."
Jekyll.logger.info "", "done."
end
# Private: Watch for file changes and rebuild the site.
@@ -67,11 +57,43 @@ module Jekyll
# options - A Hash of options passed to the command
#
# Returns nothing.
def watch(_site, options)
External.require_with_graceful_fail 'jekyll-watch'
Jekyll::Watcher.watch(options)
def watch(site, options)
require 'listen'
listener = Listen.to(
options['source'],
:ignore => ignore_paths(options),
:force_polling => options['force_polling']
) do |modified, added, removed|
t = Time.now.strftime("%Y-%m-%d %H:%M:%S")
n = modified.length + added.length + removed.length
print Jekyll.logger.formatted_topic("Regenerating:") + "#{n} files at #{t} "
begin
process_site(site)
puts "...done."
rescue => e
puts "...error:"
Jekyll.logger.warn "Error:", e.message
Jekyll.logger.warn "Error:", "Run jekyll build --trace for more information."
end
end
listener.start
Jekyll.logger.info "Auto-regeneration:", "enabled for '#{source}'"
unless options['serving']
trap("INT") do
listener.stop
puts " Halting auto-regeneration."
exit 0
end
loop { sleep 1000 }
end
end
end # end of class << self
end
end
end

View File

@@ -1,40 +0,0 @@
module Jekyll
module Commands
class Clean < Command
class << self
def init_with_program(prog)
prog.command(:clean) do |c|
c.syntax 'clean [subcommand]'
c.description 'Clean the site (removes site output and metadata file) without building.'
add_build_options(c)
c.action do |_, options|
Jekyll::Commands::Clean.process(options)
end
end
end
def process(options)
options = configuration_from_options(options)
destination = options['destination']
metadata_file = File.join(options['source'], '.jekyll-metadata')
sass_cache = File.join(options['source'], '.sass-cache')
remove(destination, checker_func: :directory?)
remove(metadata_file, checker_func: :file?)
remove(sass_cache, checker_func: :directory?)
end
def remove(filename, checker_func: :file?)
if File.public_send(checker_func, filename)
Jekyll.logger.info "Cleaner:", "Removing #{filename}..."
FileUtils.rm_rf(filename)
else
Jekyll.logger.info "Cleaner:", "Nothing to do for #{filename}."
end
end
end
end
end
end

View File

@@ -0,0 +1,30 @@
module Jekyll
module Commands
class Docs < Command
class << self
def init_with_program(prog)
prog.command(:docs) do |c|
c.syntax 'docs'
c.description "Launch local server with docs for Jekyll v#{Jekyll::VERSION}"
c.option 'port', '-P', '--port [PORT]', 'Port to listen on'
c.option 'host', '-H', '--host [HOST]', 'Host to bind to'
c.action do |args, options|
options.merge!({
'source' => File.expand_path("../../../site", File.dirname(__FILE__)),
'destination' => File.expand_path("../../../site/_site", File.dirname(__FILE__))
})
Jekyll::Commands::Build.process(options)
Jekyll::Commands::Serve.process(options)
end
end
end
end
end
end
end

View File

@@ -2,15 +2,16 @@ module Jekyll
module Commands
class Doctor < Command
class << self
def init_with_program(prog)
prog.command(:doctor) do |c|
c.syntax 'doctor'
c.description 'Search site and print specific deprecation warnings'
c.alias(:hyde)
c.option 'config', '--config CONFIG_FILE[,CONFIG_FILE2,...]', Array, 'Custom configuration file'
c.option '--config CONFIG_FILE[,CONFIG_FILE2,...]', Array, 'Custom configuration file'
c.action do |_, options|
c.action do |args, options|
Jekyll::Commands::Doctor.process(options)
end
end
@@ -29,66 +30,41 @@ module Jekyll
def healthy?(site)
[
fsnotify_buggy?(site),
!deprecated_relative_permalinks(site),
!conflicting_urls(site),
!urls_only_differ_by_case(site)
!conflicting_urls(site)
].all?
end
def deprecated_relative_permalinks(site)
if site.config['relative_permalinks']
Jekyll::Deprecator.deprecation_message "Your site still uses relative" \
" permalinks, which was removed in" \
" Jekyll v3.0.0."
return true
contains_deprecated_pages = false
site.pages.each do |page|
if page.uses_relative_permalinks
Jekyll.logger.warn "Deprecation:", "'#{page.path}' uses relative" +
" permalinks which will be deprecated in" +
" Jekyll v2.0.0 and beyond."
contains_deprecated_pages = true
end
end
contains_deprecated_pages
end
def conflicting_urls(site)
conflicting_urls = false
urls = {}
urls = collect_urls(urls, site.pages, site.dest)
urls = collect_urls(urls, site.posts.docs, site.dest)
urls = collect_urls(urls, site.posts, site.dest)
urls.each do |url, paths|
next unless paths.size > 1
conflicting_urls = true
Jekyll.logger.warn "Conflict:", "The URL '#{url}' is the destination" \
" for the following pages: #{paths.join(", ")}"
if paths.size > 1
conflicting_urls = true
Jekyll.logger.warn "Conflict:", "The URL '#{url}' is the destination" +
" for the following pages: #{paths.join(", ")}"
end
end
conflicting_urls
end
def fsnotify_buggy?(_site)
return true unless Utils::Platforms.osx?
if Dir.pwd != `pwd`.strip
Jekyll.logger.error " " + <<-STR.strip.gsub(/\n\s+/, "\n ")
We have detected that there might be trouble using fsevent on your
operating system, you can read https://github.com/thibaudgg/rb-fsevent/wiki/no-fsevents-fired-(OSX-bug)
for possible work arounds or you can work around it immediately
with `--force-polling`.
STR
false
end
true
end
def urls_only_differ_by_case(site)
urls_only_differ_by_case = false
urls = case_insensitive_urls(site.pages + site.docs_to_write, site.dest)
urls.each do |case_insensitive_url, real_urls|
next unless real_urls.uniq.size > 1
urls_only_differ_by_case = true
Jekyll.logger.warn "Warning:", "The following URLs only differ" \
" by case. On a case-insensitive file system one of the URLs" \
" will be overwritten by the other: #{real_urls.join(", ")}"
end
urls_only_differ_by_case
end
private
def collect_urls(urls, things, destination)
things.each do |thing|
dest = thing.destination(destination)
@@ -101,14 +77,8 @@ module Jekyll
urls
end
def case_insensitive_urls(things, destination)
things.inject({}) do |memo, thing|
dest = thing.destination(destination)
(memo[dest.downcase] ||= []) << dest
memo
end
end
end
end
end
end

View File

@@ -1,31 +0,0 @@
module Jekyll
module Commands
class Help < Command
class << self
def init_with_program(prog)
prog.command(:help) do |c|
c.syntax 'help [subcommand]'
c.description 'Show the help message, optionally for a given subcommand.'
c.action do |args, _|
cmd = (args.first || "").to_sym
if args.empty?
puts prog
elsif prog.has_command? cmd
puts prog.commands[cmd]
else
invalid_command(prog, cmd)
abort
end
end
end
end
def invalid_command(prog, cmd)
Jekyll.logger.error "Error:", "Hmm... we don't know what the '#{cmd}' command is."
Jekyll.logger.info "Valid commands:", prog.commands.keys.join(", ")
end
end
end
end
end

View File

@@ -3,108 +3,77 @@ require 'erb'
module Jekyll
module Commands
class New < Command
class << self
def init_with_program(prog)
prog.command(:new) do |c|
c.syntax 'new PATH'
c.description 'Creates a new Jekyll site scaffold in PATH'
def self.init_with_program(prog)
prog.command(:new) do |c|
c.syntax 'new PATH'
c.description 'Creates a new Jekyll site scaffold in PATH'
c.option 'force', '--force', 'Force creation even if PATH already exists'
c.option 'blank', '--blank', 'Creates scaffolding but with empty files'
c.option 'force', '--force', 'Force creation even if PATH already exists'
c.option 'blank', '--blank', 'Creates scaffolding but with empty files'
c.action do |args, options|
Jekyll::Commands::New.process(args, options)
end
c.action do |args, options|
Jekyll::Commands::New.process(args, options)
end
end
end
def self.process(args, options = {})
raise ArgumentError.new('You must specify a path.') if args.empty?
new_blog_path = File.expand_path(args.join(" "), Dir.pwd)
FileUtils.mkdir_p new_blog_path
if preserve_source_location?(new_blog_path, options)
Jekyll.logger.abort_with "Conflict:", "#{new_blog_path} exists and is not empty."
end
if options["blank"]
create_blank_site new_blog_path
else
create_sample_files new_blog_path
File.open(File.expand_path(initialized_post_name, new_blog_path), "w") do |f|
f.write(scaffold_post_content)
end
end
def process(args, options = {})
raise ArgumentError.new('You must specify a path.') if args.empty?
Jekyll.logger.info "New jekyll site installed in #{new_blog_path}."
end
new_blog_path = File.expand_path(args.join(" "), Dir.pwd)
FileUtils.mkdir_p new_blog_path
if preserve_source_location?(new_blog_path, options)
Jekyll.logger.abort_with "Conflict:", "#{new_blog_path} exists and is not empty."
end
if options["blank"]
create_blank_site new_blog_path
else
create_sample_files new_blog_path
File.open(File.expand_path(initialized_post_name, new_blog_path), "w") do |f|
f.write(scaffold_post_content)
end
File.open(File.expand_path("Gemfile", new_blog_path), "w") do |f|
f.write(gemfile_contents)
end
end
Jekyll.logger.info "New jekyll site installed in #{new_blog_path}."
def self.create_blank_site(path)
Dir.chdir(path) do
FileUtils.mkdir(%w(_layouts _posts _drafts))
FileUtils.touch("index.html")
end
end
def create_blank_site(path)
Dir.chdir(path) do
FileUtils.mkdir(%w(_layouts _posts _drafts))
FileUtils.touch("index.html")
end
end
def self.scaffold_post_content
ERB.new(File.read(File.expand_path(scaffold_path, site_template))).result
end
def scaffold_post_content
ERB.new(File.read(File.expand_path(scaffold_path, site_template))).result
end
# Internal: Gets the filename of the sample post to be created
#
# Returns the filename of the sample post, as a String
def self.initialized_post_name
"_posts/#{Time.now.strftime('%Y-%m-%d')}-welcome-to-jekyll.markdown"
end
# Internal: Gets the filename of the sample post to be created
#
# Returns the filename of the sample post, as a String
def initialized_post_name
"_posts/#{Time.now.strftime('%Y-%m-%d')}-welcome-to-jekyll.markdown"
end
private
private
def gemfile_contents
<<-RUBY
source "https://rubygems.org"
# Hello! This is where you manage which Jekyll version is used to run.
# When you want to use a different version, change it below, save the
# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
#
# bundle exec jekyll serve
#
# This will help ensure the proper Jekyll version is running.
# Happy Jekylling!
gem "jekyll", "#{Jekyll::VERSION}"
def self.preserve_source_location?(path, options)
!options["force"] && !Dir["#{path}/**/*"].empty?
end
# If you want to use GitHub Pages, remove the "gem "jekyll"" above and
# uncomment the line below. To upgrade, run `bundle update github-pages`.
# gem "github-pages", group: :jekyll_plugins
# If you have any plugins, put them here!
# group :jekyll_plugins do
# gem "jekyll-github-metadata", "~> 1.0"
# end
RUBY
end
def self.create_sample_files(path)
FileUtils.cp_r site_template + '/.', path
FileUtils.rm File.expand_path(scaffold_path, path)
end
def preserve_source_location?(path, options)
!options["force"] && !Dir["#{path}/**/*"].empty?
end
def self.site_template
File.expand_path("../../site_template", File.dirname(__FILE__))
end
def create_sample_files(path)
FileUtils.cp_r site_template + '/.', path
FileUtils.rm File.expand_path(scaffold_path, path)
end
def site_template
File.expand_path("../../site_template", File.dirname(__FILE__))
end
def scaffold_path
"_posts/0000-00-00-welcome-to-jekyll.markdown.erb"
end
def self.scaffold_path
"_posts/0000-00-00-welcome-to-jekyll.markdown.erb"
end
end
end

View File

@@ -1,205 +1,129 @@
# -*- encoding: utf-8 -*-
module Jekyll
module Commands
class Serve < Command
class << self
COMMAND_OPTIONS = {
"ssl_cert" => ["--ssl-cert [CERT]", "X.509 (SSL) certificate."],
"host" => ["host", "-H", "--host [HOST]", "Host to bind to"],
"open_url" => ["-o", "--open-url", "Launch your browser with your site."],
"detach" => ["-B", "--detach", "Run the server in the background (detach)"],
"ssl_key" => ["--ssl-key [KEY]", "X.509 (SSL) Private Key."],
"port" => ["-P", "--port [PORT]", "Port to listen on"],
"baseurl" => ["-b", "--baseurl [URL]", "Base URL"],
"show_dir_listing" => ["--show-dir-listing",
"Show a directory listing instead of loading your index file."],
"skip_initial_build" => ["skip_initial_build", "--skip-initial-build",
"Skips the initial site build which occurs before the server is started."]
}
#
class << self
def init_with_program(prog)
prog.command(:serve) do |cmd|
cmd.description "Serve your site locally"
cmd.syntax "serve [options]"
cmd.alias :server
cmd.alias :s
prog.command(:serve) do |c|
c.syntax 'serve [options]'
c.description 'Serve your site locally'
c.alias :server
add_build_options(cmd)
COMMAND_OPTIONS.each do |key, val|
cmd.option key, *val
end
add_build_options(c)
cmd.action do |_, opts|
opts["serving"] = true
opts["watch" ] = true unless opts.key?("watch")
Build.process(opts)
Serve.process(opts)
c.option 'detach', '-B', '--detach', 'Run the server in the background (detach)'
c.option 'port', '-P', '--port [PORT]', 'Port to listen on'
c.option 'host', '-H', '--host [HOST]', 'Host to bind to'
c.option 'baseurl', '-b', '--baseurl [URL]', 'Base URL'
c.option 'skip_initial_build', '--skip-initial-build', 'Skips the initial site build which occurs before the server is started.'
c.action do |args, options|
options["serving"] ||= true
Jekyll::Commands::Build.process(options)
Jekyll::Commands::Serve.process(options)
end
end
end
#
def process(opts)
opts = configuration_from_options(opts)
destination = opts["destination"]
# Boot up a WEBrick server which points to the compiled site's root.
def process(options)
options = configuration_from_options(options)
destination = options['destination']
setup(destination)
server = WEBrick::HTTPServer.new(webrick_opts(opts)).tap { |o| o.unmount("") }
server.mount(opts["baseurl"], Servlet, destination, file_handler_opts)
Jekyll.logger.info "Server address:", server_address(server, opts)
launch_browser server, opts if opts["open_url"]
boot_or_detach server, opts
s = WEBrick::HTTPServer.new(webrick_options(options))
s.unmount("")
s.mount(
options['baseurl'],
WEBrick::HTTPServlet::FileHandler,
destination,
file_handler_options
)
Jekyll.logger.info "Server address:", server_address(s, options)
if options['detach'] # detach the server
pid = Process.fork { s.start }
Process.detach(pid)
Jekyll.logger.info "Server detached with pid '#{pid}'.", "Run `kill -9 #{pid}' to stop the server."
else # create a new server thread, then join it with current terminal
t = Thread.new { s.start }
trap("INT") { s.shutdown }
t.join
end
end
# Do a base pre-setup of WEBRick so that everything is in place
# when we get ready to party, checking for an setting up an error page
# and making sure our destination exists.
private
def setup(destination)
require_relative "serve/servlet"
require 'webrick'
FileUtils.mkdir_p(destination)
if File.exist?(File.join(destination, "404.html"))
# monkey patch WEBrick using custom 404 page (/404.html)
if File.exist?(File.join(destination, '404.html'))
WEBrick::HTTPResponse.class_eval do
def create_error_page
@header["Content-Type"] = "text/html; charset=UTF-8"
@body = IO.read(File.join(@config[:DocumentRoot], "404.html"))
@header['content-type'] = "text/html; charset=UTF-8"
@body = IO.read(File.join(@config[:DocumentRoot], '404.html'))
end
end
end
end
#
private
def webrick_opts(opts)
def webrick_options(config)
opts = {
:JekyllOptions => opts,
:DoNotReverseLookup => true,
:DocumentRoot => config['destination'],
:Port => config['port'],
:BindAddress => config['host'],
:MimeTypes => mime_types,
:DocumentRoot => opts["destination"],
:StartCallback => start_callback(opts["detach"]),
:BindAddress => opts["host"],
:Port => opts["port"],
:DirectoryIndex => %W(
index.htm
index.html
index.rhtml
index.cgi
index.xml
)
:DoNotReverseLookup => true,
:StartCallback => start_callback(config['detach']),
:DirectoryIndex => %w(index.html index.htm index.cgi index.rhtml index.xml)
}
opts[:DirectoryIndex] = [] if opts[:JekyllOptions]['show_dir_listing']
if !config['verbose']
opts.merge!({
:AccessLog => [],
:Logger => WEBrick::Log.new([], WEBrick::Log::WARN)
})
end
enable_ssl(opts)
enable_logging(opts)
opts
end
# Recreate NondisclosureName under utf-8 circumstance
private
def file_handler_opts
WEBrick::Config::FileHandler.merge({
:FancyIndexing => true,
:NondisclosureName => [
'.ht*', '~*'
]
})
end
#
private
def server_address(server, opts)
address = server.config[:BindAddress]
baseurl = "#{opts["baseurl"]}/" if opts["baseurl"]
port = server.config[:Port]
"http://#{address}:#{port}#{baseurl}"
end
#
private
def launch_browser(server, opts)
address = server_address(server, opts)
return system "start", address if Utils::Platforms.windows?
return system "xdg-open", address if Utils::Platforms.linux?
return system "open", address if Utils::Platforms.osx?
Jekyll.logger.error "Refusing to launch browser; " \
"Platform launcher unknown."
end
# Keep in our area with a thread or detach the server as requested
# by the user. This method determines what we do based on what you
# ask us to do.
private
def boot_or_detach(server, opts)
if opts["detach"]
pid = Process.fork do
server.start
end
Process.detach(pid)
Jekyll.logger.info "Server detached with pid '#{pid}'.", \
"Run `pkill -f jekyll' or `kill -9 #{pid}' to stop the server."
else
t = Thread.new { server.start }
trap("INT") { server.shutdown }
t.join
end
end
# Make the stack verbose if the user requests it.
private
def enable_logging(opts)
opts[:AccessLog] = []
level = WEBrick::Log.const_get(opts[:JekyllOptions]["verbose"] ? :DEBUG : :WARN)
opts[:Logger] = WEBrick::Log.new($stdout, level)
end
# Add SSL to the stack if the user triggers --enable-ssl and they
# provide both types of certificates commonly needed. Raise if they
# forget to add one of the certificates.
private
def enable_ssl(opts)
return if !opts[:JekyllOptions]["ssl_cert"] && !opts[:JekyllOptions]["ssl_key"]
if !opts[:JekyllOptions]["ssl_cert"] || !opts[:JekyllOptions]["ssl_key"]
raise RuntimeError, "--ssl-cert or --ssl-key missing."
end
require "openssl"
require "webrick/https"
source_key = Jekyll.sanitized_path(opts[:JekyllOptions]["source"], opts[:JekyllOptions]["ssl_key" ])
source_certificate = Jekyll.sanitized_path(opts[:JekyllOptions]["source"], opts[:JekyllOptions]["ssl_cert"])
opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.read(source_certificate))
opts[:SSLPrivateKey ] = OpenSSL::PKey::RSA.new(File.read(source_key))
opts[:EnableSSL] = true
end
private
def start_callback(detached)
unless detached
proc do
Jekyll.logger.info("Server running...", "press ctrl-c to stop.")
end
Proc.new { Jekyll.logger.info "Server running...", "press ctrl-c to stop." }
end
end
private
def mime_types
file = File.expand_path('../mime.types', File.dirname(__FILE__))
WEBrick::HTTPUtils.load_mime_types(file)
mime_types_file = File.expand_path('../mime.types', File.dirname(__FILE__))
WEBrick::HTTPUtils::load_mime_types(mime_types_file)
end
def server_address(server, options)
baseurl = "#{options['baseurl']}/" if options['baseurl']
[
"http://",
server.config[:BindAddress],
":",
server.config[:Port],
baseurl || ""
].map(&:to_s).join("")
end
# recreate NondisclosureName under utf-8 circumstance
def file_handler_options
fh_option = WEBrick::Config::FileHandler
fh_option[:NondisclosureName] = ['.ht*','~*']
fh_option
end
end
end
end
end

View File

@@ -1,61 +0,0 @@
require "webrick"
module Jekyll
module Commands
class Serve
class Servlet < WEBrick::HTTPServlet::FileHandler
DEFAULTS = {
"Cache-Control" => "private, max-age=0, proxy-revalidate, " \
"no-store, no-cache, must-revalidate"
}
def initialize(server, root, callbacks)
# So we can access them easily.
@jekyll_opts = server.config[:JekyllOptions]
set_defaults
super
end
# Add the ability to tap file.html the same way that Nginx does on our
# Docker images (or on GitHub Pages.) The difference is that we might end
# up with a different preference on which comes first.
def search_file(req, res, basename)
# /file.* > /file/index.html > /file.html
super || super(req, res, "#{basename}.html")
end
#
def do_GET(req, res)
rtn = super
validate_and_ensure_charset(req, res)
res.header.merge!(@headers)
rtn
end
#
private
def validate_and_ensure_charset(_req, res)
key = res.header.keys.grep(/content-type/i).first
typ = res.header[key]
unless typ =~ /;\s*charset=/
res.header[key] = "#{typ}; charset=#{@jekyll_opts["encoding"]}"
end
end
#
private
def set_defaults
hash_ = @jekyll_opts.fetch("webrick", {}).fetch("headers", {})
DEFAULTS.each_with_object(@headers = hash_) do |(key, val), hash|
hash[key] = val unless hash.key?(key)
end
end
end
end
end
end

View File

@@ -2,58 +2,59 @@
module Jekyll
class Configuration < Hash
# Default options. Overridden by values in _config.yml.
# Strings rather than symbols are used for compatibility with YAML.
DEFAULTS = Configuration[{
# Where things are
DEFAULTS = {
'source' => Dir.pwd,
'destination' => File.join(Dir.pwd, '_site'),
'plugins_dir' => '_plugins',
'layouts_dir' => '_layouts',
'data_dir' => '_data',
'includes_dir' => '_includes',
'collections' => {},
# Handling Reading
'safe' => false,
'include' => ['.htaccess'],
'exclude' => [],
'keep_files' => ['.git', '.svn'],
'encoding' => 'utf-8',
'markdown_ext' => 'markdown,mkdown,mkdn,mkd,md',
# Filtering Content
'show_drafts' => nil,
'limit_posts' => 0,
'future' => false,
'unpublished' => false,
# Plugins
'whitelist' => [],
'plugins' => '_plugins',
'layouts' => '_layouts',
'data_source' => '_data',
'keep_files' => ['.git','.svn'],
'gems' => [],
'collections' => nil,
# Conversion
'markdown' => 'kramdown',
'highlighter' => 'rouge',
'lsi' => false,
'excerpt_separator' => "\n\n",
'incremental' => false,
# Serving
'detach' => false, # default to not detaching the server
'port' => '4000',
'host' => '127.0.0.1',
'baseurl' => '',
'show_dir_listing' => false,
# Output Configuration
'permalink' => 'date',
'paginate_path' => '/page:num',
'timezone' => nil, # use the local timezone
'quiet' => false,
'verbose' => false,
'defaults' => [],
'encoding' => 'utf-8', # always use utf-8 encoding. NEVER FORGET
'safe' => false,
'detach' => false, # default to not detaching the server
'show_drafts' => nil,
'limit_posts' => 0,
'lsi' => false,
'future' => true, # remove and make true just default
'unpublished' => false,
'relative_permalinks' => false,
'markdown' => 'kramdown',
'highlighter' => 'pygments',
'permalink' => 'date',
'baseurl' => '',
'include' => ['.htaccess'],
'exclude' => [],
'paginate_path' => '/page:num',
'markdown_ext' => 'markdown,mkdown,mkdn,mkd,md',
'textile_ext' => 'textile',
'port' => '4000',
'host' => '0.0.0.0',
'excerpt_separator' => "\n\n",
'defaults' => [],
'maruku' => {
'use_tex' => false,
'use_divs' => false,
'png_engine' => 'blahtex',
'png_dir' => 'images/latex',
'png_url' => '/images/latex',
'fenced_code_blocks' => true
},
'rdiscount' => {
'extensions' => []
@@ -64,25 +65,33 @@ module Jekyll
},
'kramdown' => {
'auto_ids' => true,
'toc_levels' => '1..6',
'entity_output' => 'as_char',
'smart_quotes' => 'lsquo,rsquo,ldquo,rdquo',
'input' => "GFM",
'hard_wrap' => false,
'footnote_nr' => 1
'auto_ids' => true,
'footnote_nr' => 1,
'entity_output' => 'as_char',
'toc_levels' => '1..6',
'smart_quotes' => 'lsquo,rsquo,ldquo,rdquo',
'use_coderay' => false,
'coderay' => {
'coderay_wrap' => 'div',
'coderay_line_numbers' => 'inline',
'coderay_line_number_start' => 1,
'coderay_tab_width' => 4,
'coderay_bold_every' => 10,
'coderay_css' => 'style'
}
},
'redcloth' => {
'hard_breaks' => true
}
}]
}
# Public: Turn all keys into string
#
# Return a copy of the hash where all its keys are strings
def stringify_keys
reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }
end
def get_config_value_with_override(config_key, override)
override[config_key] || self[config_key] || DEFAULTS[config_key]
reduce({}) { |hsh,(k,v)| hsh.merge(k.to_s => v) }
end
# Public: Directory of the Jekyll source folder
@@ -91,26 +100,15 @@ module Jekyll
#
# Returns the path to the Jekyll source directory
def source(override)
get_config_value_with_override('source', override)
override['source'] || self['source'] || DEFAULTS['source']
end
def quiet(override = {})
get_config_value_with_override('quiet', override)
end
alias_method :quiet?, :quiet
def verbose(override = {})
get_config_value_with_override('verbose', override)
end
alias_method :verbose?, :verbose
def safe_load_file(filename)
case File.extname(filename)
when /\.toml/i
Jekyll::External.require_with_graceful_fail('toml') unless defined?(TOML)
when '.toml'
TOML.load_file(filename)
when /\.ya?ml/i
SafeYAML.load_file(filename) || {}
when /\.y(a)?ml/
SafeYAML.load_file(filename)
else
raise ArgumentError, "No parser for '#{filename}' is available. Use a .toml or .y(a)ml file instead."
end
@@ -122,14 +120,11 @@ module Jekyll
#
# Returns an Array of config files
def config_files(override)
# Adjust verbosity quickly
Jekyll.logger.adjust_verbosity(:quiet => quiet?(override), :verbose => verbose?(override))
# Get configuration from <source>/_config.yml or <source>/<config_file>
config_files = override.delete('config')
if config_files.to_s.empty?
default = %w(yml yaml).find(-> { 'yml' }) do |ext|
File.exist?(Jekyll.sanitized_path(source(override), "_config.#{ext}"))
default = %w[yml yaml].find(Proc.new { 'yml' }) do |ext|
File.exists? Jekyll.sanitized_path(source(override), "_config.#{ext}")
end
config_files = Jekyll.sanitized_path(source(override), "_config.#{default}")
@default_config_file = true
@@ -145,11 +140,11 @@ module Jekyll
# Returns this configuration, overridden by the values in the file
def read_config_file(file)
next_config = safe_load_file(file)
check_config_is_hash!(next_config, file)
raise ArgumentError.new("Configuration file: (INVALID) #{file}".yellow) unless next_config.is_a?(Hash)
Jekyll.logger.info "Configuration file:", file
next_config
rescue SystemCallError
if @default_config_file ||= nil
if @default_config_file
Jekyll.logger.warn "Configuration file:", "none"
{}
else
@@ -173,12 +168,12 @@ module Jekyll
configuration = Utils.deep_merge_hashes(configuration, new_config)
end
rescue ArgumentError => err
Jekyll.logger.warn "WARNING:", "Error reading configuration. " \
Jekyll.logger.warn "WARNING:", "Error reading configuration. " +
"Using defaults (and options)."
$stderr.puts "#{err}"
end
configuration.fix_common_issues.backwards_compatibilize.add_default_collections
configuration.fix_common_issues.backwards_compatibilize
end
# Public: Split a CSV string into an array containing its values
@@ -197,128 +192,68 @@ module Jekyll
def backwards_compatibilize
config = clone
# Provide backwards-compatibility
if config.key?('auto') || config.key?('watch')
Jekyll::Deprecator.deprecation_message "Auto-regeneration can no longer" \
" be set from your configuration file(s). Use the"\
" --[no-]watch/-w command-line option instead."
if config.has_key?('auto') || config.has_key?('watch')
Jekyll.logger.warn "Deprecation:", "Auto-regeneration can no longer" +
" be set from your configuration file(s). Use the"+
" --watch/-w command-line option instead."
config.delete('auto')
config.delete('watch')
end
if config.key? 'server'
Jekyll::Deprecator.deprecation_message "The 'server' configuration option" \
" is no longer accepted. Use the 'jekyll serve'" \
if config.has_key? 'server'
Jekyll.logger.warn "Deprecation:", "The 'server' configuration option" +
" is no longer accepted. Use the 'jekyll serve'" +
" subcommand to serve your site with WEBrick."
config.delete('server')
end
renamed_key 'server_port', 'port', config
renamed_key 'plugins', 'plugins_dir', config
renamed_key 'layouts', 'layouts_dir', config
renamed_key 'data_source', 'data_dir', config
if config.has_key? 'server_port'
Jekyll.logger.warn "Deprecation:", "The 'server_port' configuration option" +
" has been renamed to 'port'. Please update your config" +
" file accordingly."
# copy but don't overwrite:
config['port'] = config['server_port'] unless config.has_key?('port')
config.delete('server_port')
end
if config.key? 'pygments'
Jekyll::Deprecator.deprecation_message "The 'pygments' configuration option" \
" has been renamed to 'highlighter'. Please update your" \
" config file accordingly. The allowed values are 'rouge', " \
if config.has_key? 'pygments'
Jekyll.logger.warn "Deprecation:", "The 'pygments' configuration option" +
" has been renamed to 'highlighter'. Please update your" +
" config file accordingly. The allowed values are 'rouge', " +
"'pygments' or null."
config['highlighter'] = 'pygments' if config['pygments']
config.delete('pygments')
end
%w(include exclude).each do |option|
config[option] ||= []
if config[option].is_a?(String)
Jekyll::Deprecator.deprecation_message "The '#{option}' configuration option" \
" must now be specified as an array, but you specified" \
" a string. For now, we've treated the string you provided" \
%w[include exclude].each do |option|
if config.fetch(option, []).is_a?(String)
Jekyll.logger.warn "Deprecation:", "The '#{option}' configuration option" +
" must now be specified as an array, but you specified" +
" a string. For now, we've treated the string you provided" +
" as a list of comma-separated values."
config[option] = csv_to_array(config[option])
end
config[option].map!(&:to_s)
end
if (config['kramdown'] || {}).key?('use_coderay')
Jekyll::Deprecator.deprecation_message "Please change 'use_coderay'" \
" to 'enable_coderay' in your configuration file."
config['kramdown']['use_coderay'] = config['kramdown'].delete('enable_coderay')
end
if config.fetch('markdown', 'kramdown').to_s.downcase.eql?("maruku")
Jekyll.logger.abort_with "Error:", "You're using the 'maruku' " \
"Markdown processor, which has been removed as of 3.0.0. " \
"We recommend you switch to Kramdown. To do this, replace " \
"`markdown: maruku` with `markdown: kramdown` in your " \
"`_config.yml` file."
Jekyll::Deprecator.deprecation_message "You're using the 'maruku' " +
"Markdown processor. Maruku support has been deprecated and will " +
"be removed in 3.0.0. We recommend you switch to Kramdown."
end
config
end
def fix_common_issues
config = clone
if config.key?('paginate') && (!config['paginate'].is_a?(Integer) || config['paginate'] < 1)
Jekyll.logger.warn "Config Warning:", "The `paginate` key must be a" \
if config.has_key?('paginate') && (!config['paginate'].is_a?(Integer) || config['paginate'] < 1)
Jekyll.logger.warn "Config Warning:", "The `paginate` key must be a" +
" positive integer or nil. It's currently set to '#{config['paginate'].inspect}'."
config['paginate'] = nil
end
config
end
def add_default_collections
config = clone
return config if config['collections'].nil?
if config['collections'].is_a?(Array)
config['collections'] = Hash[config['collections'].map { |c| [c, {}] }]
end
config['collections']['posts'] ||= {}
config['collections']['posts']['output'] = true
config['collections']['posts']['permalink'] = style_to_permalink(config['permalink'])
config
end
def renamed_key(old, new, config, _ = nil)
if config.key?(old)
Jekyll::Deprecator.deprecation_message "The '#{old}' configuration" \
"option has been renamed to '#{new}'. Please update your config " \
"file accordingly."
config[new] = config.delete(old)
end
end
private
def style_to_permalink(permalink_style)
case permalink_style.to_sym
when :pretty
"/:categories/:year/:month/:day/:title/"
when :none
"/:categories/:title:output_ext"
when :date
"/:categories/:year/:month/:day/:title:output_ext"
when :ordinal
"/:categories/:year/:y_day/:title:output_ext"
else
permalink_style.to_s
end
end
# Private: Checks if a given config is a hash
#
# extracted_config - the value to check
# file - the file from which the config was extracted
#
# Raises an ArgumentError if given config is not a hash
def check_config_is_hash!(extracted_config, file)
unless extracted_config.is_a?(Hash)
raise ArgumentError.new("Configuration file: (INVALID) #{file}".yellow)
end
end
end
end

View File

@@ -8,9 +8,7 @@ module Jekyll
#
# Returns the String prefix.
def self.highlighter_prefix(highlighter_prefix = nil)
if !defined?(@highlighter_prefix) || !highlighter_prefix.nil?
@highlighter_prefix = highlighter_prefix
end
@highlighter_prefix = highlighter_prefix if highlighter_prefix
@highlighter_prefix
end
@@ -22,9 +20,7 @@ module Jekyll
#
# Returns the String suffix.
def self.highlighter_suffix(highlighter_suffix = nil)
if !defined?(@highlighter_suffix) || !highlighter_suffix.nil?
@highlighter_suffix = highlighter_suffix
end
@highlighter_suffix = highlighter_suffix if highlighter_suffix
@highlighter_suffix
end

View File

@@ -5,7 +5,7 @@ module Jekyll
priority :lowest
def matches(_ext)
def matches(ext)
true
end

View File

@@ -1,62 +1,38 @@
module Jekyll
module Converters
class Markdown < Converter
highlighter_prefix "\n"
highlighter_suffix "\n"
safe true
def setup
return if @setup ||= false
unless (@parser = get_processor)
Jekyll.logger.error "Invalid Markdown processor given:", @config["markdown"]
Jekyll.logger.info "", "Custom processors are not loaded in safe mode" if @config["safe"]
Jekyll.logger.error "", "Available processors are: #{valid_processors.join(", ")}"
raise Errors::FatalException, "Bailing out; invalid Markdown processor."
end
highlighter_prefix "\n"
highlighter_suffix "\n"
def setup
return if @setup
@parser =
case @config['markdown'].downcase
when 'redcarpet' then RedcarpetParser.new(@config)
when 'kramdown' then KramdownParser.new(@config)
when 'rdiscount' then RDiscountParser.new(@config)
when 'maruku' then MarukuParser.new(@config)
else
# So they can't try some tricky bullshit or go down the ancestor chain, I hope.
if allowed_custom_class?(@config['markdown'])
self.class.const_get(@config['markdown']).new(@config)
else
Jekyll.logger.error "Invalid Markdown Processor:", "#{@config['markdown']}"
Jekyll.logger.error "", "Valid options are [ maruku | rdiscount | kramdown | redcarpet ]"
raise FatalException, "Invalid Markdown Processor: #{@config['markdown']}"
end
end
@setup = true
end
def get_processor
case @config["markdown"].downcase
when "redcarpet" then return RedcarpetParser.new(@config)
when "kramdown" then return KramdownParser.new(@config)
when "rdiscount" then return RDiscountParser.new(@config)
else
get_custom_processor
end
end
# Public: Provides you with a list of processors, the ones we
# support internally and the ones that you have provided to us (if you
# are not in safe mode.)
def valid_processors
%W(rdiscount kramdown redcarpet) + third_party_processors
end
# Public: A list of processors that you provide via plugins.
# This is really only available if you are not in safe mode, if you are
# in safe mode (re: GitHub) then there will be none.
def third_party_processors
self.class.constants - \
%w(KramdownParser RDiscountParser RedcarpetParser PRIORITIES).map(
&:to_sym
)
end
def extname_list
@extname_list ||= @config['markdown_ext'].split(',').map do |e|
".#{e.downcase}"
end
end
def matches(ext)
extname_list.include?(ext.downcase)
rgx = '^\.(' + @config['markdown_ext'].gsub(',','|') +')$'
ext =~ Regexp.new(rgx, Regexp::IGNORECASE)
end
def output_ext(_ext)
def output_ext(ext)
".html"
end
@@ -66,26 +42,16 @@ module Jekyll
end
private
def get_custom_processor
converter_name = @config["markdown"]
if custom_class_allowed?(converter_name)
self.class.const_get(converter_name).new(@config)
end
end
# Private: Determine whether a class name is an allowed custom
# markdown class name.
# Private: Determine whether a class name is an allowed custom markdown
# class name
#
# parser_name - the name of the parser class
#
# Returns true if the parser name contains only alphanumeric
# characters and is defined within Jekyll::Converters::Markdown
private
def custom_class_allowed?(parser_name)
parser_name !~ /[^A-Za-z0-9_]/ && self.class.constants.include?(
parser_name.to_sym
)
# Returns true if the parser name contains only alphanumeric characters
# and is defined within Jekyll::Converters::Markdown
def allowed_custom_class?(parser_name)
parser_name !~ /[^A-Za-z0-9]/ && self.class.constants.include?(parser_name.to_sym)
end
end
end

View File

@@ -1,117 +1,28 @@
# Frozen-string-literal: true
# Encoding: utf-8
module Jekyll
module Converters
class Markdown
class KramdownParser
CODERAY_DEFAULTS = {
"css" => "style",
"bold_every" => 10,
"line_numbers" => "inline",
"line_number_start" => 1,
"tab_width" => 4,
"wrap" => "div"
}.freeze
def initialize(config)
Jekyll::External.require_with_graceful_fail "kramdown"
@main_fallback_highlighter = config["highlighter"] || "rouge"
@config = config["kramdown"] || {}
@highlighter = nil
setup
end
# Setup and normalize the configuration:
# * Create Kramdown if it doesn't exist.
# * Set syntax_highlighter, detecting enable_coderay and merging highlighter if none.
# * Merge kramdown[coderay] into syntax_highlighter_opts stripping coderay_.
# * Make sure `syntax_highlighter_opts` exists.
def setup
@config["syntax_highlighter"] ||= highlighter
@config["syntax_highlighter_opts"] ||= {}
@config["coderay"] ||= {} # XXX: Legacy.
modernize_coderay_config
make_accessible
require 'kramdown'
@config = config
rescue LoadError
STDERR.puts 'You are missing a library required for Markdown. Please run:'
STDERR.puts ' $ [sudo] gem install kramdown'
raise FatalException.new("Missing dependency: kramdown")
end
def convert(content)
Kramdown::Document.new(content, @config).to_html
end
private
def make_accessible(hash = @config)
proc_ = proc { |hash_, key| hash_[key.to_s] if key.is_a?(Symbol) }
hash.default_proc = proc_
hash.each do |_, val|
make_accessible val if val.is_a?(
Hash
)
end
end
# config[kramdown][syntax_higlighter] > config[kramdown][enable_coderay] > config[highlighter]
# Where `enable_coderay` is now deprecated because Kramdown
# supports Rouge now too.
private
def highlighter
return @highlighter if @highlighter
if @config["syntax_highlighter"]
return @highlighter = @config[
"syntax_highlighter"
]
end
@highlighter = begin
if @config.key?("enable_coderay") && @config["enable_coderay"]
Jekyll::Deprecator.deprecation_message "You are using 'enable_coderay', " \
"use syntax_highlighter: coderay in your configuration file."
"coderay"
else
@main_fallback_highlighter
# Check for use of coderay
if @config['kramdown']['use_coderay']
%w[wrap line_numbers line_numbers_start tab_width bold_every css default_lang].each do |opt|
key = "coderay_#{opt}"
@config['kramdown'][key] = @config['kramdown']['coderay'][key] unless @config['kramdown'].has_key?(key)
end
end
Kramdown::Document.new(content, Utils.symbolize_hash_keys(@config["kramdown"])).to_html
end
private
def strip_coderay_prefix(hash)
hash.each_with_object({}) do |(key, val), hsh|
cleaned_key = key.gsub(/\Acoderay_/, "")
if key != cleaned_key
Jekyll::Deprecator.deprecation_message(
"You are using '#{key}'. Normalizing to #{cleaned_key}."
)
end
hsh[cleaned_key] = val
end
end
# If our highlighter is CodeRay we go in to merge the CodeRay defaults
# with your "coderay" key if it's there, deprecating it in the
# process of you using it.
private
def modernize_coderay_config
if highlighter == "coderay"
Jekyll::Deprecator.deprecation_message "You are using 'kramdown.coderay' in your configuration, " \
"please use 'syntax_highlighter_opts' instead."
@config["syntax_highlighter_opts"] = begin
strip_coderay_prefix(
@config["syntax_highlighter_opts"] \
.merge(CODERAY_DEFAULTS) \
.merge(@config["coderay"])
)
end
end
end
end
end
end

View File

@@ -0,0 +1,55 @@
module Jekyll
module Converters
class Markdown
class MarukuParser
def initialize(config)
require 'maruku'
@config = config
@errors = []
load_divs_library if @config['maruku']['use_divs']
load_blahtext_library if @config['maruku']['use_tex']
# allow fenced code blocks (new in Maruku 0.7.0)
MaRuKu::Globals[:fenced_code_blocks] = !!@config['maruku']['fenced_code_blocks']
rescue LoadError
STDERR.puts 'You are missing a library required for Markdown. Please run:'
STDERR.puts ' $ [sudo] gem install maruku'
raise FatalException.new("Missing dependency: maruku")
end
def load_divs_library
require 'maruku/ext/div'
STDERR.puts 'Maruku: Using extended syntax for div elements.'
end
def load_blahtext_library
require 'maruku/ext/math'
STDERR.puts "Maruku: Using LaTeX extension. Images in `#{@config['maruku']['png_dir']}`."
# Switch off MathML output
MaRuKu::Globals[:html_math_output_mathml] = false
MaRuKu::Globals[:html_math_engine] = 'none'
# Turn on math to PNG support with blahtex
# Resulting PNGs stored in `images/latex`
MaRuKu::Globals[:html_math_output_png] = true
MaRuKu::Globals[:html_png_engine] = @config['maruku']['png_engine']
MaRuKu::Globals[:html_png_dir] = @config['maruku']['png_dir']
MaRuKu::Globals[:html_png_url] = @config['maruku']['png_url']
end
def print_errors_and_fail
print @errors.join
raise MaRuKu::Exception, "MaRuKu encountered problem(s) while converting your markup."
end
def convert(content)
converted = Maruku.new(content, :error_stream => @errors).to_html.strip
print_errors_and_fail unless @errors.empty?
converted
end
end
end
end
end

View File

@@ -3,9 +3,13 @@ module Jekyll
class Markdown
class RDiscountParser
def initialize(config)
Jekyll::External.require_with_graceful_fail "rdiscount"
require 'rdiscount'
@config = config
@rdiscount_extensions = @config['rdiscount']['extensions'].map(&:to_sym)
@rdiscount_extensions = @config['rdiscount']['extensions'].map { |e| e.to_sym }
rescue LoadError
STDERR.puts 'You are missing a library required for Markdown. Please run:'
STDERR.puts ' $ [sudo] gem install rdiscount'
raise FatalException.new("Missing dependency: rdiscount")
end
def convert(content)

View File

@@ -2,19 +2,19 @@ module Jekyll
module Converters
class Markdown
class RedcarpetParser
module CommonMethods
def add_code_tags(code, lang)
code = code.to_s
code = code.sub(/<pre>/, "<pre><code class=\"language-#{lang}\" data-lang=\"#{lang}\">")
code = code.sub(/<\/pre>/, "</code></pre>")
code
code = code.sub(/<\/pre>/,"</code></pre>")
end
end
module WithPygments
include CommonMethods
def block_code(code, lang)
Jekyll::External.require_with_graceful_fail("pygments")
require 'pygments'
lang = lang && lang.split.first || "text"
add_code_tags(
Pygments.highlight(code, :lexer => lang, :options => { :encoding => 'utf-8' }),
@@ -29,7 +29,7 @@ module Jekyll
include CommonMethods
def code_wrap(code)
"<figure class=\"highlight\"><pre>#{CGI::escapeHTML(code)}</pre></figure>"
"<div class=\"highlight\"><pre>#{CGI::escapeHTML(code)}</pre></div>"
end
def block_code(code, lang)
@@ -48,46 +48,52 @@ module Jekyll
end
protected
def rouge_formatter(_lexer)
Rouge::Formatters::HTML.new(:wrap => false)
def rouge_formatter(opts = {})
Rouge::Formatters::HTML.new(opts.merge(wrap: false))
end
end
def initialize(config)
External.require_with_graceful_fail("redcarpet")
require 'redcarpet'
@config = config
@redcarpet_extensions = {}
@config['redcarpet']['extensions'].each { |e| @redcarpet_extensions[e.to_sym] = true }
@renderer ||= class_with_proper_highlighter(@config['highlighter'])
end
@renderer ||= case @config['highlighter']
when 'pygments'
Class.new(Redcarpet::Render::HTML) do
include WithPygments
end
when 'rouge'
Class.new(Redcarpet::Render::HTML) do
begin
require 'rouge'
require 'rouge/plugins/redcarpet'
rescue LoadError => e
Jekyll.logger.error "You are missing the 'rouge' gem. Please run:"
Jekyll.logger.error " $ [sudo] gem install rouge"
Jekyll.logger.error "Or add 'rouge' to your Gemfile."
raise FatalException.new("Missing dependency: rouge")
end
def class_with_proper_highlighter(highlighter)
case highlighter
when "pygments"
Class.new(Redcarpet::Render::HTML) do
include WithPygments
end
when "rouge"
Class.new(Redcarpet::Render::HTML) do
Jekyll::External.require_with_graceful_fail(%w(
rouge
rouge/plugins/redcarpet
))
if Rouge.version < '1.3.0'
abort "Please install Rouge 1.3.0 or greater and try running Jekyll again."
end
unless Gem::Version.new(Rouge.version) > Gem::Version.new("1.3.0")
abort "Please install Rouge 1.3.0 or greater and try running Jekyll again."
end
include Rouge::Plugins::Redcarpet
include CommonMethods
include WithRouge
end
else
Class.new(Redcarpet::Render::HTML) do
include WithoutHighlighting
end
end
include Rouge::Plugins::Redcarpet
include CommonMethods
include WithRouge
end
else
Class.new(Redcarpet::Render::HTML) do
include WithoutHighlighting
end
end
rescue LoadError
STDERR.puts 'You are missing a library required for Markdown. Please run:'
STDERR.puts ' $ [sudo] gem install redcarpet'
raise FatalException.new("Missing dependency: redcarpet")
end
def convert(content)

View File

@@ -1,34 +0,0 @@
class Kramdown::Parser::SmartyPants < Kramdown::Parser::Kramdown
def initialize(source, options)
super
@block_parsers = [:block_html]
@span_parsers = [:smart_quotes, :html_entity, :typographic_syms, :span_html]
end
end
module Jekyll
module Converters
class SmartyPants < Converter
safe true
priority :low
def initialize(config)
Jekyll::External.require_with_graceful_fail "kramdown"
@config = config["kramdown"].dup || {}
@config[:input] = :SmartyPants
end
def matches(_)
false
end
def output_ext(_)
nil
end
def convert(content)
Kramdown::Document.new(content, @config).to_html.chomp
end
end
end
end

View File

@@ -0,0 +1,50 @@
module Jekyll
module Converters
class Textile < Converter
safe true
highlighter_prefix '<notextile>'
highlighter_suffix '</notextile>'
def setup
return if @setup
require 'redcloth'
@setup = true
rescue LoadError
STDERR.puts 'You are missing a library required for Textile. Please run:'
STDERR.puts ' $ [sudo] gem install RedCloth'
raise FatalException.new("Missing dependency: RedCloth")
end
def matches(ext)
rgx = '(' + @config['textile_ext'].gsub(',','|') +')'
ext =~ Regexp.new(rgx, Regexp::IGNORECASE)
end
def output_ext(ext)
".html"
end
def convert(content)
setup
# Shortcut if config doesn't contain RedCloth section
return RedCloth.new(content).to_html if @config['redcloth'].nil?
# List of attributes defined on RedCloth
# (from http://redcloth.rubyforge.org/classes/RedCloth/TextileDoc.html)
attrs = ['filter_classes', 'filter_html', 'filter_ids', 'filter_styles',
'hard_breaks', 'lite_mode', 'no_span_caps', 'sanitize_html']
r = RedCloth.new(content)
# Set attributes in r if they are NOT nil in the config
attrs.each do |attr|
r.instance_variable_set("@#{attr}".to_sym, @config['redcloth'][attr]) unless @config['redcloth'][attr].nil?
end
r.to_html
end
end
end
end

View File

@@ -25,7 +25,13 @@ module Jekyll
# Whether the file is published or not, as indicated in YAML front-matter
def published?
!(data.key?('published') && data['published'] == false)
!(data.has_key?('published') && data['published'] == false)
end
# Returns merged option hash for File.read of self.site (if exists)
# and a given param
def merged_file_read_opts(opts)
(site ? site.file_read_opts : {}).merge(opts)
end
# Read the YAML frontmatter.
@@ -36,54 +42,31 @@ module Jekyll
#
# Returns nothing.
def read_yaml(base, name, opts = {})
filename = File.join(base, name)
begin
self.content = File.read(site.in_source_dir(base, name),
Utils.merged_file_read_opts(site, opts))
self.content = File.read(File.join(base, name),
merged_file_read_opts(opts))
if content =~ /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m
self.content = $POSTMATCH
self.data = SafeYAML.load(Regexp.last_match(1))
self.data = SafeYAML.load($1)
end
rescue SyntaxError => e
Jekyll.logger.warn "YAML Exception reading #{filename}: #{e.message}"
Jekyll.logger.warn "YAML Exception reading #{File.join(base, name)}: #{e.message}"
rescue Exception => e
Jekyll.logger.warn "Error reading file #{filename}: #{e.message}"
Jekyll.logger.warn "Error reading file #{File.join(base, name)}: #{e.message}"
end
self.data ||= {}
validate_data! filename
validate_permalink! filename
self.data
end
def validate_data!(filename)
unless self.data.is_a?(Hash)
raise Errors::InvalidYAMLFrontMatterError, "Invalid YAML front matter in #{filename}"
end
end
def validate_permalink!(filename)
if self.data['permalink'] && self.data['permalink'].size == 0
raise Errors::InvalidPermalinkError, "Invalid permalink in #{filename}"
end
end
# Transform the contents based on the content type.
#
# Returns the transformed contents.
# Returns nothing.
def transform
converters.reduce(content) do |output, converter|
begin
converter.convert output
rescue => e
Jekyll.logger.error "Conversion error:", "#{converter.class} encountered an error while converting '#{path}':"
Jekyll.logger.error("", e.to_s)
raise e
end
end
self.content = converter.convert(content)
rescue => e
Jekyll.logger.error "Conversion error:", "There was an error converting" +
" '#{path}'."
raise e
end
# Determine the extension depending on content_type.
@@ -91,15 +74,15 @@ module Jekyll
# Returns the String extension for the output file.
# e.g. ".html" for an HTML output file.
def output_ext
Jekyll::Renderer.new(site, self).output_ext
converter.output_ext(ext)
end
# Determine which converter to use based on this convertible's
# extension.
#
# Returns the Converter instance.
def converters
@converters ||= site.converters.select { |c| c.matches(ext) }.sort
def converter
@converter ||= site.converters.find { |c| c.matches(ext) }
end
# Render Liquid in the content
@@ -109,8 +92,8 @@ module Jekyll
# info - the info for Liquid
#
# Returns the converted content
def render_liquid(content, payload, info, path)
site.liquid_renderer.file(path).parse(content).render!(payload, info)
def render_liquid(content, payload, info, path = nil)
Liquid::Template.parse(content).render!(payload, info)
rescue Tags::IncludeTagError => e
Jekyll.logger.error "Liquid Exception:", "#{e.message} in #{e.path}, included in #{path || self.path}"
raise e
@@ -123,9 +106,9 @@ module Jekyll
#
# Returns the Hash representation of this Convertible.
def to_liquid(attrs = nil)
further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map do |attribute|
further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map { |attribute|
[attribute, send(attribute)]
end]
}]
defaults = site.frontmatter_defaults.all(relative_path, type)
Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data)
@@ -136,15 +119,12 @@ module Jekyll
#
# Returns the type of self.
def type
if is_a?(Page)
:pages
end
end
# returns the owner symbol for hook triggering
def hook_owner
if is_a?(Page)
:pages
if is_a?(Post)
:post
elsif is_a?(Page)
:page
elsif is_a?(Draft)
:draft
end
end
@@ -154,46 +134,25 @@ module Jekyll
# Returns true if the extname belongs to the set of extensions
# that asset files use.
def asset_file?
sass_file? || coffeescript_file?
end
# Determine whether the document is a Sass file.
#
# Returns true if extname == .sass or .scss, false otherwise.
def sass_file?
%w(.sass .scss).include?(ext)
end
# Determine whether the document is a CoffeeScript file.
#
# Returns true if extname == .coffee, false otherwise.
def coffeescript_file?
'.coffee'.eql?(ext)
%w[.sass .scss .coffee].include?(ext)
end
# Determine whether the file should be rendered with Liquid.
#
# Always returns true.
# Returns false if the document is either an asset file or a yaml file,
# true otherwise.
def render_with_liquid?
true
!asset_file?
end
# Determine whether the file should be placed into layouts.
#
# Returns false if the document is an asset file.
# Returns false if the document is either an asset file or a yaml file,
# true otherwise.
def place_in_layout?
!asset_file?
end
# Checks if the layout specified in the document actually exists
#
# layout - the layout to check
#
# Returns true if the layout is invalid, false if otherwise
def invalid_layout?(layout)
!data["layout"].nil? && layout.nil? && !(self.is_a? Jekyll::Excerpt)
end
# Recursively render layouts
#
# layouts - a list of the layouts
@@ -204,26 +163,15 @@ module Jekyll
def render_all_layouts(layouts, payload, info)
# recursively render layouts
layout = layouts[data["layout"]]
Jekyll.logger.warn("Build Warning:", "Layout '#{data["layout"]}' requested in #{path} does not exist.") if invalid_layout? layout
used = Set.new([layout])
while layout
Jekyll.logger.debug "Rendering Layout:", path
payload["content"] = output
payload["layout"] = Utils.deep_merge_hashes(payload["layout"] || {}, layout.data)
payload = Utils.deep_merge_hashes(payload, {"content" => output, "page" => layout.data})
self.output = render_liquid(layout.content,
payload,
info,
File.join(site.config['layouts_dir'], layout.name))
# Add layout to dependency tree
site.regenerator.add_dependency(
site.in_source_dir(path),
site.in_source_dir(layout.path)
)
File.join(site.config['layouts'], layout.name))
if layout = layouts[layout.data["layout"]]
if used.include?(layout)
@@ -237,34 +185,24 @@ module Jekyll
# Add any necessary layouts to this convertible document.
#
# payload - The site payload Drop or Hash.
# payload - The site payload Hash.
# layouts - A Hash of {"name" => "layout"}.
#
# Returns nothing.
def do_layout(payload, layouts)
Jekyll.logger.debug "Rendering:", self.relative_path
Jekyll.logger.debug "Pre-Render Hooks:", self.relative_path
Jekyll::Hooks.trigger hook_owner, :pre_render, self, payload
info = { :filters => [Jekyll::Filters], :registers => { :site => site, :page => payload["page"] } }
info = { :filters => [Jekyll::Filters], :registers => { :site => site, :page => payload['page'] } }
# render and transform content (this becomes the final content of the object)
payload["highlighter_prefix"] = converters.first.highlighter_prefix
payload["highlighter_suffix"] = converters.first.highlighter_suffix
payload["highlighter_prefix"] = converter.highlighter_prefix
payload["highlighter_suffix"] = converter.highlighter_suffix
if render_with_liquid?
Jekyll.logger.debug "Rendering Liquid:", self.relative_path
self.content = render_liquid(content, payload, info, path)
end
Jekyll.logger.debug "Rendering Markup:", self.relative_path
self.content = transform
self.content = render_liquid(content, payload, info) if render_with_liquid?
transform
# output keeps track of what will finally be written
self.output = content
render_all_layouts(layouts, payload, info) if place_in_layout?
Jekyll.logger.debug "Post-Render Hooks:", self.relative_path
Jekyll::Hooks.trigger hook_owner, :post_render, self
end
# Write the generated page file to the destination directory.
@@ -278,7 +216,6 @@ module Jekyll
File.open(path, 'wb') do |f|
f.write(output)
end
Jekyll::Hooks.trigger hook_owner, :post_write, self
end
# Accessor for data properties by Liquid.

View File

@@ -1,12 +1,9 @@
module Jekyll
module Deprecator
extend self
def process(args)
class Deprecator
def self.process(args)
no_subcommand(args)
arg_is_present? args, "--server", "The --server command has been replaced by the \
'serve' subcommand."
arg_is_present? args, "--serve", "The --server command has been replaced by the \
'serve' subcommand."
arg_is_present? args, "--no-server", "To build Jekyll without launching a server, \
use the 'build' subcommand."
arg_is_present? args, "--auto", "The switch '--auto' has been replaced with '--watch'."
@@ -17,30 +14,23 @@ module Jekyll
arg_is_present? args, "--paginate", "The 'paginate' setting can only be set in your \
config files."
arg_is_present? args, "--url", "The 'url' setting can only be set in your config files."
no_subcommand(args)
end
def no_subcommand(args)
if args.size > 0 && args.first =~ /^--/ && !%w(--help --version).include?(args.first)
deprecation_message "Jekyll now uses subcommands instead of just switches. Run `jekyll help` to find out more."
abort
def self.no_subcommand(args)
if args.size > 0 && args.first =~ /^--/ && !%w[--help --version].include?(args.first)
Jekyll.logger.error "Deprecation:", "Jekyll now uses subcommands instead of just \
switches. Run `jekyll --help' to find out more."
end
end
def arg_is_present?(args, deprecated_argument, message)
def self.arg_is_present?(args, deprecated_argument, message)
if args.include?(deprecated_argument)
deprecation_message(message)
end
end
def deprecation_message(message)
def self.deprecation_message(message)
Jekyll.logger.error "Deprecation:", message
end
def defaults_deprecate_type(old, current)
Jekyll.logger.warn "Defaults:", "The '#{old}' type has become '#{current}'."
Jekyll.logger.warn "Defaults:", "Please update your front-matter defaults to use 'type: #{current}'."
end
end
end

View File

@@ -1,42 +1,20 @@
# encoding: UTF-8
module Jekyll
class Document
include Comparable
attr_reader :path, :site, :extname, :collection
attr_accessor :content, :output
YAML_FRONT_MATTER_REGEXP = /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m
DATELESS_FILENAME_MATCHER = /^(.+\/)*(.*)(\.[^.]+)$/
DATE_FILENAME_MATCHER = /^(.+\/)*(\d+-\d+-\d+)-(.*)(\.[^.]+)$/
attr_reader :path, :site
attr_accessor :content, :collection, :output
# Create a new Document.
#
# site - the Jekyll::Site instance to which this Document belongs
# path - the path to the file
# relations - a hash with keys :site and :collection, the values of which
# are the Jekyll::Site and Jekyll::Collection to which this
# Document belong.
#
# Returns nothing.
def initialize(path, relations = {})
def initialize(path, relations)
@site = relations[:site]
@path = path
@extname = File.extname(path)
@collection = relations[:collection]
@has_yaml_header = nil
if draft?
categories_from_path("_drafts")
else
categories_from_path(collection.relative_directory)
end
data.default_proc = proc do |_, key|
site.frontmatter_defaults.find(relative_path, collection.label, key)
end
trigger_hooks(:post_init)
end
# Fetch the Document's data.
@@ -44,44 +22,7 @@ module Jekyll
# Returns a Hash containing the data. An empty hash is returned if
# no data was read.
def data
@data ||= {}
end
# Merge some data in with this document's data.
#
# Returns the merged data.
def merge_data!(other, source: "YAML front matter")
if other.key?('categories') && !other['categories'].nil?
if other['categories'].is_a?(String)
other['categories'] = other['categories'].split(" ").map(&:strip)
end
other['categories'] = (data['categories'] || []) | other['categories']
end
Utils.deep_merge_hashes!(data, other)
if data.key?('date') && !data['date'].is_a?(Time)
data['date'] = Utils.parse_date(
data['date'].to_s,
"Document '#{relative_path}' does not have a valid date in the #{source}."
)
end
data
end
def date
data['date'] ||= (draft? ? source_file_mtime : site.time)
end
def source_file_mtime
@source_file_mtime ||= File.mtime(path)
end
# Returns whether the document is a draft. This is only the case if
# the document is in the 'posts' collection but in a different
# directory than '_posts'.
#
# Returns whether the document is a draft.
def draft?
data['draft'] ||= relative_path.index(collection.relative_directory).nil? && collection.label == "posts"
@data ||= Hash.new
end
# The path to the document, relative to the site source.
@@ -89,28 +30,23 @@ module Jekyll
# Returns a String path which represents the relative path
# from the site source to this document
def relative_path
@relative_path ||= Pathname.new(path).relative_path_from(Pathname.new(site.source)).to_s
end
# The output extension of the document.
#
# Returns the output extension
def output_ext
Jekyll::Renderer.new(site, self).output_ext
end
# The base filename of the document, without the file extname.
#
# Returns the basename without the file extname.
def basename_without_ext
@basename_without_ext ||= File.basename(path, '.*')
Pathname.new(path).relative_path_from(Pathname.new(site.source)).to_s
end
# The base filename of the document.
#
# suffix - (optional) the suffix to be removed from the end of the filename
#
# Returns the base filename of the document.
def basename
@basename ||= File.basename(path)
def basename(suffix = "")
File.basename(path, suffix)
end
# The extension name of the document.
#
# Returns the extension name of the document.
def extname
File.extname(path)
end
# Produces a "cleaned" relative path.
@@ -125,15 +61,14 @@ module Jekyll
#
# Returns the cleaned relative path of the document.
def cleaned_relative_path
@cleaned_relative_path ||=
relative_path[0..-extname.length - 1].sub(collection.relative_directory, "")
relative_path[0 .. -extname.length - 1].sub(collection.relative_directory, "")
end
# Determine whether the document is a YAML file.
#
# Returns true if the extname is either .yml or .yaml, false otherwise.
def yaml_file?
%w(.yaml .yml).include?(extname)
%w[.yaml .yml].include?(extname)
end
# Determine whether the document is an asset file.
@@ -142,21 +77,7 @@ module Jekyll
# Returns true if the extname belongs to the set of extensions
# that asset files use.
def asset_file?
sass_file? || coffeescript_file?
end
# Determine whether the document is a Sass file.
#
# Returns true if extname == .sass or .scss, false otherwise.
def sass_file?
%w(.sass .scss).include?(extname)
end
# Determine whether the document is a CoffeeScript file.
#
# Returns true if extname == .coffee, false otherwise.
def coffeescript_file?
'.coffee'.eql?(extname)
%w[.sass .scss .coffee].include?(extname)
end
# Determine whether the file should be rendered with Liquid.
@@ -164,7 +85,7 @@ module Jekyll
# Returns false if the document is either an asset file or a yaml file,
# true otherwise.
def render_with_liquid?
!(coffeescript_file? || yaml_file?)
!(asset_file? || yaml_file?)
end
# Determine whether the file should be placed into layouts.
@@ -187,7 +108,11 @@ module Jekyll
#
# Returns the Hash of key-value pairs for replacement in the URL.
def url_placeholders
@url_placeholders ||= Drops::UrlDrop.new(self)
{
collection: collection.label,
path: cleaned_relative_path,
output_ext: Jekyll::Renderer.new(site, self).output_ext
}
end
# The permalink for this Document.
@@ -202,30 +127,21 @@ module Jekyll
#
# Returns the computed URL for the document.
def url
@url = URL.new({
:template => url_template,
:placeholders => url_placeholders,
:permalink => permalink
@url ||= URL.new({
template: url_template,
placeholders: url_placeholders,
permalink: permalink
}).to_s
end
def [](key)
data[key]
end
# The full path to the output file.
#
# base_directory - the base path of the output directory
#
# Returns the full path to the output file of this document.
def destination(base_directory)
dest = site.in_dest_dir(base_directory)
path = site.in_dest_dir(dest, URL.unescape_path(url))
if url.end_with? "/"
path = File.join(path, "index.html")
else
path << output_ext unless path.end_with? output_ext
end
path = Jekyll.sanitized_path(base_directory, url)
path = File.join(path, "index.html") if url =~ /\/$/
path
end
@@ -240,15 +156,23 @@ module Jekyll
File.open(path, 'wb') do |f|
f.write(output)
end
end
trigger_hooks(:post_write)
# Returns merged option hash for File.read of self.site (if exists)
# and a given param
#
# opts - override options
#
# Return the file read options hash.
def merged_file_read_opts(opts)
site ? site.file_read_opts.merge(opts) : opts
end
# Whether the file is published or not, as indicated in YAML front-matter
#
# Returns true if the 'published' key is specified in the YAML front-matter and not `false`.
def published?
!(data.key?('published') && data['published'] == false)
!(data.has_key?('published') && data['published'] == false)
end
# Read in the file and assign the content and data based on the file contents.
@@ -257,86 +181,46 @@ module Jekyll
#
# Returns nothing.
def read(opts = {})
Jekyll.logger.debug "Reading:", relative_path
if yaml_file?
@data = SafeYAML.load_file(path)
else
begin
defaults = @site.frontmatter_defaults.all(url, collection.label.to_sym)
merge_data!(defaults, source: "front matter defaults") unless defaults.empty?
self.content = File.read(path, Utils.merged_file_read_opts(site, opts))
if content =~ YAML_FRONT_MATTER_REGEXP
self.content = $POSTMATCH
data_file = SafeYAML.load(Regexp.last_match(1))
merge_data!(data_file, source: "YAML front matter") if data_file
unless defaults.empty?
@data = defaults
end
@content = File.read(path, merged_file_read_opts(opts))
if content =~ /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m
@content = $POSTMATCH
data_file = SafeYAML.load($1)
unless data_file.nil?
@data = Utils.deep_merge_hashes(defaults, data_file)
end
end
post_read
rescue SyntaxError => e
Jekyll.logger.error "Error:", "YAML Exception reading #{path}: #{e.message}"
puts "YAML Exception reading #{path}: #{e.message}"
rescue Exception => e
if e.is_a? Jekyll::Errors::FatalException
raise e
end
Jekyll.logger.error "Error:", "could not read file #{path}: #{e.message}"
puts "Error reading file #{path}: #{e.message}"
end
end
end
def post_read
if relative_path =~ DATE_FILENAME_MATCHER
date, slug, ext = $2, $3, $4
if !data['date'] || data['date'].to_i == site.time.to_i
merge_data!({"date" => date}, source: "filename")
end
elsif relative_path =~ DATELESS_FILENAME_MATCHER
slug, ext = $2, $3
end
# Try to ensure the user gets a title.
data["title"] ||= Utils.titleize_slug(slug)
# Only overwrite slug & ext if they aren't specified.
data['slug'] ||= slug
data['ext'] ||= ext
populate_categories
populate_tags
generate_excerpt
end
# Add superdirectories of the special_dir to categories.
# In the case of es/_posts, 'es' is added as a category.
# In the case of _posts/es, 'es' is NOT added as a category.
#
# Returns nothing.
def categories_from_path(special_dir)
superdirs = relative_path.sub(/#{special_dir}(.*)/, '').split(File::SEPARATOR).reject do |c|
c.empty? || c.eql?(special_dir) || c.eql?(basename)
end
merge_data!({ 'categories' => superdirs }, source: "file path")
end
def populate_categories
merge_data!({
'categories' => (
Array(data['categories']) + Utils.pluralized_array_from_hash(data, 'category', 'categories')
).map(&:to_s).flatten.uniq
})
end
def populate_tags
merge_data!({
"tags" => Utils.pluralized_array_from_hash(data, "tag", "tags").flatten
})
end
# Create a Liquid-understandable version of this Document.
#
# Returns a Hash representing this Document's data.
def to_liquid
@to_liquid ||= Drops::DocumentDrop.new(self)
if data.is_a?(Hash)
Utils.deep_merge_hashes data, {
"output" => output,
"content" => content,
"path" => path,
"relative_path" => relative_path,
"url" => url,
"collection" => collection.label
}
else
data
end
end
# The inspect string for this document.
@@ -351,7 +235,7 @@ module Jekyll
#
# Returns the content of the document
def to_s
output || content || 'NO CONTENT'
output || content
end
# Compare this document against another document.
@@ -359,11 +243,8 @@ module Jekyll
#
# Returns -1, 0, +1 or nil depending on whether this doc's path is less than,
# equal or greater than the other doc's path. See String#<=> for more details.
def <=>(other)
return nil unless other.respond_to?(:data)
cmp = data['date'] <=> other.data['date']
cmp = path <=> other.path if cmp.nil? || cmp == 0
cmp
def <=>(anotherDocument)
path <=> anotherDocument.path
end
# Determine whether this document should be written.
@@ -375,77 +256,5 @@ module Jekyll
collection && collection.write?
end
# The Document excerpt_separator, from the YAML Front-Matter or site
# default excerpt_separator value
#
# Returns the document excerpt_separator
def excerpt_separator
(data['excerpt_separator'] || site.config['excerpt_separator']).to_s
end
# Whether to generate an excerpt
#
# Returns true if the excerpt separator is configured.
def generate_excerpt?
!excerpt_separator.empty?
end
def next_doc
pos = collection.docs.index { |post| post.equal?(self) }
if pos && pos < collection.docs.length - 1
collection.docs[pos + 1]
else
nil
end
end
def previous_doc
pos = collection.docs.index { |post| post.equal?(self) }
if pos && pos > 0
collection.docs[pos - 1]
else
nil
end
end
def trigger_hooks(hook_name, *args)
Jekyll::Hooks.trigger collection.label.to_sym, hook_name, self, *args if collection
Jekyll::Hooks.trigger :documents, hook_name, self, *args
end
def id
@id ||= File.join(File.dirname(url), (data['slug'] || basename_without_ext).to_s)
end
# Calculate related posts.
#
# Returns an Array of related Posts.
def related_posts
Jekyll::RelatedPosts.new(self).build
end
# Override of normal respond_to? to match method_missing's logic for
# looking in @data.
def respond_to?(method, include_private = false)
data.key?(method.to_s) || super
end
# Override of method_missing to check in @data for the key.
def method_missing(method, *args, &blck)
if data.key?(method.to_s)
Jekyll.logger.warn "Deprecation:", "Document##{method} is now a key in the #data hash."
Jekyll.logger.warn "", "Called by #{caller.first}."
data[method.to_s]
else
super
end
end
private # :nodoc:
def generate_excerpt
if generate_excerpt?
data["excerpt"] ||= Jekyll::Excerpt.new(self)
end
end
end
end

40
lib/jekyll/draft.rb Normal file
View File

@@ -0,0 +1,40 @@
module Jekyll
class Draft < Post
# Valid post name regex (no date)
MATCHER = /^(.*)(\.[^.]+)$/
# Draft name validator. Draft filenames must be like:
# my-awesome-post.textile
#
# Returns true if valid, false if not.
def self.valid?(name)
name =~ MATCHER
end
# Get the full path to the directory containing the draft files
def containing_dir(source, dir)
File.join(source, dir, '_drafts')
end
# The path to the draft source file, relative to the site source
def relative_path
File.join(@dir, '_drafts', @name)
end
# Extract information from the post filename.
#
# name - The String filename of the post file.
#
# Returns nothing.
def process(name)
m, slug, ext = *name.match(MATCHER)
self.date = File.mtime(File.join(@base, name))
self.slug = slug
self.ext = ext
end
end
end

View File

@@ -1,22 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class CollectionDrop < Drop
extend Forwardable
mutable false
def_delegator :@obj, :write?, :output
def_delegators :@obj, :label, :docs, :files, :directory,
:relative_directory
def to_s
docs.to_s
end
private
def_delegator :@obj, :metadata, :fallback_data
end
end
end

View File

@@ -1,34 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class DocumentDrop < Drop
extend Forwardable
mutable false
def_delegator :@obj, :next_doc, :next
def_delegator :@obj, :previous_doc, :previous
def_delegator :@obj, :relative_path, :path
def_delegators :@obj, :id, :output, :content, :to_s, :relative_path, :url
def collection
@obj.collection.label
end
def excerpt
fallback_data['excerpt'].to_s
end
def <=>(other)
return nil unless other.is_a? DocumentDrop
cmp = self['date'] <=> other['date']
cmp = self['path'] <=> other['path'] if cmp.nil? || cmp == 0
cmp
end
private
def_delegator :@obj, :data, :fallback_data
end
end
end

View File

@@ -1,176 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class Drop < Liquid::Drop
NON_CONTENT_METHODS = [:[], :[]=, :inspect, :to_h, :fallback_data].freeze
# Get or set whether the drop class is mutable.
# Mutability determines whether or not pre-defined fields may be
# overwritten.
#
# is_mutable - Boolean set mutability of the class (default: nil)
#
# Returns the mutability of the class
def self.mutable(is_mutable = nil)
if is_mutable
@is_mutable = is_mutable
else
@is_mutable = false
end
end
def self.mutable?
@is_mutable
end
# Create a new Drop
#
# obj - the Jekyll Site, Collection, or Document required by the
# drop.
#
# Returns nothing
def initialize(obj)
@obj = obj
@mutations = {} # only if mutable: true
end
# Access a method in the Drop or a field in the underlying hash data.
# If mutable, checks the mutations first. Then checks the methods,
# and finally check the underlying hash (e.g. document front matter)
# if all the previous places didn't match.
#
# key - the string key whose value to fetch
#
# Returns the value for the given key, or nil if none exists
def [](key)
if self.class.mutable? && @mutations.key?(key)
@mutations[key]
elsif self.class.invokable? key
public_send key
else
fallback_data[key]
end
end
# Set a field in the Drop. If mutable, sets in the mutations and
# returns. If not mutable, checks first if it's trying to override a
# Drop method and raises a DropMutationException if so. If not
# mutable and the key is not a method on the Drop, then it sets the
# key to the value in the underlying hash (e.g. document front
# matter)
#
# key - the String key whose value to set
# val - the Object to set the key's value to
#
# Returns the value the key was set to unless the Drop is not mutable
# and the key matches a method in which case it raises a
# DropMutationException.
def []=(key, val)
if respond_to?("#{key}=")
public_send("#{key}=", val)
elsif respond_to? key
if self.class.mutable?
@mutations[key] = val
else
raise Errors::DropMutationException, "Key #{key} cannot be set in the drop."
end
else
fallback_data[key] = val
end
end
# Generates a list of strings which correspond to content getter
# methods.
#
# Returns an Array of strings which represent method-specific keys.
def content_methods
@content_methods ||= (
self.class.instance_methods(false) - NON_CONTENT_METHODS
).map(&:to_s).reject do |method|
method.end_with?("=")
end
end
# Check if key exists in Drop
#
# key - the string key whose value to fetch
#
# Returns true if the given key is present
def key?(key)
if self.class.mutable && @mutations.key?(key)
true
else
respond_to?(key) || fallback_data.key?(key)
end
end
# Generates a list of keys with user content as their values.
# This gathers up the Drop methods and keys of the mutations and
# underlying data hashes and performs a set union to ensure a list
# of unique keys for the Drop.
#
# Returns an Array of unique keys for content for the Drop.
def keys
(content_methods |
@mutations.keys |
fallback_data.keys).flatten
end
# Generate a Hash representation of the Drop by resolving each key's
# value. It includes Drop methods, mutations, and the underlying object's
# data. See the documentation for Drop#keys for more.
#
# Returns a Hash with all the keys and values resolved.
def to_h
keys.each_with_object({}) do |(key, _), result|
result[key] = self[key]
end
end
alias_method :to_hash, :to_h
# Inspect the drop's keys and values through a JSON representation
# of its keys and values.
#
# Returns a pretty generation of the hash representation of the Drop.
def inspect
require 'json'
JSON.pretty_generate to_h
end
# Collects all the keys and passes each to the block in turn.
#
# block - a block which accepts one argument, the key
#
# Returns nothing.
def each_key(&block)
keys.each(&block)
end
def merge(other, &block)
self.dup.tap do |me|
if block.nil?
me.merge!(other)
else
me.merge!(other, block)
end
end
end
def merge!(other)
other.each_key do |key|
if block_given?
self[key] = yield key, self[key], other[key]
else
if Utils.mergable?(self[key]) && Utils.mergable?(other[key])
self[key] = Utils.deep_merge_hashes(self[key], other[key])
next
end
self[key] = other[key] unless other[key].nil?
end
end
end
end
end
end

View File

@@ -1,21 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class JekyllDrop < Liquid::Drop
class << self
def global
@global ||= JekyllDrop.new
end
end
def version
Jekyll::VERSION
end
def environment
Jekyll.env
end
end
end
end

View File

@@ -1,38 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class SiteDrop < Drop
extend Forwardable
mutable false
def_delegator :@obj, :site_data, :data
def_delegators :@obj, :time, :pages, :static_files, :documents,
:tags, :categories
def [](key)
if @obj.collections.key?(key) && key != "posts"
@obj.collections[key].docs
else
super(key)
end
end
def posts
@site_posts ||= @obj.posts.docs.sort { |a, b| b <=> a }
end
def html_pages
@site_html_pages ||= @obj.pages.select { |page| page.html? || page.url.end_with?("/") }
end
def collections
@site_collections ||= @obj.collections.values.map(&:to_liquid)
end
private
def_delegator :@obj, :config, :fallback_data
end
end
end

View File

@@ -1,25 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class UnifiedPayloadDrop < Drop
mutable true
attr_accessor :page, :layout, :content, :paginator
attr_accessor :highlighter_prefix, :highlighter_suffix
def jekyll
JekyllDrop.global
end
def site
@site_drop ||= SiteDrop.new(@obj)
end
private
def fallback_data
@fallback_data ||= {}
end
end
end
end

View File

@@ -1,83 +0,0 @@
# encoding: UTF-8
module Jekyll
module Drops
class UrlDrop < Drop
extend Forwardable
mutable false
def_delegator :@obj, :cleaned_relative_path, :path
def_delegator :@obj, :output_ext, :output_ext
def collection
@obj.collection.label
end
def name
Utils.slugify(@obj.basename_without_ext)
end
def title
Utils.slugify(@obj.data['slug'], :mode => "pretty", :cased => true) ||
Utils.slugify(@obj.basename_without_ext, :mode => "pretty", :cased => true)
end
def slug
Utils.slugify(@obj.data['slug']) || Utils.slugify(@obj.basename_without_ext)
end
def categories
category_set = Set.new
Array(@obj.data['categories']).each do |category|
category_set << category.to_s.downcase
end
category_set.to_a.join('/')
end
def year
@obj.date.strftime("%Y")
end
def month
@obj.date.strftime("%m")
end
def day
@obj.date.strftime("%d")
end
def hour
@obj.date.strftime("%H")
end
def minute
@obj.date.strftime("%M")
end
def second
@obj.date.strftime("%S")
end
def i_day
@obj.date.strftime("%-d")
end
def i_month
@obj.date.strftime("%-m")
end
def short_month
@obj.date.strftime("%b")
end
def short_year
@obj.date.strftime("%y")
end
def y_day
@obj.date.strftime("%j")
end
end
end
end

View File

@@ -1,6 +1,6 @@
module Jekyll
class EntryFilter
SPECIAL_LEADING_CHARACTERS = ['.', '_', '#', '~'].freeze
SPECIAL_LEADING_CHARACTERS = ['.', '_', '#'].freeze
attr_reader :site
@@ -47,7 +47,7 @@ module Jekyll
def excluded?(entry)
excluded = glob_include?(site.exclude, relative_to_source(entry))
Jekyll.logger.debug "EntryFilter:", "excluded #{relative_to_source(entry)}" if excluded
Jekyll.logger.debug "excluded?(#{relative_to_source(entry)}) ==> #{excluded}"
excluded
end

View File

@@ -1,14 +1,4 @@
module Jekyll
module Errors
FatalException = Class.new(::RuntimeError)
DropMutationException = Class.new(FatalException)
InvalidPermalinkError = Class.new(FatalException)
InvalidYAMLFrontMatterError = Class.new(FatalException)
MissingDependencyException = Class.new(FatalException)
InvalidDateError = Class.new(FatalException)
InvalidPostNameError = Class.new(FatalException)
PostURLError = Class.new(FatalException)
class FatalException < StandardError
end
end

View File

@@ -1,42 +1,48 @@
require 'jekyll/convertible'
require 'forwardable'
module Jekyll
class Excerpt
include Convertible
extend Forwardable
attr_accessor :doc
attr_accessor :content, :ext
attr_writer :output
attr_accessor :post
attr_accessor :content, :output, :ext
def_delegators :@doc, :site, :name, :ext, :relative_path, :extname,
:render_with_liquid?, :collection, :related_posts
def_delegator :@post, :site, :site
def_delegator :@post, :name, :name
def_delegator :@post, :ext, :ext
# Initialize this Excerpt instance.
# Initialize this Post instance.
#
# doc - The Document.
# site - The Site.
# base - The String path to the dir containing the post file.
# name - The String filename of the post file.
#
# Returns the new Excerpt.
def initialize(doc)
self.doc = doc
self.content = extract_excerpt(doc.content)
# Returns the new Post.
def initialize(post)
self.post = post
self.content = extract_excerpt(post.content)
end
# Fetch YAML front-matter data from related doc, without layout key
def to_liquid
post.to_liquid(post.class::EXCERPT_ATTRIBUTES_FOR_LIQUID)
end
# Fetch YAML front-matter data from related post, without layout key
#
# Returns Hash of doc data
# Returns Hash of post data
def data
@data ||= doc.data.dup
@data ||= post.data.dup
@data.delete("layout")
@data.delete("excerpt")
@data
end
def trigger_hooks(*)
end
# 'Path' of the excerpt.
#
# Returns the path for the doc this excerpt belongs to with #excerpt appended
# Returns the path for the post this excerpt belongs to with #excerpt appended
def path
File.join(doc.path, "#excerpt")
File.join(post.path, "#excerpt")
end
# Check if excerpt includes a string
@@ -46,43 +52,28 @@ module Jekyll
(output && output.include?(something)) || content.include?(something)
end
# The UID for this doc (useful in feeds).
# e.g. /2008/11/05/my-awesome-doc
# The UID for this post (useful in feeds).
# e.g. /2008/11/05/my-awesome-post
#
# Returns the String UID.
def id
"#{doc.id}#excerpt"
File.join(post.dir, post.slug, "#excerpt")
end
def to_s
output || content
end
def to_liquid
doc.data['excerpt'] = nil
@to_liquid ||= doc.to_liquid
doc.data['excerpt'] = self
@to_liquid
end
# Returns the shorthand String identifier of this doc.
# Returns the shorthand String identifier of this Post.
def inspect
"<Excerpt: #{self.id}>"
end
def output
@output ||= Renderer.new(doc.site, self, site.site_payload).run
end
def place_in_layout?
false
end
protected
# Internal: Extract excerpt from the content
#
# By default excerpt is your first paragraph of a doc: everything before
# By default excerpt is your first paragraph of a post: everything before
# the first two new lines:
#
# ---
@@ -96,16 +87,16 @@ module Jekyll
# [1]: http://example.com/
#
# This is fairly good option for Markdown and Textile files. But might cause
# problems for HTML docs (which is quite unusual for Jekyll). If default
# problems for HTML posts (which is quite unusual for Jekyll). If default
# excerpt delimiter is not good for you, you might want to set your own via
# configuration option `excerpt_separator`. For example, following is a good
# alternative for HTML docs:
# alternative for HTML posts:
#
# # file: _config.yml
# excerpt_separator: "<!-- more -->"
#
# Notice that all markdown-style link references will be appended to the
# excerpt. So the example doc above will have this excerpt source:
# excerpt. So the example post above will have this excerpt source:
#
# First paragraph with [link][1].
#
@@ -114,14 +105,11 @@ module Jekyll
# Excerpts are rendered same time as content is rendered.
#
# Returns excerpt String
def extract_excerpt(doc_content)
head, _, tail = doc_content.to_s.partition(doc.excerpt_separator)
def extract_excerpt(post_content)
separator = site.config['excerpt_separator']
head, _, tail = post_content.partition(separator)
if tail.empty?
head
else
"" << head << "\n\n" << tail.scan(/^\[[^\]]+\]:.+$/).join("\n")
end
"" << head << "\n\n" << tail.scan(/^\[[^\]]+\]:.+$/).join("\n")
end
end
end

View File

@@ -1,59 +0,0 @@
module Jekyll
module External
class << self
#
# Gems that, if installed, should be loaded.
# Usually contain subcommands.
#
def blessed_gems
%w(
jekyll-docs
jekyll-import
)
end
#
# Require a gem or file if it's present, otherwise silently fail.
#
# names - a string gem name or array of gem names
#
def require_if_present(names, &block)
Array(names).each do |name|
begin
require name
rescue LoadError
Jekyll.logger.debug "Couldn't load #{name}. Skipping."
block.call(name) if block
false
end
end
end
#
# Require a gem or gems. If it's not present, show a very nice error
# message that explains everything and is much more helpful than the
# normal LoadError.
#
# names - a string gem name or array of gem names
#
def require_with_graceful_fail(names)
Array(names).each do |name|
begin
Jekyll.logger.debug "Requiring:", "#{name}"
require name
rescue LoadError => e
Jekyll.logger.error "Dependency Error:", <<-MSG
Yikes! It looks like you don't have #{name} or one of its dependencies installed.
In order to use Jekyll as currently configured, you'll need to install this gem.
The full error message from Ruby is: '#{e.message}'
If you run into trouble, you can find helpful resources at http://jekyllrb.com/help/!
MSG
raise Jekyll::Errors::MissingDependencyException.new(name)
end
end
end
end
end
end

View File

@@ -1,9 +1,19 @@
require 'uri'
require 'json'
require 'date'
module Jekyll
module Filters
# Convert a Textile string into HTML output.
#
# input - The Textile String to convert.
#
# Returns the HTML formatted String.
def textilize(input)
site = @context.registers[:site]
converter = site.getConverterImpl(Jekyll::Converters::Textile)
converter.convert(input)
end
# Convert a Markdown string into HTML output.
#
# input - The Markdown String to convert.
@@ -11,54 +21,10 @@ module Jekyll
# Returns the HTML formatted String.
def markdownify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Jekyll::Converters::Markdown)
converter = site.getConverterImpl(Jekyll::Converters::Markdown)
converter.convert(input)
end
# Convert quotes into smart quotes.
#
# input - The String to convert.
#
# Returns the smart-quotified String.
def smartify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Jekyll::Converters::SmartyPants)
converter.convert(input)
end
# Convert a Sass string into CSS output.
#
# input - The Sass String to convert.
#
# Returns the CSS formatted String.
def sassify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Jekyll::Converters::Sass)
converter.convert(input)
end
# Convert a Scss string into CSS output.
#
# input - The Scss String to convert.
#
# Returns the CSS formatted String.
def scssify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Jekyll::Converters::Scss)
converter.convert(input)
end
# Slugify a filename or title.
#
# input - The filename or title to slugify.
# mode - how string is slugified
#
# Returns the given filename or title as a lowercase URL String.
# See Utils.slugify for more detail.
def slugify(input, mode=nil)
Utils.slugify(input, :mode => mode)
end
# Format a date in short format e.g. "27 Jan 2011".
#
# date - the Time to format.
@@ -117,7 +83,7 @@ module Jekyll
#
# Returns the escaped String.
def xml_escape(input)
input.to_s.encode(:xml => :attr).gsub(/\A"|"\Z/, "")
CGI.escapeHTML(input.to_s)
end
# CGI escape a string for use in a URL. Replaces any special characters
@@ -189,7 +155,7 @@ module Jekyll
#
# Returns the converted json string
def jsonify(input)
as_liquid(input).to_json
input.to_json
end
# Group an array of items by a property
@@ -205,7 +171,7 @@ module Jekyll
input.group_by do |item|
item_property(item, property).to_s
end.inject([]) do |memo, i|
memo << { "name" => i.first, "items" => i.last, "size" => i.last.size }
memo << {"name" => i.first, "items" => i.last}
end
else
input
@@ -215,14 +181,13 @@ module Jekyll
# Filter an array of objects
#
# input - the object array
# property - property within each object to filter by
# key - key within each object to filter by
# value - desired value
#
# Returns the filtered array of objects
def where(input, property, value)
return input unless input.is_a?(Enumerable)
input = input.values if input.is_a?(Hash)
input.select { |object| Array(item_property(object, property)).map(&:to_s).include?(value.to_s) }
return input unless input.is_a?(Array)
input.select { |object| item_property(object, property) == value }
end
# Sort an array of objects
@@ -233,9 +198,6 @@ module Jekyll
#
# Returns the filtered array of objects
def sort(input, property = nil, nils = "first")
if input.nil?
raise ArgumentError.new("Cannot sort a null object.")
end
if property.nil?
input.sort
else
@@ -245,11 +207,11 @@ module Jekyll
when nils == "last"
order = + 1
else
raise ArgumentError.new("Invalid nils order: " \
raise ArgumentError.new("Invalid nils order: " +
"'#{nils}' is not a valid nils order. It must be 'first' or 'last'.")
end
input.sort do |apple, orange|
input.sort { |apple, orange|
apple_property = item_property(apple, property)
orange_property = item_property(orange, property)
@@ -260,64 +222,15 @@ module Jekyll
else
apple_property <=> orange_property
end
end
}
end
end
def pop(array, input = 1)
return array unless array.is_a?(Array)
new_ary = array.dup
new_ary.pop(input.to_i || 1)
new_ary
end
def push(array, input)
return array unless array.is_a?(Array)
new_ary = array.dup
new_ary.push(input)
new_ary
end
def shift(array, input = 1)
return array unless array.is_a?(Array)
new_ary = array.dup
new_ary.shift(input.to_i || 1)
new_ary
end
def unshift(array, input)
return array unless array.is_a?(Array)
new_ary = array.dup
new_ary.unshift(input)
new_ary
end
def sample(input, num = 1)
return input unless input.respond_to?(:sample)
n = num.to_i rescue 1
if n == 1
input.sample
else
input.sample(n)
end
end
# Convert an object into its String representation for debugging
#
# input - The Object to be converted
#
# Returns a String representation of the object.
def inspect(input)
xml_escape(input.inspect)
end
private
def time(input)
case input
when Time
input.clone
when Date
input.to_time
input
when String
Time.parse(input) rescue Time.at(input.to_i)
when Numeric
@@ -325,7 +238,7 @@ module Jekyll
else
Jekyll.logger.error "Invalid Date:", "'#{input}' is not a valid datetime."
exit(1)
end.localtime
end
end
def groupable?(element)
@@ -341,27 +254,5 @@ module Jekyll
item[property.to_s]
end
end
def as_liquid(item)
case item
when Hash
pairs = item.map { |k, v| as_liquid([k, v]) }
Hash[pairs]
when Array
item.map { |i| as_liquid(i) }
else
if item.respond_to?(:to_liquid)
liquidated = item.to_liquid
# prevent infinite recursion for simple types (which return `self`)
if liquidated == item
item
else
as_liquid(liquidated)
end
else
item
end
end
end
end
end

View File

@@ -1,188 +1,148 @@
module Jekyll
# This class handles custom defaults for YAML frontmatter settings.
# These are set in _config.yml and apply both to internal use (e.g. layout)
# and the data available to liquid.
#
# It is exposed via the frontmatter_defaults method on the site class.
class FrontmatterDefaults
# Initializes a new instance.
def initialize(site)
@site = site
end
class Configuration
# This class handles custom defaults for YAML frontmatter settings.
# These are set in _config.yml and apply both to internal use (e.g. layout)
# and the data available to liquid.
#
# It is exposed via the frontmatter_defaults method on the site class.
class FrontmatterDefaults
# Initializes a new instance.
def initialize(site)
@site = site
end
def update_deprecated_types(set)
return set unless set.key?('scope') && set['scope'].key?('type')
# Finds a default value for a given setting, filtered by path and type
#
# path - the path (relative to the source) of the page, post or :draft the default is used in
# type - a symbol indicating whether a :page, a :post or a :draft calls this method
#
# Returns the default value or nil if none was found
def find(path, type, setting)
value = nil
old_scope = nil
set['scope']['type'] =
case set['scope']['type']
when 'page'
Deprecator.defaults_deprecate_type('page', 'pages')
'pages'
when 'post'
Deprecator.defaults_deprecate_type('post', 'posts')
'posts'
when 'draft'
Deprecator.defaults_deprecate_type('draft', 'drafts')
'drafts'
matching_sets(path, type).each do |set|
if set['values'].has_key?(setting) && has_precedence?(old_scope, set['scope'])
value = set['values'][setting]
old_scope = set['scope']
end
end
value
end
# Collects a hash with all default values for a page or post
#
# path - the relative path of the page or post
# type - a symbol indicating the type (:post, :page or :draft)
#
# Returns a hash with all default values (an empty hash if there are none)
def all(path, type)
defaults = {}
old_scope = nil
matching_sets(path, type).each do |set|
if has_precedence?(old_scope, set['scope'])
defaults.merge! set['values']
old_scope = set['scope']
else
defaults = set['values'].merge(defaults)
end
end
defaults
end
private
# Checks if a given default setting scope matches the given path and type
#
# scope - the hash indicating the scope, as defined in _config.yml
# path - the path to check for
# type - the type (:post, :page or :draft) to check for
#
# Returns true if the scope applies to the given path and type
def applies?(scope, path, type)
applies_path?(scope, path) && applies_type?(scope, type)
end
def applies_path?(scope, path)
return true if scope['path'].empty?
scope_path = Pathname.new(scope['path'])
Pathname.new(sanitize_path(path)).ascend do |path|
if path == scope_path
return true
end
end
end
def applies_type?(scope, type)
!scope.has_key?('type') || scope['type'] == type.to_s
end
# Checks if a given set of default values is valid
#
# set - the default value hash, as defined in _config.yml
#
# Returns true if the set is valid and can be used in this class
def valid?(set)
set.is_a?(Hash) && set['scope'].is_a?(Hash) && set['scope']['path'].is_a?(String) && set['values'].is_a?(Hash)
end
# Determines if a new scope has precedence over an old one
#
# old_scope - the old scope hash, or nil if there's none
# new_scope - the new scope hash
#
# Returns true if the new scope has precedence over the older
def has_precedence?(old_scope, new_scope)
return true if old_scope.nil?
new_path = sanitize_path(new_scope['path'])
old_path = sanitize_path(old_scope['path'])
if new_path.length != old_path.length
new_path.length >= old_path.length
elsif new_scope.has_key? 'type'
true
else
set['scope']['type']
end
set
end
def ensure_time!(set)
return set unless set.key?('values') && set['values'].key?('date')
return set if set['values']['date'].is_a?(Time)
set['values']['date'] = Utils.parse_date(set['values']['date'], "An invalid date format was found in a front-matter default set: #{set}")
set
end
# Finds a default value for a given setting, filtered by path and type
#
# path - the path (relative to the source) of the page, post or :draft the default is used in
# type - a symbol indicating whether a :page, a :post or a :draft calls this method
#
# Returns the default value or nil if none was found
def find(path, type, setting)
value = nil
old_scope = nil
matching_sets(path, type).each do |set|
if set['values'].key?(setting) && has_precedence?(old_scope, set['scope'])
value = set['values'][setting]
old_scope = set['scope']
!old_scope.has_key? 'type'
end
end
value
end
# Collects a hash with all default values for a page or post
#
# path - the relative path of the page or post
# type - a symbol indicating the type (:post, :page or :draft)
#
# Returns a hash with all default values (an empty hash if there are none)
def all(path, type)
defaults = {}
old_scope = nil
matching_sets(path, type).each do |set|
if has_precedence?(old_scope, set['scope'])
defaults = Utils.deep_merge_hashes(defaults, set['values'])
old_scope = set['scope']
# Collects a list of sets that match the given path and type
#
# Returns an array of hashes
def matching_sets(path, type)
valid_sets.select do |set|
applies?(set['scope'], path, type)
end
end
# Returns a list of valid sets
#
# This is not cached to allow plugins to modify the configuration
# and have their changes take effect
#
# Returns an array of hashes
def valid_sets
sets = @site.config['defaults']
return [] unless sets.is_a?(Array)
sets.select do |set|
unless valid?(set)
Jekyll.logger.warn "Default:", "An invalid default set was found"
end
valid?(set)
end
end
# Sanitizes the given path by removing a leading and addding a trailing slash
def sanitize_path(path)
if path.nil? || path.empty?
""
else
defaults = Utils.deep_merge_hashes(set['values'], defaults)
path.gsub(/\A\//, '').gsub(/([^\/])\z/, '\1/')
end
end
defaults
end
private
# Checks if a given default setting scope matches the given path and type
#
# scope - the hash indicating the scope, as defined in _config.yml
# path - the path to check for
# type - the type (:post, :page or :draft) to check for
#
# Returns true if the scope applies to the given path and type
def applies?(scope, path, type)
applies_path?(scope, path) && applies_type?(scope, type)
end
def applies_path?(scope, path)
return true if !scope.key?('path') || scope['path'].empty?
scope_path = Pathname.new(scope['path'])
Pathname.new(sanitize_path(path)).ascend do |ascended_path|
if ascended_path.to_s == scope_path.to_s
return true
end
end
end
# Determines whether the scope applies to type.
# The scope applies to the type if:
# 1. no 'type' is specified
# 2. the 'type' in the scope is the same as the type asked about
#
# scope - the Hash defaults set being asked about application
# type - the type of the document being processed / asked about
# its defaults.
#
# Returns true if either of the above conditions are satisfied,
# otherwise returns false
def applies_type?(scope, type)
!scope.key?('type') || scope['type'].eql?(type.to_s)
end
# Checks if a given set of default values is valid
#
# set - the default value hash, as defined in _config.yml
#
# Returns true if the set is valid and can be used in this class
def valid?(set)
set.is_a?(Hash) && set['values'].is_a?(Hash)
end
# Determines if a new scope has precedence over an old one
#
# old_scope - the old scope hash, or nil if there's none
# new_scope - the new scope hash
#
# Returns true if the new scope has precedence over the older
def has_precedence?(old_scope, new_scope)
return true if old_scope.nil?
new_path = sanitize_path(new_scope['path'])
old_path = sanitize_path(old_scope['path'])
if new_path.length != old_path.length
new_path.length >= old_path.length
elsif new_scope.key? 'type'
true
else
!old_scope.key? 'type'
end
end
# Collects a list of sets that match the given path and type
#
# Returns an array of hashes
def matching_sets(path, type)
valid_sets.select do |set|
!set.key?('scope') || applies?(set['scope'], path, type)
end
end
# Returns a list of valid sets
#
# This is not cached to allow plugins to modify the configuration
# and have their changes take effect
#
# Returns an array of hashes
def valid_sets
sets = @site.config['defaults']
return [] unless sets.is_a?(Array)
sets.map do |set|
if valid?(set)
ensure_time!(update_deprecated_types(set))
else
Jekyll.logger.warn "Defaults:", "An invalid front-matter default set was found:"
Jekyll.logger.warn "#{set}"
nil
end
end.compact
end
# Sanitizes the given path by removing a leading and adding a trailing slash
def sanitize_path(path)
if path.nil? || path.empty?
""
else
path.gsub(/\A\//, '').gsub(/([^\/])\z/, '\1')
end
end
end
end
end

View File

@@ -1,3 +1,4 @@
module Jekyll
Generator = Class.new(Plugin)
class Generator < Plugin
end
end

View File

@@ -1,102 +1,62 @@
module Jekyll
module Hooks
DEFAULT_PRIORITY = 20
# compatibility layer for octopress-hooks users
PRIORITY_MAP = {
:low => 10,
:normal => 20,
:high => 30
}.freeze
class HookCollection
include Enumerable
# initial empty hooks
@registry = {
:site => {
:after_init => [],
:after_reset => [],
:post_read => [],
:pre_render => [],
:post_render => [],
:post_write => []
},
:pages => {
:post_init => [],
:pre_render => [],
:post_render => [],
:post_write => []
},
:posts => {
:post_init => [],
:pre_render => [],
:post_render => [],
:post_write => []
},
:documents => {
:post_init => [],
:pre_render => [],
:post_render => [],
:post_write => []
}
}
# map of all hooks and their priorities
@hook_priority = {}
NotAvailable = Class.new(RuntimeError)
Uncallable = Class.new(RuntimeError)
# register hook(s) to be called later, public API
def self.register(owners, event, priority: DEFAULT_PRIORITY, &block)
Array(owners).each do |owner|
register_one(owner, event, priority_value(priority), &block)
end
end
# Ensure the priority is a Fixnum
def self.priority_value(priority)
return priority if priority.is_a?(Fixnum)
PRIORITY_MAP[priority] || DEFAULT_PRIORITY
end
# register a single hook to be called later, internal API
def self.register_one(owner, event, priority, &block)
@registry[owner] ||={
:post_init => [],
:pre_render => [],
:post_render => [],
:post_write => []
}
unless @registry[owner][event]
raise NotAvailable, "Invalid hook. #{owner} supports only the " \
"following hooks #{@registry[owner].keys.inspect}"
def each(&block)
if block.nil?
hook_methods
else
hook_methods.each &block
end
end
unless block.respond_to? :call
raise Uncallable, "Hooks must respond to :call"
def hook_methods
@hook_methods ||= Array.new
end
insert_hook owner, event, priority, &block
end
def self.insert_hook(owner, event, priority, &block)
@hook_priority[block] = "#{priority}.#{@hook_priority.size}".to_f
@registry[owner][event] << block
end
# interface for Jekyll core components to trigger hooks
def self.trigger(owner, event, *args)
# proceed only if there are hooks to call
return unless @registry[owner]
return unless @registry[owner][event]
# hooks to call for this owner and event
hooks = @registry[owner][event]
# sort and call hooks according to priority and load order
hooks.sort_by { |h| @hook_priority[h] }.each do |hook|
hook.call(*args)
def add_hook(proc)
hook_methods << proc
end
def exec(*args)
if args.empty?
hook_methods.each { |hook| hook.call }
else
hook_methods.each do |hook|
args.each { |arg| hook.call(arg) }
end
end
end
end
%w[
post_reset
pre_read
post_read
pre_generate
post_generate
pre_render
post_render
pre_cleanup
post_cleanup
pre_write
post_write
].each do |method|
declaration = <<-METH
def #{method}(method_name, *args)
cr = caller
((@hooks ||= Hash.new).fetch(method_name.to_s, HookCollection.new)).add_hook -> { cr.send(method_name.to_sym, args) }
end
def #{method}_exec(*args)
((@hooks ||= Hash.new).fetch(method_name.to_s, HookCollection.new)).exec(*args)
end
METH
puts declaration
class_eval declaration
end
end
end

View File

@@ -8,9 +8,6 @@ module Jekyll
# Gets the name of this layout.
attr_reader :name
# Gets the path to this layout.
attr_reader :path
# Gets/Sets the extension of this layout.
attr_accessor :ext
@@ -29,7 +26,6 @@ module Jekyll
@site = site
@base = base
@name = name
@path = site.in_source_dir(base, name)
self.data = {}

View File

@@ -38,12 +38,12 @@ module Jekyll
end
def layout_directory_inside_source
site.in_source_dir(site.config['layouts_dir'])
Jekyll.sanitized_path(site.source, site.config['layouts'])
end
def layout_directory_in_cwd
dir = Jekyll.sanitized_path(Dir.pwd, site.config['layouts_dir'])
if File.directory?(dir) && !site.safe
dir = Jekyll.sanitized_path(Dir.pwd, site.config['layouts'])
if File.directory?(dir)
dir
else
nil

View File

@@ -1,39 +0,0 @@
require 'jekyll/liquid_renderer/file'
require 'jekyll/liquid_renderer/table'
module Jekyll
class LiquidRenderer
def initialize(site)
@site = site
reset
end
def reset
@stats = {}
end
def file(filename)
filename = @site.in_source_dir(filename).sub(/\A#{Regexp.escape(@site.source)}\//, '')
LiquidRenderer::File.new(self, filename).tap do
@stats[filename] ||= {}
@stats[filename][:count] ||= 0
@stats[filename][:count] += 1
end
end
def increment_bytes(filename, bytes)
@stats[filename][:bytes] ||= 0
@stats[filename][:bytes] += bytes
end
def increment_time(filename, time)
@stats[filename][:time] ||= 0.0
@stats[filename][:time] += time
end
def stats_table(n = 50)
LiquidRenderer::Table.new(@stats).to_s(n)
end
end
end

View File

@@ -1,50 +0,0 @@
module Jekyll
class LiquidRenderer
class File
def initialize(renderer, filename)
@renderer = renderer
@filename = filename
end
def parse(content)
measure_time do
@template = Liquid::Template.parse(content, line_numbers: true)
end
self
end
def render(*args)
measure_time do
measure_bytes do
@template.render(*args)
end
end
end
def render!(*args)
measure_time do
measure_bytes do
@template.render!(*args)
end
end
end
private
def measure_bytes
yield.tap do |str|
@renderer.increment_bytes(@filename, str.bytesize)
end
end
def measure_time
before = Time.now
yield
ensure
after = Time.now
@renderer.increment_time(@filename, after - before)
end
end
end
end

View File

@@ -1,94 +0,0 @@
module Jekyll
class LiquidRenderer::Table
def initialize(stats)
@stats = stats
end
def to_s(n = 50)
data = data_for_table(n)
widths = table_widths(data)
generate_table(data, widths)
end
private
def generate_table(data, widths)
str = "\n"
table_head = data.shift
str << generate_row(table_head, widths)
str << generate_table_head_border(table_head, widths)
data.each do |row_data|
str << generate_row(row_data, widths)
end
str << "\n"
str
end
def generate_table_head_border(row_data, widths)
str = ""
row_data.each_index do |cell_index|
str << '-' * widths[cell_index]
str << '-+-' unless cell_index == row_data.length-1
end
str << "\n"
str
end
def generate_row(row_data, widths)
str = ''
row_data.each_with_index do |cell_data, cell_index|
if cell_index == 0
str << cell_data.ljust(widths[cell_index], ' ')
else
str << cell_data.rjust(widths[cell_index], ' ')
end
str << ' | ' unless cell_index == row_data.length-1
end
str << "\n"
str
end
def table_widths(data)
widths = []
data.each do |row|
row.each_with_index do |cell, index|
widths[index] = [ cell.length, widths[index] ].compact.max
end
end
widths
end
def data_for_table(n)
sorted = @stats.sort_by { |_, file_stats| -file_stats[:time] }
sorted = sorted.slice(0, n)
table = [%w(Filename Count Bytes Time)]
sorted.each do |filename, file_stats|
row = []
row << filename
row << file_stats[:count].to_s
row << format_bytes(file_stats[:bytes])
row << "%.3f" % file_stats[:time]
table << row
end
table
end
def format_bytes(bytes)
bytes /= 1024.0
"%.2fK" % bytes
end
end
end

Some files were not shown because too many files have changed in this diff Show More