-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRakefile
5068 lines (4061 loc) · 155 KB
/
Rakefile
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
#------------------------------------------------------------------------
# (The MIT License)
#
# Copyright (c) 2008-2014 Rhomobile, Inc.
#
# 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.
#
# http://rhomobile.com
#------------------------------------------------------------------------
require_relative 'lib/build/rho_packages.rb'
require File.join(File.dirname(__FILE__), 'lib/build/required_time.rb')
# RequiredTime.hook()
$task_execution_time = false
require 'find'
require 'erb'
#require 'rdoc/task'
require 'base64'
require 'digest/sha2'
require 'digest/md5'
require 'io/console'
require 'json'
require 'net/https'
require 'open-uri'
require 'openssl'
require 'pathname'
require 'rexml/document'
require 'securerandom'
require 'uri'
# It does not work on Mac OS X. rake -T prints nothing. So I comment this hack out.
# NB: server build scripts depend on proper rake -T functioning.
=begin
#Look, another big fat hack. Make it so we can remove tasks from rake -T by setting comment to nil
module Rake
class Task
attr_accessor :comment
end
end
=end
# Restore process error mode on Windows.
# Error mode controls wether system error message boxes will be shown to user.
# Java disables message boxes and we enable them back.
#if RUBY_PLATFORM =~ /(win|w)32$/
# require 'win32/process'
# class WindowsError
# include Windows::Error
# end
# WindowsError.new.SetErrorMode(0)
#end
#------------------------------------------------------------------------
$app_basedir = pwd
$startdir = File.dirname(__FILE__)
$startdir.gsub!('\\', '/')
chdir File.dirname(__FILE__), :verbose => Rake.application.options.trace
require File.join(pwd, 'lib/build/jake.rb')
require File.join(pwd, 'lib/build/GeneratorTimeChecker.rb')
require File.join(pwd, 'lib/build/CheckSumCalculator.rb')
require File.join(pwd, 'lib/build/SiteChecker.rb')
require File.join(pwd, 'lib/build/ExtendedString.rb')
require File.join(pwd, 'lib/build/rhohub.rb')
require File.join(pwd, 'lib/build/BuildOutput.rb')
require File.join(pwd, 'lib/build/BuildConfig.rb')
require File.join(pwd, 'lib/build/RhoHubAccount.rb')
require File.join(pwd, 'lib/build/rhoDevelopment.rb')
#load File.join(pwd, 'platform/bb/build/bb.rake')
load File.join(pwd, 'platform/android/build/android.rake')
load File.join(pwd, 'platform/iphone/rbuild/iphone.rake')
load File.join(pwd, 'platform/wm/build/wm.rake')
load File.join(pwd, 'platform/linux/tasks/linux.rake')
load File.join(pwd, 'platform/wp8/build/wp.rake')
load File.join(pwd, 'platform/osx/build/osx.rake')
$timestamp_start_milliseconds = 0
def print_timestamp(msg = 'just for info')
if $timestamp_start_milliseconds == 0
$timestamp_start_milliseconds = (Time.now.to_f*1000.0).to_i
end
curmillis = (Time.now.to_f*1000.0).to_i - $timestamp_start_milliseconds
puts '-$TIME$- message [ '+msg+' ] time is { '+Time.now.utc.iso8601+' } milliseconds from start ('+curmillis.to_s+')'
end
#------------------------------------------------------------------------
def get_dir_hash(dir, init = nil)
hash = init
hash = Digest::SHA2.new if hash.nil?
Dir.glob(dir + "/**/*").each do |f|
hash << f
hash.file(f) if File.file? f
end
hash
end
#------------------------------------------------------------------------
namespace "framework" do
task :spec do
loadpath = $LOAD_PATH.inject("") { |load_path,pe| load_path += " -I" + pe }
rhoruby = ""
if RUBY_PLATFORM =~ /(win|w)32$/
rhoruby = 'res\\build-tools\\RhoRuby'
elsif RUBY_PLATFORM =~ /darwin/
rhoruby = 'res/build-tools/RubyMac'
else
rhoruby = 'res/build-tools/rubylinux'
end
puts `#{rhoruby} -I#{File.expand_path('spec/framework_spec/app/')} -I#{File.expand_path('lib/framework')} -I#{File.expand_path('lib/test')} -Clib/test framework_test.rb`
end
end
$application_build_configs_keys = ['security_token', 'encrypt_database', 'android_title', 'iphone_db_in_approot', 'iphone_set_approot', 'iphone_userpath_in_approot', "iphone_use_new_ios7_status_bar_style", "iphone_full_screen", "webkit_outprocess", "webengine", "create_eb_js"]
$winxpe_build = false
def make_application_build_config_header_file
f = StringIO.new("", "w+")
f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
#f.puts "// Generated #{Time.now.to_s}"
f.puts ""
f.puts "#include <string.h>"
f.puts "#include <common/RhoConf.h>"
f.puts ""
f.puts '//#include "app_build_configs.h"'
if $rhosimulator_build
f.puts '#include "common/RhoSimConf.h"'
end
f.puts ""
f.puts 'static const char* keys[] = { ""'
$application_build_configs.keys.each do |key|
f.puts ',"'+key+'"'
end
f.puts '};'
f.puts ''
count = 1
f.puts 'static const char* values[] = { ""'
$application_build_configs.keys.each do |key|
value = $application_build_configs[key].to_s().gsub('\\', "\\\\\\")
value = value.gsub('"', "\\\"")
f.puts ',"'+ value +'"'
count = count + 1
end
f.puts '};'
f.puts ''
f.puts '#define APP_BUILD_CONFIG_COUNT '+count.to_s
f.puts ''
f.puts 'const char* get_app_build_config_item(const char* key) {'
f.puts ' int i;'
f.puts ' const char* szValue;'
if $rhosimulator_build
f.puts ' if (strcmp(key, "security_token") == 0) {'
f.puts ' return rho_simconf_getString("security_token");'
f.puts ' }'
end
f.puts ""
f.puts ' szValue = rho_conf_getString(key);'
f.puts ' if (strcmp(szValue, "") != 0)'
f.puts ' return szValue;'
f.puts ""
f.puts ' for (i = 1; i < APP_BUILD_CONFIG_COUNT; i++) {'
f.puts ' if (strcmp(key, keys[i]) == 0) {'
f.puts ' return values[i];'
f.puts ' }'
f.puts ' }'
f.puts ' return 0;'
f.puts '}'
f.puts ''
Jake.modify_file_if_content_changed(File.join($startdir, "platform", "shared", "common", "app_build_configs.c"), f)
end
def make_application_build_capabilities_header_file
puts "%%% Prepare capability header file %%%"
f = StringIO.new("", "w+")
f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
#f.puts "// Generated #{Time.now.to_s}"
f.puts ""
caps = []
capabilities = $app_config["capabilities"]
if capabilities != nil && capabilities.is_a?(Array)
capabilities.each do |cap|
caps << cap
end
end
caps.sort.each do |cap|
f.puts '#define APP_BUILD_CAPABILITY_'+cap.upcase
end
f.puts ''
if $js_application
puts '#define RHO_NO_RUBY'
f.puts '#define RHO_NO_RUBY'
f.puts '#define RHO_NO_RUBY_API'
else
puts '//#define RHO_NO_RUBY'
end
Jake.modify_file_if_content_changed(File.join($startdir, "platform", "shared", "common", "app_build_capabilities.h"), f)
end
def make_application_build_config_java_file
f = StringIO.new("", "w+")
f.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
#f.puts "// Generated #{Time.now.to_s}"
f.puts "package com.rho;"
f.puts ""
f.puts "public class AppBuildConfig {"
f.puts 'static final String keys[] = { ""'
$application_build_configs.keys.each do |key|
f.puts ',"'+key+'"'
end
f.puts '};'
f.puts ''
count = 1
f.puts 'static final String values[] = { ""'
$application_build_configs.keys.each do |key|
f.puts ',"'+$application_build_configs[key]+'"'
count = count + 1
end
f.puts '};'
f.puts ''
f.puts 'static final int APP_BUILD_CONFIG_COUNT = '+count.to_s + ';'
f.puts ''
f.puts 'public static String getItem(String key){'
f.puts ' for (int i = 1; i < APP_BUILD_CONFIG_COUNT; i++) {'
f.puts ' if ( key.compareTo( keys[i]) == 0) {'
f.puts ' return values[i];'
f.puts ' }'
f.puts ' }'
f.puts ' return null;'
f.puts '}'
f.puts "}"
Jake.modify_file_if_content_changed( File.join( $startdir, "platform/bb/RubyVM/src/com/rho/AppBuildConfig.java" ), f )
end
def update_rhoprofiler_java_file
use_profiler = $app_config['profiler'] || ($app_config[$current_platform] && $app_config[$current_platform]['profiler'])
use_profiler = use_profiler && use_profiler.to_i() != 0 ? true : false
content = ""
File.open( File.join( $startdir, "platform/bb/RubyVM/src/com/rho/RhoProfiler.java" ), 'rb' ){ |f| content = f.read() }
is_find = nil
if use_profiler
is_find = content.sub!( 'RHO_STRIP_PROFILER = true;', 'RHO_STRIP_PROFILER = false;' )
else
is_find = content.sub!( 'RHO_STRIP_PROFILER = false;', 'RHO_STRIP_PROFILER = true;' )
end
if is_find
puts "RhoProfiler.java has been modified: RhoProfiler is " + (use_profiler ? "enabled!" : "disabled!")
File.open( File.join( $startdir, "platform/bb/RubyVM/src/com/rho/RhoProfiler.java" ), 'wb' ){ |f| f.write(content) }
end
end
def update_rhodefs_header_file
use_profiler = $app_config['profiler'] || ($app_config[$current_platform] && $app_config[$current_platform]['profiler'])
use_profiler = use_profiler && use_profiler.to_i() != 0 ? true : false
content = ""
File.open( File.join( $startdir, "platform/shared/common/RhoDefs.h" ), 'rb' ){ |f| content = f.read() }
is_find = nil
if use_profiler
is_find = content.sub!( '#define RHO_STRIP_PROFILER 1', '#define RHO_STRIP_PROFILER 0' )
else
is_find = content.sub!( '#define RHO_STRIP_PROFILER 0', '#define RHO_STRIP_PROFILER 1' )
end
if is_find
puts "RhoDefs.h has been modified: RhoProfiler is " + (use_profiler ? "enabled!" : "disabled!")
File.open( File.join( $startdir, "platform/shared/common/RhoDefs.h" ), 'wb' ){ |f| f.write(content) }
end
end
namespace :dev do
namespace :update do
desc 'This command initializes original state files. It needs for correct execution of command partial update from CLI. The first partial update cannot find out source code changes if initialize didn\'t execute before it'
task :initialize => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
mkdir_p RhoDevelopment::Configuration::development_directory
updated_list_filename = File.join(RhoDevelopment::Configuration::application_root, 'upgrade_package_add_files.txt')
removed_list_filename = File.join(RhoDevelopment::Configuration::application_root, 'upgrade_package_remove_files.txt')
#WindowsMobile
RhoDevelopment.setup(RhoDevelopment::Configuration::development_directory, 'wm')
RhoDevelopment::check_changes_from_last_build(updated_list_filename, removed_list_filename)
#iPhone
RhoDevelopment.setup(RhoDevelopment::Configuration::development_directory, 'iphone')
RhoDevelopment::check_changes_from_last_build(updated_list_filename, removed_list_filename)
#Android
RhoDevelopment.setup(RhoDevelopment::Configuration::development_directory, 'android')
RhoDevelopment::check_changes_from_last_build(updated_list_filename, removed_list_filename)
end
desc 'If source code was changed - builds partial update for all platforms and notifies all subscribers'
task :partial => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
unless RhoDevelopment::Configuration::has_enabled_subscribers?
puts 'Enabled subscribers not found'.warning
exit 1
end
RhoDevelopment::WebServer.ensure_running
filename = RhoDevelopment::Configuration::next_filename_for_downloading()
RhoDevelopment::WebServer.dispatch_task(RhoDevelopment::PartialUpdateTask.new(filename));
end
desc 'Builds full update bundle for all platforms and notifies all subscribers'
task :full => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
unless RhoDevelopment::Configuration::has_enabled_subscribers?
puts 'Enabled subscribers not found'.warning
exit 1
end
RhoDevelopment::WebServer.ensure_running
filename = RhoDevelopment::Configuration::next_filename_for_downloading()
RhoDevelopment::WebServer::dispatch_task(RhoDevelopment::AllPlatformsFullBundleBuildingTask.new(filename))
RhoDevelopment::WebServer::dispatch_task(RhoDevelopment::AllSubscribersFullUpdateNotifyingTask.new(filename))
end
desc 'It builds update with files from diff file list for all platforms and notifies all subscribers'
task :build_and_notify => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
unless RhoDevelopment::Configuration::has_enabled_subscribers?
puts 'Enabled subscribers not found'.warning
exit 1
end
RhoDevelopment::WebServer.ensure_running
filename = RhoDevelopment::Configuration::next_filename_for_downloading()
RhoDevelopment::WebServer::dispatch_task(RhoDevelopment::AllPlatformsPartialBundleBuildingTask.new(filename))
RhoDevelopment::WebServer::dispatch_task(RhoDevelopment::AllSubscribersPartialUpdateNotifyingTask.new(filename))
end
desc 'It launches watcher for source code and builds partial update and notifies all subscribers on each change'
task :auto => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
RhoDevelopment::WebServer.ensure_running
pid = RhoDevelopment::WebServer::get_auto_update_pid
if pid
puts 'Another auto updating process is already launched'.warning
exit 1
end
updater = RhoDevelopment::AutoUpdater.new
updater.add_directory(File.join($app_basedir, '/public'))
updater.add_directory(File.join($app_basedir, '/app'))
updater.run
end
namespace 'auto' do
desc 'It stops auto update process'
task :stop => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
pid = RhoDevelopment::WebServer::get_auto_update_pid
if pid
RhoDevelopment::Platform::terminate_process(pid)
RhoDevelopment::WebServer::set_auto_update_pid(0)
else
puts 'Auto updating is not launched'.warning
exit 1
end
end
end
end
namespace :webserver do
desc 'It launches development web server. It is certain object which controls executing scheduling tasks, handles requests etc..'
task :start => ['config:common'] do
RhoDevelopment::Configuration::application_root = $app_basedir
RhoDevelopment::WebServer.ensure_running
end
task :privateStart => ['config:initialize'] do
RhoDevelopment::Configuration::application_root = $app_basedir
server = RhoDevelopment::WebServer.new
server.start
end
desc 'It shut down development web server'
task :stop do
RhoDevelopment::Configuration::application_root = $app_basedir
RhoDevelopment::WebServer::stop
end
end
namespace :network do
desc 'Discover application on devices in local network - application should be executed on devices'
task :discovery, [:mask] => ['config:initialize'] do |t, args|
RhoDevelopment::Configuration::application_root = $app_basedir
finder = RhoDevelopment::DeviceFinder.new
if args[:mask] == nil
finder.run
else
finder.discovery((args[:mask]).split('.')[0, 3].join('.'))
end
end
desc 'Return string with available networks masks separated by semicolon. It needs for RhoStudio'
task :list do
addresses = RhoDevelopment::Network::available_addresses
if (addresses.empty?)
puts 'Network interfaces were not found.'.warning
exit 1
else
addresses.each {
|each|
_mask = each.split('.')[0, 3].join('.')
print "#{_mask}.*"
print ';' if addresses.last != each
}
end
end
end
end
#------------------------------------------------------------------------
#TODO: call clean from all platforms scripts
namespace "clean" do
task :common => "config:common" do
if $config["platform"] == "bb"
return
end
rm_rf File.join($app_path, "bin/tmp") if File.exists? File.join($app_path, "bin/tmp")
end
task :generated => "config:common" do
if $config["platform"] == "bb"
return
end
rm_rf File.join($app_path, "bin/tmp") if File.exists? File.join($app_path, "bin/tmp")
rm_rf File.join($app_path, "bin/RhoBundle") if File.exists? File.join($app_path, "bin/RhoBundle")
extpaths = $app_config["extpaths"]
$app_config["extensions"].each do |extname|
puts 'ext - ' + extname
extpath = nil
extpaths.each do |p|
ep = File.join(p, extname)
if File.exists?( ep ) && is_ext_supported(ep)
extpath = ep
break
end
end
if extpath.nil?
extpath = find_ext_ingems(extname)
if extpath
extpath = nil unless is_ext_supported(extpath)
end
end
if (extpath.nil?) && (extname != 'motoapi')
raise "Can't find extension '#{extname}'. Aborting build.\nExtensions search paths are:\n#{extpaths}"
end
unless extpath.nil?
extyml = File.join(extpath, "ext.yml")
#puts "extyml " + extyml
if File.file? extyml
extconf = Jake.config(File.open(extyml))
type = Jake.getBuildProp( "exttype", extconf )
#wm_type = extconf["wm"]["exttype"] if extconf["wm"]
if type != "prebuilt" #&& wm_type != "prebuilt"
rm_rf File.join(extpath, "ext", "shared", "generated")
rm_rf File.join(extpath, "ext", "platform", "android", "generated")
rm_rf File.join(extpath, "ext", "platform", "iphone", "generated")
rm_rf File.join(extpath, "ext", "platform", "osx", "generated")
rm_rf File.join(extpath, "ext", "platform", "wm", "generated")
rm_rf File.join(extpath, "ext", "platform", "wp8", "generated")
rm_rf File.join(extpath, "ext", "public", "api", "generated")
end
end
end
end
end
end
#------------------------------------------------------------------------
def get_conf(key_path, default = nil)
result = nil
key_sections = key_path.split('/').reject { |c| c.empty? }
[$app_config, $config, $shared_conf].each do |config|
if !config.nil?
curr = config
key_sections.each_with_index do |section, i|
if !curr[section].nil?
curr = curr[section]
else
break
end
if (i == key_sections.length-1) && !curr.nil?
result = curr
end
end
break if !result.nil?
end
end
result = nil if result.kind_of?(String) && result.strip.empty?
result.nil? ? default : result
end
#------------------------------------------------------------------------
#token handling
def get_app_list()
result = JSON.parse(Rhohub::App.list())
end
def from_boolean(v)
v == true ? "YES" : "NO"
end
def time_to_str(time)
d_h_m_s = [60,60,24].reduce([time]) { |m,o| m.unshift(m.shift.divmod(o)).flatten }
best = []
["day","hour","minute","second"].each_with_index do |v, i|
if d_h_m_s[i] > 0
best << d_h_m_s[i].to_s + " " + v + ((d_h_m_s[i] > 1) ? "s" : "")
end
end
best.empty? ? "now" : best.first(2).join(" ")
end
def sort_by_distance(array, template)
template.nil? ? array : array.sort_by { |s| distance(template, s) }
end
def rhohub_make_request(srv)
if block_given?
build_was_proxy_problem = false
begin
yield
rescue Timeout::Error, Errno::ETIMEDOUT, Errno::EINVAL, Errno::ECONNRESET,
Errno::ECONNREFUSED, SocketError => e
unless RestClient.proxy.nil? || RestClient.proxy.empty?
BuildOutput.put_log(BuildOutput::WARNING,'Could not connect using proxy server, retrying without proxy','Connection problem')
RestClient.proxy = ''
build_was_proxy_problem = true
retry
else
if build_was_proxy_problem
BuildOutput.put_log(BuildOutput::WARNING,"Could not connect to server #{get_server(srv,'')}\n#{e.inspect}",'Network problem')
else
BuildOutput.put_log(BuildOutput::WARNING,"Could not connect to server #{get_server(srv,'')}. If you are behind proxy please set http(s)_proxy ENV variable",'Network problem')
end
exit 1
end
rescue EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
puts "Http request problem: #{e.inspect}"
rescue RestClient::RequestFailed => e
puts "Http request problem: #{e.message}"
rescue RestClient::ExceptionWithResponse => e
# do nothing, this is is 404 or something like that
end
if RestClient.proxy != $proxy
$proxy = RestClient.proxy
end
end
end
def check_update_token_file(server_list, user_acc, token_folder, subscription_level = -1)
is_valid = -2
if user_acc.is_valid_token?()
Rhohub.token = user_acc.token
is_valid = user_acc.is_outdated() ? 0 : 2
if (user_acc.is_outdated() || (subscription_level > user_acc.subscription_level))
servers_sorted = sort_by_distance(server_list, user_acc.server)
servers_sorted.each do |srv|
Rhohub.url = srv
if (subscription_level > user_acc.subscription_level)
puts "Connecting to #{get_server(srv,'')}"
rhohub_make_request(srv) do
subscription = Rhohub::Subscription.check()
user_acc.subscription = subscription
end
if user_acc.subscription_level >= subscription_level
user_acc.server = srv
break
end
end
end
is_valid = user_acc.subscription_level >= 0 ? 2 : 0
if is_valid == 0
servers_sorted.each do |srv|
Rhohub.url = srv
user_apps = nil
begin
user_apps = get_app_list()
rescue Exception => e
user_apps = nil
end
if user_apps.nil?
user_acc.token = nil
is_valid = -1
else
is_valid = 1
end
if is_valid > 0
user_acc.server = srv
break
end
end
end
end
Rhohub.url = user_acc.server if is_valid > 0
if (user_acc.is_valid_token?() && user_acc.changed)
user_acc.save_token(token_folder)
end
else
is_valid = -2
end
is_valid
end
def read_and_delete_files( file_list )
result = []
if file_list.kind_of?(String)
file_list = [file_list]
end
if file_list.kind_of?(Array)
file_list.each do |read_file|
f_size = File.size?(read_file)
if !f_size.nil? && f_size < 1024
begin
result << File.read(read_file)
File.delete(read_file)
rescue Exception => e
puts "Reading file exception #{e.inspect}"
end
end
end
end
result
end
$server_list = ['https://rms.rhomobile.com/api/v1']
$selected_server = $server_list.first
def get_server(url, default)
url = default if url.nil? || url.empty?
scheme, user_info, host, port, registry, path, opaque, query, fragment = URI.split(url)
case scheme
when "http"
URI::HTTP.build({:host => host, :port => port}).to_s
when "https"
URI::HTTPS.build({:host => host, :port => port}).to_s
else
""
end
end
namespace 'token' do
task :initialize => "config:load" do
$user_acc = RhoHubAccount.new()
server_url = get_conf('cloud/server_url', $server_list)
server_list = []
if server_url.kind_of?(String)
server_list << server_url
elsif server_url.kind_of?(Array)
server_list.concat(server_url)
elsif !server_url.nil?
raise "Invalid server_url setting! #{server_url.inspect}"
end
server_list.select!{|url| url =~ /\A#{URI::regexp(['http', 'https'])}\z/}
$server_list = server_list unless server_list.empty?
SiteChecker.site = $server_list.first
Rhohub.url = $server_list.first
if !($proxy.nil? || $proxy.empty?)
SiteChecker.proxy = $proxy
RestClient.proxy = $proxy
end
end
task :login => [:initialize] do
puts 'Login to cloud build system'
if $stdin.tty?
print "Username: "
username = STDIN.gets.chomp.downcase
if username.empty?
BuildOutput.note('Empty username, login stopped')
exit 1
end
print "Password: "
STDIN.tty?
password = STDIN.noecho(&:gets).chomp
print $/
if password.empty?
BuildOutput.note('Empty password, login stopped')
exit 1
end
else
username = STDIN.readline.chomp
password = STDIN.readline.chomp
end
token = nil
sort_by_distance($server_list, $user_acc.server).each do |server|
Rhohub.url = server
rhohub_make_request(server) do
info = Rhohub::Token.login(username, password)
token = JSON.parse(info)["token"]
if token != nil
$user_acc.server = server
end
end
break if !token.nil?
end
if token.nil?
srv_address = URI.join( get_server($user_acc.server, $server_list.first), '/forgot')
BuildOutput.error( "Could not login using your username and password, please verify them and try again. \nIf you forgot your password you can reset at #{srv_address}", 'Invalid username or password')
exit 1
end
if !(token.nil? || token.empty?) && RhoHubAccount.is_valid_token?(token)
Rake::Task["token:set"].invoke(token)
else
BuildOutput.error( "Could not receive API token from cloud build server", 'Internal error')
exit 1
end
end
task :read, [:force_re_app_check] => [:initialize] do |t, args|
args.with_defaults(:force_re_app_check => "false")
if !$user_acc.read_token_from_env()
$user_acc.read_token_from_files($rhodes_home)
end
Rhohub.url = sort_by_distance($server_list, $user_acc.server).first
if !$user_acc.is_valid_token?()
last_read_token = nil
search_paths = [Rake.application.original_dir, $app_path, $rhodes_home]
files = search_paths.compact.uniq.map{|d| File.join(d,'token.txt')}
read_and_delete_files(files).each do |token|
if RhoHubAccount.is_valid_token?(token)
last_read_token = token
end
end
$user_acc.token = last_read_token
end
if $user_acc.is_valid_token?()
force_re_app_check_level = 0
if $re_app
force_re_app_check_level = 1
end
if to_boolean(args[:force_re_app_check])
force_re_app_check_level = 3
end
# check existing API token
case check_update_token_file($server_list, $user_acc, $rhodes_home, force_re_app_check_level )
when 2
#BuildOutput.put_log( BuildOutput::NOTE, "Token and subscription are valid", "Token check" );
when 1
BuildOutput.put_log( BuildOutput::WARNING, "Token is valid, could not check subcription", "Token check" );
when 0
BuildOutput.put_log( BuildOutput::WARNING, "Cloud not check token online", "Token check" );
else
BuildOutput.put_log( BuildOutput::ERROR, "Cloud build server API token is not valid!", 'Token check');
exit 1
end
end
if $user_acc.is_valid_token?()
Rhohub.token = $user_acc.token
end
if $user_acc.server.empty?
$user_acc.server = $server_list.first
end
$selected_server = get_server($user_acc.server, $server_list.first)
end
task :check => [:read] do
puts "TokenValid[#{from_boolean($user_acc.is_valid_token?())}]"
puts "TokenChecked[#{from_boolean($user_acc.remaining_time() > 0)}]"
puts "SubscriptionValid[#{from_boolean($user_acc.is_valid_subscription?())}]"
puts "SubscriptionChecked[#{from_boolean($user_acc.remaining_subscription_time() > 0)}]"
end
desc "Show token and user subscription information"
task :info => [:initialize] do
Rake::Task['token:read'].reenable()
Rake::Task['token:read'].invoke(true)
puts "Login complete: " + from_boolean($user_acc.is_valid_token?())
if $user_acc.is_valid_token?()
token_remaining = $user_acc.remaining_time()
if token_remaining > 0
puts "Token will be checked after " + time_to_str($user_acc.remaining_time())
else
puts "Token should be checked"
BuildOutput.warning( "Unable to connect to cloud build servers to validate your token information.\nPlease ensure you have a valid network connection and your proxy settings are configured correctly.", 'Token check error')
end
puts "Subscription plan: " + $user_acc.subsciption_plan()
subs_valid = $user_acc.is_valid_subscription?()
puts "Local subscripton cache valid: " + from_boolean(subs_valid)
if subs_valid
puts "Local subscription cache will be valid for " + time_to_str($user_acc.remaining_subscription_time())
end
end
end
task :get => [:read] do
if $user_acc.is_valid_token?()
puts "Token[#{$user_acc.token}]"
else
puts "TokenNotSet!"
exit 1
end
end
task :set, [:token] => [:initialize] do |t, args|
if RhoHubAccount.is_valid_token?(args[:token])
$user_acc.token = args[:token]
else
BuildOutput.error('Invalid Rhomobile API token !', 'Token check')
exit 1
end
if $user_acc.is_valid_token?()
case check_update_token_file($server_list, $user_acc, $rhodes_home, 3)
when 2
BuildOutput.put_log( BuildOutput::NOTE, "Token and subscription are valid", "Token check")
when 1
BuildOutput.put_log( BuildOutput::WARNING,"Token is valid, could not check subscription", "Token check")
when 0
BuildOutput.put_log( BuildOutput::ERROR, 'Could not check token online', 'Token check')
exit 1
else
BuildOutput.put_log( BuildOutput::ERROR, 'Rhomobile API token is not valid!', 'Token check')
exit 1
end
end
end
task :clear => [:initialize] do
RhoHubAccount.remove_account_files($rhodes_home)
end
task :setup => [:read] do
if !$user_acc.is_valid_token?()
have_input = STDIN.tty? && STDOUT.tty?
BuildOutput.put_log( BuildOutput::NOTE, "In order to use #{$re_app ? 'Rhoelements' : 'Rhodes'} framework you need to log in into your rhomobile account.
If you don't have account please register at " + URI.join($server_list.first, '/').to_s + ( have_input ? 'To stop build just press enter.' : '') )
if have_input
Rake::Task['token:login'].invoke()
end
end
end
end
def distance(a, b, case_insensitive = false)
as = a.to_s
bs = b.to_s
if case_insensitive
as = as.downcase
bs = bs.downcase
end
rows = as.size + 1
cols = bs.size + 1
dist = [ Array.new(cols) {|k| k}, Array.new(cols) {0}, Array.new(cols) {0} ]
(1...rows).each do |i|
k = i % 3
dist[k][0] = i
(1...cols).each do |j|
cost = as[i - 1] == bs[j - 1] ? 0 : 1
d1 = dist[k - 1][j] + 1
d2 = dist[k][j - 1] + 1
d3 = dist[k - 1][j - 1] + cost
d_now = [d1, d2, d3].min