forked from mattetti/merb-book
-
Notifications
You must be signed in to change notification settings - Fork 1
/
merb.thor
2020 lines (1765 loc) · 68.7 KB
/
merb.thor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
require 'rubygems'
require 'thor'
require 'fileutils'
require 'yaml'
# Important - don't change this line or its position
MERB_THOR_VERSION = '0.2.1'
##############################################################################
module ColorfulMessages
# red
def error(*messages)
puts messages.map { |msg| "\033[1;31m#{msg}\033[0m" }
end
# yellow
def warning(*messages)
puts messages.map { |msg| "\033[1;33m#{msg}\033[0m" }
end
# green
def success(*messages)
puts messages.map { |msg| "\033[1;32m#{msg}\033[0m" }
end
alias_method :message, :success
# magenta
def note(*messages)
puts messages.map { |msg| "\033[1;35m#{msg}\033[0m" }
end
# blue
def info(*messages)
puts messages.map { |msg| "\033[1;34m#{msg}\033[0m" }
end
end
##############################################################################
require 'rubygems/dependency_installer'
require 'rubygems/uninstaller'
require 'rubygems/dependency'
module GemManagement
include ColorfulMessages
# Install a gem - looks remotely and local gem cache;
# won't process rdoc or ri options.
def install_gem(gem, options = {})
refresh = options.delete(:refresh) || []
from_cache = (options.key?(:cache) && options.delete(:cache))
if from_cache
install_gem_from_cache(gem, options)
else
version = options.delete(:version)
Gem.configuration.update_sources = false
# Limit source index to install dir
update_source_index(options[:install_dir]) if options[:install_dir]
installer = Gem::DependencyInstaller.new(options.merge(:user_install => false))
# Force-refresh certain gems by excluding them from the current index
if !options[:ignore_dependencies] && refresh.respond_to?(:include?) && !refresh.empty?
source_index = installer.instance_variable_get(:@source_index)
source_index.gems.each do |name, spec|
source_index.gems.delete(name) if refresh.include?(spec.name)
end
end
exception = nil
begin
installer.install gem, version
rescue Gem::InstallError => e
exception = e
rescue Gem::GemNotFoundException => e
if from_cache && gem_file = find_gem_in_cache(gem, version)
puts "Located #{gem} in gem cache..."
installer.install gem_file
else
exception = e
end
rescue => e
exception = e
end
if installer.installed_gems.empty? && exception
error "Failed to install gem '#{gem} (#{version || 'any version'})' (#{exception.message})"
end
ensure_bin_wrapper_for_installed_gems(installer.installed_gems, options)
installer.installed_gems.each do |spec|
success "Successfully installed #{spec.full_name}"
end
return !installer.installed_gems.empty?
end
end
# Install a gem - looks in the system's gem cache instead of remotely;
# won't process rdoc or ri options.
def install_gem_from_cache(gem, options = {})
version = options.delete(:version)
Gem.configuration.update_sources = false
installer = Gem::DependencyInstaller.new(options.merge(:user_install => false))
exception = nil
begin
if gem_file = find_gem_in_cache(gem, version)
puts "Located #{gem} in gem cache..."
installer.install gem_file
else
raise Gem::InstallError, "Unknown gem #{gem}"
end
rescue Gem::InstallError => e
exception = e
end
if installer.installed_gems.empty? && exception
error "Failed to install gem '#{gem}' (#{e.message})"
end
ensure_bin_wrapper_for_installed_gems(installer.installed_gems, options)
installer.installed_gems.each do |spec|
success "Successfully installed #{spec.full_name}"
end
end
# Install a gem from source - builds and packages it first then installs.
#
# Examples:
# install_gem_from_source(source_dir, :install_dir => ...)
# install_gem_from_source(source_dir, gem_name)
# install_gem_from_source(source_dir, :skip => [...])
def install_gem_from_source(source_dir, *args)
installed_gems = []
opts = args.last.is_a?(Hash) ? args.pop : {}
Dir.chdir(source_dir) do
gem_name = args[0] || File.basename(source_dir)
gem_pkg_dir = File.join(source_dir, 'pkg')
gem_pkg_glob = File.join(gem_pkg_dir, "#{gem_name}-*.gem")
skip_gems = opts.delete(:skip) || []
# Cleanup what's already there
clobber(source_dir)
FileUtils.mkdir_p(gem_pkg_dir) unless File.directory?(gem_pkg_dir)
# Recursively process all gem packages within the source dir
skip_gems << gem_name
packages = package_all(source_dir, skip_gems)
if packages.length == 1
# The are no subpackages for the main package
refresh = [gem_name]
else
# Gather all packages into the top-level pkg directory
packages.each do |pkg|
FileUtils.copy_entry(pkg, File.join(gem_pkg_dir, File.basename(pkg)))
end
# Finally package the main gem - without clobbering the already copied pkgs
package(source_dir, false)
# Gather subgems to refresh during installation of the main gem
refresh = packages.map do |pkg|
File.basename(pkg, '.gem')[/^(.*?)-([\d\.]+)$/, 1] rescue nil
end.compact
# Install subgems explicitly even if ignore_dependencies is set
if opts[:ignore_dependencies]
refresh.each do |name|
gem_pkg = Dir[File.join(gem_pkg_dir, "#{name}-*.gem")][0]
install_pkg(gem_pkg, opts)
end
end
end
ensure_bin_wrapper_for(opts[:install_dir], opts[:bin_dir], *installed_gems)
# Finally install the main gem
if install_pkg(Dir[gem_pkg_glob][0], opts.merge(:refresh => refresh))
installed_gems = refresh
else
installed_gems = []
end
end
installed_gems
end
def install_pkg(gem_pkg, opts = {})
if (gem_pkg && File.exists?(gem_pkg))
# Needs to be executed from the directory that contains all packages
Dir.chdir(File.dirname(gem_pkg)) { install_gem(gem_pkg, opts) }
else
false
end
end
# Uninstall a gem.
def uninstall_gem(gem, options = {})
if options[:version] && !options[:version].is_a?(Gem::Requirement)
options[:version] = Gem::Requirement.new ["= #{options[:version]}"]
end
update_source_index(options[:install_dir]) if options[:install_dir]
Gem::Uninstaller.new(gem, options).uninstall rescue nil
end
def clobber(source_dir)
Dir.chdir(source_dir) do
system "#{Gem.ruby} -S rake -s clobber" unless File.exists?('Thorfile')
end
end
def package(source_dir, clobber = true)
Dir.chdir(source_dir) do
if File.exists?('Thorfile')
thor ":package"
elsif File.exists?('Rakefile')
rake "clobber" if clobber
rake "package"
end
end
Dir[File.join(source_dir, 'pkg/*.gem')]
end
def package_all(source_dir, skip = [], packages = [])
if Dir[File.join(source_dir, '{Rakefile,Thorfile}')][0]
name = File.basename(source_dir)
Dir[File.join(source_dir, '*', '{Rakefile,Thorfile}')].each do |taskfile|
package_all(File.dirname(taskfile), skip, packages)
end
packages.push(*package(source_dir)) unless skip.include?(name)
end
packages.uniq
end
def rake(cmd)
cmd << " >/dev/null" if $SILENT && !Gem.win_platform?
system "#{Gem.ruby} -S #{which('rake')} -s #{cmd} >/dev/null"
end
def thor(cmd)
cmd << " >/dev/null" if $SILENT && !Gem.win_platform?
system "#{Gem.ruby} -S #{which('thor')} #{cmd}"
end
# Use the local bin/* executables if available.
def which(executable)
if File.executable?(exec = File.join(Dir.pwd, 'bin', executable))
exec
else
executable
end
end
# Partition gems into system, local and missing gems
def partition_dependencies(dependencies, gem_dir)
system_specs, local_specs, missing_deps = [], [], []
if gem_dir && File.directory?(gem_dir)
gem_dir = File.expand_path(gem_dir)
::Gem.clear_paths; ::Gem.path.unshift(gem_dir)
::Gem.source_index.refresh!
dependencies.each do |dep|
gemspecs = ::Gem.source_index.search(dep)
local = gemspecs.reverse.find { |s| s.loaded_from.index(gem_dir) == 0 }
if local
local_specs << local
elsif gemspecs.last
system_specs << gemspecs.last
else
missing_deps << dep
end
end
::Gem.clear_paths
else
dependencies.each do |dep|
gemspecs = ::Gem.source_index.search(dep)
if gemspecs.last
system_specs << gemspecs.last
else
missing_deps << dep
end
end
end
[system_specs, local_specs, missing_deps]
end
# Create a modified executable wrapper in the specified bin directory.
def ensure_bin_wrapper_for(gem_dir, bin_dir, *gems)
options = gems.last.is_a?(Hash) ? gems.last : {}
options[:no_minigems] ||= []
if bin_dir && File.directory?(bin_dir)
gems.each do |gem|
if gemspec_path = Dir[File.join(gem_dir, 'specifications', "#{gem}-*.gemspec")].last
spec = Gem::Specification.load(gemspec_path)
enable_minigems = !options[:no_minigems].include?(spec.name)
spec.executables.each do |exec|
executable = File.join(bin_dir, exec)
message "Writing executable wrapper #{executable}"
File.open(executable, 'w', 0755) do |f|
f.write(executable_wrapper(spec, exec, enable_minigems))
end
end
end
end
end
end
def ensure_bin_wrapper_for_installed_gems(gemspecs, options)
if options[:install_dir] && options[:bin_dir]
gems = gemspecs.map { |spec| spec.name }
ensure_bin_wrapper_for(options[:install_dir], options[:bin_dir], *gems)
end
end
private
def executable_wrapper(spec, bin_file_name, minigems = true)
requirements = ['minigems', 'rubygems']
requirements.reverse! unless minigems
try_req, then_req = requirements
<<-TEXT
#!/usr/bin/env ruby
#
# This file was generated by Merb's GemManagement
#
# The application '#{spec.name}' is installed as part of a gem, and
# this file is here to facilitate running it.
begin
require '#{try_req}'
rescue LoadError
require '#{then_req}'
end
# use gems dir if ../gems exists - eg. only for ./bin/#{bin_file_name}
if File.directory?(gems_dir = File.join(File.dirname(__FILE__), '..', 'gems'))
$BUNDLE = true; Gem.clear_paths; Gem.path.replace([File.expand_path(gems_dir)])
ENV["PATH"] = "\#{File.dirname(__FILE__)}:\#{gems_dir}/bin:\#{ENV["PATH"]}"
if (local_gem = Dir[File.join(gems_dir, "specifications", "#{spec.name}-*.gemspec")].last)
version = File.basename(local_gem)[/-([\\.\\d]+)\\.gemspec$/, 1]
end
end
version ||= "#{Gem::Requirement.default}"
if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
version = $1
ARGV.shift
end
gem '#{spec.name}', version
load '#{bin_file_name}'
TEXT
end
def find_gem_in_cache(gem, version)
spec = if version
version = Gem::Requirement.new ["= #{version}"] unless version.is_a?(Gem::Requirement)
Gem.source_index.find_name(gem, version).first
else
Gem.source_index.find_name(gem).sort_by { |g| g.version }.last
end
if spec && File.exists?(gem_file = "#{spec.installation_path}/cache/#{spec.full_name}.gem")
gem_file
end
end
def update_source_index(dir)
Gem.source_index.load_gems_in(File.join(dir, 'specifications'))
end
end
##############################################################################
class SourceManager
include ColorfulMessages
attr_accessor :source_dir
def initialize(source_dir)
self.source_dir = source_dir
end
def clone(name, url)
FileUtils.cd(source_dir) do
raise "destination directory already exists" if File.directory?(name)
system("git clone --depth 1 #{url} #{name}")
end
rescue => e
error "Unable to clone #{name} repository (#{e.message})"
end
def update(name, url)
if File.directory?(repository_dir = File.join(source_dir, name))
FileUtils.cd(repository_dir) do
repos = existing_repos(name)
fork_name = url[/.com\/+?(.+)\/.+\.git/u, 1]
if url == repos["origin"]
# Pull from the original repository - no branching needed
info "Pulling from origin: #{url}"
system "git fetch; git checkout master; git rebase origin/master"
elsif repos.values.include?(url) && fork_name
# Update and switch to a remote branch for a particular github fork
info "Switching to remote branch: #{fork_name}"
system "git checkout -b #{fork_name} #{fork_name}/master"
system "git rebase #{fork_name}/master"
elsif fork_name
# Create a new remote branch for a particular github fork
info "Adding a new remote branch: #{fork_name}"
system "git remote add -f #{fork_name} #{url}"
system "git checkout -b #{fork_name} #{fork_name}/master"
else
warning "No valid repository found for: #{name}"
end
end
return true
else
warning "No valid repository found at: #{repository_dir}"
end
rescue => e
error "Unable to update #{name} repository (#{e.message})"
return false
end
def existing_repos(name)
repos = []
FileUtils.cd(File.join(source_dir, name)) do
repos = %x[git remote -v].split("\n").map { |branch| branch.split(/\s+/) }
end
Hash[*repos.flatten]
end
end
##############################################################################
module MerbThorHelper
attr_accessor :force_gem_dir
def self.included(base)
base.send(:include, ColorfulMessages)
base.extend ColorfulMessages
end
def use_edge_gem_server
::Gem.sources << 'http://edge.merbivore.com'
end
def source_manager
@_source_manager ||= SourceManager.new(source_dir)
end
def extract_repositories(names)
repos = []
names.each do |name|
if repo_url = Merb::Source.repo(name, options[:sources])
# A repository entry for this dependency exists
repo = [name, repo_url]
repos << repo unless repos.include?(repo)
elsif (repo_name = Merb::Stack.lookup_repository_name(name)) &&
(repo_url = Merb::Source.repo(repo_name, options[:sources]))
# A parent repository entry for this dependency exists
repo = [repo_name, repo_url]
unless repos.include?(repo)
puts "Found #{repo_name}/#{name} at #{repo_url}"
repos << repo
end
end
end
repos
end
def update_dependency_repositories(dependencies)
repos = extract_repositories(dependencies.map { |d| d.name })
update_repositories(repos)
end
def update_repositories(repos)
repos.each do |(name, url)|
if File.directory?(repository_dir = File.join(source_dir, name))
message "Updating or branching #{name}..."
source_manager.update(name, url)
else
message "Cloning #{name} repository from #{url}..."
source_manager.clone(name, url)
end
end
end
def install_dependency(dependency, opts = {})
version = dependency.version_requirements.to_s
install_opts = default_install_options.merge(:version => version)
Merb::Gem.install(dependency.name, install_opts.merge(opts))
end
def install_dependency_from_source(dependency, opts = {})
matches = Dir[File.join(source_dir, "**", dependency.name, "{Rakefile,Thorfile}")]
matches.reject! { |m| File.basename(m) == 'Thorfile' }
if matches.length == 1 && matches[0]
if File.directory?(gem_src_dir = File.dirname(matches[0]))
begin
Merb::Gem.install_gem_from_source(gem_src_dir, default_install_options.merge(opts))
puts "Installed #{dependency.name}"
return true
rescue => e
warning "Unable to install #{dependency.name} from source (#{e.message})"
end
else
msg = "Unknown directory: #{gem_src_dir}"
warning "Unable to install #{dependency.name} from source (#{msg})"
end
elsif matches.length > 1
error "Ambigous source(s) for dependency: #{dependency.name}"
matches.each { |m| puts "- #{m}" }
end
return false
end
def clobber_dependencies!
if options[:force] && gem_dir && File.directory?(gem_dir)
# Remove all existing local gems by clearing the gems directory
if dry_run?
note 'Clearing existing local gems...'
else
message 'Clearing existing local gems...'
FileUtils.rm_rf(gem_dir) && FileUtils.mkdir_p(default_gem_dir)
end
elsif !local.empty?
# Uninstall all local versions of the gems to install
if dry_run?
note 'Uninstalling existing local gems:'
local.each { |gemspec| note "Uninstalled #{gemspec.name}" }
else
message 'Uninstalling existing local gems:' if local.size > 1
local.each do |gemspec|
Merb::Gem.uninstall(gemspec.name, default_uninstall_options)
end
end
end
end
def display_gemspecs(gemspecs)
if gemspecs.empty?
puts "- none"
else
gemspecs.each do |spec|
if hint = Dir[File.join(spec.full_gem_path, '*.strategy')][0]
strategy = File.basename(hint, '.strategy')
puts "- #{spec.full_name} (#{strategy})"
else
puts "~ #{spec.full_name}" # unknown strategy
end
end
end
end
def display_dependencies(dependencies)
if dependencies.empty?
puts "- none"
else
dependencies.each { |d| puts "- #{d.name} (#{d.version_requirements})" }
end
end
def default_install_options
{ :install_dir => gem_dir, :bin_dir => bin_dir, :ignore_dependencies => ignore_dependencies? }
end
def default_uninstall_options
{ :install_dir => gem_dir, :bin_dir => bin_dir, :ignore => true, :all => true, :executables => true }
end
def dry_run?
options[:"dry-run"]
end
def ignore_dependencies?
options[:"ignore-dependencies"]
end
# The current working directory, or Merb app root (--merb-root option).
def working_dir
@_working_dir ||= File.expand_path(options['merb-root'] || Dir.pwd)
end
# We should have a ./src dir for local and system-wide management.
def source_dir
@_source_dir ||= File.join(working_dir, 'src')
create_if_missing(@_source_dir)
@_source_dir
end
# If a local ./gems dir is found, return it.
def gem_dir
return force_gem_dir if force_gem_dir
if File.directory?(dir = default_gem_dir)
dir
end
end
def default_gem_dir
File.join(working_dir, 'gems')
end
# If we're in a Merb app, we can have a ./bin directory;
# create it if it's not there.
def bin_dir
@_bin_dir ||= begin
if gem_dir
dir = File.join(working_dir, 'bin')
create_if_missing(dir)
dir
end
end
end
# Helper to create dir unless it exists.
def create_if_missing(path)
FileUtils.mkdir(path) unless File.exists?(path)
end
def sudo
ENV['THOR_SUDO'] ||= "sudo"
sudo = Gem.win_platform? ? "" : ENV['THOR_SUDO']
end
def local_gemspecs(directory = gem_dir)
if File.directory?(specs_dir = File.join(directory, 'specifications'))
Dir[File.join(specs_dir, '*.gemspec')].map do |gemspec_path|
gemspec = Gem::Specification.load(gemspec_path)
gemspec.loaded_from = gemspec_path
gemspec
end
else
[]
end
end
end
##############################################################################
$SILENT = true # don't output all the mess some rake package tasks spit out
module Merb
class Gem < Thor
include MerbThorHelper
extend GemManagement
attr_accessor :system, :local, :missing
global_method_options = {
"--merb-root" => :optional, # the directory to operate on
"--version" => :optional, # gather specific version of gem
"--ignore-dependencies" => :boolean # don't install sub-dependencies
}
method_options global_method_options
def initialize(*args); super; end
# List gems that match the specified criteria.
#
# By default all local gems are listed. When the first argument is 'all' the
# list is partitioned into system an local gems; specify 'system' to show
# only system gems. A second argument can be used to filter on a set of known
# components, like all merb-more gems for example.
#
# Examples:
#
# merb:gem:list # list all local gems - the default
# merb:gem:list all # list system and local gems
# merb:gem:list system # list only system gems
# merb:gem:list all merb-more # list only merb-more related gems
# merb:gem:list --version 0.9.8 # list gems that match the version
desc 'list [all|local|system] [comp]', 'Show installed gems'
def list(filter = 'local', comp = nil)
deps = comp ? Merb::Stack.select_component_dependencies(dependencies, comp) : dependencies
self.system, self.local, self.missing = Merb::Gem.partition_dependencies(deps, gem_dir)
case filter
when 'all'
message 'Installed system gems:'
display_gemspecs(system)
message 'Installed local gems:'
display_gemspecs(local)
when 'system'
message 'Installed system gems:'
display_gemspecs(system)
when 'local'
message 'Installed local gems:'
display_gemspecs(local)
else
warning "Invalid listing filter '#{filter}'"
end
end
# Install the specified gems.
#
# All arguments should be names of gems to install.
#
# When :force => true then any existing versions of the gems to be installed
# will be uninstalled first. It's important to note that so-called meta-gems
# or gems that exactly match a set of Merb::Stack.components will have their
# sub-gems uninstalled too. For example, uninstalling merb-more will install
# all contained gems: merb-action-args, merb-assets, merb-gen, ...
#
# Examples:
#
# merb:gem:install merb-core merb-slices # install all specified gems
# merb:gem:install merb-core --version 0.9.8 # install a specific version of a gem
# merb:gem:install merb-core --force # uninstall then subsequently install the gem
# merb:gem:install merb-core --cache # try to install locally from system gems
# merb:gem:install merb --merb-edge # install from edge.merbivore.com
desc 'install GEM_NAME [GEM_NAME, ...]', 'Install a gem from rubygems'
method_options "--cache" => :boolean,
"--dry-run" => :boolean,
"--force" => :boolean,
"--merb-edge" => :boolean
def install(*names)
opts = { :version => options[:version], :cache => options[:cache] }
use_edge_gem_server if options[:"merb-edge"]
current_gem = nil
# uninstall existing gems of the ones we're going to install
uninstall(*names) if options[:force]
message "Installing #{names.length} #{names.length == 1 ? 'gem' : 'gems'}..."
puts "This may take a while..."
names.each do |gem_name|
current_gem = gem_name
if dry_run?
note "Installing #{current_gem}..."
else
message "Installing #{current_gem}..."
self.class.install(gem_name, default_install_options.merge(opts))
end
end
rescue => e
error "Failed to install #{current_gem ? current_gem : 'gem'} (#{e.message})"
end
# Uninstall the specified gems.
#
# By default all specified gems are uninstalled. It's important to note that
# so-called meta-gems or gems that match a set of Merb::Stack.components will
# have their sub-gems uninstalled too. For example, uninstalling merb-more
# will install all contained gems: merb-action-args, merb-assets, ...
#
# Existing dependencies will be clobbered; when :force => true then all gems
# will be cleared, otherwise only existing local dependencies of the
# matching component set will be removed.
#
# Examples:
#
# merb:gem:uninstall merb-core merb-slices # uninstall all specified gems
# merb:gem:uninstall merb-core --version 0.9.8 # uninstall a specific version of a gem
desc 'uninstall GEM_NAME [GEM_NAME, ...]', 'Unstall a gem'
method_options "--dry-run" => :boolean
def uninstall(*names)
opts = { :version => options[:version] }
current_gem = nil
if dry_run?
note "Uninstalling any existing gems of: #{names.join(', ')}"
else
message "Uninstalling any existing gems of: #{names.join(', ')}"
names.each do |gem_name|
current_gem = gem_name
Merb::Gem.uninstall(gem_name, default_uninstall_options) rescue nil
# if this gem is a meta-gem or a component set name, remove sub-gems
(Merb::Stack.components(gem_name) || []).each do |comp|
Merb::Gem.uninstall(comp, default_uninstall_options) rescue nil
end
end
end
rescue => e
error "Failed to uninstall #{current_gem ? current_gem : 'gem'} (#{e.message})"
end
# Recreate all gems from gems/cache on the current platform.
#
# This task should be executed as part of a deployment setup, where the
# deployment system runs this after the app has been installed.
# Usually triggered by Capistrano, God...
#
# It will regenerate gems from the bundled gems cache for any gem that has
# C extensions - which need to be recompiled for the target deployment platform.
#
# Note: at least gems/cache and gems/specifications should be in your SCM.
desc 'redeploy', 'Recreate all gems on the current platform'
method_options "--dry-run" => :boolean, "--force" => :boolean
def redeploy
require 'tempfile' # for Dir::tmpdir access
if gem_dir && File.directory?(cache_dir = File.join(gem_dir, 'cache'))
specs = local_gemspecs
message "Recreating #{specs.length} gems from cache..."
puts "This may take a while..."
specs.each do |gemspec|
if File.exists?(gem_file = File.join(cache_dir, "#{gemspec.full_name}.gem"))
gem_file_copy = File.join(Dir::tmpdir, File.basename(gem_file))
if dry_run?
note "Recreating #{gemspec.full_name}"
else
message "Recreating #{gemspec.full_name}"
if options[:force] && File.directory?(gem = File.join(gem_dir, 'gems', gemspec.full_name))
puts "Removing existing #{gemspec.full_name}"
FileUtils.rm_rf(gem)
end
# Copy the gem to a temporary file, because otherwise RubyGems/FileUtils
# will complain about copying identical files (same source/destination).
FileUtils.cp(gem_file, gem_file_copy)
Merb::Gem.install(gem_file_copy, :install_dir => gem_dir, :ignore_dependencies => true)
File.delete(gem_file_copy)
end
end
end
else
error "No application local gems directory found"
end
end
private
# Return dependencies for all installed gems; both system-wide and locally;
# optionally filters on :version requirement.
def dependencies
version_req = if options[:version]
::Gem::Requirement.create(options[:version])
else
::Gem::Requirement.default
end
if gem_dir
::Gem.clear_paths; ::Gem.path.unshift(gem_dir)
::Gem.source_index.refresh!
end
deps = []
::Gem.source_index.each do |fullname, gemspec|
if version_req.satisfied_by?(gemspec.version)
deps << ::Gem::Dependency.new(gemspec.name, "= #{gemspec.version}")
end
end
::Gem.clear_paths if gem_dir
deps.sort
end
public
# Install gem with some default options.
def self.install(name, options = {})
defaults = {}
defaults[:cache] = false unless opts[:install_dir]
install_gem(name, defaults.merge(options))
end
# Uninstall gem with some default options.
def self.uninstall(name, options = {})
defaults = { :ignore => true, :executables => true }
uninstall_gem(name, defaults.merge(options))
end
end
class Tasks < Thor
include MerbThorHelper
# Show merb.thor version information
#
# merb:tasks:version # show the current version info
# merb:tasks:version --info # show extended version info
desc 'version', 'Show verion info'
method_options "--info" => :boolean
def version
message "Currently installed merb.thor version: #{MERB_THOR_VERSION}"
if options[:version]
self.options = { :"dry-run" => true }
self.update # run update task with dry-run enabled
end
end
# Update merb.thor tasks from remotely available version
#
# merb:tasks:update # update merb.thor
# merb:tasks:update --force # force-update merb.thor
# merb:tasks:update --dry-run # show version info only
desc 'update [URL]', 'Fetch the latest merb.thor and install it locally'
method_options "--dry-run" => :boolean, "--force" => :boolean
def update(url = 'http://merbivore.com/merb.thor')
require 'open-uri'
require 'rubygems/version'
remote_file = open(url)
code = remote_file.read
# Extract version information from the source code
if version = code[/^MERB_THOR_VERSION\s?=\s?('|")([\.\d]+)('|")/,2]
# borrow version comparison from rubygems' Version class
current_version = ::Gem::Version.new(MERB_THOR_VERSION)
remote_version = ::Gem::Version.new(version)
if current_version >= remote_version
puts "currently installed: #{current_version}"
if current_version != remote_version
puts "available version: #{remote_version}"
end
info "No update of merb.thor necessary#{options[:force] ? ' (forced)' : ''}"
proceed = options[:force]
elsif current_version < remote_version
puts "currently installed: #{current_version}"
puts "available version: #{remote_version}"
proceed = true
end
if proceed && !dry_run?
File.open(File.join(__FILE__), 'w') do |f|
f.write(code)
end
success "Installed the latest merb.thor (v#{version})"
end
else
raise "invalid source-code data"
end
rescue OpenURI::HTTPError
error "Error opening #{url}"
rescue => e
error "An error occurred (#{e.message})"
end
end
#### MORE LOW-LEVEL TASKS ####
class Source < Thor
group 'core'
include MerbThorHelper
extend GemManagement
attr_accessor :system, :local, :missing
global_method_options = {
"--merb-root" => :optional, # the directory to operate on
"--ignore-dependencies" => :boolean, # don't install sub-dependencies
"--sources" => :optional # a yml config to grab sources from
}
method_options global_method_options
def initialize(*args); super; end
# List source repositories, of either local or known sources.
#
# Examples:
#
# merb:source:list # list all local sources
# merb:source:list available # list all known sources
desc 'list [local|available]', 'Show git source repositories'
def list(mode = 'local')
if mode == 'available'
message 'Available source repositories:'
repos = self.class.repos(options[:sources])
repos.keys.sort.each { |name| puts "- #{name}: #{repos[name]}" }
elsif mode == 'local'
message 'Current source repositories:'
Dir[File.join(source_dir, '*')].each do |src|
next unless File.directory?(src)
src_name = File.basename(src)
unless (repos = source_manager.existing_repos(src_name)).empty?
puts "#{src_name}"
repos.keys.sort.each { |b| puts "- #{b}: #{repos[b]}" }
end
end
else
error "Unknown listing: #{mode}"
end
end
# Install the specified gems.
#
# All arguments should be names of gems to install.
#
# When :force => true then any existing versions of the gems to be installed
# will be uninstalled first. It's important to note that so-called meta-gems
# or gems that exactly match a set of Merb::Stack.components will have their
# sub-gems uninstalled too. For example, uninstalling merb-more will install
# all contained gems: merb-action-args, merb-assets, merb-gen, ...
#
# Examples:
#