Merge pull request #4848 from jekyll/new-theme-command

Merge pull request 4848
This commit is contained in:
jekyllbot 2016-05-19 22:13:05 -07:00
commit ee2c41ad6a
15 changed files with 432 additions and 0 deletions

View File

@ -3,6 +3,11 @@ Feature: Writing themes
I want to be able to make a gemified theme
In order to share my awesome style skillz with other Jekyllites
Scenario: Generating a new theme scaffold
When I run jekyll new-theme my-cool-theme
Then I should get a zero exit status
And the my-cool-theme directory should exist
Scenario: A theme with SCSS
Given I have a configuration file with "theme" set to "test-theme"
And I have a css directory

View File

@ -68,6 +68,7 @@ module Jekyll
autoload :StaticFile, 'jekyll/static_file'
autoload :Stevenson, 'jekyll/stevenson'
autoload :Theme, 'jekyll/theme'
autoload :ThemeBuilder, 'jekyll/theme_builder'
autoload :URL, 'jekyll/url'
autoload :Utils, 'jekyll/utils'
autoload :VERSION, 'jekyll/version'

View File

@ -0,0 +1,33 @@
require "erb"
class Jekyll::Commands::NewTheme < Jekyll::Command
class << self
def init_with_program(prog)
prog.command(:"new-theme") do |c|
c.syntax "new-theme NAME"
c.description "Creates a new Jekyll theme scaffold"
c.action do |args, _|
Jekyll::Commands::NewTheme.process(args)
end
end
end
def process(args)
if !args || args.empty?
raise Jekyll::Errors::InvalidThemeName, "You must specify a theme name."
end
new_theme_name = args.join("_")
theme = Jekyll::ThemeBuilder.new(new_theme_name)
if theme.path.exist?
Jekyll.logger.abort_with "Conflict:", "#{theme.path} already exists."
end
theme.create!
Jekyll.logger.info "Your new Jekyll theme, #{theme.name}," \
" is ready for you in #{theme.path}!"
Jekyll.logger.info "For help getting started, read #{theme.path}/README.md."
end
end
end

View File

@ -2,6 +2,8 @@ module Jekyll
module Errors
FatalException = Class.new(::RuntimeError)
InvalidThemeName = Class.new(FatalException)
DropMutationException = Class.new(FatalException)
InvalidPermalinkError = Class.new(FatalException)
InvalidYAMLFrontMatterError = Class.new(FatalException)

117
lib/jekyll/theme_builder.rb Normal file
View File

@ -0,0 +1,117 @@
class Jekyll::ThemeBuilder
SCAFFOLD_DIRECTORIES = %w(
_layouts _includes _sass example example/_posts
).freeze
attr_reader :name, :path
def initialize(theme_name)
@name = theme_name.to_s.tr(" ", "_").gsub(/_+/, "_")
@path = Pathname.new(File.expand_path(name, Dir.pwd))
end
def create!
create_directories
create_gemspec
create_accessories
create_example_site
initialize_git_repo
end
private
def root
@root ||= Pathname.new(File.expand_path("../", __dir__))
end
def template_file(filename)
[
root.join("theme_template", "#{filename}.erb"),
root.join("theme_template", filename.to_s)
].find(&:exist?)
end
def template(filename)
erb.render(template_file(filename).read)
end
def erb
@erb ||= ERBRenderer.new(self)
end
def mkdir_p(directories)
Array(directories).each do |directory|
full_path = path.join(directory)
Jekyll.logger.info "create", full_path.to_s
FileUtils.mkdir_p(full_path)
end
end
def write_file(filename, contents)
full_path = path.join(filename)
Jekyll.logger.info "create", full_path.to_s
File.write(full_path, contents)
end
def create_directories
mkdir_p(SCAFFOLD_DIRECTORIES)
end
def create_gemspec
write_file("Gemfile", template("Gemfile"))
write_file("#{name}.gemspec", template("theme.gemspec"))
end
def create_accessories
%w(README.md Rakefile CODE_OF_CONDUCT.md LICENSE.txt).each do |filename|
write_file(filename, template(filename))
end
end
def create_example_site
%w(example/_config.yml example/index.html example/style.scss).each do |filename|
write_file(filename, template(filename))
end
write_file(
"example/_posts/#{Time.now.strftime("%Y-%m-%d")}-my-example-post.md",
template("example/_post.md")
)
end
def initialize_git_repo
Jekyll.logger.info "initialize", path.join(".git").to_s
Dir.chdir(path.to_s) { `git init` }
end
def user_name
@user_name ||= `git config user.name`.chomp
end
def user_email
@user_email ||= `git config user.email`.chomp
end
class ERBRenderer
extend Forwardable
def_delegator :@theme_builder, :name, :theme_name
def_delegator :@theme_builder, :user_name, :user_name
def_delegator :@theme_builder, :user_email, :user_email
def initialize(theme_builder)
@theme_builder = theme_builder
end
def jekyll_pessimistic_version
Jekyll::VERSION.split(".").take(2).join(".")
end
def theme_directories
SCAFFOLD_DIRECTORIES
end
def render(contents)
ERB.new(contents).result binding
end
end
end

View File

@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
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.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at <%= user_email %>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@ -0,0 +1,2 @@
source "https://rubygems.org"
gemspec

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 <%= user_name %>
Permission is hereby granted, free of charge, to any person obtaining a copy
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
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
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
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,46 @@
# <%= theme_name %>
Welcome to your new Jekyll theme! In this directory, you'll find the files you need to be able to package up your theme into a gem. Put your layouts in `_layouts`, your includes in `_includes` and your sass in `_sass`. To experiment with this code, add some sample content and run `bundle exec jekyll serve` this directory is setup just like a Jekyll site!
TODO: Delete this and the text above, and describe your gem
## Installation
Add this line to your Jekyll site's Gemfile:
```ruby
gem <%= theme_name.inspect %>
```
And add this line to your Jekyll site:
```yaml
theme: <%= theme_name %>
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install <%= theme_name %>
## Usage
TODO: Write usage instructions here. Describe your available layouts, includes, and/or sass.
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/hello. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## Development
To set up your environment to develop this theme, run `bundle install`.
To test your theme, run `bundle exec rake preview` and open your browser at `http://localhost:4000`. This starts a Jekyll server using your theme and the contents of the `example/` directory. As you make modifications to your theme and to the example site, your site will regenerate and you should see the changes in the browser after a refresh.
## License
The theme is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

View File

@ -0,0 +1,74 @@
require "bundler/gem_tasks"
require "jekyll"
require "listen"
def listen_ignore_paths(base, options)
[
/_config\.ya?ml/,
/_site/,
/\.jekyll-metadata/
]
end
def listen_handler(base, options)
site = Jekyll::Site.new(options)
Jekyll::Command.process_site(site)
proc do |modified, added, removed|
t = Time.now
c = modified + added + removed
n = c.length
relative_paths = c.map{ |p| Pathname.new(p).relative_path_from(base).to_s }
print Jekyll.logger.message("Regenerating:", "#{relative_paths.join(", ")} changed... ")
begin
Jekyll::Command.process_site(site)
puts "regenerated in #{Time.now - t} seconds."
rescue => e
puts "error:"
Jekyll.logger.warn "Error:", e.message
Jekyll.logger.warn "Error:", "Run jekyll build --trace for more information."
end
end
end
task :preview do
base = Pathname.new('.').expand_path
options = {
"source" => base.join('example').to_s,
"destination" => base.join('example/_site').to_s,
"force_polling" => false,
"serving" => true,
"theme" => <%= theme_name.inspect %>
}
options = Jekyll.configuration(options)
ENV["LISTEN_GEM_DEBUGGING"] = "1"
listener = Listen.to(
base.join("_includes"),
base.join("_layouts"),
base.join("_sass"),
options["source"],
:ignore => listen_ignore_paths(base, options),
:force_polling => options['force_polling'],
&(listen_handler(base, options))
)
begin
listener.start
Jekyll.logger.info "Auto-regeneration:", "enabled for '#{options["source"]}'"
unless options['serving']
trap("INT") do
listener.stop
puts " Halting auto-regeneration."
exit 0
end
loop { sleep 1000 }
end
rescue ThreadError
# You pressed Ctrl-C, oh my!
end
Jekyll::Commands::Serve.process(options)
end

View File

@ -0,0 +1 @@
theme: <%= theme_name %>

View File

@ -0,0 +1,13 @@
---
# Specify a layout from your theme!
# This will be the layout users specify for their posts.
---
Eos eu docendi tractatos sapientem, brute option menandri in vix, quando vivendo accommodare te ius. Nec melius fastidii constituam id, viderer theophrastus ad sit, hinc semper periculis cum id. Noluisse postulant assentior est in, no choro sadipscing repudiandae vix. Vis in euismod delenit dignissim. Ex quod nostrum sit, suas decore animal id ius, nobis solet detracto quo te.
{% comment %}
Might you have an include in your theme? Why not try it here!
{% include my-themes-great-include.html %}
{% endcomment %}
No laudem altera adolescens has, volumus lucilius eum no. Eam ei nulla audiam efficiantur. Suas affert per no, ei tale nibh sea. Sea ne magna harum, in denique scriptorem sea, cetero alienum tibique ei eos. Labores persequeris referrentur eos ei.

View File

@ -0,0 +1,14 @@
---
# Specify a layout from your theme!
---
Lorem ipsum dolor sit amet, quo id prima corrumpit pertinacia, id ius dolor dolores, an veri pertinax explicari mea. Agam solum et qui, his id ludus graeco adipiscing. Duis theophrastus nam in, at his vidisse atomorum. Tantas gloriatur scripserit ne eos. Est wisi tempor habemus at, ei graeco dissentiet eos. Ne usu aliquip sanctus conceptam, te vis ignota animal, modus latine contentiones ius te.
{% for post in site.posts %}
<h2>{{ post.title }}</h2>
<blockquote>{{ post.excerpt }}</blockquote>
{% endfor %}
Te falli veritus sea, at molestiae scribentur deterruisset vix, et mea zril phaedrum vulputate. No cum dicit consulatu. Ut has nostro noluisse expetendis, te pro quaeque disputando, eu sed summo omnes. Eos at tale aperiam, usu cu propriae quaestio constituto, sed aperiam erroribus temporibus an.
Quo eu liber mediocritatem, vix an delectus eleifend, iuvaret suscipit ei vel. Partem invenire per an, mea postulant dissentias eu, ius tantas audire nominavi eu. Dicunt tritani veritus ex vis, mei in case sententiae. At exerci democritum nam, cu lobortis iracundia mei. Alia eligendi consectetuer eu sed, paulo docendi noluisse sit ex.

View File

@ -0,0 +1,7 @@
---
---
// Here, you can test out the Sass/SCSS that you include in your theme.
// Simply `@import` the necessary file(s) to get the proper styles on the site.
// E.g.:
// @import "a-file-from-my-theme";

View File

@ -0,0 +1,22 @@
# coding: utf-8
Gem::Specification.new do |spec|
spec.name = <%= theme_name.inspect %>
spec.version = "0.1.0"
spec.authors = [<%= user_name.inspect %>]
spec.email = [<%= user_email.inspect %>]
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
spec.metadata["plugin_type"] = "theme"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(exe|<%= theme_directories.join("|") %>)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.add_development_dependency "jekyll", "~> <%= jekyll_pessimistic_version %>"
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
end