middleman/middleman-cli/lib/middleman-cli/init.rb

91 lines
2.3 KiB
Ruby
Raw Normal View History

2011-12-29 07:52:51 +01:00
# CLI Module
2011-12-21 21:13:28 +01:00
module Middleman::Cli
2011-12-29 07:52:51 +01:00
# A thor task for creating new projects
2015-01-04 21:23:35 +01:00
class Init < Thor::Group
include Thor::Actions
2015-01-04 21:23:35 +01:00
check_unknown_options!
2015-01-04 21:23:35 +01:00
argument :target, type: :string, default: '.'
2015-01-04 21:23:35 +01:00
class_option 'template',
aliases: '-T',
default: 'middleman/middleman-templates-default',
desc: 'Use a project template'
# Do not run bundle install
2015-01-04 21:23:35 +01:00
class_option 'skip-bundle',
type: :boolean,
aliases: '-B',
default: false,
desc: 'Skip bundle install'
2011-12-29 07:52:51 +01:00
# The init task
2015-01-04 21:23:35 +01:00
def init
require 'tmpdir'
2014-08-15 05:34:31 +02:00
repo_path, repo_branch = if shortname?(options[:template])
require 'open-uri'
require 'json'
api = 'http://directory.middlemanapp.com/api'
uri = ::URI.parse("#{api}/#{options[:template]}.json")
begin
data = ::JSON.parse(uri.read)
data['links']['github']
2014-08-15 05:34:31 +02:00
data['links']['github'].split('#')
rescue ::OpenURI::HTTPError
2015-01-04 21:23:35 +01:00
say "Template `#{options[:template]}` not found in Middleman Directory."
say 'Did you mean to use a full `user/repo` path?'
exit
end
else
2014-08-15 05:34:31 +02:00
repo_name, repo_branch = options[:template].split('#')
[repository_path(repo_name), repo_branch]
end
Dir.mktmpdir do |dir|
2014-08-15 05:34:31 +02:00
cmd = repo_branch ? "clone -b #{repo_branch}" : 'clone'
run("git #{cmd} #{repo_path} #{dir}")
2015-01-04 21:23:35 +01:00
inside(target) do
thorfile = File.join(dir, 'Thorfile')
if File.exist?(thorfile)
::Thor::Util.load_thorfile(thorfile)
2015-01-04 21:23:35 +01:00
invoke 'middleman:generator'
else
source_paths << dir
directory dir, '.', exclude_pattern: /\.git\/|\.gitignore$/
end
2015-01-04 21:23:35 +01:00
run('bundle install') unless ENV['TEST'] || options[:'skip-bundle']
end
end
end
protected
def shortname?(repo)
repo.split('/').length != 2
end
def repository_path(repo)
"git://github.com/#{repo}.git"
end
2015-01-04 21:23:35 +01:00
# Add to CLI
Base.register(self, 'init', 'init TARGET [options]', 'Create new project at TARGET')
2015-01-04 21:23:35 +01:00
# Map "i", "new" and "n" to "init"
Base.map(
'i' => 'init',
'new' => 'init',
'n' => 'init'
)
end
end