-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase.py
1841 lines (1623 loc) · 64.6 KB
/
base.py
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
import argparse
import atexit
import calendar
import codecs
import collections
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import fileinput
from functools import wraps
import hashlib
import inspect
import json
import logging
import multiprocessing
from multiprocessing import Pool
import operator
import os
from os.path import expanduser
import pickle
import platform
import random
import re
import select
import shutil
import smtplib
import socket
import subprocess
import sys
import threading
import time
import uuid
import zipfile
try:
import distro
import urllib2
import win32com.client # install pywin32
except ImportError:
pass
try:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
except ImportError:
pass
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of times to try (not retry) before giving up
:type tries: int
:param delay: initial delay between retries in seconds
:type delay: int
:param backoff: backoff multiplier e.g. value of 2 will double the delay
each retry
:type backoff: int
:param logger: logger to use. If None, print
:type logger: logging.Logger instance
"""
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
print(msg)
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
class Util:
@staticmethod
def execute(
cmd,
show_cmd=True,
exit_on_error=True,
return_out=False,
show_duration=False,
dryrun=False,
shell=True,
log_file='',
timeout=0,
):
if show_duration:
timer = Timer()
orig_cmd = cmd
if show_cmd:
Util.cmd(orig_cmd)
fail_file = Util.format_slash('%s-%s' % (ScriptRepo.IGNORE_FAIL_FILE, uuid.uuid4()))
if not dryrun:
Util.ensure_file(fail_file)
if Util.HOST_OS == Util.WINDOWS:
remove_cmd = 'del'
else:
remove_cmd = 'rm'
cmd = '%s && %s %s' % (cmd, remove_cmd, fail_file)
if log_file:
cmd = '(%s) 2>&1 | tee -a %s' % (cmd, log_file)
ret = 0
out = ''
if timeout or return_out:
process = subprocess.Popen(
cmd, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8'
)
if timeout:
process_timer = threading.Timer(timeout, process.kill)
process_timer.start()
try:
out, _ = process.communicate()
finally:
if timeout:
if not process_timer.is_alive():
ret = 1
process_timer.cancel()
else:
ret = os.system(cmd)
if os.path.exists(fail_file):
Util.ensure_nofile(fail_file)
if not ret:
ret = 1
if ret:
if exit_on_error:
Util.error('Failed to execute command [%s]' % cmd)
else:
Util.warning('Failed to execute command [%s]' % cmd)
if show_duration:
Util.info(
'%s was spent to execute command "%s" in function "%s"'
% (timer.stop(), orig_cmd, inspect.stack()[1][3])
)
return [ret, out]
@staticmethod
# Do not care about out, log_file
# Do care about timeout
def simple_execute(cmd, show_cmd=True, exit_on_error=True, show_duration=False, dryrun=False, timeout=0):
if show_duration:
timer = Timer()
if show_cmd:
Util.cmd(cmd)
# fail_file can be deleted only if shell is False
if timeout:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process_timer = threading.Timer(timeout, process.kill)
process_timer.start()
try:
process.communicate()
finally:
if process_timer.is_alive():
ret = 0
else:
ret = 1
process_timer.cancel()
else:
ret = os.system(cmd)
if ret:
if exit_on_error:
Util.error('Failed to execute command [%s]' % cmd)
else:
Util.warning('Failed to execute command [%s]' % cmd)
if show_duration:
Util.info(
'%s was spent to execute command "%s" in function "%s"' % (timer.stop(), cmd, inspect.stack()[1][3])
)
return [ret, '']
@staticmethod
def _msg(msg, show_strace=False):
m = inspect.stack()[1][3].upper()
if show_strace:
m += ', File "%s", Line: %s, Function %s' % inspect.stack()[2][1:4]
m = '[%s] %s' % (m, msg)
print(m)
@staticmethod
def info(msg):
Util._msg(msg)
@staticmethod
def warning(msg):
Util._msg(msg, show_strace=True)
@staticmethod
def cmd(msg):
Util._msg(msg)
@staticmethod
def debug(msg):
Util._msg(msg)
@staticmethod
def strace(msg):
Util._msg(msg)
@staticmethod
def error(msg, abort=True, error_code=1):
Util._msg(msg, show_strace=True)
if abort:
quit(error_code)
@staticmethod
def not_implemented():
Util.error('not_implemented() at line %s' % inspect.stack()[1][2])
@staticmethod
def chdir(dir_path, verbose=False):
if verbose:
Util.info('Enter ' + dir_path)
os.chdir(dir_path)
@staticmethod
def print_cwd():
Util.info(os.getcwd())
@staticmethod
def get_dir(path):
return os.path.split(os.path.realpath(path))[0]
@staticmethod
def ensure_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
@staticmethod
def ensure_nodir(dir):
if os.path.exists(dir):
shutil.rmtree(dir)
@staticmethod
def ensure_file(file_path):
Util.ensure_dir(os.path.dirname(os.path.abspath(file_path)))
if not os.path.exists(file_path):
open(file_path, 'w').close()
@staticmethod
def ensure_nofile(file_path):
if os.path.exists(file_path):
os.remove(file_path)
@staticmethod
def ensure_newfile(file_path):
Util.ensure_nofile(file_path)
Util.ensure_file(file_path)
@staticmethod
def ensure_symlink(src, dst):
if os.path.exists(dst):
return
os.symlink(src, dst)
@staticmethod
def pkg_installed(pkg):
cmd = 'dpkg -s ' + pkg + ' >/dev/null'
ret, _ = Util.execute(cmd, show_cmd=False, return_out=False, exit_on_error=False)
if ret:
return False
else:
return True
@staticmethod
def install_pkg(pkg):
if Util.pkg_installed(pkg):
return True
else:
Util.info('Package ' + pkg + ' is installing...')
cmd = 'sudo apt-get install --force-yes -y ' + pkg
result = Util.execute(cmd)
if result[0]:
Util.warning('Package ' + pkg + ' installation failed')
return False
else:
return True
@staticmethod
def ensure_pkg(pkgs):
ret = True
pkg_list = pkgs.split(' ')
for pkg in pkg_list:
ret &= Util.install_pkg(pkg)
return ret
@staticmethod
def read_file(file_path):
if not os.path.exists(file_path):
return []
f = open(file_path)
lines = [line.rstrip('\n') for line in f]
if len(lines) > 0:
while lines[-1] == '':
del lines[-1]
f.close()
return lines
@staticmethod
def append_file(file_path, content):
Util.ensure_file(file_path)
python_ver = Util.get_python_ver()
if python_ver[0] == 3:
types = [str]
else:
types = [str, unicode]
if type(content) in types:
content = [content]
f = open(file_path, 'a+')
for line in content:
f.write(line + '\n')
f.close()
@staticmethod
def load_json(file_path):
f = open(file_path)
content = json.load(f)
f.close()
return content
@staticmethod
def dump_json(file_path, content, indent=2, sort_keys=False):
Util.ensure_file(file_path)
f = open(file_path, 'r+')
f.seek(0)
f.truncate()
json.dump(content, f, indent=indent, sort_keys=sort_keys)
f.close()
@staticmethod
def get_datetime(format='%Y%m%d%H%M%S'):
return time.strftime(format, time.localtime())
@staticmethod
def get_env(env):
return os.getenv(env)
@staticmethod
def set_env(env, value, verbose=False):
if value:
os.environ[env] = value
elif env in os.environ:
del os.environ[env]
if verbose:
Util.info('%s=%s' % (env, value))
# get seconds since 1970-01-01
@staticmethod
def get_epoch_second():
return int(time.time())
@staticmethod
def has_recent_change(file_path, interval=24 * 3600):
# Don't follow symlinks when getting the time of last modification of path, otherwise it
# will get the time of the original file, not the symbolic link, and throw FileNotFound
# error if the original file is removed.
if Util.get_epoch_second() - os.stat(file_path, follow_symlinks=False).st_mtime < interval:
return True
else:
return False
@staticmethod
def prepend_path(path):
paths = Util.get_env('PATH').split(Util.ENV_SPLITTER)
new_paths = path.split(Util.ENV_SPLITTER)
for tmp_path in paths:
if tmp_path not in new_paths:
new_paths.append(tmp_path)
Util.set_env('PATH', Util.ENV_SPLITTER.join(new_paths))
@staticmethod
def remove_path(path):
paths = Util.get_env('PATH').split(Util.ENV_SPLITTER)
for tmp_path in paths:
if tmp_path == path:
paths.remove(tmp_path)
Util.set_env('PATH', Util.ENV_SPLITTER.join(paths))
@staticmethod
def del_filetype_in_dir(dir_path, filetype):
for root, dirs, files in os.walk(dir_path):
for name in files:
if name.endswith('.%s' % filetype):
os.remove(os.path.join(root, name))
@staticmethod
def has_depot_tools_in_path():
paths = Util.get_env('PATH').split(Util.ENV_SPLITTER)
for tmp_path in paths:
if re.search('depot_tools$', tmp_path):
return True
else:
return False
@staticmethod
def set_proxy(address, port):
http_proxy = '%s:%s' % (address, port)
https_proxy = '%s:%s' % (address, port)
Util.set_env('http_proxy', http_proxy)
Util.set_env('https_proxy', https_proxy)
Util.set_env('no_proxy', '127.0.0.1')
@staticmethod
def clear_proxy():
Util.set_env('http_proxy', '')
Util.set_env('https_proxy', '')
@staticmethod
def get_caller_name():
return inspect.stack()[1][3]
@staticmethod
# ver is in format a.b.c.d
# return 1 if ver_a > ver_b
# return 0 if ver_a == ver_b
# return -1 if ver_a < ver_b
def cmp_ver(ver_a, ver_b):
vers_a = [int(x) for x in ver_a.split('.')]
vers_b = [int(x) for x in ver_b.split('.')]
# make sure two lists have same length and add 0s for short one.
len_a = len(vers_a)
len_b = len(vers_b)
len_max = max(len_a, len_b)
len_diff = abs(len_a - len_b)
vers_diff = []
for _ in range(len_diff):
vers_diff.append(0)
if len_a < len_b:
vers_a.extend(vers_diff)
elif len_b < len_a:
vers_b.extend(vers_diff)
index = 0
while index < len_max:
if vers_a[index] > vers_b[index]:
return 1
elif vers_a[index] < vers_b[index]:
return -1
index += 1
return 0
@staticmethod
def strace_function(frame, event, arg, indent=[0]):
file_path = frame.f_code.co_filename
function_name = frame.f_code.co_name
file_name = file_path.split('/')[-1]
if not file_path[:4] == '/usr' and not file_path == '<string>':
if event == 'call':
indent[0] += 2
Util.strace('-' * indent[0] + '> call %s:%s' % (file_name, function_name))
elif event == 'return':
Util.strace('<' + '-' * indent[0] + ' exit %s:%s' % (file_name, function_name))
indent[0] -= 2
return Util.strace_function
@staticmethod
# Get the dir of symbolic link, for example: /workspace/project/chromium instead of /workspace/project/gyagp/share/python
def get_symlink_dir():
if sys.argv[0][0] == '/': # Absolute path
script_path = sys.argv[0]
else:
script_path = os.getcwd() + '/' + sys.argv[0]
return os.path.split(script_path)[0]
@staticmethod
def union_list(a, b):
return list(set(a).union(set(b)))
@staticmethod
def intersect_list(a, b):
return list(set(a).intersection(set(b)))
@staticmethod
def diff_list(a, b):
return list(set(a).difference(set(b)))
# To use SMTP_SERVER, you need to add machine name into /etc/postfix/main.cf
@staticmethod
def send_email(subject, content='', sender='', to='', type=''):
if not sender:
sender = '[email protected]'
if not to:
to = '[email protected]'
if not type:
type = 'plain'
if isinstance(to, list):
to = ','.join(to)
if isinstance(content, list):
content = '\n\n'.join(content)
to_list = to.split(',')
msg = MIMEMultipart('alternative')
msg['From'] = sender
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(content, type))
try:
smtp = smtplib.SMTP(Util.SMTP_SERVER)
smtp.sendmail(sender, to_list, msg.as_string())
Util.info('Email was sent successfully')
except Exception as e:
Util.error('Failed to send mail: %s' % e)
finally:
smtp.quit()
@staticmethod
def get_quotation():
if Util.HOST_OS == Util.WINDOWS:
quotation = '\"'
else:
quotation = '\''
return quotation
@staticmethod
def format_slash(s):
if sys.platform == 'win32':
return s.replace('/', '\\')
else:
return s.replace('\\', '/')
@staticmethod
@retry(Exception, tries=5, delay=3, backoff=2)
def urlopen_with_retry(url):
return urllib2.urlopen(url)
@staticmethod
def cal_relative_out_dir(target_arch, target_os, symbol_level=0, no_component_build=False, dcheck=False):
relative_out_dir = 'out-%s-%s' % (target_arch, target_os)
relative_out_dir += '-symbol%s' % symbol_level
if no_component_build:
relative_out_dir += '-nocomponent'
else:
relative_out_dir += '-component'
if dcheck:
relative_out_dir += '-dcheck'
else:
relative_out_dir += '-nodcheck'
return relative_out_dir
@staticmethod
def parse_git_line(
lines, index, tmp_rev, tmp_hash, tmp_author, tmp_date, tmp_subject, tmp_insertion, tmp_deletion, tmp_is_roll
):
line = lines[index]
strip_line = line.strip()
# hash
match = re.match(Util.COMMIT_STR, line)
if match:
tmp_hash = match.group(1)
# author
match = re.match('Author:', lines[index])
if match:
match = re.search('<(.*@.*)@.*>', line)
if match:
tmp_author = match.group(1)
else:
match = re.search(r'(\S+@\S+)', line)
if match:
tmp_author = match.group(1)
tmp_author = tmp_author.lstrip('<')
tmp_author = tmp_author.rstrip('>')
else:
tmp_author = line.rstrip('\n').replace('Author:', '').strip()
Util.warning('The author %s is in abnormal format' % tmp_author)
# date & subject
match = re.match('Date:(.*)', line)
if match:
tmp_date = match.group(1).strip()
index += 2
tmp_subject = lines[index].strip()
match = re.match(r'Roll (.*) ([a-zA-Z0-9]+)..([a-zA-Z0-9]+) \((\d+) commits\)', tmp_subject)
if match and match.group(1) != 'src-internal':
tmp_is_roll = True
# rev
# < r291561, use below format
# example: git-svn-id: svn://svn.chromium.org/chrome/trunk/src@291560 0039d316-1c4b-4281-b951-d872f2087c98
match = re.match('git-svn-id: svn://svn.chromium.org/chrome/trunk/src@(.*) .*', strip_line)
if match:
tmp_rev = int(match.group(1))
# >= r291561, use below format
# example: Cr-Commit-Position: refs/heads/main@{#349370}
match = re.match('Cr-Commit-Position: refs/heads/main@{#(.*)}', strip_line)
if match:
tmp_rev = int(match.group(1))
if re.match(r'(\d+) files? changed', strip_line):
match = re.search(r'(\d+) insertion(s)*\(\+\)', strip_line)
if match:
tmp_insertion = int(match.group(1))
else:
tmp_insertion = 0
match = re.search(r'(\d+) deletion(s)*\(-\)', strip_line)
if match:
tmp_deletion = int(match.group(1))
else:
tmp_deletion = 0
return (tmp_rev, tmp_hash, tmp_author, tmp_date, tmp_subject, tmp_insertion, tmp_deletion, tmp_is_roll)
@staticmethod
def get_browser_path(browser_name, target_os=None):
if not target_os:
target_os = Util.HOST_OS
if target_os == Util.CHROMEOS:
browser_path = '/opt/google/chrome/chrome'
elif target_os == Util.DARWIN:
if browser_name == 'chrome_canary':
browser_path = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
elif browser_name == 'chrome_dev':
browser_path = '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev'
elif browser_name == 'chrome_beta':
browser_path = '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta'
elif browser_name == 'chrome_stable':
browser_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
elif target_os == Util.LINUX:
if browser_name == 'chrome_dev':
browser_path = '/usr/bin/google-chrome-unstable'
elif browser_name == 'chrome_beta':
browser_path = '/usr/bin/google-chrome-beta'
elif browser_name == 'chrome_stable':
browser_path = '/usr/bin/google-chrome-stable'
elif target_os == Util.WINDOWS:
if browser_name == 'chrome_canary':
browser_path = '%s/Google/Chrome SxS/Application/chrome.exe' % Util.LOCALAPPDATA_DIR
elif browser_name == 'chrome_dev':
browser_path = '%s/Google/Chrome Dev/Application/chrome.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'chrome_beta':
browser_path = '%s/Google/Chrome Beta/Application/chrome.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'chrome_stable':
browser_path = '%s/Google/Chrome/Application/chrome.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'firefox_nightly':
browser_path = '%s/Nightly/firefox.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'edge':
browser_path = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
return browser_path
@staticmethod
def get_webdriver(browser_name, browser_path='', browser_options='', webdriver_file='', debug=False, target_os=''):
if not target_os:
target_os = Util.HOST_OS
# options
options = []
if 'chrome' in browser_name:
# --start-maximized doesn't work on darwin
if target_os in [Util.DARWIN]:
options.append('--start-fullscreen')
elif target_os in [Util.WINDOWS, Util.LINUX]:
options.append('--start-maximized')
if target_os != Util.CHROMEOS:
options.extend(
[
'--disk-cache-dir=/dev/null',
'--disk-cache-size=1',
'--user-data-dir=%s' % (ScriptRepo.USER_DATA_DIR),
]
)
if debug:
service_args = ["--verbose", "--log-path=%s/chromedriver.log" % ScriptRepo.IGNORE_LOG_DIR]
else:
service_args = []
if browser_options:
options.extend(browser_options.split(','))
# browser_path
if not browser_path:
out_dir = Util.cal_relative_out_dir('x86_64', Util.HOST_OS)
if target_os == Util.CHROMEOS:
browser_path = '/opt/google/chrome/chrome'
elif target_os == Util.DARWIN:
if browser_name == 'chrome':
browser_path = (
Util.PROJECT_CHROMIUM_DIR + '/%s/Release/Chromium.app/Contents/MacOS/Chromium' % out_dir
)
elif browser_name == 'chrome_canary':
browser_path = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
elif target_os == Util.LINUX:
if browser_name == 'chrome':
browser_path = Util.PROJECT_CHROMIUM_DIR + '/%s/Release/chrome' % out_dir
elif browser_name == 'chrome_stable':
browser_path = '/usr/bin/google-chrome-stable'
elif browser_name == 'chrome_canary':
browser_path = '/usr/bin/google-chrome-unstable'
elif target_os == Util.WINDOWS:
if browser_name == 'chrome':
browser_path = Util.PROJECT_CHROMIUM_DIR + '/%s/Release/chrome.exe' % out_dir
elif browser_name == 'chrome_stable':
browser_path = '%s/Google/Chrome/Application/chrome.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'chrome_beta':
browser_path = '%s/Google/Chrome Beta/Application/chrome.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'chrome_dev':
browser_path = '%s/Google/Chrome Dev/Application/chrome.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'chrome_canary':
browser_path = '%s/../Local/Google/Chrome SxS/Application/chrome.exe' % Util.APPDATA_DIR
elif browser_name == 'firefox_nightly':
browser_path = '%s/Nightly/firefox.exe' % Util.PROGRAMFILES_DIR
elif browser_name == 'edge':
browser_path = 'C:/windows/systemapps/Microsoft.MicrosoftEdge_8wekyb3d8bbwe/MicrosoftEdge.exe'
# webdriver_file
if not webdriver_file:
if target_os == Util.CHROMEOS:
webdriver_file = '/user/local/chromedriver/chromedriver'
elif browser_name == 'chrome':
if Util.HOST_OS == Util.DARWIN:
chrome_dir = browser_path.replace('/Chromium.app/Contents/MacOS/Chromium', '')
else:
chrome_dir = os.path.dirname(os.path.realpath(browser_path))
webdriver_file = '%s%s' % (Util.format_slash(chrome_dir + '/chromedriver'), Util.EXEC_SUFFIX)
elif target_os in [Util.DARWIN, Util.LINUX, Util.WINDOWS]:
if 'chrome' in browser_name:
webdriver_file = ScriptRepo.CHROMEDRIVER_FILE
elif 'firefox' in browser_name:
webdriver_file = Util.FIREFOXDRIVER_PATH
elif 'edge' in browser_name:
webdriver_file = Util.EDGEDRIVER_PATH
# driver
if target_os == Util.CHROMEOS:
import chromeoswebdriver
driver = chromeoswebdriver.chromedriver(extra_chrome_flags=options).driver
elif target_os in [Util.DARWIN, Util.LINUX, Util.WINDOWS]:
if 'chrome' in browser_name:
chrome_options = webdriver.ChromeOptions()
for option in options:
chrome_options.add_argument(option)
chrome_options.binary_location = browser_path
if debug:
service_args = ["--verbose", "--log-path=%s/chromedriver.log" % ScriptRepo.IGNORE_LOG_DIR]
else:
service_args = []
driver = webdriver.Chrome(
executable_path=webdriver_file, chrome_options=chrome_options, service_args=service_args
)
elif 'firefox' in browser_name:
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
capabilities = DesiredCapabilities.FIREFOX
capabilities['marionette'] = True
# capabilities['binary'] = browser_path
driver = webdriver.Firefox(capabilities=capabilities, executable_path=webdriver_file)
elif 'edge' in browser_name:
driver = webdriver.Edge(webdriver_file)
if not browser_path:
Util.error('Could not find module at %s' % browser_path)
else:
Util.info('Use module at %s' % browser_path)
if not webdriver_file:
Util.error('Could not find webdriver at %s' % webdriver_file)
else:
Util.info('Use webdriver at %s' % webdriver_file)
if not driver:
Util.error('Could not get webdriver')
return driver
@staticmethod
def get_md5(path, verbose=False):
if verbose:
info('Calculating md5 of %s' % path)
if Util.need_sudo(path):
name = os.path.basename(path)
Util.execute('sudo cp %s /tmp' % path, show_cmd=False)
Util.execute('sudo chmod +r /tmp/%s' % name, show_cmd=False)
md5 = hashlib.md5(open('/tmp/%s' % name, 'rb').read()).hexdigest()
Util.execute('sudo rm /tmp/%s' % name, show_cmd=False)
else:
md5 = hashlib.md5(open(path, 'rb').read()).hexdigest()
return md5
@staticmethod
def has_path(path):
if Util.need_sudo(path):
result = Util.execute('sudo ls %s' % path, show_cmd=False, exit_on_error=False)
if result[0] == 0:
return True
else:
return False
else:
return os.path.exists(path)
@staticmethod
def has_link(path):
if Util.need_sudo(path) or Util.HOST_OS == Util.WINDOWS:
cmd = 'file "%s"' % path
if Util.need_sudo(path):
cmd = 'sudo ' + cmd
_, out = Util.execute(cmd, show_cmd=False, return_out=True)
if re.search('symbolic link to', str(out)):
return True
else:
return False
else:
return os.path.islink(path)
@staticmethod
def use_drive(s):
m = re.match('/(.)/', s)
if m:
drive = m.group(1)
s = s.replace('/%s/' % drive, '%s:/' % drive.capitalize())
return s
# get the real file from symbolic link
@staticmethod
def get_link(path):
if not Util.has_link(path):
error('%s is not a symbolic link' % path)
if Util.need_sudo(path) or Util.HOST_OS == Util.WINDOWS:
cmd = 'file "%s"' % path
if Util.need_sudo(path):
cmd = 'sudo ' + cmd
_, out = Util.execute(cmd, show_cmd=False, return_out=True)
match = re.search('symbolic link to (.*)', str(out))
link = match.group(1).strip()
if Util.HOST_OS == Util.WINDOWS:
link = Util.use_drive(link)
return link
else:
return os.readlink(path) # pylint: disable=E1101
@staticmethod
def need_sudo(path):
sudo_paths = ['chroot/sbin', '/var', '/etc']
for sudo_path in sudo_paths:
if re.match(sudo_path, path):
return True
else:
return False
# return True if there is a real update
# is_sylk: If true, just copy as a symbolic link
# dir_xxx means directory
# name_xxx means file name
# path_xxx means full path of file
# need_bk means if it needs .bk file
@staticmethod
def copy_file(src_dir, src_name, dest_dir, dest_name='', is_sylk=False, need_bk=True, show_cmd=False):
if not os.path.exists(dest_dir):
# we do not warn here as it's a normal case
# warning(dest_dir + ' does not exist')
return False
if not dest_name:
dest_name = src_name
dest_path = dest_dir + '/' + dest_name
dest_path_bk = dest_path + '.bk'
# hack the src_name to support machine specific config
# For example, hostapd.conf
# src_name is changed here, so we can't put this before dest_path definition
if os.path.exists(src_dir + '/' + Util.HOST_NAME + '-' + src_name):
src_name = Util.HOST_NAME + '-' + src_name
src_path = src_dir + '/' + src_name
if not os.path.exists(src_path):
Util.warning(src_path + ' does not exist')
return False
need_copy = False
need_bk_tmp = False
has_update = False
if not Util.has_path(dest_path) or Util.has_link(dest_path) != is_sylk:
need_copy = True
need_bk_tmp = True
has_update = True
elif is_sylk: # both are symbolic link
if Util.get_link(dest_path) != src_path:
need_copy = True
need_bk_tmp = True
has_update = True
else: # same link
if not Util.has_path(dest_path_bk):
need_bk_tmp = True
has_update = True
else:
if Util.get_md5(dest_path) != Util.get_md5(dest_path_bk):
need_bk_tmp = True
has_update = True
else: # both are real files
if not os.path.exists(dest_path_bk):
need_bk_tmp = True
if Util.get_md5(dest_path) != Util.get_md5(src_path):
need_copy = True
need_bk_tmp = True
has_update = True
# print need_copy, need_bk_tmp, has_update
need_sudo = Util.need_sudo(dest_dir)
if need_bk_tmp and need_bk:
if Util.HOST_OS == Util.WINDOWS:
os.remove(dest_path_bk)
shutil.copyfile(dest_path, dest_path_bk)
else:
cmd = f'rm -f {dest_path_bk}'
if need_sudo:
cmd = f'sudo {cmd}'
Util.execute(cmd, show_cmd=show_cmd, exit_on_error=False)
cmd = f'cp -f "{dest_path}" "{dest_path_bk}"'
if need_sudo:
cmd = f'sudo {cmd}'
Util.execute(cmd, show_cmd=show_cmd, exit_on_error=False)
if need_copy:
if Util.HOST_OS == Util.WINDOWS:
os.remove(dest_path)
else:
cmd = f'rm "{dest_path}"'
if need_sudo:
cmd = f'sudo {cmd}'
Util.execute(cmd, show_cmd=show_cmd, exit_on_error=False)
if is_sylk:
if Util.HOST_OS == Util.WINDOWS:
cmd = f'mklink "{dest_path}" "{src_path}"'
else:
cmd = f'ln -s {src_path} {dest_path}'
result = Util.execute(cmd, show_cmd=show_cmd)
if result[0]:
error(f'Failed to execute {cmd}. You may need to run cmd with administrator priviledge')
else:
if Util.HOST_OS == Util.WINDOWS:
shutil.copyfile(src_path, dest_path)
else:
cmd = f'cp -rf {src_path} {dest_path}'
if need_sudo:
cmd = f'sudo {cmd}'
result = Util.execute(cmd, show_cmd=show_cmd)
if result[0]:
error(f'Failed to execute {cmd}. You may need to run cmd with administrator priviledge')
return has_update
@staticmethod
def copy_files(src_dir, dest_dir):