-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathopenstudio_cli.rb
More file actions
1980 lines (1611 loc) · 58.8 KB
/
openstudio_cli.rb
File metadata and controls
1980 lines (1611 loc) · 58.8 KB
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
########################################################################################################################
# OpenStudio(R), Copyright (c) Alliance for Sustainable Energy, LLC.
# See also https://openstudio.net/license
########################################################################################################################
require 'openstudio'
#File.open('E:\test\test.log', 'w') do |f|
# ENV.each_key {|k| f.puts "#{k} = #{ENV[k]}" }
#end
#Signal.trap('INT') { abort }
require 'logger'
require 'optparse'
require 'stringio'
require 'rbconfig'
#include OpenStudio::Workflow::Util::IO
$argv = ARGV.dup
$logger = Logger.new(STDOUT)
#$logger.level = Logger::ERROR
$logger.level = Logger::WARN
#$logger.level = Logger::DEBUG
#OpenStudio::Logger.instance.standardOutLogger.disable
#OpenStudio::Logger.instance.standardOutLogger.setLogLevel(OpenStudio::Warn)
OpenStudio::Logger.instance.standardOutLogger.setLogLevel(OpenStudio::Error)
OpenStudio.autoload(:Airflow, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:EnergyPlus, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:EPJSON, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:GbXML, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:Gltf, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:ISOModel, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:Measure, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:Ruleset, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:Model, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:OSVersion, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:Radiance, ":/openstudio_init_extended.rb")
OpenStudio.autoload(:SDD, ":/openstudio_init_extended.rb")
# debug Gem::Resolver, must go before resolver is required
#ENV['DEBUG_RESOLVER'] = "1"
original_arch = nil
if RbConfig::CONFIG['arch'] =~ /x64-mswin64/
# assume that system ruby of 'x64-mingw32' architecture was used to create bundle
original_arch = RbConfig::CONFIG['arch']
RbConfig::CONFIG['arch'] = 'x64-mingw32'
end
# load embedded ruby gems
require 'rubygems'
require 'rubygems/version'
Gem::Platform.local
if original_arch
RbConfig::CONFIG['arch'] = original_arch
end
module Gem
class Specification < BasicSpecification
# This isn't ideal but there really is no available method to add specs for our use case.
# Using self.dirs=() works for ruby official gems but since it appends the dir paths with 'specifications' it breaks for bundled gem specs
def self.add_spec spec
warn "Gem::Specification.add_spec is deprecated and will be removed in RubyGems 3.0" unless Gem::Deprecate.skip
# TODO: find all extraneous adds
# puts
# p :add_spec => [spec.full_name, caller.reject { |s| s =~ /minitest/ }]
# TODO: flush the rest of the crap from the tests
# raise "no dupes #{spec.full_name} in #{all_names.inspect}" if
# _all.include? spec
raise "nil spec!" unless spec # TODO: remove once we're happy with tests
return if _all.include? spec
_all << spec
stubs << spec
(@@stubs_by_name[spec.name] ||= []) << spec
@@stubs_by_name[spec.name].sort_by! { |s| s.version }
_resort!(_all)
_resort!(stubs)
end
def gem_dir
embedded = false
tmp_loaded_from = loaded_from.clone
if tmp_loaded_from.chars.first == ':'
tmp_loaded_from[0] = ''
embedded = true
end
joined = File.join(gems_dir, full_name)
if embedded
test = /bundler\/gems/.match(tmp_loaded_from)
if test
@gem_dir = ':' + (File.dirname tmp_loaded_from)
else
@gem_dir = joined
end
else
@gem_dir = File.expand_path joined
end
end
def full_gem_path
# TODO: This is a heavily used method by gems, so we'll need
# to aleast just alias it to #gem_dir rather than remove it.
embedded = false
tmp_loaded_from = loaded_from.clone
if tmp_loaded_from.chars.first == ':'
tmp_loaded_from[0] = ''
embedded = true
end
joined = File.join(gems_dir, full_name)
if embedded
test = /bundler\/gems/.match(tmp_loaded_from)
if test
@full_gem_path = ':' + (File.dirname tmp_loaded_from)
# @full_gem_path.untaint
return @full_gem_path
else
@full_gem_path = joined
# @full_gem_path.untaint
return @full_gem_path
end
else
@full_gem_path = File.expand_path joined
# @full_gem_path.untaint
end
return @full_gem_path if File.directory? @full_gem_path
@full_gem_path = File.expand_path File.join(gems_dir, original_name)
end
def gems_dir
# TODO: this logic seems terribly broken, but tests fail if just base_dir
@gems_dir = File.join(loaded_from && base_dir || Gem.dir, "gems")
end
def base_dir
return Gem.dir unless loaded_from
embedded = false
tmp_loaded_from = loaded_from.clone
if tmp_loaded_from.chars.first == ':'
tmp_loaded_from[0] = ''
embedded = true
end
test = /bundler\/gems/.match(tmp_loaded_from)
result = if (default_gem? || test) then
File.dirname File.dirname File.dirname tmp_loaded_from
else
File.dirname File.dirname tmp_loaded_from
end
if embedded
result = ':' + result
end
@base_dir = result
end
end
end
# have to do some forward declaration and pre-require to get around autoload cycles
#module Bundler
#end
# This is the code chunk to allow for an embedded IRB shell. From Jason Roelofs, found on StackOverflow
module IRB # :nodoc:
def self.start_session(binding)
unless @__initialized
args = ARGV
ARGV.replace(ARGV.dup)
IRB.setup(nil)
ARGV.replace(args)
@__initialized = true
end
workspace = WorkSpace.new(binding)
irb = Irb.new(workspace)
@CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
@CONF[:MAIN_CONTEXT] = irb.context
catch(:IRB_EXIT) do
irb.eval_input
end
end
end
# This is the save puts to use to catch EPIPE. Uses `puts` on the given IO object and safely ignores any Errno::EPIPE
#
# @param [String] message Message to output
# @param [Hash] opts Options hash
#
def safe_puts(message=nil, opts=nil)
message ||= ''
opts = {
io: $stdout,
printer: :puts
}.merge(opts || {})
begin
opts[:io].send(opts[:printer], message)
rescue Errno::EPIPE
# This is what makes this a `safe` puts
return
end
end
# This is a convenience method that properly handles duping the originally argv array so that it is not destroyed. This
# method will also automatically detect "-h" and "--help" and print help. And if any invalid options are detected, the
# help will be printed, as well
#
# @param [Object, nil] opts An instance of OptionParse to parse against, defaults to a new OptionParse instance
# @param [Array, nil] argv The argv input to be parsed, defaults to $argv
# @return[Array, nil] If this method returns `nil`, then you should assume that help was printed and parsing failed
#
def parse_options(opts=nil, argv=nil)
# Creating a shallow copy of the arguments so the OptionParser
# doesn't destroy the originals.
argv ||= $argv.dup
# Default opts to a blank optionparser if none is given
opts ||= OptionParser.new
# Add the help option, which must be on every command.
opts.on_tail('-h', '--help', 'Print this help') do
safe_puts(opts.help)
return nil
end
opts.parse!(argv)
return argv
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
raise "Error: Invalid CLI option, #{opts.help.chomp}"
end
# Method to clean the args. Windows cmd.exe treats single quotes as regular chars so we strip them if found.
def clean_argv(argv)
argv.each_index do |i|
# puts "Argument #{i}=<#{argv[i]}>"
if argv[i].start_with?("'") and argv[i].end_with?("'")
argv[i] = argv[i][1..-2]
# puts " Cleaned #{i}=<#{argv[i]}>"
end
end
return argv
end
# This method will split the argv given into three parts: the flags to this command, the command, and the flags to
# the command. For example:
# -v status -h -v
# The above would yield 3 parts:
# ["-v"]
# "status"
# ["-h", "-v"]
# These parts are useful because the first is a list of arguments given to the current command, the second is a
# command, and the third are the commands given to the command
#
# @param [Array] argv The input to be split
# @param [Array] command_list Hash of commands to look for
# @return [Array] The split command as [main arguments, sub command, sub command arguments]
#
def split_main_and_subcommand(argv, command_list)
# Initialize return variables
main_args = nil
sub_command = nil
sub_args = []
commands = []
command_list.keys.each {|k| commands << k.to_s}
# We split the arguments into two: One set containing any flags before a word, and then the rest. The rest are what
# get actually sent on to the command
argv.each_index do |i|
if commands.index(argv[i])
main_args = argv[0, i]
sub_command = argv[i]
sub_args = argv[i+1..-1]
break
elsif argv[i].end_with?('.rb')
main_args = argv[0, i]
sub_command = 'execute_ruby_script'
sub_args = argv[i..-1]
break
end
end
# Handle the case that argv was empty or didn't contain any command
main_args = argv.dup if main_args.nil?
[main_args, sub_command, sub_args]
end
# parse the main args, those that come before the sub command
def parse_main_args(main_args)
# Unset RUBY ENVs if previously set (e.g. rvm sets these in shell)
ENV.delete('GEM_HOME') if ENV['GEM_HOME']
ENV.delete('GEM_PATH') if ENV['GEM_PATH']
ENV.delete('BUNDLE_GEMFILE') if ENV['BUNDLE_GEMFILE']
ENV.delete('BUNDLE_PATH') if ENV['BUNDLE_PATH']
ENV.delete('BUNDLE_WITHOUT') if ENV['BUNDLE_WITHOUT']
$logger.debug "Parsing main_args #{main_args}"
# verbose already handled
main_args.delete('--verbose')
# Operate on the include option to add to $LOAD_PATH
remove_indices = []
new_path = []
main_args.each_index do |i|
if main_args[i] == '-I' || main_args[i] == '--include'
# remove from further processing
remove_indices << i
remove_indices << i+1
dir = main_args[i + 1]
if dir.nil?
$logger.error "#{main_args[i]} requires second argument DIR"
return false
elsif !File.exist?(dir) || !File.directory?(dir)
# DLM: Ruby doesn't warn for this
#$logger.warn "'#{dir}' passed to #{main_args[i]} is not a directory"
end
new_path << dir
elsif main_args[i] == '--no-ssl'
$logger.warn "'--no-ssl' flag is deprecated"
end
end
remove_indices.reverse_each {|i| main_args.delete_at(i)}
if !new_path.empty?
new_path = new_path.concat($LOAD_PATH)
$logger.info "Setting $LOAD_PATH to #{new_path}"
$LOAD_PATH.clear
new_path.each {|p| $LOAD_PATH << p}
end
# Operate on the gem_path option to set GEM_PATH
remove_indices = []
new_path = []
main_args.each_index do |i|
if main_args[i] == '--gem_path'
# remove from further processing
remove_indices << i
remove_indices << i+1
dir = main_args[i + 1]
if dir.nil?
$logger.error "#{main_args[i]} requires second argument DIR"
return false
elsif !File.exist?(dir) || !File.directory?(dir)
# DLM: Ruby doesn't warn for this
#$logger.warn "'#{dir}' passed to #{main_args[i]} is not a directory"
end
new_path << dir
end
end
remove_indices.reverse_each {|i| main_args.delete_at(i)}
if !new_path.empty?
new_path = new_path.join(File::PATH_SEPARATOR)
$logger.info "Setting GEM_PATH to #{new_path}"
ENV['GEM_PATH'] = new_path
end
# Operate on the gem_home option to set GEM_HOME
if main_args.include? '--gem_home'
option_index = main_args.index '--gem_home'
path_index = option_index + 1
new_home = main_args[path_index]
main_args.slice! path_index
main_args.slice! main_args.index '--gem_home'
$logger.info "Setting GEM_HOME to #{new_home}"
ENV['GEM_HOME'] = new_home
end
# Operate on the bundle option to set BUNDLE_GEMFILE
use_bundler = false
if main_args.include? '--bundle'
option_index = main_args.index '--bundle'
path_index = option_index + 1
gemfile = main_args[path_index]
main_args.slice! path_index
main_args.slice! main_args.index '--bundle'
$logger.info "Setting BUNDLE_GEMFILE to #{gemfile}"
ENV['BUNDLE_GEMFILE'] = gemfile
use_bundler = true
end
if main_args.include? '--bundle_path'
option_index = main_args.index '--bundle_path'
path_index = option_index + 1
bundle_path = main_args[path_index]
main_args.slice! path_index
main_args.slice! main_args.index '--bundle_path'
$logger.info "Setting BUNDLE_PATH to #{bundle_path}"
ENV['BUNDLE_PATH'] = bundle_path
elsif use_bundler
# bundle was requested but bundle_path was not provided
$logger.warn "Bundle activated but ENV['BUNDLE_PATH'] is not set"
$logger.info "Setting BUNDLE_PATH to ':/ruby/3.2.0/'"
ENV['BUNDLE_PATH'] = ':/ruby/3.2.0/'
end
if main_args.include? '--bundle_without'
option_index = main_args.index '--bundle_without'
path_index = option_index + 1
bundle_without = main_args[path_index]
main_args.slice! path_index
main_args.slice! main_args.index '--bundle_without'
$logger.info "Setting BUNDLE_WITHOUT to #{bundle_without}"
ENV['BUNDLE_WITHOUT'] = bundle_without
elsif use_bundler
# bundle was requested but bundle_path was not provided
$logger.info "Bundle activated but ENV['BUNDLE_WITHOUT'] is not set"
# match configuration in build_openstudio_gems
$logger.info "Setting BUNDLE_WITHOUT to 'test'"
ENV['BUNDLE_WITHOUT'] = 'test'
# ignore any local config on disk
#DLM: this would be correct if the bundle was created here
#it would not be correct if the bundle was transfered from another computer
#ENV['BUNDLE_IGNORE_CONFIG'] = 'true'
end
Gem::Deprecate.skip = true
# find all the embedded gems
original_embedded_gems = {}
begin
EmbeddedScripting::fileNames.each do |f|
if md = /specifications\/.*\.gemspec$/.match(f) ||
md = /bundler\/.*\.gemspec$/.match(f)
begin
spec = EmbeddedScripting::getFileAsString(f)
s = eval(spec)
# These require io-console, which we don't have on Windows
if Gem.win_platform?
next if s.name == 'reline'
next if s.name == 'debug'
next if s.name == 'irb'
next if s.name == 'readline'
end
s.loaded_from = f
# This is shenanigans because otherwise rubygems will think extensions are missing
# But we are initing them manually so they are not missing
# Here the missing_extensions? method is redefined for only this instance "s"
class << s
define_method(:missing_extensions?) { false }
end
original_embedded_gems[s.name] = s
init_count = 0
Gem::Specification.each {|x| init_count += 1}
# if already have an equivalent spec this will be a no-op
Gem::Specification.add_spec(s)
post_count = 0
Gem::Specification.each {|x| post_count += 1}
if post_count == init_count
$logger.debug "Found system gem #{s.name} #{s.version}, overrides embedded gem"
end
rescue LoadError => e
safe_puts e.message
rescue => e
safe_puts e.message
end
end
end
rescue NameError => e
# EmbeddedScripting not available
end
original_load_path = $LOAD_PATH.clone
embedded_gems_to_activate = []
# Identify the embedded gems (don't activate them yet)
current_dir = Dir.pwd
begin
# get a list of all the embedded gems
dependencies = []
original_embedded_gems.each_value do |spec|
$logger.debug "Adding dependency on #{spec.name} '~> #{spec.version}'"
dependencies << Gem::Dependency.new(spec.name, "~> #{spec.version}")
end
# resolve dependencies
activation_errors = false
resolver = Gem::Resolver.for_current_gems(dependencies)
activation_requests = resolver.resolve
$logger.debug "Processing #{activation_requests.size} activation requests"
activation_requests.each do |request|
do_activate = true
spec = request.spec
# check if this is one of our embedded gems
if original_embedded_gems[spec.name]
# check if gem can be loaded from RUBYLIB, this supports developer use case
original_load_path.each do |lp|
if File.exist?(File.join(lp, spec.name)) || File.exist?(File.join(lp, spec.name + '.rb')) || File.exist?(File.join(lp, spec.name + '.so'))
$logger.debug "Found #{spec.name} in '#{lp}', overrides gem #{spec.spec_file}"
do_activate = false
break
end
end
end
if do_activate
embedded_gems_to_activate << spec
end
end
if activation_errors
return false
end
ensure
Dir.chdir(current_dir)
end
# Load the bundle before activating any embedded gems
if use_bundler
embedded_gems_to_activate.each do |spec|
if spec.name == "bundler"
$logger.debug "Activating gem #{spec.spec_file}"
begin
# Activate will manipulate the $LOAD_PATH to include the gem
spec.activate
rescue Gem::LoadError
# There may be conflicts between the bundle and the embedded gems,
# those will be logged here
$logger.error "Error activating gem #{spec.spec_file}"
activation_errors = true
end
end
end
current_dir = Dir.pwd
original_arch = nil
if RbConfig::CONFIG['arch'] =~ /x64-mswin64/
# assume that system ruby of 'x64-mingw32' architecture was used to create bundle
original_arch = RbConfig::CONFIG['arch']
$logger.info "Temporarily replacing arch '#{original_arch}' with 'x64-mingw32' for Bundle"
RbConfig::CONFIG['arch'] = 'x64-mingw32'
end
# require bundler
# have to do some forward declaration and pre-require to get around autoload cycles
require 'bundler/errors'
#require 'bundler/environment_preserver'
require 'bundler/plugin'
#require 'bundler/rubygems_ext'
require 'bundler/rubygems_integration'
require 'bundler/version'
require 'bundler/ruby_version'
#require 'bundler/constants'
#require 'bundler/current_ruby'
require 'bundler/gem_helpers'
#require 'bundler/plugin'
require 'bundler/source'
require 'bundler/definition'
require 'bundler/dsl'
require 'bundler/uri_credentials_filter'
require 'bundler'
begin
# activate bundled gems
# bundler will look in:
# 1) ENV["BUNDLE_GEMFILE"]
# 2) find_file("Gemfile", "gems.rb")
#require 'bundler/setup'
groups = Bundler.definition.groups
keep_groups = []
without_groups = ENV['BUNDLE_WITHOUT']
$logger.info "without_groups = #{without_groups}"
groups.each do |g|
$logger.info "g = #{g}"
if without_groups.include?(g.to_s)
$logger.info "Bundling without group '#{g}'"
else
keep_groups << g
end
end
$logger.info "Bundling with groups [#{keep_groups.join(',')}]"
remaining_specs = []
Bundler.definition.specs_for(keep_groups).each {|s| remaining_specs << s.name}
$logger.info "Specs to be included [#{remaining_specs.join(',')}]"
Bundler.setup(*keep_groups)
ensure
if original_arch
$logger.info "Restoring arch '#{original_arch}'"
RbConfig::CONFIG['arch'] = original_arch
end
Dir.chdir(current_dir)
end
end
original_load_path = $LOAD_PATH.clone
embedded_gems_to_activate.each do |spec|
$logger.debug "Activating gem #{spec.spec_file}"
begin
# Activate will manipulate the $LOAD_PATH to include the gem
spec.activate
rescue Gem::LoadError
# There may be conflicts between the bundle and the embedded gems,
# those will be logged here
$logger.error "Error activating gem #{spec.spec_file}"
activation_errors = true
end
end
# Get all of the embedded gem paths which were added by activating the embedded gems
# This is used by embedded_help::require
$EMBEDDED_GEM_PATH = $LOAD_PATH - original_load_path
# Make sure no non embedded paths snuck in
$EMBEDDED_GEM_PATH = $EMBEDDED_GEM_PATH.select {|p| p.to_s.chars.first == ':'}
# Restore LOAD_PATH
$LOAD_PATH.reject! {|p| not original_load_path.any? p}
# Handle -e commands
remove_indices = []
$eval_cmds = []
main_args.each_index do |i|
if main_args[i] == '-e' || main_args[i] == '--execute'
# remove from further processing
remove_indices << i
remove_indices << i+1
cmd = main_args[i + 1]
if cmd.nil?
$logger.error "#{main_args[i]} requires second argument CMD"
return false
end
$eval_cmds << cmd
end
end
remove_indices.reverse_each {|i| main_args.delete_at(i)}
if !main_args.empty?
$logger.error "Unknown arguments #{main_args} found"
return false
end
return true
end
# This CLI class processes the input args and invokes the proper command class
class CLI
# This constant maps commands to classes in this CLI and stores meta-data on them
def command_list
{
run: [ Proc.new { ::Run }, {primary: true, working: true}],
#apply_measure: [ Proc.new { ::ApplyMeasure }, {primary: true, working: false}], # DLM: remove, can do this with run
gem_list: [ Proc.new { ::GemList }, {primary: false, working: true}],
#gem_install: [ Proc.new { ::InstallGem }, {primary: false, working: false}], # DLM: needs Ruby built with FFI
measure: [ Proc.new { ::Measure }, {primary: true, working: false}],
update: [ Proc.new { ::Update }, {primary: true, working: false}],
execute_ruby_script: [ Proc.new { ::ExecuteRubyScript }, {primary: false, working: true}],
#interactive_ruby: [ Proc.new { ::InteractiveRubyShell }, {primary: false, working: false}], # DLM: not working
openstudio_version: [ Proc.new { ::OpenStudioVersion }, {primary: true, working: true}],
energyplus_version: [ Proc.new { ::EnergyPlusVersion }, {primary: true, working: true}],
ruby_version: [ Proc.new { ::RubyVersion }, {primary: false, working: true}],
list_commands: [ Proc.new { ::ListCommands }, {primary: true, working: true}]
}
end
# This method instantiates the global variables $main_args, $sub_command, and $sub_args
#
# @param [Array] argv The arguments passed through the CLI
# @return [Object] An instance of the CLI class with initialized globals
#
def initialize(argv)
argv = clean_argv(argv)
$main_args, $sub_command, $sub_args = split_main_and_subcommand(argv, command_list)
if $main_args.include? '--verbose'
$logger.level = Logger::DEBUG
OpenStudio::Logger.instance.standardOutLogger.setLogLevel(OpenStudio::Debug)
end
$logger.info("CLI Parsed Inputs: #{$main_args.inspect} #{$sub_command.inspect} #{$sub_args.inspect}")
end
# Checks to see if it should print the main help, and if not parses the command into a class and executes it
def execute
$logger.debug "Main arguments are #{$main_args}"
$logger.debug "Sub-command is #{$sub_command}"
$logger.debug "Sub-arguments are #{$sub_args}"
if $main_args.include?('-h') || $main_args.include?('--help')
# Help is next in short-circuiting everything. Print
# the help and exit.
help
return 0
end
if $main_args.include?('--version')
# Version is next in short-circuiting everything. Print it and exit.
# This is to have the same behavior as pretty much every CLI, you expect
# `<cli> --version` to return the version
safe_puts OpenStudio.openStudioLongVersion
return 0
end
if !parse_main_args($main_args)
help
return 1
end
# -e commands detected
if !$eval_cmds.empty?
$eval_cmds.each do |cmd|
$logger.debug "Executing cmd: #{cmd}"
eval(cmd, BINDING)
end
if $sub_command
$logger.warn "Evaluate mode detected, ignoring sub_command #{$sub_command}"
return 0
end
return 0
end
# If we reached this far then we must have a command. If not,
# then we also just print the help and exit.
command_plugin = nil
if $sub_command
command_plugin = command_list[$sub_command.to_sym]
end
if !command_plugin || !$sub_command
help
return 1
end
command_class = command_plugin[0].call
$logger.debug("Invoking command class: #{command_class} #{$sub_args.inspect}")
# Initialize and execute the command class, returning the exit status.
result = 0
begin
result = command_class.new.execute($sub_args)
rescue Interrupt
$logger.error '?'
result = 1
end
result = 0 unless result.is_a?(Integer)
result
end
# Prints out the help text for the CLI
#
# @param [Boolean] list_all If set to true, the help prints all commands, however it otherwise only prints those
# marked as primary in #command_list
# @param [Boolean] quiet If set to true, list only the names of commands without the header
# @return [void]
# @see #command_list #::ListCommands
#
def help(list_all=false, quiet=false)
if quiet
commands = ['-h','--help',
'--verbose',
'-i', '--include',
'-e', '--execute',
'--gem_path', '--gem_home', '--bundle', '--bundle_path', '--bundle_without']
command_list.each do |key, data|
# Skip non-primary commands. These only show up in extended
# help output.
next unless data[1][:primary] unless list_all
commands << key.to_s
end
safe_puts commands #.join(" ")
else
opts = OptionParser.new do |o|
o.banner = 'Usage: openstudio [options] <command> [<args>]'
o.separator ''
o.on('-h', '--help', 'Print this help.')
o.on('--verbose', 'Print the full log to STDOUT')
o.on('-I', '--include DIR', 'Add additional directory to add to front of Ruby $LOAD_PATH (may be used more than once)')
o.on('-e', '--execute CMD', 'Execute one line of script (may be used more than once). Returns after executing commands.')
o.on('--gem_path DIR', 'Add additional directory to add to front of GEM_PATH environment variable (may be used more than once)')
o.on('--gem_home DIR', 'Set GEM_HOME environment variable')
o.on('--bundle GEMFILE', 'Use bundler for GEMFILE')
o.on('--bundle_path BUNDLE_PATH', 'Use bundler installed gems in BUNDLE_PATH')
o.on('--bundle_without WITHOUT_GROUPS', 'Space separated list of groups for bundler to exclude in WITHOUT_GROUPS. Surround multiple groups with quotes like "test development".')
o.separator ''
o.separator 'Common commands:'
# Add the available commands as separators in order to print them
# out as well.
commands = {}
longest = 0
command_list.each do |key, data|
# Skip non-primary commands. These only show up in extended
# help output.
next unless data[1][:primary] unless list_all
key = key.to_s
klass = data[0].call
commands[key] = klass.synopsis
longest = key.length if key.length > longest
end
commands.keys.sort.each do |key|
o.separator " #{key.ljust(longest+2)} #{commands[key]}"
end
o.separator ''
o.separator 'For help on any individual command run `openstudio COMMAND -h`'
unless list_all
o.separator ''
o.separator 'Additional commands are available, but are either more advanced'
o.separator 'or not commonly used. To see all commands, run the command'
o.separator '`openstudio list_commands`.'
end
end
safe_puts opts.help
end
end
end
# Class to execute part or all of an OSW workflow
class Run
# Provides text for the main help functionality
def self.synopsis
'Executes an OpenStudio Workflow file'
end
# Executes the standard, or one of two custom, workflows using the workflow-gem
#
# @param [Array] sub_argv Options passed to the run command from the user input
# @return [Fixnum] Return status
#
def execute(sub_argv)
$logger.info "Run, sub_argv = #{sub_argv}"
# options are local to this method, run_methods are what get passed to workflow gem
run_options = {}
# Hidden option shhhhh
run_options[:fast] = false
if sub_argv.delete '--fast'
run_options[:fast] = true
end
options = {}
options[:debug] = false
options[:no_simulation] = false
options[:osw_path] = './workflow.osw'
options[:post_process] = false
options[:ep_json] = false
options[:ft_options] = {}
options[:show_stdout] = false
options[:add_timings] = false
options[:style_stdout] = false
# TODO: I don't know if there's any value harcoding a default here really
# options[:ft_options] = {
# :runcontrolspecialdays => true,
# :ip_tabular_output => false,
# :no_lifecyclecosts => false,
# :no_sqlite_output => false,
# :no_html_output => false,
# :no_variable_dictionary => false,
# :no_space_translation => false,
# }
opts = OptionParser.new do |o|
o.banner = 'Usage: openstudio run [options]'
o.separator ''
o.separator 'Options:'
o.separator ''
o.on('-w', '--workflow [FILE]', 'Specify the FILE path to the workflow to run') do |osw_path|
options[:osw_path] = osw_path
end
o.on('-m', '--measures_only', 'Only run the OpenStudio and EnergyPlus measures') do
options[:no_simulation] = true
end
o.on('-p', '--postprocess_only', 'Only run the reporting measures') do
options[:post_process] = true
end
o.on('--export-epJSON', 'export epJSON file format. The default is IDF') do
options[:ep_json] = true
end
o.on('-s', '--socket PORT', 'Pipe status messages to a socket on localhost PORT') do |port|
options[:socket] = port
end
o.on('--show-stdout', 'Prints the output of the workflow run in real time to the console, including E+ output') do
options[:show_stdout] = true
end
o.on('--debug', 'Includes additional outputs for debugging failing workflows and does not clean up the run directory') do |f|
options[:debug] = f
end
o.separator ""
o.separator "Forward Translator Options:"
o.on('--[no-]runcontrolspecialdays', "Include RunControlSpecialDays (Holidays) [Default: True]") do |b|
options[:ft_options][:runcontrolspecialdays] = b
end
o.on('--set-ip-tabular-output', "Request IP units from E+ Tabular (HTML) Report [Default: False]") do |b|
options[:ft_options][:ip_tabular_output] = b
end
o.on('--[no-]lifecyclecosts', "Include LifeCycleCosts [Default: True]") do |b|
options[:ft_options][:no_lifecyclecosts] = !b
end
o.on('--[no-]sqlite-output', "Request Output:SQLite from E+ [Default: True]") do |b|
options[:ft_options][:no_sqlite_output] = !b
end
o.on('--[no-]html-output', "Request Output:Table:SummaryReports report from E+ [Default: True]") do |b|
options[:ft_options][:no_html_output] = !b
end
o.on('--[no-]space-translation', "Add individual E+ Space [Default: True]") do |b|
options[:ft_options][:no_space_translation] = !b
end
o.separator ""
o.separator "Stdout Options: only available when --show-stdout is passed"
o.on('--add-timings', 'Print the start, end and elapsed times of each state of the simulation.') do
options[:add_timings] = true
end
o.on('--style-stdout', 'Style the stdout output to more clearly show the start and end of each state of the simulation') do
options[:style_stdout] = true
end
o.separator ""
end
# Parse the options
argv = parse_options(opts, sub_argv)
return 0 if argv.nil?