-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathmbed.py
executable file
·3470 lines (2957 loc) · 145 KB
/
mbed.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
#!/usr/bin/env python
# Copyright (c) 2016-2019 Arm Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied.
# pylint: disable=too-many-arguments, too-many-locals, too-many-branches, too-many-lines, line-too-long,
# pylint: disable=too-many-nested-blocks, too-many-public-methods, too-many-instance-attributes, too-many-statements
# pylint: disable=invalid-name, missing-docstring, bad-continuation
from __future__ import print_function
try:
# Python 2
basestring = (unicode, str)
from urlparse import urlparse
from urllib2 import urlopen
from urllib import quote
except NameError:
# Python 3
basestring = str
from urllib.parse import urlparse, quote
from urllib.request import urlopen
import traceback
import sys
import re
import subprocess
import os
import json
import platform
import contextlib
import shutil
import stat
import errno
import ctypes
from itertools import chain, repeat
import time
import zipfile
import argparse
from random import randint
from contextlib import contextmanager
# Application version
ver = '1.10.2'
# Default paths to Mercurial and Git
hg_cmd = 'hg'
git_cmd = 'git'
# override python command when running standalone Mbed CLI
python_cmd = sys.executable
if os.path.basename(python_cmd).startswith('mbed'):
python_cmd = 'python'
ignores = [
# Version control folders
".hg",
".git",
".svn",
".CVS",
".cvs",
# Version control fallout
"*.orig",
# mbed Tools
"BUILD",
".build",
".export",
# Online IDE caches
".msub",
".meta",
".ctags*",
# uVision project files
"*.uvproj",
"*.uvopt",
# Eclipse project files
"*.project",
"*.cproject",
"*.launch",
# IAR project files
"*.ewp",
"*.eww",
# GCC make
"/Makefile",
"Debug",
# HTML files
"*.htm",
# Settings files
".mbed",
"*.settings",
"mbed_settings.py",
# Python
"*.py[cod]",
"# subrepo ignores",
]
# git & url (no #rev)
regex_repo_url = r'^(git\://|file\://|ssh\://|https?\://|)(([^/:@]+)(\:([^/:@]+))?@)?([^/:]{3,})(\:\d+)?[:/](.+?)(\.git|\.hg|\/?)$'
# mbed url is subset of hg. mbed doesn't support ssh transport though so https? urls cannot be converted to ssh
regex_mbed_url = r'^(https?)://(([^/:@]+)(\:([^/:@]+))?@)?([\w\-\.]*mbed\.(co\.uk|org|com))(\:\d+)?[:/](.+?)/?$'
# mbed sdk builds url are treated specially
regex_build_url = r'^(https?://([\w\-\.]*mbed\.(co\.uk|org|com))/(users|teams)/([\w\-]{1,32})/(repos|code)/([\w\-]+))/builds/?([\w\-]{6,40}|tip)?/?$'
# valid .lib reference to local (unpublished) repo - dir#rev
regex_local_ref = r'^([\w.+-][\w./+-]*?)/?(?:#(.*))?$'
# valid .lib reference to repo - url#rev
regex_url_ref = r'^(.*/([\w.+-]+)(?:\.\w+)?)/?(?:#(.*))?$'
# match official release tags
regex_rels_official = r'^(release|rel|mbed-os|[rv]+)?[.-]?\d+(\.\d+)*$'
# match rc/beta/alpha release tags
regex_rels_all = r'^(release|rel|mbed-os|[rv]+)?[.-]?\d+(\.\d+)*([a-z0-9.-]+)?$'
# base url for all mbed related repos (used as sort of index)
mbed_base_url = 'https://github.com/ARMmbed'
# default mbed OS url
mbed_os_url = 'https://github.com/ARMmbed/mbed-os'
# default mbed library url
mbed_lib_url = 'https://mbed.org/users/mbed_official/code/mbed/builds/'
# mbed SDK tools needed for programs based on mbed SDK library
mbed_sdk_tools_url = 'https://mbed.org/users/mbed_official/code/mbed-sdk-tools'
# a list of public SCM service (github/butbucket) which support http, https and ssh schemas
public_scm_services = ['bitbucket.org', 'github.com', 'gitlab.com']
# commands that don't get the current work path shown
skip_workpath_commands = ["config", "cfg", "conf"]
# verbose logging
verbose = False
very_verbose = False
install_requirements = True
cache_repositories = True
mbed_app_file_name = "mbed_app.json"
# stores current working directory for recursive operations
cwd_root = ""
_cwd = os.getcwd()
# Logging and output
def log(msg, is_error=False):
sys.stderr.write(msg) if is_error else sys.stdout.write(msg)
def message(msg):
if very_verbose:
return "[mbed-%s] %s\n" % (os.getpid(), msg)
else:
return "[mbed] %s\n" % msg
def info(msg, level=1):
if level <= 0 or verbose:
for line in msg.splitlines():
log(message(line))
def action(msg):
for line in msg.splitlines():
log(message(line))
def warning(msg):
lines = msg.splitlines()
log(message("WARNING: %s" % lines.pop(0)), True)
for line in lines:
log(" %s\n" % line, True)
log("---\n", True)
def error(msg, code=-1):
lines = msg.splitlines()
log(message("ERROR: %s" % lines.pop(0)), True)
for line in lines:
log(" %s\n" % line, True)
log("---\n", True)
sys.exit(code)
def offline_warning(offline, top=True):
if top and offline:
log("\n")
log(".=============================== OFFLINE MODE ================================.\n")
log("| Offline mode is enabled. No connections to remote repositories will be |\n")
log("| made and only locally cached repositories will be used. |\n")
log("| This might break some actions if non-cached repositories are referenced. |\n")
log("'============================================================================='\n\n")
def progress_cursor():
while True:
for cursor in '|/-\\':
yield cursor
progress_spinner = progress_cursor()
def progress():
sys.stdout.write(next(progress_spinner))
sys.stdout.flush()
sys.stdout.write('\b')
def show_progress(title, percent, max_width=80):
if sys.stdout.isatty():
percent = round(float(percent), 2)
show_percent = '%.2f' % percent
bwidth = max_width - len(str(title)) - len(show_percent) - 6 # 6 equals the spaces and paddings between title, progress bar and percentage
sys.stdout.write('%s |%s%s| %s%%\r' % (str(title), '#' * int(percent * bwidth // 100), '-' * (bwidth - int(percent * bwidth // 100)), show_percent))
sys.stdout.flush()
def hide_progress(max_width=80):
if sys.stdout.isatty():
sys.stdout.write("\r%s\r" % (' ' * max_width))
def create_default_mbed_app():
# Default data content
if not os.path.exists(mbed_app_file_name):
data = {'target_overrides':{'*':{'platform.stdio-baud-rate': 9600}}}
with open(mbed_app_file_name, "w") as mbed_app_file:
json.dump(data, mbed_app_file, indent=4)
# Process execution
class ProcessException(Exception):
pass
def popen(command, **kwargs):
# print for debugging
info("Exec \"%s\" in \"%s\"" % (' '.join(command), getcwd()))
proc = None
try:
proc = subprocess.Popen(command, **kwargs)
except OSError as e:
if e.args[0] == errno.ENOENT:
error(
"Could not execute \"%s\" in \"%s\".\n"
"You can verify that it's installed and accessible from your current path by executing \"%s\".\n" % (' '.join(command), getcwd(), command[0]), e.args[0])
else:
raise e
if proc and proc.wait() != 0:
raise ProcessException(proc.returncode, command[0], ' '.join(command), getcwd())
return proc
def pquery(command, output_callback=None, stdin=None, **kwargs):
if very_verbose:
info("Exec \"%s\" in \"%s\"" % (' '.join(command), getcwd()))
try:
proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
except OSError as e:
if e.args[0] == errno.ENOENT:
error(
"Could not execute \"%s\" in \"%s\".\n"
"You can verify that it's installed and accessible from your current path by executing \"%s\".\n" % (' '.join(command), getcwd(), command[0]), e.args[0])
else:
raise e
if output_callback:
line = ""
while 1:
s = str(proc.stderr.read(1))
line += s
if s == '\r' or s == '\n':
output_callback(line, s)
line = ""
if proc.returncode is None:
proc.poll()
else:
break
stdout, _ = proc.communicate(stdin)
if very_verbose:
log(stdout.decode(sys.getfilesystemencoding()).strip() + "\n")
if proc.returncode != 0:
raise ProcessException(proc.returncode, command[0], ' '.join(command), getcwd())
return stdout.decode(sys.getfilesystemencoding())
def rmtree_readonly(directory):
if os.path.islink(directory):
os.remove(directory)
else:
def remove_readonly(func, path, _):
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree(directory, onerror=remove_readonly)
def sizeof_fmt(num, suffix='B'):
for unit in ['','K','M','G','T','P','E','Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
# Directory navigation
@contextlib.contextmanager
def cd(newdir):
global _cwd
prevdir = getcwd()
os.chdir(newdir)
_cwd = newdir
try:
yield
finally:
os.chdir(prevdir)
_cwd = prevdir
def getcwd():
global _cwd
return _cwd
def relpath(root, path):
return path[len(root)+1:]
def staticclass(cls):
for k, v in cls.__dict__.items():
if hasattr(v, '__call__') and not k.startswith('__'):
setattr(cls, k, staticmethod(v))
return cls
# Handling for multiple version controls
scms = {}
def scm(name):
def _scm(cls):
scms[name] = cls()
return cls
return _scm
# pylint: disable=no-self-argument, no-method-argument, no-member, no-self-use, unused-argument
@scm('bld')
@staticclass
class Bld(object):
name = 'bld'
default_branch = 'default'
def init(path):
if not os.path.exists(path):
os.mkdir(path)
else:
if len(os.listdir(path)) > 1:
error("Directory \"%s\" is not empty." % path)
def cleanup():
info("Cleaning up library build folder")
for fl in os.listdir('.'):
if not fl.startswith('.'):
if os.path.isfile(fl):
os.remove(fl)
else:
shutil.rmtree(fl)
def clone(url, path=None, depth=None, protocol=None):
m = Bld.isvalidurl(url)
if not m:
raise ProcessException(1, "Not a library build URL")
try:
Bld.init(path)
with cd(path):
rev = Hg.remoteid(m.group(1), 'tip')
if not rev:
error("Unable to fetch library build information")
Bld.seturl(url+'/'+rev)
except Exception as e:
if os.path.isdir(path):
rmtree_readonly(path)
error(e.args[1], e.args[0])
def fetch_rev(url, rev):
rev_file = os.path.join('.'+Bld.name, '.rev-' + rev + '.zip')
try:
if not os.path.exists(rev_file):
action("Downloading library build \"%s\" (might take a while)" % rev)
inurl = urlopen(url)
with open(rev_file, 'wb') as outfd:
data = None
while data != '':
# Download and write the data in 1 MB chunks
data = inurl.read(1024 * 1024)
outfd.write(data)
except Exception:
if os.path.isfile(rev_file):
os.remove(rev_file)
raise Exception(128, "Download failed!\nPlease try again later.")
def unpack_rev(rev):
rev_file = os.path.join('.'+Bld.name, '.rev-' + rev + '.zip')
try:
with zipfile.ZipFile(rev_file) as zf:
action("Unpacking library build \"%s\" in \"%s\"" % (rev, getcwd()))
zf.extractall('.')
except:
if os.path.isfile(rev_file):
os.remove(rev_file)
raise Exception(128, "An error occurred while unpacking library archive \"%s\" in \"%s\"" % (rev_file, getcwd()))
def checkout(rev, clean=False):
url = Bld.geturl()
m = Bld.isvalidurl(url)
if not m:
raise ProcessException(1, "Not a library build URL")
rev = Hg.remoteid(m.group(1), rev)
if not rev:
error("Unable to fetch library build information")
arch_url = m.group(1) + '/archive/' + rev + '.zip'
Bld.fetch_rev(arch_url, rev)
if rev != Bld.getrev() or clean:
Bld.cleanup()
info("Checkout \"%s\" in %s" % (rev, os.path.basename(getcwd())))
try:
Bld.unpack_rev(rev)
Bld.seturl(url+'/'+rev)
except Exception as e:
error(e.args[1], e.args[0])
def update(rev=None, clean=False, clean_files=False, is_local=False):
return Bld.checkout(rev, clean)
def untracked():
return ""
def isvalidurl(url):
return re.match(regex_build_url, url.strip().replace('\\', '/'))
def seturl(url):
info("Setting url to \"%s\" in %s" % (url, getcwd()))
if not os.path.exists('.'+Bld.name):
os.mkdir('.'+Bld.name)
fl = os.path.join('.'+Bld.name, 'bldrc')
try:
with open(fl, 'w') as f:
f.write(url)
except IOError:
error("Unable to write bldrc file in \"%s\"" % fl, 1)
def geturl():
with open(os.path.join('.bld', 'bldrc')) as f:
url = f.read().strip()
m = Bld.isvalidurl(url)
return m.group(1)+'/builds' if m else ''
def getrev():
with open(os.path.join('.bld', 'bldrc')) as f:
url = f.read().strip()
m = Bld.isvalidurl(url)
return m.group(8) if m else ''
def getbranch():
return "default"
def gettags(rev=None):
return []
# pylint: disable=no-self-argument, no-method-argument, no-member, no-self-use, unused-argument
@scm('hg')
@staticclass
class Hg(object):
name = 'hg'
default_branch = 'default'
ignore_file = os.path.join('.hg', 'hgignore')
def init(path=None):
popen([hg_cmd, 'init'] + ([path] if path else []) + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def cleanup():
return True
def clone(url, name=None, depth=None, protocol=None):
if verbose or very_verbose:
popen([hg_cmd, 'clone', formaturl(url, protocol), name] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
else:
pquery([hg_cmd, 'clone', '--config', 'progress.assume-tty=true', formaturl(url, protocol), name], output_callback=Hg.action_progress)
hide_progress()
def add(dest):
info("Adding reference \"%s\"" % dest)
try:
popen([hg_cmd, 'add', dest] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
except ProcessException:
pass
def remove(dest):
info("Removing reference \"%s\" " % dest)
try:
pquery([hg_cmd, 'rm', '-f', dest] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
except ProcessException:
pass
def commit(msg=None):
popen([hg_cmd, 'commit'] + (['-m', msg] if msg else []) + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def publish(all_refs=None):
popen([hg_cmd, 'push'] + (['--new-branch'] if all_refs else []) + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def fetch():
info("Fetching revisions from remote repository to \"%s\"" % os.path.basename(getcwd()))
popen([hg_cmd, 'pull'] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def discard():
info("Discarding local changes in \"%s\"" % os.path.basename(getcwd()))
popen([hg_cmd, 'update', '-C'] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def checkout(rev, clean=False, clean_files=False):
info("Checkout \"%s\" in %s" % (rev if rev else "latest", os.path.basename(getcwd())))
if clean_files:
files = pquery([hg_cmd, 'status', '--no-status', '-ui']).splitlines()
for f in files:
info("Remove untracked file \"%s\"" % f)
os.remove(f)
popen([hg_cmd, 'update'] + (['-C'] if clean else []) + (['-r', rev] if rev else []) + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def update(rev=None, clean=False, clean_files=False, is_local=False):
if not is_local:
Hg.fetch()
Hg.checkout(rev, clean, clean_files)
def status():
return pquery([hg_cmd, 'status'] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def dirty():
return pquery([hg_cmd, 'status', '-q'])
def untracked():
return pquery([hg_cmd, 'status', '--no-status', '-u']).splitlines()
def outgoing():
try:
pquery([hg_cmd, 'outgoing'])
return 1
except ProcessException as e:
if e.args[0] != 1:
raise e
return 0
def seturl(url):
info("Setting url to \"%s\" in %s" % (url, getcwd()))
hgrc = os.path.join('.hg', 'hgrc')
tagpaths = '[paths]'
remote = 'default'
lines = []
try:
with open(hgrc) as f:
lines = f.read().splitlines()
except IOError:
pass
if tagpaths in lines:
idx = lines.index(tagpaths)
m = re.match(r'^([\w_]+)\s*=\s*(.*)$', lines[idx+1])
if m:
remote = m.group(1)
del lines[idx+1]
lines.insert(idx, remote+' = '+url)
else:
lines.append(tagpaths)
lines.append(remote+' = '+url)
def geturl():
tagpaths = '[paths]'
default_url = ''
url = ''
try:
with open(os.path.join('.hg', 'hgrc')) as f:
lines = f.read().splitlines()
if tagpaths in lines:
idx = lines.index(tagpaths)
m = re.match(r'^([\w_]+)\s*=\s*(.*)$', lines[idx+1])
if m:
if m.group(1) == 'default':
default_url = m.group(2)
else:
url = m.group(2)
except IOError:
pass
if default_url:
url = default_url
return formaturl(url or pquery([hg_cmd, 'paths', 'default']).strip())
def getrev():
if os.path.isfile(os.path.join('.hg', 'dirstate')):
from io import open
with open(os.path.join('.hg', 'dirstate'), 'rb') as f:
return "".join('{:02x}'.format(x) for x in bytearray(f.read(6)))
else:
return ""
def getbranch():
return pquery([hg_cmd, 'branch']).strip() or ""
def gettags():
tags = []
refs = pquery([hg_cmd, 'tags']).strip().splitlines() or []
for ref in refs:
m = re.match(r'^(.+?)\s+(\d+)\:([a-f0-9]+)$', ref)
if m:
tags.append([m.group(3), m.group(1)])
return tags
def remoteid(url, rev=None):
return pquery([hg_cmd, 'id', '--id', url] + (['-r', rev] if rev else [])).strip() or ""
def hgrc():
hook = 'ignore.local = .hg/hgignore'
hgrc = os.path.join('.hg', 'hgrc')
try:
with open(hgrc) as f:
exists = hook in f.read().splitlines()
except IOError:
exists = False
if not exists:
try:
with open(hgrc, 'a') as f:
f.write('[ui]\n')
f.write(hook + '\n')
except IOError:
error("Unable to write hgrc file in \"%s\"" % hgrc, 1)
def ignores():
Hg.hgrc()
try:
with open(Hg.ignore_file, 'w') as f:
f.write("syntax: glob\n"+'\n'.join(ignores)+'\n')
except IOError:
error("Unable to write ignore file in \"%s\"" % os.path.join(getcwd(), Hg.ignore_file), 1)
def ignore(dest):
Hg.hgrc()
try:
with open(Hg.ignore_file) as f:
exists = dest in f.read().splitlines()
except IOError:
exists = False
if not exists:
try:
with open(Hg.ignore_file, 'a') as f:
f.write(dest + '\n')
except IOError:
error("Unable to write ignore file in \"%s\"" % os.path.join(getcwd(), Hg.ignore_file), 1)
def unignore(dest):
Hg.ignore_file = os.path.join('.hg', 'hgignore')
try:
with open(Hg.ignore_file) as f:
lines = f.read().splitlines()
except IOError:
lines = []
if dest in lines:
lines.remove(dest)
try:
with open(Hg.ignore_file, 'w') as f:
f.write('\n'.join(lines) + '\n')
except IOError:
error("Unable to write ignore file in \"%s\"" % os.path.join(getcwd(), Hg.ignore_file), 1)
def action_progress(line, sep):
m = re.match(r'(\w+).+?\s+(\d+)/(\d+)\s+.*?', line)
if m:
if m.group(1) == "manifests":
show_progress('Downloading', (float(m.group(2)) / float(m.group(3))) * 20)
if m.group(1) == "files":
show_progress('Downloading', (float(m.group(2)) / float(m.group(3))) * 100)
# pylint: disable=no-self-argument, no-method-argument, no-member, no-self-use, unused-argument
@scm('git')
@staticclass
class Git(object):
name = 'git'
default_branch = 'master'
ignore_file = os.path.join('.git', 'info', 'exclude')
def init(path=None):
popen([git_cmd, 'init'] + ([path] if path else []) + ([] if very_verbose else ['-q']))
def cleanup():
info("Cleaning up Git index")
pquery([git_cmd, 'checkout', '--detach', 'HEAD'] + ([] if very_verbose else ['-q'])) # detach head so local branches are deletable
branches = []
lines = pquery([git_cmd, 'branch']).strip().splitlines() # fetch all local branches
for line in lines:
if re.match(r'^\*?\s+\((.+)\)$', line):
continue
line = re.sub(r'\s+', '', line)
branches.append(line)
for branch in branches: # delete all local branches so the new repo clone is not poluted
pquery([git_cmd, 'branch', '-D', branch])
def clone(url, name=None, depth=None, protocol=None):
if verbose or very_verbose:
popen([git_cmd, 'clone', formaturl(url, protocol), name] + (['--depth', depth] if depth else []) + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
else:
pquery([git_cmd, 'clone', '--progress', formaturl(url, protocol), name] + (['--depth', depth] if depth else []), output_callback=Git.action_progress)
hide_progress()
def add(dest):
info("Adding reference "+dest)
try:
popen([git_cmd, 'add', dest] + (['-v'] if very_verbose else []))
except ProcessException:
pass
def remove(dest):
info("Removing reference "+dest)
try:
pquery([git_cmd, 'rm', '-f', dest] + ([] if very_verbose else ['-q']))
except ProcessException:
pass
def commit(msg=None):
popen([git_cmd, 'commit', '-a'] + (['-m', msg] if msg else []) + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def publish(all_refs=None):
if all_refs:
popen([git_cmd, 'push', '--all'] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
else:
remote = Git.getremote()
branch = Git.getbranch()
if remote and branch:
popen([git_cmd, 'push', remote, branch] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
else:
err = "Unable to publish outgoing changes for \"%s\" in \"%s\".\n" % (os.path.basename(getcwd()), getcwd())
if not remote:
error(err+"The local repository is not associated with a remote one.", 1)
if not branch:
error(err+"Working set is not on a branch.", 1)
def fetch():
info("Fetching revisions from remote repository to \"%s\"" % os.path.basename(getcwd()))
popen([git_cmd, 'fetch', '--all', '--tags', '--force'] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def discard(clean_files=False):
info("Discarding local changes in \"%s\"" % os.path.basename(getcwd()))
pquery([git_cmd, 'reset', 'HEAD'] + ([] if very_verbose else ['-q'])) # unmarks files for commit
pquery([git_cmd, 'checkout', '.'] + ([] if very_verbose else ['-q'])) # undo modified files
pquery([git_cmd, 'clean', '-fd'] + (['-x'] if clean_files else []) + (['-q'] if very_verbose else ['-q'])) # cleans up untracked files and folders
def merge(dest):
info("Merging \"%s\" with \"%s\"" % (os.path.basename(getcwd()), dest))
popen([git_cmd, 'merge', dest] + (['-v'] if very_verbose else ([] if verbose else ['-q'])))
def checkout(rev, clean=False):
if not rev:
return
info("Checkout \"%s\" in %s" % (rev, os.path.basename(getcwd())))
branch = None
refs = Git.getbranches(rev)
for ref in refs: # re-associate with a local or remote branch (rev is the same)
m = re.match(r'^(.*?)\/(.*?)$', ref)
if m and m.group(2) != "HEAD": # matches origin/<branch> and isn't HEAD ref
if not os.path.exists(os.path.join('.git', 'refs', 'heads', m.group(2))): # okay only if local branch with that name doesn't exist (git will checkout the origin/<branch> in that case)
branch = m.group(2)
elif ref != "HEAD":
branch = ref # matches local branch and isn't HEAD ref
if branch:
info("Revision \"%s\" matches a branch \"%s\" reference. Re-associating with branch" % (rev, branch))
popen([git_cmd, 'checkout', branch] + ([] if very_verbose else ['-q']))
break
if not branch:
popen([git_cmd, 'checkout', rev] + (['-f'] if clean else []) + ([] if very_verbose else ['-q']))
def update(rev=None, clean=False, clean_files=False, is_local=False):
if not is_local:
Git.fetch()
if clean:
Git.discard(clean_files)
if rev:
Git.checkout(rev, clean)
else:
remote = Git.getremote()
branch = Git.getbranch()
if remote and branch:
try:
Git.merge('%s/%s' % (remote, branch))
except ProcessException:
pass
else:
err = "Unable to update \"%s\" in \"%s\"." % (os.path.basename(getcwd()), getcwd())
if not remote:
info(err+"\nThe local repository is not associated with a remote one.\nYou should associate your repository with a remote one.")
if not branch:
info(err+"\nThe working set is not on a branch.\nYou should switch to a branch or create a new one from the current revision.")
def status():
return pquery([git_cmd, 'status', '-s'] + (['-v'] if very_verbose else []))
def dirty():
return pquery([git_cmd, 'status', '-uno', '--porcelain'])
def untracked():
return pquery([git_cmd, 'ls-files', '--others', '--exclude-standard']).splitlines()
def outgoing():
# Get default remote
remote = Git.getremote()
if not remote:
return -1
# Get current branch
branch = Git.getbranch()
if not branch:
# Default to "master" in detached mode
branch = "master"
# Check if local branch exists. If not, then just carry on
try:
pquery([git_cmd, 'rev-parse', '%s' % branch])
except ProcessException:
return 0
# Check if remote branch exists. If not, then it's a new branch
try:
if not pquery([git_cmd, 'rev-parse', '%s/%s' % (remote, branch)]):
return 1
except ProcessException:
return 1
# Check for outgoing commits for the same remote branch only if it exists locally and remotely
return 1 if pquery([git_cmd, 'log', '%s/%s..%s' % (remote, branch, branch)]) else 0
# Checks whether current working tree is detached
def isdetached():
return True if Git.getbranch() == "" else False
# Finds default remote
def getremote():
remote = None
remotes = Git.getremotes('push')
for r in remotes:
remote = r[0]
# Prefer origin which is Git's default remote when cloning
if r[0] == "origin":
break
return remote
# Finds all associated remotes for the specified remote type
def getremotes(rtype='fetch'):
result = []
remotes = pquery([git_cmd, 'remote', '-v']).strip().splitlines()
for remote in remotes:
remote = re.split(r'\s', remote)
t = re.sub('[()]', '', remote[2])
if not rtype or rtype == t:
result.append([remote[0], remote[1], t])
return result
def seturl(url):
info("Setting url to \"%s\" in %s" % (url, getcwd()))
return pquery([git_cmd, 'remote', 'set-url', 'origin', url]).strip()
def geturl():
url = ""
remotes = Git.getremotes()
for remote in remotes:
url = remote[1]
if remote[0] == "origin": # Prefer origin URL
break
return formaturl(url)
def getrev():
return pquery([git_cmd, 'rev-parse', 'HEAD']).strip()
# Gets current branch or returns empty string if detached
def getbranch(rev='HEAD'):
try:
branch = pquery([git_cmd, 'rev-parse', '--symbolic-full-name', '--abbrev-ref', rev]).strip()
except ProcessException:
branch = "master"
return branch if branch != "HEAD" else ""
# Get all refs
def getrefs():
try:
return pquery([git_cmd, 'show-ref', '--dereference']).strip().splitlines()
except ProcessException:
return []
# Finds branches (local or remote). Will match rev if specified
def getbranches(rev=None, ret_rev=False):
result = []
refs = Git.getrefs()
for ref in refs:
m = re.match(r'^(.+)\s+refs\/(heads|remotes)\/(.+)$', ref)
if m and (not rev or m.group(1).startswith(rev)):
result.append(m.group(1) if ret_rev else m.group(3))
return result
# Finds tags. Will match rev if specified
def gettags():
tags = []
refs = Git.getrefs()
for ref in refs:
m = re.match(r'^(.+)\s+refs\/tags\/(.+)$', ref)
if m:
t = m.group(2)
if re.match(r'^(.+)\^\{\}$', t): # detect tag "pointer"
t = re.sub(r'\^\{\}$', '', t) # remove "pointer" chars, e.g. some-tag^{}
for tag in tags:
if tag[1] == t:
tags.remove(tag)
tags.append([m.group(1), t])
return tags
# Finds branches a rev belongs to
def revbranches(rev):
branches = []
lines = pquery([git_cmd, 'branch', '-a', '--contains'] + ([rev] if rev else [])).strip().splitlines()
for line in lines:
if re.match(r'^\*?\s+\((.+)\)$', line):
continue
line = re.sub(r'\s+', '', line)
branches.append(line)
return branches
def ignores():
try:
ignore_file_parent_directory = os.path.dirname(Git.ignore_file)
if not os.path.exists(ignore_file_parent_directory):
os.mkdir(ignore_file_parent_directory)
with open(Git.ignore_file, 'w') as f:
f.write('\n'.join(ignores)+'\n')
except IOError:
error("Unable to write ignore file in \"%s\"" % os.path.join(getcwd(), Git.ignore_file), 1)
def ignore(dest):
try:
with open(Git.ignore_file) as f:
exists = dest in f.read().splitlines()
except IOError:
exists = False
if not exists:
try:
ignore_file_parent_directory = os.path.dirname(Git.ignore_file)
if not os.path.exists(ignore_file_parent_directory):
os.mkdir(ignore_file_parent_directory)
with open(Git.ignore_file, 'a') as f:
f.write(dest.replace("\\", "/") + '\n')
except IOError:
error("Unable to write ignore file in \"%s\"" % os.path.join(getcwd(), Git.ignore_file), 1)
def unignore(dest):
try:
with open(Git.ignore_file) as f:
lines = f.read().splitlines()
except IOError:
lines = []
if dest in lines:
lines.remove(dest)
try:
ignore_file_parent_directory = os.path.dirname(Git.ignore_file)
if not os.path.exists(ignore_file_parent_directory):
os.mkdir(ignore_file_parent_directory)
with open(Git.ignore_file, 'w') as f:
f.write('\n'.join(lines) + '\n')
except IOError:
error("Unable to write ignore file in \"%s\"" % os.path.join(getcwd(), Git.ignore_file), 1)
def action_progress(line, sep):
m = re.match(r'([\w :]+)\:\s*(\d+)% \((\d+)/(\d+)\)', line)
if m:
if m.group(1) == "remote: Compressing objects" and int(m.group(4)) > 100:
show_progress('Preparing', (float(m.group(3)) / float(m.group(4))) * 100)
if m.group(1) == "Receiving objects":
show_progress('Downloading', (float(m.group(3)) / float(m.group(4))) * 80)
if m.group(1) == "Resolving deltas":