This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
tasks.rb
1454 lines (1108 loc) · 32.5 KB
/
tasks.rb
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 -Ku
# encoding: utf-8
require 'set'
require 'yaml'
require 'fileutils'
require 'pathname'
require 'thor'
require 'addressable/uri'
require 'ruby-github'
require 'json'
require 'rest_client'
class ::Project
def self.command_names
%w[ sync bundle:install bundle:update bundle:show bundle:force gem:install gem:uninstall spec release implode status list ci ]
end
def self.command_name(name)
command_fragments(name).join('_')
end
def self.command_class_name(name)
command_fragments(name).map { |fragment| fragment.capitalize }.join('::')
end
def self.command_fragments(name)
name.split(':').map { |fragment| fragment }
end
command_names.each do |name|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{command_name(name)}(options = {})
new(options).send(:#{command_name(name)})
end
def #{command_name(name)}
start = Time.now if env.benchmark?
self.class.invoke :before, '#{command_name(name)}', env, repos
@repos.each do |repo|
@logger.progress!
results[repo.name] = command_class('#{name}').new(repo, env, @logger).run
end
self.class.invoke :after, '#{command_name(name)}', env, repos
if env.benchmark?
elapsed = (Time.now - start).to_i
message = "Finished 'dm:#{name}' in \#{formatted_time(elapsed)}"
puts
puts '-' * message.length
puts message
puts '-' * message.length
end
results
end
RUBY
end
attr_reader :env
attr_reader :root
attr_reader :repos
attr_reader :options
attr_reader :results
attr_accessor :commands
def initialize(options = {})
@options = options
@env = environment_class.new(name, @options)
@root = @env.root
@repos = Repositories.new(@root, name, @env.included, @env.excluded + excluded_repos)
@logger = Logger.new(@env, @repos.count)
@commands = {}
@results = {}
end
def environment_class
Environment
end
def command_class(name)
return commands[name] if commands[name]
Utils.full_const_get(self.class.command_class_name(name), Command)
end
def self.before(command_name, &block)
((@before ||= {})[command_name] ||= []) << block
end
def self.after(command_name, &block)
((@after ||= {})[command_name] ||= []) << block
end
def self.invoke(kind, name, *args)
hooks = instance_variable_get("@#{kind}")
return unless hooks && hooks[name]
hooks[name].each { |hook| hook.call(*args) }
end
def formatted_time(time)
hours = (time / 3600).to_i
minutes = (time / 60 - hours * 60).to_i
seconds = (time - (minutes * 60 + hours * 3600))
"%02d:%02d:%02d" % [hours, minutes, seconds]
end
class Metadata
class Source
def self.new(filename, *args)
return super if self < Source
if filename.file?
Yaml.new(filename)
else
Github.new(filename, *args)
end
end
attr_reader :filename
def initialize(filename)
@filename = filename
end
def load
raise NotImplementedError
end
def save(repositories)
File.open(filename, 'w') do |f|
f.write(YAML.dump({
'repositories' => repositories.map { |repo| { 'name' => repo['name'], 'url' => repo['url'] } }
}))
end
repositories
end
class Github < Source
attr_reader :username
def initialize(filename, username)
super(filename)
@username = username
end
def load
save(GitHub::API.user(username).repositories)
end
end
class Yaml< Source
def load
YAML.load(File.open(filename))['repositories'].map do |repo|
Struct.new(:name, :url).new(repo['name'], repo['url'])
end
end
end
end
attr_reader :root
attr_reader :name
attr_reader :repositories
attr_reader :filename
def self.load(root, name)
new(root, name).repositories
end
def initialize(root, name)
@root, @name = root, name
@filename = @root.join(config_file_name)
@source = Source.new(@filename, name)
@repositories = @source.load
end
def save
@source.save(repositories)
self
end
def config_file_name
'dm-dev.yml'
end
def include?(url)
repositories.map { |repo| repo.url}.include?(url)
end
end
module Utils
def self.full_const_get(name, root = Object)
obj = root
namespaces(name).each do |x|
# This is required because const_get tries to look for constants in the
# ancestor chain, but we only want constants that are HERE
obj = obj.const_defined?(x) ? obj.const_get(x) : obj.const_missing(x)
end
obj
end
def self.namespaced?(const_name)
namespaces(const_name).size > 1
end
def self.namespaces(const_name)
path = const_name.to_s.split('::')
path.shift if path.first.empty?
path
end
end
class Repositories
include Enumerable
def initialize(root, user, repos, excluded_repos)
@root, @user = root, user
@repos = repos
@excluded_repos = excluded_repos
@metadata = Metadata.new(@root, @user)
@repositories = selected_repositories.map do |repo|
Repository.new(@root, repo)
end
end
def each
@repositories.each { |repo| yield(repo) }
end
def add(name, url)
if @metadata.include?(url)
puts "#{url} is already managed by dm-dev"
else
@metadata.repositories << Struct.new(:name, :url).new(name, url)
@metadata.save
end
end
private
def selected_repositories
if use_current_directory?
@metadata.repositories.select { |repo| managed_repo?(repo) }
else
@metadata.repositories.select { |repo| include_repo?(repo) }
end
end
def managed_repo?(repo)
repo.name == relative_path_name
end
def include_repo?(repo)
if @repos
!excluded_repo?(repo) && (include_all? || @repos.include?(repo.name))
else
!excluded_repo?(repo)
end
end
def excluded_repo?(repo)
@excluded_repos.include?(repo.name)
end
def use_current_directory?
@repos.nil? && inside_available_repo? && !include_all?
end
def inside_available_repo?
@metadata.repositories.map(&:name).include?(relative_path_name)
end
def include_all?
explicitly_specified = @repos.respond_to?(:each) && @repos.count == 1 && @repos.first == 'all'
if inside_available_repo?
explicitly_specified
else
@repos.nil? || explicitly_specified
end
end
def relative_path_name
Pathname(Dir.pwd).relative_path_from(@root).to_s
end
end
class Repository
attr_reader :path
attr_reader :name
attr_reader :uri
def initialize(root, repo)
@name = repo.name
@path = root.join(@name)
@uri = Addressable::URI.parse(repo.url)
end
def installable?
path.join('Gemfile').file?
end
end
class Environment
attr_reader :name
attr_reader :options
attr_reader :root
attr_reader :included
attr_reader :excluded
attr_reader :rubies
attr_reader :bundle_root
attr_reader :gemset
attr_reader :command_options
def initialize(name, options)
@name = name
@options = options
@root = Pathname(@options[:root ] || ENV['DM_DEV_ROOT' ] || Dir.pwd)
@bundle_root = Pathname(@options[:bundle_root] || ENV['DM_DEV_BUNDLE_ROOT'] || @root.join(default_bundle_root))
@rubies = @options[:rubies ] || (ENV['DM_DEV_RUBIES' ] ? normalize(ENV['DM_DEV_RUBIES' ]) : default_rubies)
@included = @options[:include ] || (ENV['DM_DEV_INCLUDE' ] ? normalize(ENV['DM_DEV_INCLUDE']) : default_included)
@excluded = @options[:exclude ] || (ENV['DM_DEV_EXCLUDE' ] ? normalize(ENV['DM_DEV_EXCLUDE']) : default_excluded)
@gemset = @options[:gemset ] || ENV['DM_DEV_GEMSET' ]
@verbose = @options[:verbose ] || (ENV['VERBOSE' ] == 'true')
@silent = @options[:silent ] || (ENV['SILENT' ] == 'true')
@pretend = @options[:pretend ] || (ENV['PRETEND' ] == 'true')
@benchmark = @options[:benchmark ] || (ENV['BENCHMARK' ] == 'true')
@command_options = @options[:command_options ] || nil
@collect_output = @options[:collect_output ] || false
end
def default_bundle_root
'DM_DEV_BUNDLE_ROOT'
end
def default_included
nil # means all
end
def default_excluded
[] # overwrite in subclasses
end
def default_rubies
%w[ 1.8.7 1.9.2 jruby rbx ]
end
def verbose?
@verbose
end
def silent?
@silent
end
def pretend?
@pretend
end
def benchmark?
@benchmark
end
def collect_output?
@collect_output
end
private
def normalize(string)
string.gsub(',', ' ').split(' ')
end
end
class Logger
attr_reader :progress
def initialize(env, repo_count)
@env = env
@progress = 0
@total = repo_count
@padding = @total.to_s.length
@verbose = @env.verbose?
@pretend = @env.pretend?
end
def log(repo, action, command = nil, msg = nil)
return if @env.silent?
command = command.to_s.squeeze(' ').strip # TODO also do for actually executed commands
if @pretend || @verbose
puts command
else
puts '[%0*d/%d] %s %s %s%s' % format(repo, action, command, msg)
end
end
def progress!
@progress += 1
end
def format(repo, action, command, msg)
[ @padding, @progress, @total, action, repo.name, msg, @verbose ? ": #{command}" : '' ]
end
end
class Command
attr_reader :repo
attr_reader :env
attr_reader :root
attr_reader :path
attr_reader :uri
attr_reader :logger
attr_reader :results
attr_reader :output
def initialize(repo, env, logger)
@repo = repo
@env = env
@root = @env.root
@path = @root.join(@repo.name)
@uri = @repo.uri
@logger = logger
@verbose = @env.verbose?
@results = []
end
def before
# overwrite in subclasses
end
def run
log_directory_change
FileUtils.cd(working_dir) do
if block_given?
yield
else
execute
end
end
results
end
def after
# overwrite in subclasses
end
def execute
if executable?
before
unless suppress_log? || skip?
log(command)
end
unless pretend?
sleep(timeout)
start_time = Time.now
shell(command) unless skip?
duration = (Time.now - start_time).to_i
@results << { :status => status, :output => output, :duration => duration }
end
after
else
if verbose? && !pretend?
log(command, "SKIPPED! - #{explanation}")
end
end
end
def skip?
false
end
def status
if skip?
:skipped
else
$? && $?.success? ? :pass : :fail
end
end
# overwrite in subclasses
def command
raise NotImplementedError
end
# overwrite in subclasses
def executable?
true
end
# overwrite in subclasses
def suppress_log?
false
end
# overwrite in subclasses
def explanation
'reason unknown'
end
def log_directory_change
if needs_directory_change? && (verbose? || pretend?)
log "cd #{working_dir}"
end
end
def needs_directory_change?
Dir.pwd != working_dir.to_s
end
def ignored?
ignored_repos.include?(repo.name)
end
# overwrite in subclasses
def ignored_repos
[]
end
# overwrite in subclasses
def working_dir
path
end
def verbose?
@verbose
end
def pretend?
@env.pretend?
end
def collect_output?
env.collect_output?
end
def verbosity
verbose? ? verbose : silent
end
# overwrite in subclasses
def verbose
end
def silent
' > /dev/null 2>&1'
end
# overwrite in subclasses
def timeout
0
end
# overwrite in subclasses
def action
end
def log(command = nil, msg = nil)
logger.log(repo, action, command, msg)
end
def shell(command)
if collect_output?
@output = %x[#{command}]
else
system(command)
end
end
class List < ::Project::Command
def run
log
end
end
class Sync < Command
def self.new(repo, env, logger)
return super unless self == Sync
if env.root.join(repo.name).directory?
Pull.new(repo, env, logger)
else
Clone.new(repo, env, logger)
end
end
class Clone < Sync
def initialize(repo, env, logger)
super
@git_uri = uri.dup
@git_uri.scheme = 'git'
if env.options[:development]
@git_uri.to_s.sub!('://', '@').sub!('/', ':')
end
end
def command
"git clone #{@git_uri}.git #{verbosity}"
end
def working_dir
root
end
def action
'Cloning'
end
end
class Pull < Sync
def command
"git checkout master #{verbosity}; git pull --rebase #{verbosity}"
end
def action
'Pulling'
end
def target_revision
env.options[:revision]
end
def revision
%x[git rev-parse HEAD].chomp!
end
def skip?
target_revision == revision
end
end
end
class Rvm < Command
attr_reader :rubies
def initialize(repo, env, logger)
super
@rubies = env.rubies
end
def command
"rvm #{rubies.join(',')}"
end
class Exec < Rvm
attr_reader :ruby
def run
super do
rubies.each do |ruby|
@ruby = ruby
if block_given?
yield(ruby)
else
execute
end
end
end
end
private
def command
"rvm #{@ruby} exec bash -c"
end
def action
"[#{@ruby}]"
end
end
end
class Bundle < Rvm::Exec
class Install < Bundle
def bundle_command
'install'
end
end
class Update < Bundle
def bundle_command
'update'
end
end
class Show < Bundle
def bundle_command
'show'
end
end
class Force < ::Project::Command
def command
'rm Gemfile.*'
end
end
def initialize(repo, env, logger)
super
@bundle_root = env.bundle_root
rubies.each { |ruby| bundle_path(ruby).mkpath }
end
def before
super
make_gemfile
end
def executable?
!ignored? && repo.installable?
end
def command
"#{super} \"#{environment} bundle #{bundle_command} #{options} #{verbosity}\""
end
def action
"#{super} bundle #{bundle_command}"
end
def environment
"BUNDLE_PATH='#{bundle_path(ruby)}' BUNDLE_GEMFILE='#{gemfile}'"
end
def bundle_path(ruby)
@bundle_root.join(ruby)
end
def gemfile
"Gemfile.#{ruby}"
end
def bundled?
working_dir.join("Gemfile.#{ruby}.lock").file?
end
def make_gemfile
unless working_dir.join(gemfile).file?
master = working_dir.join(master_gemfile)
log "cp #{master} #{gemfile}"
unless pretend?
FileUtils.cp(master, gemfile)
end
end
end
def master_gemfile
'Gemfile'
end
def options
nil
end
def explanation
if ignored?
"because it's ignored"
elsif !repo.installable?
"because it's missing a Gemfile"
else
"reason unknown"
end
end
end
class Spec < Bundle
def run
if print_matrix?
puts "\nh2. %s\n\n" % repo.name
puts '| RUBY | %s |' % env.adapters(repo).join(' | ')
end
super do |ruby|
print '| %s |' % ruby if print_matrix?
if block_given?
yield ruby
else
execute
if print_matrix?
print ' %s |' % [ status ]
end
end
end
end
def bundle_command
if env.command_options
"exec spec #{env.command_options.join(' ')}"
else
'exec rake spec'
end
end
def action
"#{super} Testing"
end
def print_matrix?
executable? && !verbose? && !pretend?
end
def suppress_log?
!executable? || print_matrix?
end
def skip?
target_revision && !clean?
end
def target_revision
env.options[:revision]
end
def clean?
%x[git status] =~ /working directory clean/
end
end
class Gem < Rvm
class Install < Gem
def command
"#{super} gem build #{gemspec_file}; #{super} gem install #{gem} --no-ri --no-rdoc"
end
def action
'Installing'
end
end
class Uninstall < Gem
def command
"#{super} gem uninstall #{repo.name} --version #{version}"
end
def action
'Uninstalling'
end
end
def before
create_gemset = "rvm gemset create #{env.gemset}"
log create_gemset if env.gemset && verbose?
system create_gemset if env.gemset && !pretend?
end
def rubies
env.gemset ? super.map { |ruby| "#{ruby}@#{env.gemset}" } : super
end
def gem
"#{working_dir.join(repo.name)}-#{version}.gem"
end
def gemspec_file
"#{working_dir.join(repo.name)}.gemspec"
end
def version
::Gem::Specification.load(working_dir.join(gemspec_file)).version.to_s
end
end
class Release < Command
def run
# TODO move to its own command
clean_repository(project_name)
FileUtils.cd(working_dir) do
log(command)
system(command) unless pretend?
end
end
def command
'rake release'
end
def action
'Releasing'
end
end
class Implode < Command
def run
log command
system command unless pretend?
end
def command
"rm -rf #{working_dir} #{verbosity}"
end
def action
'Deleting'
end
end
class Status < Command
def run
log "cd #{working_dir}" if verbose? || pretend?
FileUtils.cd(working_dir) do
log command
system command unless pretend?
end
end
def command
"git status"
end
def action
'git status'
end
end
end
end
module DataMapper
module CI
SERVICE_URL = ENV['TESTOR_SERVER'] || 'http://localhost:3000'
class Client
class Job
attr_reader :id
attr_reader :platform