-
Notifications
You must be signed in to change notification settings - Fork 3
/
psa
executable file
·1075 lines (808 loc) · 35 KB
/
psa
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/python
# This file is part of the PySide project.
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
"""
%prog <command> [arguments]
Helper script to work with PySide projects
init - creates a new project from the template
build-deb - creates binary package of current project
update - updates data from the current project
list - lists the available templates
help - for help on a specific command
To display the arguments for each command run %prog --help
"""
DOCS = __doc__.split('\n\n')
USAGE, DESCRIPTION = DOCS[0], '\n\n'.join(DOCS[1:])
TEMPLATES = {}
from optparse import OptionParser, OptionGroup
import re
import os
import fnmatch
import string
import sys
import textwrap
import logging
import shutil
import tempfile
import subprocess
import glob
import pwd
from contextlib import contextmanager
from ConfigParser import ConfigParser
try:
__import__('stdeb')
except ImportError:
logging.warning('stdeb not available. Support for building deb packages disabled.')
class BuildError(Exception):
'''Raised for errors during the build'''
class RequirementsError(Exception):
'''Raised for errors during the build'''
# Utility functions
@contextmanager
def working_directory(path):
'''Simple context manager to change the working directory'''
current_dir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(current_dir)
def remove_directory(abs_dir):
if os.path.exists(abs_dir):
try:
logging.info('Cleaning deb_dist directory...')
shutil.rmtree(abs_dir)
except OSError:
fatal('Cannot clean directory! Aborting.')
def execute_with_log(args, logfilename, on_error):
'''Execute a program writing its output to a log file'''
with open(logfilename, 'w') as log_file:
proc = subprocess.Popen(args, stdout=log_file, stderr=subprocess.STDOUT)
proc.communicate()
if proc.returncode and on_error:
raise on_error
def encode_icon(png, base64):
'''Encodes an icon to base64'''
with open(base64, 'w') as base64_handle:
proc = subprocess.Popen(['uuencode', '-m', png, png],
stdout=base64_handle)
proc.communicate()
if proc.returncode:
raise BuildError('Failed to encode icon')
# Handling packages
def unpack_control(debfile, targetdir):
'''Unpack 'debfile' to 'targetdir' '''
if subprocess.call(['dpkg', '-x', debfile, targetdir]):
raise BuildError('Failed to extract the deb file for icon insertion')
if subprocess.call(['dpkg-deb', '--control', debfile, os.path.join(targetdir, 'DEBIAN')]):
raise BuildError('Failed to extract the control file for icon insertion')
if not os.path.isfile(os.path.join(targetdir, 'DEBIAN', 'control')):
raise BuildError('Failed to find the control file for icon insertion')
def repackage(directory, debfile):
if subprocess.call(['fakeroot', 'dpkg', '-b', directory, debfile]):
raise BuildError('Failed to repackage the project')
# Project template classes
#Sections from http://wiki.maemo.org/Task:Package_categories#New_list_for_Diablo
PERMITTED_SECTIONS = ["desktop",
"development",
"education",
"games",
"graphics",
"multimedia",
"navigation",
"network",
"office",
"science",
"system",
"utilities"]
# Categories from http://standards.freedesktop.org/menu-spec/latest/apa.html
PERMITTED_CATEGORIES = ["AudioVideo",
"Audio",
"Video",
"Development",
"Education",
"Game",
"Graphics",
"Network",
"Office"
"Settings",
"System",
"Utility"]
class PluginMount(type):
'''Hook to list all plugins'''
def __init__(mcs, name, bases, attrs):
if not hasattr(mcs, 'plugins'):
mcs.plugins = {}
else:
mcs.plugins[name] = mcs
def get_plugins(mcs):
'''Lists all plugins'''
return mcs.plugins
class Project(object):
'''Base project class'''
__metaclass__ = PluginMount
class QmlProject(Project):
'''Basic qml project class.'''
no_process_patterns = []
def __init__(self, template_info):
'''Initializes the instance with default values'''
Project.__init__(self)
self.template_info = template_info
self._slug = 'dummyproject'
self.projectdir = ''
self.parser = None
def get_slug(self):
return self._slug
def set_slug(self, value):
'''Slug checks'''
if value.startswith('-') or value.endswith('-'):
raise ValueError('Slug must not start nor end with a dash')
if re.search('[^a-zA-Z0-9\-]', value) is not None:
raise ValueError('Slug must be only alphanumeric and dash characters')
self._slug = value
slug = property(get_slug, set_slug)
def placeholders(self):
'''Returns the mapping of substitutions for template processing'''
return dict(PROJECT=self.slug, PYVERSION='%d.%d'%(sys.version_info[:2]))
def init(self, slug, args):
'''Initializes the project folder'''
self.pre_init()
self.slug = slug
self.projectdir = os.path.abspath(os.path.join(os.curdir, slug))
if os.path.exists(self.projectdir):
fatal("Project directory " + self.slug + " already exists! Aborting.")
self.init_option_parser()
options, args = self.process_options(args)
self.init_fields(options)
self.copy_template_files()
self.process_fields()
self.write_project_config_file()
self.post_init()
def pre_init(self):
'''Pre-init checks'''
def post_init(self):
'''Post init actions'''
def write_project_config_file(self):
'''Initializes the file with the project configuration information'''
with open(os.path.join(self.projectdir, self.slug + '.psa'), 'wb') as project_config:
parser = ConfigParser()
parser.add_section('Project')
for key, value in self.placeholders().items():
parser.set('Project', key, value)
parser.set('Project', 'template', self.template_info.name)
parser.write(project_config)
def add_external_file(self, source, target):
'''Copies an external file into this project folder.
source - path to the source file
target - path to the target relative to the project root
'''
shutil.copy(source, os.path.join(self.projectdir, target))
def init_option_parser(self):
'''Creates the parser and add options.
Subclasses can extend this method with extra options
'''
self.parser = OptionParser()
def process_options(self, args):
'''Parses the argument list and returns options and extra arguments'''
return self.parser.parse_args(args)
def init_fields(self, options):
'''Check for extra options.
This method can be reimplemented to check for additional options
'''
return self, options # dummy return to make pylint shut up
def copy_template_files(self):
'''Copy the template files to project folder, replacing the project information'''
# Make root dir
os.makedirs(self.projectdir)
for root, dirnames, filenames in os.walk(self.template_info.path):
for dirname in dirnames:
os.makedirs(os.path.join(self.projectdir, dirname))
folder = root.replace(self.template_info.path, '')
if folder.startswith('/'):
folder = folder[1:]
for filename in filenames:
if not filename.endswith('.template'):
continue
targetname = os.path.basename(filename).replace('.template', '')
targetname = targetname.replace('templateproject', self.slug)
target = os.path.join(self.projectdir, folder, targetname)
source = os.path.join(root, filename)
shutil.copy(source, target)
if self.should_process(targetname):
self.process(target)
def process_fields(self):
'''Replaces the project items for the placeholders'''
for root, _, filenames in os.walk(self.projectdir):
for filename in filenames:
abs_filename = os.path.abspath(os.path.join(root, filename))
self.process(abs_filename)
def should_process(self, filename):
'''Checks if this file should be processed.
Currently just checks a predefined list of file patterns'''
filename = os.path.basename(filename)
for pattern in self.no_process_patterns:
if fnmatch.fnmatch(filename, pattern):
return False
return True
def process(self, filename):
'''Replaces the placeholders in the source file'''
tempfd, tempfilename = tempfile.mkstemp(text=True)
temp = os.fdopen(tempfd, 'w')
try:
with open(filename, 'r') as source:
for line in source:
newline = string.Template(line).substitute(self.placeholders())
temp.write(newline)
logging.debug('Finished writing temp file for %s', filename)
except (IOError,), error:
logging.critical('Error processing file %s. Reason: %s',
os.path.basename(filename), error)
sys.exit(1)
else:
temp.close()
shutil.move(tempfilename, filename)
@classmethod
def from_info(cls, info):
'''Creates a new instance of a template from the given project info'''
instance = cls()
instance.fill_info(info)
return instance
def fill_info(self, info):
'''Fill project attributes from the info dictionary'''
self.slug = info['project']
self.projectdir = os.path.abspath(os.curdir)
def build(self, _=None):
'''Builds the project'''
logging.debug('Building the project')
self.pre_build()
self.execute_build()
self.post_build()
def pre_build(self):
'''Get things ready for building, like verifying dependencies.'''
def execute_build(self):
'''Execute the proper build'''
def post_build(self):
'''Execute extra build steps'''
def update(self, args=None):
'''Updates sections of the project'''
print 'Updating the project'
self.init_option_parser()
options, args = self.process_options(args)
self.init_fields(options)
self.pre_update(options, args)
self.execute_update(options, args)
self.post_update(options, args)
def pre_update(self, options, args):
'''Get things ready for updating, like verifying dependencies.'''
def execute_update(self, options, args):
'''Execute the proper update'''
def post_update(self, options, args):
'''Execute extra update steps'''
class DebProject(QmlProject):
'''Generic template for debian packages. Will be subclassed for Harmattan,
Fremantle and Ubuntu templates
'''
# Mapping for folders in the template
# Extensions that shouldn't be processed for placeholders
no_process_patterns = ['*.jpg', '*.png']
def __init__(self, template_info):
'''Initializes the instance with default values'''
QmlProject.__init__(self, template_info)
self.appname = 'PySide app'
self.description = 'A PySide example'
self.maintainer = ''
self.email = ''
self.category = 'Development'
self.section = 'development'
def pre_build(self):
if not 'stdeb' in sys.modules:
raise RequirementsError('stdeb is needed to build debian packages')
proc = subprocess.Popen(['uuencode', '--version'], stdout=subprocess.PIPE)
proc.communicate()
if proc.returncode:
raise RequirementsError('uuencode is needed to insert icon in debian packages')
def execute_build(self):
'''Execute the proper build'''
remove_directory(os.path.abspath(os.path.join(os.curdir, 'deb_dist')))
# create packaging with stdeb
cmd = 'python setup.py --command-packages=stdeb.command sdist_dsc'
args = cmd.split()
execute_with_log(args, 'sdist-dsc.log',
on_error=BuildError('Failed to build initial package.'))
# store packaging directory
files = os.listdir(os.path.join(self.projectdir, 'deb_dist'))
packaging_dir = []
for f in files:
if os.path.isdir(os.path.join(self.projectdir, 'deb_dist', f)):
packaging_dir.append(f)
if len(packaging_dir) != 1:
raise BuildError('More than one source directory, not sure where to look')
full_dir = os.path.join(self.projectdir, 'deb_dist', packaging_dir[0])
# modify debian/control Depends field
# In this point we remove the ${python:Depends} variable automatically
# put in there by stdeb; this is necessary because this variable was
# being substituted by an incorrect Python version in some platforms
# (e.g. Ubuntu Natty); so, to avoid potential problems we just get rid of it.
# The mandatory dependencies (python-pyside.qtgui and others), specified
# in stdeb.cfg, will pull the default Python anyway if it is not already present.
control_file = os.path.join(full_dir, 'debian', 'control')
with open(control_file, 'r') as f:
old_control = f.read()
new_control = old_control.replace('${python:Depends},', '')
with open(control_file, 'w') as f:
f.write(new_control)
# run dpkg-buildpackage
cmd = 'dpkg-buildpackage -D -rfakeroot -uc -b'
args = cmd.split()
with working_directory(full_dir):
execute_with_log(args, 'dpkg-buildpackage.log',
on_error=BuildError('Failed to build initial package.'))
debfile = glob.glob('deb_dist/*.deb')[0]
self.insert_icon(os.path.abspath(debfile))
return os.path.abspath(debfile)
def insert_icon(self, abs_debfile):
'''Inserts the local project icon'''
abs_tempdir = tempfile.mkdtemp(prefix='psatmp')
icon_filename = self.slug + '.png'
try:
unpack_control(abs_debfile, abs_tempdir)
abs_png = os.path.join(self.projectdir, icon_filename)
abs_base64 = os.path.join(self.projectdir, self.slug + '.base64')
encode_icon(abs_png, abs_base64)
with open(os.path.join(abs_tempdir, 'DEBIAN', 'control'), 'ab') as control_handle:
control_handle.write('Maemo-Icon-26:\n')
with open(abs_base64, 'rb') as base64_handle:
for line in base64_handle:
if line.startswith('begin') or line.startswith('end'):
continue
control_handle.write(' %s' % line)
repackage(abs_tempdir, abs_debfile)
except:
raise
finally:
shutil.rmtree(abs_tempdir)
def fill_info(self, info):
super(DebProject, self).fill_info(info)
self.appname = info['APPNAME'.lower()]
self.description = info['DESC'.lower()]
self.maintainer = info['MAINTAINER'.lower()]
self.email = info['EMAIL'.lower()]
self.section = info['SECTION'.lower()]
self.category = info['CATEGORY'.lower()]
def placeholders(self):
'''Returns the mapping of substitutions for template processing'''
data = super(DebProject, self).placeholders().copy()
data.update(dict(APPNAME=self.appname,
DESC=self.description,
CATEGORY=self.category,
SECTION=self.section,
MAINTAINER=self.maintainer,
EMAIL=self.email))
return data
def init_option_parser(self):
'''Add Debian options to the argument parser'''
super(DebProject, self).init_option_parser()
group = OptionGroup(self.parser, "Options for init and update commands for debian templates")
group.add_option("-a", "--app-name", action="store",
dest="appname", help="Human-readable application name")
group.add_option("-s", "--section", action="store",
dest="section", help="Application section")
group.add_option("-d", "--description", action="store",
dest="desc", help="Application short description")
group.add_option("-c", "--category", action="store",
dest="category", help="Application category")
group.add_option("-p", "--slug", action="store",
dest="slug", help="Project slug (init only)")
self.parser.add_option_group(group)
def init_fields(self, options):
'''Check for extra options.
This method can be reimplemented to check for additional options
'''
# currently option handling is split between template (where they are used)
# and the proper psa script, where they are added to the option parser.
self.init_appname_and_description(options)
self.init_section_and_category(options)
self.init_maintainer_and_email()
def init_appname_and_description(self, options):
'''Initialize the application name and description'''
if options.appname is not None:
self.appname = options.appname
if options.desc is not None:
self.description = options.desc
def init_section_and_category(self, options):
'''Checks for section and category options'''
if options.section:
if options.section in PERMITTED_SECTIONS:
self.section = options.section
else:
fatal("Error: Invalid section; please use a valid section from\
http://wiki.maemo.org/Task:Package_categories#New_list_for_Diablo")
if options.category:
if options.category in PERMITTED_CATEGORIES:
self.category = options.category
else:
fatal("Error: Invalid category; please use a valid category from " +\
"http://standards.freedesktop.org/menu-spec/latest/apa.html")
def init_maintainer_and_email(self):
'''Guesses maintainer name and email'''
if os.getenv('DEBFULLNAME') is not None:
self.maintainer = os.getenv('DEBFULLNAME')
else:
# if there is no DEBFULLNAME environment variable, get full name from /etc/passwd
currentuser = pwd.getpwnam(os.getlogin())
self.maintainer = currentuser.pw_gecos.split(',')[0]
if os.getenv('DEBEMAIL') is not None:
self.email = os.getenv('DEBEMAIL')
else:
self.email = "email@example.com"
def execute_update(self, options, args):
'''Execute field updates'''
if options.section is not None:
if options.section not in PERMITTED_SECTIONS:
fatal("Invalid section; please use a valid section from http://wiki.maemo.org/Task:Package_categories#New_list_for_Diablo")
filename = 'stdeb.cfg'
with open(filename, 'rb') as f:
oldfile = f.read()
match = re.search(r'Section:.+', oldfile)
oldSection = match.group().split('/')[1]
newfile = oldfile.replace('Section: user/' + oldSection, 'Section: user/' + options.section)
shutil.copy(filename, 'stdeb.cfg.old')
with open(filename, 'wb') as f:
f.write(newfile)
print 'Application Section updated! The old stdeb.cfg was saved as stdeb.cfg.old'
if options.category is not None:
if options.category not in PERMITTED_CATEGORIES:
fatal("Invalid category; please use a valid category from http://standards.freedesktop.org/menu-spec/latest/apa.html")
filename = self.slug + '.desktop'
with open(filename, 'rb') as f:
oldfile = f.read()
match = re.search(r'Categories=.+', oldfile)
oldCategory = match.group()[:-1].split("=")[1]
newfile = oldfile.replace(oldCategory, options.category)
shutil.copy(filename, filename + '.old')
with open(filename, 'wb') as f:
f.write(newfile)
print 'Application category updated! The old ' + filename + ' was saved as ' + filename + '.old'
if options.appname is not None:
filename = self.slug + '.desktop'
with open(filename, 'rb') as f:
oldfile = f.read()
match = re.search(r'Name=.+', oldfile)
oldAppName = match.group().split("=")[1]
newfile = oldfile.replace(oldAppName, options.appname)
shutil.copy(filename, filename + '.old')
with open(filename, 'wb') as f:
f.write(newfile)
print 'Application name updated! The old ' + filename + ' was saved as ' + filename + '.old'
if options.desc is not None:
filename = 'setup.py'
with open(filename, 'rb') as f:
oldfile = f.read()
match = re.search(r'description=.+', oldfile)
oldDescription = match.group()[:-1].split("=")[1]
newfile = oldfile.replace(oldDescription, '"' + options.desc + '"')
shutil.copy(filename, filename + '.old')
with open(filename, 'wb') as f:
f.write(newfile)
print 'Application short description updated! The old ' + filename + ' was saved as ' + filename + '.old'
class Harmattan(DebProject):
'''Customizations for Harmattan packaging.
Mainly adding credentials and signature file
'''
name = 'harmattan'
refhashmake = None
deb_add = None
def pre_build(self):
DebProject.pre_build(self)
# Load refhashmake and deb-add modules
if 'PSA_ROOT' in os.environ:
sys.path.append(os.path.join(os.environ['PSA_ROOT'], 'scripts'))
try:
self.refhashmake = __import__('refhashmake')
self.deb_add = __import__('deb_add')
except ImportError:
# Try the prefix install
sys.path.append(os.path.join(sys.prefix, 'share', 'psa', 'scripts'))
try:
self.refhashmake = __import__('refhashmake')
self.deb_add = __import__('deb_add')
except ImportError:
raise RequirementsError("Can't find harmattan modules")
finally:
sys.path.remove(os.path.join(sys.prefix, 'share', 'psa', 'scripts'))
finally:
if 'PSA_ROOT' in os.environ:
sys.path.remove(os.path.join(os.environ['PSA_ROOT'], 'scripts'))
def execute_build(self):
'''Overriden from DebProject'''
abs_debfile = super(Harmattan, self).execute_build()
self.add_credentials(abs_debfile)
def add_credentials(self, abs_debfile):
'''Creates the signature file and adds aegis credentials'''
abs_tempdir = tempfile.mkdtemp(prefix='psatmp')
try:
if subprocess.call(['dpkg', '-x', abs_debfile, abs_tempdir]):
raise BuildError('Failed to extract the deb file for icon insertion')
if subprocess.call(['dpkg-deb', '--control', abs_debfile, os.path.join(abs_tempdir, 'DEBIAN')]):
raise BuildError('Failed to extract the control file for icon insertion')
if not os.path.isfile(os.path.join(abs_tempdir, 'DEBIAN', 'control')):
raise BuildError('Failed to find the control file for icon insertion')
self.create_digsums(abs_tempdir)
if subprocess.call(['fakeroot', 'dpkg', '-b', abs_tempdir, abs_debfile]):
raise BuildError('Failed to repackage.')
self.inject_credentials(abs_debfile, abs_tempdir)
finally:
shutil.rmtree(abs_tempdir)
def inject_credentials(self, abs_debfile, abs_tempdir):
'''Adds the credential to the existing debian file
abs_debfile - absolute path to the deb file to be modified.
abs_tempdir - absolute path to the directory with the exploded package.
'''
abs_credential = os.path.abspath(os.path.join(self.projectdir, self.slug + '.aegis'))
try:
if os.path.getsize(abs_credential) == 0:
logging.info("Empty signature file. Skipping.")
return
except os.error:
logging.warning("Couldn't open aegis file. Skipping.")
return
with working_directory(os.path.join(self.projectdir, 'deb_dist')):
self.deb_add.add(abs_source=abs_credential,
target='_aegis',
abs_control=os.path.join(abs_tempdir, 'DEBIAN', 'control'),
abs_debfile=abs_debfile)
def create_digsums(self, abs_tempdir):
'''Writes the signature file to the given directory
abs_tempdir - Absolute path to the directory with the exploded debian
package.
'''
data_matches = []
control_matches = []
for root, _, filenames in os.walk(abs_tempdir):
if filenames and 'DEBIAN' not in root:
for filename in filenames:
tmp = '/'.join(os.path.join(root.split('/')[3:]))
data_matches.append(os.path.join(tmp, filename))
elif filenames and 'DEBIAN' in root:
for filename in filenames:
tmp = '/'.join(os.path.join(root.split('/')[4:]))
control_matches.append(os.path.join(tmp, filename))
abs_sigfilename = os.path.join(abs_tempdir, 'DEBIAN', 'digsigsums')
with working_directory(abs_tempdir):
argv = ['-c', '-a', '-o', 'com.nokia.maemo', '-r', '-f'] + data_matches
options, _ = self.refhashmake.parse_args(argv)
with open(abs_sigfilename, 'w') as sig_file:
for filename in data_matches:
logging.debug('Processing file: %s', filename)
self.refhashmake.process_file(filename, options, stream=sig_file)
with working_directory(os.path.join(abs_tempdir, 'DEBIAN')):
argv = ['-c', '-a', '-o', 'com.nokia.maemo', '-p', 'var/lib/dpkg/info/%s.' % self.slug, '-r',
'-f'] + control_matches
options, _ = self.refhashmake.parse_args(argv)
with open(abs_sigfilename, 'a') as sig_file:
for filename in control_matches:
logging.debug('Processing file: %s', filename)
self.refhashmake.process_file(filename, options, stream=sig_file)
class Fremantle(DebProject):
'''Template class'''
name = 'fremantle'
def pre_init(self):
'''Init checks'''
self.check_py25()
def pre_build(self):
'''Build checks'''
DebProject.pre_build(self)
self.check_py25()
def check_py25(self):
'''Is python 2.5 available?'''
try:
subprocess.call('python2.5 -c 42'.split())
except OSError:
raise RequirementsError('Fremantle projects require python2.5')
# Had to reimplement this as the original method uses textwrap.fill
# and messes up the formatting
class PsaOptionParser(OptionParser):
'''Psa own OptionParser'''
def format_description(self, formatter):
'''Returns the description unchanged'''
return self.description
def fatal(msg):
'''Simple wrapper to display an error message and exit'''
sys.stderr.write(textwrap.fill(textwrap.dedent(msg)) + '\n')
sys.exit(1)
def main():
parser = PsaOptionParser(usage=USAGE, description=DESCRIPTION)
parser.disable_interspersed_args()
parser.add_option("-v", "--verbose", action="store_true", default=False,
help="Output debug messages")
(options, args) = parser.parse_args()
if options.verbose:
logging.basicConfig(level=logging.DEBUG)
if len(args) == 0:
parser.error("You need to pass a command to psa: init, update or build-deb")
if args[0] == "init":
psa_init(args)
elif args[0] == "build-deb":
psa_build(args)
elif args[0] == "update":
psa_update(args)
elif args[0] == "list":
psa_list_templates()
else:
fatal("Unknow command. Try init, build-deb, update, or list")
def get_readme_path():
'''Returns the README file path'''
filename = 'README'
if os.path.exists(filename):
return filename
if 'PSA_ROOT' in os.environ:
return os.path.join(os.environ['PSA_ROOT'], filename)
path = os.path.join(sys.prefix, 'share', 'psa', filename)
if not os.path.exists(path):
return None
return path
def get_templates_dir():
'''Returns the directory storing the templates'''
# Try local path
if os.path.exists('templates'):
return os.path.abspath('templates')
if 'PSA_TEMPLATE_PATH' in os.environ:
return os.environ['PSA_TEMPLATE_PATH']
if 'PSA_ROOT' in os.environ:
return os.path.join(os.environ['PSA_ROOT'], 'templates')
# Try local path
if os.path.exists('templates'):
return os.path.abspath('templates')
# Finally, try the global path
path = os.path.join(sys.prefix, 'share', 'psa', 'templates')
if os.path.isdir(path):
return path
class TemplateData(object):
'''Simple representation of a template'''
def __init__(self, name='', path='', builder=None):
self.name = name
self.path = path
self.builder = builder
def load_template_data(path):
'''Loads template information for the template stored at path'''
filename = os.path.join(path, 'template.cfg')
parser = ConfigParser()
try:
with open(filename) as handle:
parser.readfp(handle, filename)
except IOError:
sys.stderr.write('Failed to load template %s\n' % path)
return None
return TemplateData(name=os.path.basename(path),
path=path,
builder=parser.get('Template', 'class'))
def get_templates():
'''Get all templates available'''
if TEMPLATES:
return TEMPLATES
templates_dir = get_templates_dir()
for root, dirnames, _ in os.walk(templates_dir):
if root != templates_dir:
break
for dirname in dirnames:
template = load_template_data(os.path.join(root, dirname))
if template:
TEMPLATES[template.name] = template
return TEMPLATES
def get_template(name):
'''Get a single template by name'''
if not TEMPLATES:
get_templates()
return TEMPLATES.get(name, None)
def get_local_config(path=None):
'''Loads the local project config file'''
if path is None:
path = os.curdir
# Guess project name from current dir name
project = os.path.basename(os.path.abspath(path))
filename = os.path.join(os.curdir, project+'.psa')
try:
with open(filename) as handle:
parser = ConfigParser()
parser.readfp(handle, filename)
config = {}
for name, value in parser.items('Project'):
config[name] = value
return config
except IOError:
return None
def psa_list_templates():
'''Print all the available templates'''
print ', '.join(get_templates())
class ProjectInfoError(Exception):
'''Exception for errors in project information'''
def psa_init(args):
'''Initializes the project directory from the request template and options
Arguments:
options - Options for the template.
args - 3-uple with command name, project slug and template.
'''
# TODO Move everything to templates.init, to allow processing the
# argument list there.
if len(args) < 3:
fatal("""\
You need to provide the project slug and the platform when
using the init command, e.g. psa init sampleproject
<platform>""")
slug = args[1]
template_name = args[2]
template = get_template(template_name)
if not template:
fatal("Error: Can't find template %s. Available templates: %s." %\
(template_name, ', '.join(get_templates())))
builder = Project.get_plugins().get(template.builder, None)(template)