-
Notifications
You must be signed in to change notification settings - Fork 177
/
core.py
8904 lines (7755 loc) · 323 KB
/
core.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
# Copyright (C) 2006 Novell Inc. All rights reserved.
# This program is free software; it may be used, copied, modified
# and distributed under the terms of the GNU General Public Licence,
# either version 2, or version 3 (at your option).
# __store_version__ is to be incremented when the format of the working copy
# "store" changes in an incompatible way. Please add any needed migration
# functionality to check_store_version().
__store_version__ = '1.0'
import codecs
import copy
import datetime
import difflib
import errno
import fnmatch
import glob
import hashlib
import locale
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time
from functools import cmp_to_key, total_ordering
from http.client import IncompleteRead
from io import StringIO
from pathlib import Path
from typing import Optional, Dict, Union, List, Iterable
from urllib.parse import urlsplit, urlunsplit, urlparse, quote_plus, urlencode, unquote
from urllib.error import HTTPError
from urllib.request import pathname2url
from xml.etree import ElementTree as ET
try:
import distro
except ImportError:
distro = None
from . import __version__
from . import _private
from . import conf
from . import meter
from . import oscerr
from .connection import http_request, http_GET, http_POST, http_PUT, http_DELETE
from .store import Store
from .util.helper import decode_list, decode_it, raw_input, _html_escape
ET_ENCODING = "unicode"
def compare(a, b): return cmp(a[1:], b[1:])
def cmp(a, b):
return (a > b) - (a < b)
DISTURL_RE = re.compile(r"^(?P<bs>.*)://(?P<apiurl>.*?)/(?P<project>.*?)/(?P<repository>.*?)/(?P<revision>.*)-(?P<source>.*)$")
BUILDLOGURL_RE = re.compile(r"^(?P<apiurl>https?://.*?)/build/(?P<project>.*?)/(?P<repository>.*?)/(?P<arch>.*?)/(?P<package>.*?)/_log$")
BUFSIZE = 1024 * 1024
store = '.osc'
new_project_templ = """\
<project name="%(name)s">
<title></title> <!-- Short title of NewProject -->
<description></description>
<!-- This is for a longer description of the purpose of the project -->
<person role="maintainer" userid="%(user)s" />
<person role="bugowner" userid="%(user)s" />
<!-- remove this block to publish your packages on the mirrors -->
<publish>
<disable />
</publish>
<build>
<enable />
</build>
<debuginfo>
<enable />
</debuginfo>
<!-- remove this comment to enable one or more build targets
<repository name="openSUSE_Factory">
<path project="openSUSE:Factory" repository="snapshot" />
<arch>x86_64</arch>
<arch>i586</arch>
</repository>
<repository name="openSUSE_13.2">
<path project="openSUSE:13.2" repository="standard"/>
<arch>x86_64</arch>
<arch>i586</arch>
</repository>
<repository name="openSUSE_13.1">
<path project="openSUSE:13.1" repository="standard"/>
<arch>x86_64</arch>
<arch>i586</arch>
</repository>
<repository name="Fedora_21">
<path project="Fedora:21" repository="standard" />
<arch>x86_64</arch>
<arch>i586</arch>
</repository>
<repository name="SLE_12">
<path project="SUSE:SLE-12:GA" repository="standard" />
<arch>x86_64</arch>
<arch>i586</arch>
</repository>
-->
</project>
"""
new_package_templ = """\
<package name="%(name)s">
<title></title> <!-- Title of package -->
<description></description> <!-- for long description -->
<!-- following roles are inherited from the parent project
<person role="maintainer" userid="%(user)s"/>
<person role="bugowner" userid="%(user)s"/>
-->
<!--
<url>PUT_UPSTREAM_URL_HERE</url>
-->
<!--
use one of the examples below to disable building of this package
on a certain architecture, in a certain repository,
or a combination thereof:
<disable arch="x86_64"/>
<disable repository="SUSE_SLE-10"/>
<disable repository="SUSE_SLE-10" arch="x86_64"/>
Possible sections where you can use the tags above:
<build>
</build>
<debuginfo>
</debuginfo>
<publish>
</publish>
<useforbuild>
</useforbuild>
Please have a look at:
http://en.opensuse.org/Restricted_formats
Packages containing formats listed there are NOT allowed to
be packaged in the openSUSE Buildservice and will be deleted!
-->
</package>
"""
new_attribute_templ = """\
<attributes>
<attribute namespace="" name="">
<value><value>
</attribute>
</attributes>
"""
new_user_template = """\
<person>
<login>%(user)s</login>
<email>PUT_EMAIL_ADDRESS_HERE</email>
<realname>PUT_REAL_NAME_HERE</realname>
<watchlist>
<project name="home:%(user)s"/>
</watchlist>
</person>
"""
new_group_template = """\
<group>
<title>%(group)s</title>
<person>
<person userid=""/>
</person>
</group>
"""
info_templ = """\
Project name: %s
Package name: %s
Path: %s
API URL: %s
Source URL: %s
srcmd5: %s
Revision: %s
Link info: %s
"""
new_pattern_template = """\
<!-- See https://github.com/openSUSE/libzypp/tree/master/zypp/parser/yum/schema/patterns.rng -->
<!--
<pattern xmlns="http://novell.com/package/metadata/suse/pattern"
xmlns:rpm="http://linux.duke.edu/metadata/rpm">
<name></name>
<summary></summary>
<description></description>
<uservisible/>
<category lang="en"></category>
<rpm:requires>
<rpm:entry name="must-have-package"/>
</rpm:requires>
<rpm:recommends>
<rpm:entry name="package"/>
</rpm:recommends>
<rpm:suggests>
<rpm:entry name="anotherpackage"/>
</rpm:suggests>
</pattern>
-->
"""
buildstatus_symbols = {'succeeded': '.',
'disabled': ' ',
'expansion error': 'U', # obsolete with OBS 2.0
'unresolvable': 'U',
'failed': 'F',
'broken': 'B',
'blocked': 'b',
'building': '%',
'finished': 'f',
'scheduled': 's',
'locked': 'L',
'excluded': 'x',
'dispatching': 'd',
'signing': 'S',
}
# os.path.samefile is available only under Unix
def os_path_samefile(path1, path2):
try:
return os.path.samefile(path1, path2)
except AttributeError:
return os.path.realpath(path1) == os.path.realpath(path2)
@total_ordering
class File:
"""represent a file, including its metadata"""
def __init__(self, name, md5, size, mtime, skipped=False):
self.name = name
self.md5 = md5
self.size = size
self.mtime = mtime
self.skipped = skipped
def __repr__(self):
return self.name
def __str__(self):
return self.name
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
self_data = (self.name, self.md5, self.size, self.mtime, self.skipped)
other_data = (other.name, other.md5, other.size, other.mtime, other.skipped)
return self_data == other_data
def __lt__(self, other):
self_data = (self.name, self.md5, self.size, self.mtime, self.skipped)
other_data = (other.name, other.md5, other.size, other.mtime, other.skipped)
return self_data < other_data
@classmethod
def from_xml_node(cls, node):
assert node.tag == "entry"
kwargs = {
"name": node.get("name"),
"md5": node.get("md5"),
"size": int(node.get("size")),
"mtime": int(node.get("mtime")),
"skipped": "skipped" in node.attrib,
}
return cls(**kwargs)
def to_xml_node(self, parent_node):
attributes = {
"name": self.name,
"md5": self.md5,
"size": str(int(self.size)),
"mtime": str(int(self.mtime)),
}
if self.skipped:
attributes["skipped"] = "true"
new_node = ET.SubElement(parent_node, "entry", attributes)
return new_node
class Serviceinfo:
"""Source service content
"""
def __init__(self):
"""creates an empty serviceinfo instance"""
self.services = []
self.apiurl: Optional[str] = None
self.project: Optional[str] = None
self.package: Optional[str] = None
def read(self, serviceinfo_node, append=False):
"""read in the source services ``<services>`` element passed as
elementtree node.
"""
def error(msg, xml):
data = 'invalid service format:\n%s' % ET.tostring(xml, encoding=ET_ENCODING)
raise ValueError("%s\n\n%s" % (data, msg))
if serviceinfo_node is None:
return
if not append:
self.services = []
services = serviceinfo_node.findall('service')
for service in services:
name = service.get('name')
if name is None:
error("invalid service definition. Attribute name missing.", service)
if len(name) < 3 or '/' in name:
error("invalid service name: %s" % name, service)
mode = service.get('mode', '')
data = {'name': name, 'mode': mode}
command = [name]
for param in service.findall('param'):
option = param.get('name')
if option is None:
error("%s: a parameter requires a name" % name, service)
value = ''
if param.text:
value = param.text
command.append('--' + option)
# hmm is this reasonable or do we want to allow real
# options (e.g., "--force" (without an argument)) as well?
command.append(value)
data['command'] = command
self.services.append(data)
def getProjectGlobalServices(self, apiurl: str, project: str, package: str):
self.apiurl = apiurl
# get all project wide services in one file, we don't store it yet
u = makeurl(apiurl, ['source', project, package], query='cmd=getprojectservices')
try:
f = http_POST(u)
root = ET.parse(f).getroot()
self.read(root, True)
self.project = project
self.package = package
except HTTPError as e:
if e.code == 404 and package != '_project':
self.getProjectGlobalServices(apiurl, project, '_project')
self.package = package
elif e.code != 403 and e.code != 400:
raise e
def addVerifyFile(self, serviceinfo_node, filename: str):
f = open(filename, 'rb')
digest = hashlib.sha256(f.read()).hexdigest()
f.close()
r = serviceinfo_node
s = ET.Element("service", name="verify_file")
ET.SubElement(s, "param", name="file").text = filename
ET.SubElement(s, "param", name="verifier").text = "sha256"
ET.SubElement(s, "param", name="checksum").text = digest
r.append(s)
return r
def addDownloadUrl(self, serviceinfo_node, url_string: str):
url = urlparse(url_string)
protocol = url.scheme
host = url.netloc
path = url.path
r = serviceinfo_node
s = ET.Element("service", name="download_url")
ET.SubElement(s, "param", name="protocol").text = protocol
ET.SubElement(s, "param", name="host").text = host
ET.SubElement(s, "param", name="path").text = path
r.append(s)
return r
def addSetVersion(self, serviceinfo_node):
r = serviceinfo_node
s = ET.Element("service", name="set_version", mode="buildtime")
r.append(s)
return r
def addGitUrl(self, serviceinfo_node, url_string: Optional[str]):
r = serviceinfo_node
s = ET.Element("service", name="obs_scm")
ET.SubElement(s, "param", name="url").text = url_string
ET.SubElement(s, "param", name="scm").text = "git"
r.append(s)
return r
def addTarUp(self, serviceinfo_node):
r = serviceinfo_node
s = ET.Element("service", name="tar", mode="buildtime")
r.append(s)
return r
def addRecompressTar(self, serviceinfo_node):
r = serviceinfo_node
s = ET.Element("service", name="recompress", mode="buildtime")
ET.SubElement(s, "param", name="file").text = "*.tar"
ET.SubElement(s, "param", name="compression").text = "xz"
r.append(s)
return r
def execute(self, dir, callmode: Optional[str] = None, singleservice=None, verbose: Optional[bool] = None):
old_dir = os.path.join(dir, '.old')
# if 2 osc instances are executed at a time one, of them fails on .old file existence
# sleep up to 10 seconds until we can create the directory
for i in reversed(range(10)):
try:
os.mkdir(old_dir)
break
except FileExistsError:
time.sleep(1)
if i == 0:
msg = f'"{old_dir}" exists, please remove it'
raise oscerr.OscIOError(None, msg)
try:
result = self._execute(dir, old_dir, callmode, singleservice, verbose)
finally:
shutil.rmtree(old_dir)
return result
def _execute(
self, dir, old_dir, callmode: Optional[str] = None, singleservice=None, verbose: Optional[bool] = None
):
# cleanup existing generated files
for filename in os.listdir(dir):
if filename.startswith('_service:') or filename.startswith('_service_'):
os.rename(os.path.join(dir, filename),
os.path.join(old_dir, filename))
allservices = self.services or []
service_names = [s['name'] for s in allservices]
if singleservice and singleservice not in service_names:
# set array to the manual specified singleservice, if it is not part of _service file
data = {'name': singleservice, 'command': [singleservice], 'mode': callmode}
allservices = [data]
elif singleservice:
allservices = [s for s in allservices if s['name'] == singleservice]
# set the right called mode or the service would be skipped below
for s in allservices:
s['mode'] = callmode
if not allservices:
# short-circuit to avoid a potential http request in vc_export_env
# (if there are no services to execute this http request is
# useless)
return 0
# services can detect that they run via osc this way
os.putenv("OSC_VERSION", get_osc_version())
# set environment when using OBS 2.3 or later
if self.project is not None:
# These need to be kept in sync with bs_service
os.putenv("OBS_SERVICE_APIURL", self.apiurl)
os.putenv("OBS_SERVICE_PROJECT", self.project)
os.putenv("OBS_SERVICE_PACKAGE", self.package)
# also export vc env vars (some services (like obs_scm) use them)
vc_export_env(self.apiurl)
# recreate files
ret = 0
for service in allservices:
if callmode != "all":
if service['mode'] == "buildtime":
continue
if service['mode'] == "serveronly" and callmode != "local":
continue
if service['mode'] == "manual" and callmode != "manual":
continue
if service['mode'] != "manual" and callmode == "manual":
continue
if service['mode'] == "disabled" and callmode != "disabled":
continue
if service['mode'] != "disabled" and callmode == "disabled":
continue
if service['mode'] != "trylocal" and service['mode'] != "localonly" and callmode == "trylocal":
continue
temp_dir = None
try:
temp_dir = tempfile.mkdtemp(dir=dir, suffix='.%s.service' % service['name'])
cmd = service['command']
if not os.path.exists("/usr/lib/obs/service/" + cmd[0]):
raise oscerr.PackageNotInstalled("obs-service-%s" % cmd[0])
cmd[0] = "/usr/lib/obs/service/" + cmd[0]
cmd = cmd + ["--outdir", temp_dir]
if conf.config['verbose'] or verbose or conf.config['debug']:
print("Run source service:", ' '.join(cmd))
r = run_external(*cmd)
if r != 0:
print("Aborting: service call failed: ", ' '.join(cmd))
# FIXME: addDownloadUrlService calls si.execute after
# updating _services.
return r
if service['mode'] == "manual" or service['mode'] == "disabled" or service['mode'] == "trylocal" or service['mode'] == "localonly" or callmode == "local" or callmode == "trylocal" or callmode == "all":
for filename in os.listdir(temp_dir):
os.rename(os.path.join(temp_dir, filename), os.path.join(dir, filename))
else:
name = service['name']
for filename in os.listdir(temp_dir):
os.rename(os.path.join(temp_dir, filename), os.path.join(dir, "_service:" + name + ":" + filename))
finally:
if temp_dir is not None:
shutil.rmtree(temp_dir)
return 0
class Linkinfo:
"""linkinfo metadata (which is part of the xml representing a directory)
"""
def __init__(self):
"""creates an empty linkinfo instance"""
self.project = None
self.package = None
self.xsrcmd5 = None
self.lsrcmd5 = None
self.srcmd5 = None
self.error = None
self.rev = None
self.baserev = None
def read(self, linkinfo_node):
"""read in the linkinfo metadata from the ``<linkinfo>`` element passed as
elementtree node.
If the passed element is ``None``, the method does nothing.
"""
if linkinfo_node is None:
return
self.project = linkinfo_node.get('project')
self.package = linkinfo_node.get('package')
self.xsrcmd5 = linkinfo_node.get('xsrcmd5')
self.lsrcmd5 = linkinfo_node.get('lsrcmd5')
self.srcmd5 = linkinfo_node.get('srcmd5')
self.error = linkinfo_node.get('error')
self.rev = linkinfo_node.get('rev')
self.baserev = linkinfo_node.get('baserev')
def islink(self):
""":return: ``True`` if the linkinfo is not empty, otherwise ``False``"""
if self.xsrcmd5 or self.lsrcmd5 or self.error is not None:
return True
return False
def isexpanded(self):
""":return: ``True`` if the package is an expanded link"""
if self.lsrcmd5 and not self.xsrcmd5:
return True
return False
def haserror(self):
""":return: ``True`` if the link is in error state (could not be applied)"""
if self.error:
return True
return False
def __str__(self):
"""return an informatory string representation"""
if self.islink() and not self.isexpanded():
return 'project %s, package %s, xsrcmd5 %s, rev %s' \
% (self.project, self.package, self.xsrcmd5, self.rev)
elif self.islink() and self.isexpanded():
if self.haserror():
return 'broken link to project %s, package %s, srcmd5 %s, lsrcmd5 %s: %s' \
% (self.project, self.package, self.srcmd5, self.lsrcmd5, self.error)
else:
return 'expanded link to project %s, package %s, srcmd5 %s, lsrcmd5 %s' \
% (self.project, self.package, self.srcmd5, self.lsrcmd5)
else:
return 'None'
class DirectoryServiceinfo:
def __init__(self):
self.code = None
self.xsrcmd5 = None
self.lsrcmd5 = None
self.error = ''
def read(self, serviceinfo_node):
if serviceinfo_node is None:
return
self.code = serviceinfo_node.get('code')
self.xsrcmd5 = serviceinfo_node.get('xsrcmd5')
self.lsrcmd5 = serviceinfo_node.get('lsrcmd5')
self.error = serviceinfo_node.find('error')
if self.error:
self.error = self.error.text
def isexpanded(self):
"""
Returns true, if the directory contains the "expanded"/generated service files
"""
return self.lsrcmd5 is not None and self.xsrcmd5 is None
def haserror(self):
return self.error is not None
# http://effbot.org/zone/element-lib.htm#prettyprint
def xmlindent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
for e in elem:
xmlindent(e, level + 1)
if not e.tail or not e.tail.strip():
e.tail = i + " "
if not e.tail or not e.tail.strip():
e.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class Project:
"""
Represent a checked out project directory, holding packages.
:Attributes:
``dir``
The directory path containing the project.
``name``
The name of the project.
``apiurl``
The endpoint URL of the API server.
``pacs_available``
List of names of packages available server-side.
This is only populated if ``getPackageList`` is set
to ``True`` in the constructor.
``pacs_have``
List of names of packages which exist server-side
and exist in the local project working copy (if
'do_package_tracking' is disabled).
If 'do_package_tracking' is enabled it represents the
list names of packages which are tracked in the project
working copy (that is it might contain packages which
exist on the server as well as packages which do not
exist on the server (for instance if the local package
was added or if the package was removed on the server-side)).
``pacs_excluded``
List of names of packages in the local project directory
which are excluded by the `exclude_glob` configuration
variable. Only set if `do_package_tracking` is enabled.
``pacs_unvers``
List of names of packages in the local project directory
which are not tracked. Only set if `do_package_tracking`
is enabled.
``pacs_broken``
List of names of packages which are tracked but do not
exist in the local project working copy. Only set if
`do_package_tracking` is enabled.
``pacs_missing``
List of names of packages which exist server-side but
are not expected to exist in the local project directory.
"""
REQ_STOREFILES = ('_project', '_apiurl')
def __init__(self, dir, getPackageList=True, progress_obj=None, wc_check=True):
"""
Constructor.
:Parameters:
`dir` : str
The directory path containing the checked out project.
`getPackageList` : bool
Set to `False` if you want to skip retrieval from the
server of the list of packages in the project .
`wc_check` : bool
"""
self.dir = Path(dir)
self.absdir = os.path.abspath(dir)
self.store = Store(dir)
self.progress_obj = progress_obj
self.name = store_read_project(self.dir)
self.scm_url = self.store.scmurl
self.apiurl = self.store.apiurl
dirty_files = []
if wc_check:
dirty_files = self.wc_check()
if dirty_files:
msg = 'Your working copy \'%s\' is in an inconsistent state.\n' \
'Please run \'osc repairwc %s\' and check the state\n' \
'of the working copy afterwards (via \'osc status %s\')' % (self.dir, self.dir, self.dir)
raise oscerr.WorkingCopyInconsistent(self.name, None, dirty_files, msg)
if getPackageList:
self.pacs_available = meta_get_packagelist(self.apiurl, self.name)
else:
self.pacs_available = []
if conf.config['do_package_tracking']:
self.pac_root = self.read_packages().getroot()
self.pacs_have = [pac.get('name') for pac in self.pac_root.findall('package')]
self.pacs_excluded = [i for i in os.listdir(self.dir)
for j in conf.config['exclude_glob']
if fnmatch.fnmatch(i, j)]
self.pacs_unvers = [i for i in os.listdir(self.dir) if i not in self.pacs_have and i not in self.pacs_excluded]
# store all broken packages (e.g. packages which where removed by a non-osc cmd)
# in the self.pacs_broken list
self.pacs_broken = []
for p in self.pacs_have:
if not os.path.isdir(os.path.join(self.absdir, p)):
# all states will be replaced with the '!'-state
# (except it is already marked as deleted ('D'-state))
self.pacs_broken.append(p)
else:
self.pacs_have = [i for i in os.listdir(self.dir) if i in self.pacs_available]
self.pacs_missing = [i for i in self.pacs_available if i not in self.pacs_have]
def wc_check(self):
global store
dirty_files = []
req_storefiles = Project.REQ_STOREFILES
if conf.config['do_package_tracking'] and self.scm_url is None:
req_storefiles += ('_packages',)
for fname in req_storefiles:
if not os.path.exists(os.path.join(self.absdir, store, fname)):
dirty_files.append(fname)
return dirty_files
def wc_repair(self, apiurl: Optional[str] = None):
store = Store(self.dir)
store.assert_is_project()
if not store.exists("_apiurl") or apiurl:
if apiurl is None:
msg = 'cannot repair wc: the \'_apiurl\' file is missing but ' \
'no \'apiurl\' was passed to wc_repair'
# hmm should we raise oscerr.WrongArgs?
raise oscerr.WorkingCopyInconsistent(self.name, None, [], msg)
# sanity check
conf.parse_apisrv_url(None, apiurl)
store.apiurl = apiurl
self.apiurl = apiurl
def checkout_missing_pacs(self, sinfos, expand_link=False, unexpand_link=False):
for pac in self.pacs_missing:
if conf.config['do_package_tracking'] and pac in self.pacs_unvers:
# pac is not under version control but a local file/dir exists
msg = 'can\'t add package \'%s\': Object already exists' % pac
raise oscerr.PackageExists(self.name, pac, msg)
if not (expand_link or unexpand_link):
sinfo = sinfos.get(pac)
if sinfo is None:
# should never happen...
continue
linked = sinfo.find('linked')
if linked is not None and linked.get('project') == self.name:
# hmm what about a linkerror (sinfo.get('lsrcmd5') is None)?
# Should we skip the package as well or should we it out?
# let's skip it for now
print('Skipping %s (link to package %s)' % (pac, linked.get('package')))
continue
print('checking out new package %s' % pac)
checkout_package(self.apiurl, self.name, pac,
pathname=getTransActPath(os.path.join(self.dir, pac)),
prj_obj=self, prj_dir=self.dir,
expand_link=expand_link or not unexpand_link, progress_obj=self.progress_obj)
def status(self, pac: str):
exists = os.path.exists(os.path.join(self.absdir, pac))
st = self.get_state(pac)
if st is None and exists:
return '?'
elif st is None:
raise oscerr.OscIOError(None, 'osc: \'%s\' is not under version control' % pac)
elif st in ('A', ' ') and not exists:
return '!'
elif st == 'D' and not exists:
return 'D'
else:
return st
def get_status(self, *exclude_states):
res = []
for pac in self.pacs_have:
st = self.status(pac)
if st not in exclude_states:
res.append((st, pac))
if '?' not in exclude_states:
res.extend([('?', pac) for pac in self.pacs_unvers])
return res
def get_pacobj(self, pac, *pac_args, **pac_kwargs):
try:
st = self.status(pac)
if st in ('?', '!') or st == 'D' and not os.path.exists(os.path.join(self.dir, pac)):
return None
return Package(os.path.join(self.dir, pac), *pac_args, **pac_kwargs)
except oscerr.OscIOError:
return None
def set_state(self, pac, state):
node = self.get_package_node(pac)
if node is None:
self.new_package_entry(pac, state)
else:
node.set('state', state)
def get_package_node(self, pac: str):
for node in self.pac_root.findall('package'):
if pac == node.get('name'):
return node
return None
def del_package_node(self, pac):
for node in self.pac_root.findall('package'):
if pac == node.get('name'):
self.pac_root.remove(node)
def get_state(self, pac: str):
node = self.get_package_node(pac)
if node is not None:
return node.get('state')
else:
return None
def new_package_entry(self, name, state):
ET.SubElement(self.pac_root, 'package', name=name, state=state)
def read_packages(self):
"""
Returns an ``xml.etree.ElementTree`` object representing the
parsed contents of the project's ``.osc/_packages`` XML file.
"""
global store
packages_file = os.path.join(self.absdir, store, '_packages')
if os.path.isfile(packages_file) and os.path.getsize(packages_file):
try:
result = ET.parse(packages_file)
except:
msg = 'Cannot read package file \'%s\'. ' % packages_file
msg += 'You can try to remove it and then run osc repairwc.'
raise oscerr.OscIOError(None, msg)
return result
else:
# scan project for existing packages and migrate them
cur_pacs = []
for data in os.listdir(self.dir):
pac_dir = os.path.join(self.absdir, data)
# we cannot use self.pacs_available because we cannot guarantee that the package list
# was fetched from the server
if data in meta_get_packagelist(self.apiurl, self.name) and is_package_dir(pac_dir) \
and Package(pac_dir).name == data:
cur_pacs.append(ET.Element('package', name=data, state=' '))
store_write_initial_packages(self.absdir, self.name, cur_pacs)
return ET.parse(os.path.join(self.absdir, store, '_packages'))
def write_packages(self):
xmlindent(self.pac_root)
store_write_string(self.absdir, '_packages', ET.tostring(self.pac_root, encoding=ET_ENCODING))
def addPackage(self, pac):
for i in conf.config['exclude_glob']:
if fnmatch.fnmatch(pac, i):
msg = 'invalid package name: \'%s\' (see \'exclude_glob\' config option)' % pac
raise oscerr.OscIOError(None, msg)
state = self.get_state(pac)
if state is None or state == 'D':
self.new_package_entry(pac, 'A')
self.write_packages()
# sometimes the new pac doesn't exist in the list because
# it would take too much time to update all data structs regularly
if pac in self.pacs_unvers:
self.pacs_unvers.remove(pac)
else:
raise oscerr.PackageExists(self.name, pac, 'package \'%s\' is already under version control' % pac)
def delPackage(self, pac, force=False):
state = self.get_state(pac.name)
can_delete = True
if state == ' ' or state == 'D':
del_files = []
for filename in pac.filenamelist + pac.filenamelist_unvers:
filestate = pac.status(filename)
if filestate == 'M' or filestate == 'C' or \
filestate == 'A' or filestate == '?':
can_delete = False
else:
del_files.append(filename)
if can_delete or force:
for filename in del_files:
pac.delete_localfile(filename)
if pac.status(filename) != '?':
# this is not really necessary
pac.put_on_deletelist(filename)
print(statfrmt('D', getTransActPath(os.path.join(pac.dir, filename))))
print(statfrmt('D', getTransActPath(os.path.join(pac.dir, os.pardir, pac.name))))
pac.write_deletelist()
self.set_state(pac.name, 'D')
self.write_packages()
else:
print('package \'%s\' has local modifications (see osc st for details)' % pac.name)
elif state == 'A':
if force:
delete_dir(pac.absdir)
self.del_package_node(pac.name)
self.write_packages()
print(statfrmt('D', pac.name))
else:
print('package \'%s\' has local modifications (see osc st for details)' % pac.name)
elif state is None:
print('package is not under version control')
else:
print('unsupported state')
def update(self, pacs=(), expand_link=False, unexpand_link=False, service_files=False):
if pacs:
for pac in pacs:
Package(os.path.join(self.dir, pac), progress_obj=self.progress_obj).update()
else:
# we need to make sure that the _packages file will be written (even if an exception
# occurs)
try:
# update complete project
# packages which no longer exists upstream
upstream_del = [pac for pac in self.pacs_have if pac not in self.pacs_available and self.get_state(pac) != 'A']
sinfo_pacs = [pac for pac in self.pacs_have if self.get_state(pac) in (' ', 'D') and pac not in self.pacs_broken]
sinfo_pacs.extend(self.pacs_missing)
sinfos = get_project_sourceinfo(self.apiurl, self.name, True, *sinfo_pacs)
for pac in upstream_del:
if self.status(pac) != '!':
p = Package(os.path.join(self.dir, pac))
self.delPackage(p, force=True)
delete_storedir(p.storedir)
try:
os.rmdir(pac)
except:
pass
self.pac_root.remove(self.get_package_node(pac))
self.pacs_have.remove(pac)
for pac in self.pacs_have:
state = self.get_state(pac)
if pac in self.pacs_broken:
if self.get_state(pac) != 'A':
checkout_package(self.apiurl, self.name, pac,
pathname=getTransActPath(os.path.join(self.dir, pac)), prj_obj=self,
prj_dir=self.dir, expand_link=not unexpand_link, progress_obj=self.progress_obj)
elif state == ' ':
# do a simple update
p = Package(os.path.join(self.dir, pac), progress_obj=self.progress_obj)
rev = None
needs_update = True
if p.scm_url is not None: