forked from tranquilit/WAPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaptpackage.py
2583 lines (2119 loc) · 100 KB
/
waptpackage.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
#!/opt/wapt/bin/python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# This file is part of WAPT
# Copyright (C) 2013 Tranquil IT Systems http://www.tranquil.it
# WAPT aims to help Windows systems administrators to deploy
# setup and update applications on users PC.
#
# WAPT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WAPT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WAPT. If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------
from waptutils import __version__
__all__ = [
'control_to_dict',
'md5_for_file',
'parse_major_minor_patch_build',
'make_version',
'PackageRequest',
'PackageEntry',
'WaptBaseRepo',
'WaptLocalRepo',
'WaptRemoteRepo',
'update_packages',
'REGEX_PACKAGE_VERSION',
'REGEX_PACKAGE_CONDITION',
'ArchitecturesList',
'EWaptException',
'EWaptBadSignature',
'EWaptCorruptedFiles',
'EWaptNotSigned',
'EWaptBadControl',
'EWaptBadSetup',
'EWaptNeedsNewerAgent',
'EWaptDiskSpace',
'EWaptBadTargetOS',
'EWaptNotAPackage',
'EWaptDownloadError',
'EWaptMissingLocalWaptFile',
'EWaptNeedsNewerAgent',
'EWaptConfigurationError',
'EWaptUnavailablePackage',
'EWaptNotSourcesDirPackage',
'EWaptPackageSignError',
'EWaptConflictingPackage',
'EWaptInstallPostponed',
'EWaptInstallError',
]
import os
import custom_zip as zipfile
import StringIO
import hashlib
import logging
import glob
import codecs
import re
import time
import json
import sys
import types
import requests
import email
import datetime
import tempfile
import email.utils
import shutil
import base64
from iniparse import RawConfigParser
import traceback
from waptutils import BaseObjectClass,Version,ensure_unicode,ZipFile,force_utf8_no_bom
from waptutils import create_recursive_zip,ensure_list,all_files
from waptutils import datetime2isodate,httpdatetime2isodate,fileutcdate,fileisoutcdate
from waptutils import default_http_headers,wget
from waptcrypto import EWaptMissingCertificate,EWaptBadCertificate
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey,SSLCRL
from waptcrypto import SSLVerifyException,hexdigest_for_data,hexdigest_for_file
logger = logging.getLogger()
def md5_for_file(fname, block_size=2**20):
"""Calculate the md5 hash of file.
Returns:
str: md5 hash as hexadecimal string.
"""
f = open(fname,'rb')
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
# From Semantic Versioning : http://semver.org/ by Tom Preston-Werner,
# valid : 0.0-0 0.0.0-0 0.0.0.0-0
REGEX_PACKAGE_VERSION = re.compile(r'^(?P<major>[0-9]+)'
'(\.(?P<minor>[0-9]+))?'
'(\.(?P<patch>[0-9]+))?'
'(\.(?P<subpatch>[0-9]+))?'
'(\-(?P<packaging>[0-9A-Za-z]+(\.[0-9A-Za-z]+)*))?$')
# tis-exodus (>2.3.4-10)
REGEX_PACKAGE_CONDITION = re.compile(r'(?P<package>[^\s()]+)\s*(\(\s*(?P<operator>[<=>]?)\s*(?P<version>\S+)\s*\))?')
def parse_major_minor_patch_build(version):
"""Parse version to major, minor, patch, pre-release, build parts.
"""
match = REGEX_PACKAGE_VERSION.match(version)
if match is None:
raise ValueError(u'%s is not valid SemVer string' % version)
verinfo = match.groupdict()
def int_or_none(name):
if name in verinfo and verinfo[name] != None :
return int(verinfo[name])
else:
return None
verinfo['major'] = int_or_none('major')
verinfo['minor'] = int_or_none('minor')
verinfo['patch'] = int_or_none('patch')
verinfo['subpatch'] = int_or_none('subpatch')
return verinfo
def make_version(major_minor_patch_build):
p1 = u'.'.join( [ "%s" % major_minor_patch_build[p] for p in ('major','minor','patch','subpatch') if major_minor_patch_build[p] != None])
if major_minor_patch_build['packaging'] != None:
return '-'.join([p1,major_minor_patch_build['packaging']])
else:
return p1
ArchitecturesList = ('all','x86','x64')
class EWaptException(Exception):
pass
class EWaptBadSignature(EWaptException):
pass
class EWaptDownloadError(EWaptException):
pass
class EWaptCorruptedFiles(EWaptException):
pass
class EWaptNotSigned(EWaptException):
pass
class EWaptBadControl(EWaptException):
pass
class EWaptBadSetup(EWaptException):
pass
class EWaptNeedsNewerAgent(EWaptException):
pass
class EWaptDiskSpace(EWaptException):
pass
class EWaptBadTargetOS(EWaptException):
pass
class EWaptNotAPackage(EWaptException):
pass
class EWaptNotSourcesDirPackage(EWaptException):
pass
class EWaptPackageSignError(EWaptException):
pass
class EWaptInstallError(EWaptException):
"""Exception raised during installation of package
msg is logged in local install database
if retry_count is None, install will be retried indefinitely until success
else install is retried at most retry_count times.
"""
def __init__(self,msg,install_status='ERROR',retry_count=None):
Exception.__init__(self,msg)
self.install_status = install_status
self.retry_count = retry_count
class EWaptInstallPostponed(EWaptInstallError):
def __init__(self,msg,install_status='POSTPONED',retry_count=5,grace_delay=3600):
EWaptInstallError.__init__(self,msg,install_status,retry_count)
self.grace_delay = grace_delay
class EWaptUnavailablePackage(EWaptInstallError):
pass
class EWaptConflictingPackage(EWaptInstallError):
pass
class EWaptRemoveError(EWaptException):
pass
class EWaptConfigurationError(EWaptException):
pass
class EWaptMissingLocalWaptFile(EWaptException):
pass
class PackageRequest(BaseObjectClass):
"""Package and version request / condition
>>> PackageRequest('7-zip( >= 7.2)')
PackageRequest('7-zip (>=7.2)')
"""
def __init__(self,package_request):
self.package_request = package_request
parts = REGEX_PACKAGE_CONDITION.match(self.package_request).groupdict()
self.package = parts['package']
self.operator = parts['operator'] or '='
self.version = Version(parts['version'])
def __cmp__(self,other):
if isinstance(other,str) or isinstance(other,unicode):
other = PackageRequest(other)
return cmp((self.package,self.version,self.operator),(other.package,other.version,other.operator))
def __str__(self):
return self.package_request
def __repr__(self):
return "PackageRequest('{package} ({operator}{version})')".format(package=self.package,operator=self.operator,version=self.version)
def control_to_dict(control,int_params=('size','installed_size')):
"""Convert a control file like object
key1: value1
key2: value2
...
list of lines into a dict
Multilines strings begins with a space
Breaks when an empty line is reached (limit between 2 package in Packages indexes)
Args:
control (file): file like object to read control from (until an empty line is reached)
int_params (list): attributes which must be converted to int
Returns:
dict
"""
result = {}
(key,value) = ('','')
while 1:
line = control.readline()
if not line or not line.strip():
break
if line.startswith(' '):
# additional lines begin with a space!
value = result[key]
value += '\n'
value += line.strip()
result[key] = value
else:
sc = line.find(':')
if sc<0:
raise EWaptBadControl(u'Invalid line (no ":" found) : %s' % line)
(key,value) = (line[:sc].strip(),line[sc+1:].strip())
key = key.lower()
if key in int_params:
try:
value = int(value)
except:
pass
result[key] = value
return result
class PackageEntry(BaseObjectClass):
"""Manage package attributes coming from either control files in WAPT package, local DB, or developement dir.
Methods to build, unzip, sign or check a package.
Methods to sign the control attributes and check them.
>>> pe = PackageEntry('testgroup','0')
>>> pe.depends = 'tis-7zip'
>>> pe.section = 'group'
>>> pe.description = 'A test package'
>>> print(pe.ascontrol())
package : testgroup
version : 0
architecture : all
section : group
priority : optional
maintainer :
description : A test package
depends : tis-7zip
conflicts :
maturity :
locale :
min_os_version :
max_os_version :
min_wapt_version :
sources :
installed_size :
signer :
signer_fingerprint:
signature_date :
signed_attributes :
>>>
"""
# minim attributes for a valid control file
required_attributes = ['package','version','architecture','section','priority']
optional_attributes = ['maintainer','description','depends','conflicts','maturity',
'locale','target_os','min_os_version','max_os_version','min_wapt_version',
'sources','installed_size','impacted_process']
# attributes which are added by _sign_control
signature_attributes = ['signer','signer_fingerprint','signature','signature_date','signed_attributes']
# these attrbutes are not written to Package control file, but only in Packages repository index
non_control_attributes = ['localpath','sourcespath','filename','size','repo_url','md5sum','repo']
# these attributes are not kept when duplicating / editing a package
not_duplicated_attributes = signature_attributes
# there files are not included in manifest file
manifest_filename_excludes = ['WAPT/signature','WAPT/signature.sha256','WAPT/manifest.sha256','WAPT/manifest.sha1']
_calculated_attributes = []
@property
def all_attributes(self):
return self.required_attributes + self.optional_attributes + self.signature_attributes + self.non_control_attributes + self._calculated_attributes
def get_default_signed_attributes(self):
all = self.required_attributes+self.optional_attributes+self.signature_attributes
all.remove('signature')
return all
def __init__(self,package='',version='0',repo='',waptfile=None, section = 'base',_default_md = 'sha256',**kwargs):
"""Initialize a Package entry with either aiitbutes or an existing package file or directory.
Args:
waptfile (str): path to wapt zipped file or wapt development directory.
package (str) : package name
version (str) : package version
any control attribute (str): initialize matching attribute
Returns:
None
"""
# temporary attributes added by join queries from local Wapt database
self._calculated_attributes=[]
self._package_content = None
self._control_updated = None
self.package=package
self.version=version
self.architecture='all'
self.section=section
self.priority='optional'
self.maintainer=''
self.description=''
self.depends=''
self.conflicts=''
self.sources=''
self.filename=''
self.size=None
self.maturity=''
self.signer=None
self.signer_fingerprint=None
self.signature=None
self.signature_date=None
self.signed_attributes=None
self.locale=''
self.target_os=''
self.min_os_version=''
self.max_os_version=''
self.min_wapt_version=''
self.installed_size=''
self.impacted_process=''
self.md5sum=''
self.repo_url=''
self.repo=repo
# directory if unzipped package files
self.sourcespath=None
# full filename of package if built
self.localpath=None
self._control_updated = False
if waptfile:
if os.path.isfile(waptfile):
self.load_control_from_wapt(waptfile)
elif os.path.isdir(waptfile):
self.load_control_from_wapt(waptfile)
else:
raise EWaptBadControl(u'Package filename or directory %s does not exist' % waptfile)
self._default_md = _default_md
self._md = None
if kwargs:
for key,value in kwargs.iteritems():
if key in self.required_attributes + self.optional_attributes:
setattr(self,key,value)
else:
raise Exception('"%s" is not a control attribute of PackageEntry an can not be set' % key)
def parse_version(self):
"""Parse version to major, minor, patch, pre-release, build parts.
"""
return parse_major_minor_patch_build(self.version)
def __getitem__(self,name):
if name is str or name is unicode:
name = name.lower()
if hasattr(self,name):
return getattr(self,name)
else:
raise Exception(u'No such attribute : %s' % name)
def __iter__(self):
for key in self.all_attributes:
yield (key, getattr(self,key))
def as_dict(self):
return dict(self)
def __unicode__(self):
return self.ascontrol(with_non_control_attributes=True)
def __str__(self):
return self.__unicode__()
def __repr__(self):
return u"PackageEntry('%s','%s') %s" % (self.package,self.version,
','.join(["%s=%s"%(key,getattr(self,key)) for key in ('architecture','maturity','locale') if (getattr(self,key) and getattr(self,key) != 'all')]))
def get(self,name,default=None):
"""Get PackageEntry property.
Args:
name (str): property to get. name is forced to lowercase.
default (any) : value to return in case the property doesn't not exist.
Returns:
any : property value
"""
if name is str or name is unicode:
name = name.lower()
if hasattr(self,name):
return getattr(self,name)
else:
return default
def __setitem__(self,name,value):
"""attribute which are not member of all_attributes list are considered _calculated
>>> p = PackageEntry('test')
>>> print p._calculated_attributes
[]
>>> p.install_date = u'2017-06-09 12:00:00'
>>> print p._calculated_attributes
[]
"""
setattr(self,name,value)
def __setattr__(self,name,value):
if name is str or name is unicode:
name = name.lower()
if name not in self.all_attributes:
self._calculated_attributes.append(name)
if name in self.required_attributes+self.optional_attributes and self._control_updated is not None and value != getattr(self,name):
self._control_updated = True
super(PackageEntry,self).__setattr__(name,value)
def __len__(self):
return len(self.all_attributes)
def __cmp__(self,entry_or_version):
def nat_cmp(a, b):
a, b = a or '', b or ''
def convert(text):
if text.isdigit():
return int(text)
else:
return text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return cmp(alphanum_key(a), alphanum_key(b))
def compare_by_keys(d1, d2):
for key in ['major', 'minor', 'patch','subpatch']:
i1,i2 = d1.get(key), d2.get(key)
# compare to partial version number (kind of wilcard)
if i1 is not None and i2 is None and not isinstance(entry_or_version,PackageEntry):
return 0
v = cmp(i1,i2)
if v:
return v
# package version
pv1, pv2 = d1.get('packaging'), d2.get('packaging')
# compare to partial version number (kind of wilcard)
if pv1 is not None and pv2 is None and not isinstance(entry_or_version,PackageEntry):
return 0
else:
pvcmp = nat_cmp(pv1, pv2)
return pvcmp or 0
try:
if isinstance(entry_or_version,PackageEntry):
result = cmp(self.package,entry_or_version.package)
if result == 0:
v1, v2 = self.parse_version(), entry_or_version.parse_version()
return compare_by_keys(v1, v2)
else:
return result
else:
v1, v2 = self.parse_version(), parse_major_minor_patch_build(entry_or_version)
return compare_by_keys(v1, v2)
except ValueError as e:
logger.warning("%s" % e)
if isinstance(entry_or_version,PackageEntry):
return cmp((self.package,self.version),(entry_or_version.package,entry_or_version.version))
else:
return cmp(self.version,entry_or_version)
def match(self, match_expr):
"""Return True if package entry match a package string like 'tis-package (>=1.0.1-00)
"""
pcv = REGEX_PACKAGE_CONDITION.match(match_expr).groupdict()
if pcv['package'] != self.package:
return False
else:
if 'operator' in pcv and pcv['operator']:
return self.match_version(pcv['operator']+pcv['version'])
else:
return True
def match_version(self, match_expr):
"""Return True if package entry match a version string condition like '>=1.0.1-00'
"""
prefix = match_expr[:2]
if prefix in ('>=', '<=', '=='):
match_version = match_expr[2:]
elif prefix and prefix[0] in ('>', '<', '='):
prefix = prefix[0]
match_version = match_expr[1:]
else:
raise ValueError(u"match_expr parameter should be in format <op><ver>, "
"where <op> is one of ['<', '>', '==', '<=', '>=']. "
"You provided: %r" % match_expr)
possibilities_dict = {
'>': (1,),
'<': (-1,),
'=': (0,),
'==': (0,),
'>=': (0, 1),
'<=': (-1, 0)
}
possibilities = possibilities_dict[prefix]
cmp_res = self.__cmp__(match_version)
return cmp_res in possibilities
def match_search(self,search):
"""Check if entry match search words
Args:
search (str): words to search for separated by spaces
Returns:
boolean: True if entry contains the words in search in correct order and at word boundaries
"""
if not search:
return True
else:
found = re.search(r'\b{}'.format(search.replace(' ',r'.*\b')),u'%s %s' % (self.package,self.description),re.IGNORECASE)
return found is not None
def load_control_from_dict(self,adict):
"""Fill in members of entry with keys from supplied dict
adict members which are not a registered control attribute are set too
and attribute name is put in list of "calculated" attributes.
Args:
adict (dict): key,value to put in this entry
Returns:
PackageEntry: self
"""
for k in adict:
setattr(self,k,adict[k])
if not k in self.all_attributes:
self._calculated_attributes.append(k)
return self
def load_control_from_wapt(self,fname=None,calc_md5=True):
"""Load package attributes from the control file (utf8 encoded) included in WAPT zipfile fname
Args:
fname (str or list): If None, try to load entry attributes from self.sourcespath or self.localpath
If fname is a list, consider fname is the lines of control file
If fname is file, it must be Wapt zipped file, and try to load control data from it
If fname is a directory, it must be root dir of unzipped package file and load control from <fname>/WAPT/control
calc_md5 (boolean): if True and fname is a zipped file, initialize md5sum attribute with md5 sum of Zipped file/
Returns:
PackageEntry: self
"""
if fname is None:
if self.sourcespath and os.path.isdir(self.sourcespath):
fname = self.sourcespath
elif self.localpath and os.path.isfile(self.localpath):
fname = self.localpath
if isinstance(fname,list):
control = StringIO.StringIO(u'\n'.join(fname))
elif os.path.isfile(fname):
with zipfile.ZipFile(fname,'r',allowZip64=True) as waptzip:
control = StringIO.StringIO(waptzip.open(u'WAPT/control').read().decode('utf8'))
elif os.path.isdir(fname):
try:
control = codecs.open(os.path.join(fname,'WAPT','control'),'r',encoding='utf8')
except Exception as e:
raise EWaptBadControl(e)
else:
raise EWaptBadControl(u'Bad or no control found for %s' % (fname,))
self.load_control_from_dict(control_to_dict(control))
self._control_updated = False
if isinstance(fname,list):
self.filename = self.make_package_filename()
self.localpath = ''
elif os.path.isfile(fname):
if calc_md5:
self.md5sum = md5_for_file(fname)
else:
self.md5sum = ''
self.size = os.path.getsize(fname)
self.filename = os.path.basename(fname)
self.localpath = os.path.abspath(fname)
elif os.path.isdir(fname):
self.filename = None
self.localpath = None
self.sourcespath = os.path.abspath(fname)
return self
def save_control_to_wapt(self,fname=None,force=True):
"""Save package attributes to the control file (utf8 encoded)
Update self.locapath or self.sourcespath if not already set.
Args:
fname (str) : base directoy of waptpackage or filepath of Zipped Packges.
If None, use self.sourcespath if exists, or self.localpath if exists
force (bool) : write control in wapt zip file even if it already exist
Returns:
PackageEntry : None if nothing written, or previous PackageEntry if new data written
Raises:
Exception: if fname is None and no sourcespath and no localpath
Exception: if control exists and force is False
"""
if fname is None:
if self.sourcespath and os.path.isdir(self.sourcespath):
fname = self.sourcespath
elif self.localpath and os.path.isfile(self.localpath):
fname = self.localpath
if fname is None:
raise Exception('Needs a wapt package directory root or WaptPackage filename to save control to')
fname = os.path.abspath(fname)
try:
old_control = PackageEntry(waptfile = fname)
except EWaptBadControl:
old_control = None
# wether data is different
write_needed = not old_control or (old_control.ascontrol() != self.ascontrol())
if not force and old_control and write_needed:
raise Exception(u'control file already exist in WAPT file %s' % fname)
if write_needed:
if os.path.isdir(fname):
if not os.path.isdir(os.path.join(fname,'WAPT')):
os.makedirs(os.path.join(fname,'WAPT'))
with codecs.open(os.path.join(fname,u'WAPT','control'),'w',encoding='utf8') as control_file:
control_file.write(self.ascontrol())
if not self.sourcespath:
self.sourcespath = fname
return old_control
else:
waptzip = zipfile.ZipFile(fname,'a',allowZip64=True,compression=zipfile.ZIP_DEFLATED)
try:
try:
previous_zi = waptzip.getinfo(u'WAPT/control')
waptzip.remove(u'WAPT/control')
except Exception as e:
logger.debug("OK %s" % repr(e))
waptzip.writestr(u'WAPT/control',self.ascontrol().encode('utf8'))
if not self.localpath:
self.localpath = fname
return old_control
finally:
if waptzip:
waptzip.close()
self._control_updated = False
else:
self._control_updated = False
return None
def ascontrol(self,with_non_control_attributes = False,with_empty_attributes=False):
"""Return control attributes and values as stored in control packages file
Each attribute on a line with key : value
If value is multiline, new line begin with a space.
Args:
with_non_control_attributes (bool) : weither to include all attributes or only those
relevant for final package content.
with_empty_attributes (bool) : weither to include attribute with empty value too or only
non empty and/or signed attributes
Returns:
str: lines of attr: value
"""
val = []
def escape_cr(s):
# format multi-lines description with a space at each line start
# format list as csv
if s and (isinstance(s,str) or isinstance(s,unicode)):
return re.sub(r'$(\n)(?=^\S)',r'\n ',s,flags=re.MULTILINE)
elif isinstance(s,list):
return ','.join([ensure_unicode(item) for item in s])
else:
if s is None:
return ''
else:
return s
for att in self.required_attributes+self.optional_attributes+self.signature_attributes:
# we add to the control file all signed attributes, the non empty ones, and all the other if required
if att in self.get_default_signed_attributes() or with_empty_attributes or getattr(self,att):
val.append(u"%-18s: %s" % (att, escape_cr(getattr(self,att))))
if with_non_control_attributes:
for att in self.non_control_attributes:
if getattr(self,att):
val.append(u"%-18s: %s" % (att, escape_cr(getattr(self,att))))
return u'\n'.join(val)
def make_package_filename(self):
"""Return the standard package filename based on current attributes
parts of control which are either 'all' or empty are not included in filename
Returns:
str: standard package filename
- packagename.wapt for host
- packagename_arch_maturity_locale.wapt for group
- packagename_version_arch_maturity_locale.wapt for others
"""
if self.section not in ['host','group'] and not (self.package and self.version and self.architecture):
raise Exception(u'Not enough information to build the package filename for %s (%s)'%(self.package,self.version))
if self.section == 'host':
return self.package+'.wapt'
elif self.section == 'group':
# we don't keep version for group
return self.package + '_'.join([f for f in (self.architecture,self.maturity,self.locale) if (f and f != 'all')]) + '.wapt'
else:
# includes only non empty fields
return '_'.join([f for f in (self.package,self.version,self.architecture,self.maturity,self.locale) if f]) + '.wapt'
def make_package_edit_directory(self):
"""Return the standard package directory to edit the package based on current attributes
Returns:
str: standard package filename
- packagename_arch_maturity_locale-wapt for softwares and groups
- packagename-wapt for host.
"""
if not (self.package):
raise Exception(u'Not enough information to build the package directory for %s'%(self.package))
# includes only non empty fields
return '_'.join([f for f in (self.package,self.architecture,self.maturity,self.locale) if (f and f != 'all')]) + '-wapt'
def asrequirement(self):
"""resturn package and version for designing this package in depends or install actions
Returns:
str: "packagename (=version)"
"""
return "%s (=%s)" % (self.package,self.version)
@property
def download_url(self):
"""Calculate the download URL for this entry
"""
if self.repo_url:
return self.repo_url+'/'+self.filename.strip('./')
else:
return None
def inc_build(self):
"""Increment last number part of version in memory"""
version_parts = self.parse_version()
for part in ('packaging','subpatch','patch','minor','major'):
if part in version_parts and version_parts[part] != None and\
(isinstance(version_parts[part],int) or version_parts[part].isdigit()):
version_parts[part] = "%i" % (int(version_parts[part])+1,)
self.version = make_version(version_parts)
return
raise EWaptBadControl(u'no build/packaging part in version number %s' % self.version)
def build_management_package(self,target_directory=None):
"""Build the WAPT package from attributes only, without setup.py
stores the result in target_directory.
self.sourcespath must be None.
Package will contain only a control file.
Args:
target_directory (str): where to create Zip wapt file.
if None, temp dir will be used.
Returns:
str: path to zipped Wapt file. It is unsigned.
>>> pe = PackageEntry('testgroup','0',description='Test package',maintainer='Hubert',sources='https://dev/svn/testgroup',architecture='x86')
>>> waptfn = pe.build_management_package()
>>> key = SSLPrivateKey('c:/private/htouvet.pem',password='monmotdepasse')
>>> crt = SSLCertificate('c:/private/htouvet.crt')
>>> pe.sign_package(crt,key)
'qrUUQeNJ3RSSeXQERrP9vD7H/Hfvw8kmBXZvczq0b2PVRKPdjMCElYKzryAbQ+2nYVDWAGSGrXxs\ny2WzhOhrdMfGfcy6YLaY5muApoArBn3CjKP5G6HypOGD5agznLEKkcUg5/Y3aIR8bL55Ylmp3RaS\nWKnezUcuA2yuNuKwHsXr9CdihK5pRyYrm5KhCNy8S7+kAJvayrUj5q8ur6z0nNMQCHEnWGN+V3MI\n84PymR1eXsuauKeYNqIESWCyyD/lFZv0JEYfrfml8rirC6yd6iTJW0OqH7gKwCEl03JpRaF91vWB\nOXN65S1j2oV8Jgjq43oa7lyywKC01a/ehQF5Jw==\n'
>>> pe.unzip_package()
'c:\\users\\htouvet\\appdata\\local\\temp\\waptob4gcd'
>>> ca = SSLCABundle('c:/wapt/ssl')
>>> pe.check_control_signature(ca)
<SSLCertificate cn=u'htouvet' issuer=u'tranquilit-ca-test' validity=2017-06-28 - 2027-06-26 Code-Signing=True CA=True>
"""
result_filename = u''
# some checks
if self.sourcespath:
raise Exception('Package must not have local sources')
# check version syntax
parse_major_minor_patch_build(self.version)
# check architecture
if not self.architecture in ArchitecturesList:
raise EWaptBadControl(u'Architecture should one of %s' % (ArchitecturesList,))
self.filename = self.make_package_filename()
control_data = self.ascontrol()
if target_directory is None:
target_directory = tempfile.gettempdir()
if not os.path.isdir(target_directory):
raise Exception('Bad target directory %s for package build' % target_directory)
result_filename = os.path.abspath(os.path.join(target_directory,self.filename))
if os.path.isfile(result_filename):
logger.warning('Target package already exists, removing %s' % result_filename)
os.unlink(result_filename)
self.localpath = result_filename
with ZipFile(result_filename,'w',allowZip64=True,compression=zipfile.ZIP_DEFLATED) as wapt_zip:
wapt_zip.writestr('WAPT/control',control_data.encode('utf8'))
return result_filename
def build_package(self,excludes=['.svn','.git','.gitignore','setup.pyc'],target_directory=None):
"""Build the WAPT package, stores the result in target_directory
Zip the content of self.sourcespath directory into a zipfile
named with default package filename based on control attributes.
Update filename attribute.
Update localpath attribute with result filepath.
Args:
excludes (list) : list of patterns for source files to exclude from built package.
target_directory (str): target directory where to store built package.
If None, use parent directory of package sources dircetory.
Returns:
str: full filepath to built wapt package
"""
result_filename = u''
# some checks
if not self.sourcespath:
raise EWaptNotSourcesDirPackage('Error building package : There is no WAPT directory in %s' % self.sourcespath)
if not os.path.isdir(os.path.join(self.sourcespath,'WAPT')):
raise EWaptNotSourcesDirPackage('Error building package : There is no WAPT directory in %s' % self.sourcespath)
control_filename = os.path.join(self.sourcespath,'WAPT','control')
if not os.path.isfile(control_filename):
raise EWaptNotSourcesDirPackage('Error building package : There is no control file in WAPT directory')
force_utf8_no_bom(control_filename)
# check version syntax
parse_major_minor_patch_build(self.version)
# check architecture
if not self.architecture in ArchitecturesList:
raise EWaptBadControl(u'Architecture should one of %s' % (ArchitecturesList,))
self.filename = self.make_package_filename()
logger.debug(u'Control data : \n%s' % self.ascontrol())
if target_directory is None:
target_directory = os.path.abspath(os.path.join(self.sourcespath,'..'))
if not os.path.isdir(target_directory):
raise Exception('Bad target directory %s for package build' % target_directory)
result_filename = os.path.abspath(os.path.join(target_directory,self.filename))
if os.path.isfile(result_filename):
logger.warning('Target package already exists, removing %s' % result_filename)
os.unlink(result_filename)
self.localpath = result_filename
allfiles = create_recursive_zip(
zipfn = result_filename,
source_root = self.sourcespath,
target_root = '' ,
excludes=excludes)
self._invalidate_package_content()
return result_filename
def _invalidate_package_content(self):
"""Remove the _package_content for host packages
"""
if hasattr(self,'_package_content'):
self._package_content = None
def _signed_content(self):
"""Return the signed control informations"""
# workaround for migration
if not self.signed_attributes and self.signature_date < '20170609':
logger.warning('Package %s has old control signature style, some attributes are not checked. Please re-sign package' % (self.localpath or self.sourcespath or self.asrequirement()))
effective_signed_attributes = ['package','version','architecture','section','priority','depends','conflicts','maturity']
else:
effective_signed_attributes = self.signed_attributes
return {att:getattr(self,att,None) for att in ensure_list(effective_signed_attributes)}
def _sign_control(self,private_key,certificate):
"""Sign the contractual attributes of the control file using
the provided key, add certificate Fingerprint and CN too
Args:
private_key (SSLPrivateKey)