forked from blair/ubuntu-precise-python-defaults
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdh_python2
More file actions
Latest commit
executable file
·699 lines (633 loc) · 29.6 KB
/
Copy pathdh_python2
File metadata and controls
executable file
·699 lines (633 loc) · 29.6 KB
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
#! /usr/bin/python
# -*- coding: UTF-8 -*- vim: et ts=4 sw=4
# Copyright © 2010-2011 Piotr Ożarowski <piotr@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ importwith_statement
importlogging
importos
importre
importsys
fromfilecmpimportdircmp, cmpfiles, cmpasfcmp
fromoptparseimportOptionParser, SUPPRESS_HELP
fromos.pathimportisabs, isdir, islink, exists, join, normpath, realpath,\
split
fromshutilimportrmtree, copyasfcopy
fromstatimportST_MODE, S_IXUSR, S_IXGRP, S_IXOTH
sys.path.insert(1, '/usr/share/python/')
fromdebpython.debhelperimportDebHelper
fromdebpython.dependsimportDependencies
fromdebpython.versionimportSUPPORTED, DEFAULT, \
debsorted, getver, vrepr, parse_pycentral_vrange, \
get_requested_versions, parse_vrange, vrange_str
importdebpython.namespaceasns
fromdebpython.pydistimportvalidateasvalidate_pydist, \
PUBLIC_DIR_RE
fromdebpython.toolsimportsitedir, relative_symlink, \
shebang2pyver, so2pyver, \
clean_egg_name, \
pyinstall, pyremove
fromdebpython.optionimportOption
# initialize script
logging.basicConfig(format='%(levelname).1s: %(module)s:%(lineno)d: '
'%(message)s')
log=logging.getLogger(__name__)
os.umask(022)
EGGnPTH_RE=re.compile(r'(.*?)(-py\d\.\d+)?(.*?)(\.egg-info|\.pth)$')
# naming conventions used in the file:
# * version - tuple of integers
# * ver - string representation of version
# * vrange - version range, pair of max and min versions
# * fn - file name (without path)
# * fpath - file path
### FILES ######################################################
deffix_locations(package):
"""Move files to the right location."""
found_versions= {}
forversioninSUPPORTED:
ver=vrepr(version)
to_check= [i%verforiin (\
'usr/local/lib/python%s/site-packages',
'usr/local/lib/python%s/dist-packages',
'var/lib/python-support/python%s',
'usr/lib/pymodules/python%s')]
ifversion>= (2, 6):
to_check.append("usr/lib/python%s/site-packages"%ver)
dstdir=sitedir(version, package)
forlocationinto_check:
srcdir="debian/%s/%s"% (package, location)
ifisdir(srcdir):
ifverinfound_versions:
log.error('files for version %s '
'found in two locations:\n %s\n %s',
ver, location, found_versions[ver])
exit(2)
log.warn('Python %s should install files in %s. '
'Did you forget "--install-layout=deb"?',
ver, sitedir(version))
ifnotisdir(dstdir):
os.makedirs(dstdir)
# TODO: what about relative symlinks?
log.debug('moving files from %s to %s', srcdir, dstdir)
os.renames(srcdir, dstdir)
found_versions[ver] =location
# do the same with debug locations
dbg_to_check= ['usr/lib/debug/%s'%iforiinto_check]
dbg_to_check.append("usr/lib/debug/usr/lib/pyshared/python%s"%ver)
dstdir=sitedir(version, package, gdb=True)
forlocationindbg_to_check:
srcdir="debian/%s/%s"% (package, location)
ifisdir(srcdir):
ifnotisdir(dstdir):
os.makedirs(dstdir)
log.debug('moving files from %s to %s', srcdir, dstdir)
os.renames(srcdir, dstdir)
### SHARING FILES ##############################################
defshare(package, stats, options):
"""Move files to /usr/share/pyshared/ if possible."""
ifpackage.endswith('-dbg'):
# nothing to share in debug packages
return
pubvers=debsorted(iforiinstats['public_vers'] ifi[0] ==2)
iflen(pubvers) >1:
forpos, version1inenumerate(pubvers):
dir1=sitedir(version1, package)
forversion2inpubvers[pos+1:]:
dir2=sitedir(version2, package)
dc=dircmp(dir1, dir2)
share_2x(dir1, dir2, dc)
eliflen(pubvers) ==1:
# TODO: remove this once file conflicts will not be needed anymore
move_to_pyshared(sitedir(pubvers[0], package))
forversioninstats['ext']:
create_ext_links(sitedir(version, package))
ifoptions.guess_versionsandpubvers:
forversioninget_requested_versions(options.vrange):
ifversionnotinpubvers:
log.debug('guessing files for Python %s', vrepr(version))
versions_without_ext=debsorted(set(pubvers) -\
stats['ext'])
ifnotversions_without_ext:
log.error('extension for python%s is missing. '
'Build extensions for all supported Python '
'versions (`pyversions -vr`) or adjust '
'X-Python-Version field or pass '
'--no-guessing-versions to dh_python2',
vrepr(version))
exit(3)
srcver=versions_without_ext[0]
ifsrcverinstats['public_vers']:
stats['public_vers'].add(version)
share_2x(sitedir(srcver, package), sitedir(version, package))
# remove duplicates
stats['requires.txt'] =set(realpath(i) foriinstats['requires.txt'])
stats['nsp.txt'] =set(realpath(i) foriinstats['nsp.txt'])
defmove_to_pyshared(dir1):
# dir1 starts with debian/packagename/usr/lib/pythonX.Y/*-packages/
debian, package, path=dir1.split('/', 2)
dstdir=join(debian, package, 'usr/share/pyshared/', \
'/'.join(dir1.split('/')[6:]))
fext=lambdafname: fname.rsplit('.', 1)[-1]
foriinos.listdir(dir1):
fpath1=join(dir1, i)
ifisdir(fpath1) andnotislink(fpath1):
ifany(fnforfninos.listdir(fpath1) iffext(fn) !='so'):
# at least one file that is not an extension
move_to_pyshared(join(dir1, i))
else:
iffext(i) =='so':
continue
fpath2=join(dstdir, i)
ifnotexists(fpath2):
ifnotexists(dstdir):
os.makedirs(dstdir)
ifislink(fpath1):
fpath1_target=os.readlink(fpath1)
ifisabs(fpath1_target):
os.symlink(fpath1_target, fpath2)
else:
fpath1_target=normpath(join(dir1, fpath1_target))
relative_symlink(fpath1_target, fpath2)
os.remove(fpath1)
else:
os.rename(fpath1, fpath2)
relative_symlink(fpath2, fpath1)
defcreate_ext_links(dir1):
"""Create extension symlinks in /usr/lib/pyshared/pythonX.Y.
These symlinks are used to let dpkg detect file conflicts with
python-support and python-central packages.
"""
debian, package, path=dir1.split('/', 2)
python, _, module_subpath=path[8:].split('/', 2)
dstdir=join(debian, package, 'usr/lib/pyshared/', python, module_subpath)
foriinos.listdir(dir1):
fpath1=join(dir1, i)
ifisdir(fpath1):
create_ext_links(fpath1)
elifi.rsplit('.', 1)[-1] =='so':
fpath2=join(dstdir, i)
ifexists(fpath2):
continue
ifnotexists(dstdir):
os.makedirs(dstdir)
relative_symlink(fpath1, join(dstdir, i))
defcreate_public_links(dir1, vrange, root=''):
"""Create public module symlinks for given directory."""
debian, package, path=dir1.split('/', 2)
versions=get_requested_versions(vrange)
forfninos.listdir(dir1):
fpath1=join(dir1, fn)
ifisdir(fpath1):
create_public_links(fpath1, vrange, join(root, fn))
else:
forversioninversions:
dstdir=join(sitedir(version, package), root)
ifnotexists(dstdir):
os.makedirs(dstdir)
relative_symlink(fpath1, join(dstdir, fn))
defshare_2x(dir1, dir2, dc=None):
"""Move common files to pyshared and create symlinks in original
locations."""
debian, package, path=dir2.split('/', 2)
# dir1 starts with debian/packagename/usr/lib/pythonX.Y/*-packages/
dstdir=join(debian, package, 'usr/share/pyshared/', \
'/'.join(dir1.split('/')[6:]))
ifnotexists(dstdir) andnotislink(dir1):
os.makedirs(dstdir)
ifdcisNone: # guess/copy mode
ifnotexists(dir2):
os.makedirs(dir2)
common_dirs= []
common_files= []
foriinos.listdir(dir1):
subdir1=join(dir1, i)
ifisdir(subdir1) andnotislink(subdir1):
common_dirs.append([i, None])
else:
# directories with .so files will be blocked earlier
common_files.append(i)
elifislink(dir1):
# skip this symlink in pyshared
# (dpkg has problems with symlinks anyway)
common_dirs= []
common_files= []
else:
common_dirs=dc.subdirs.iteritems()
common_files=dc.common_files
# dircmp returns common names only, lets check files more carefully...
common_files=cmpfiles(dir1, dir2, common_files, shallow=False)[0]
forfnincommon_files:
if'so'infn.split('.'): # foo.so, bar.so.0.1.2, etc.
# in unlikely case where extensions are exactly the same
continue
fpath1=join(dir1, fn)
fpath2=join(dir2, fn)
fpath3=join(dstdir, fn)
# do not touch symlinks created by previous loop or other tools
ifdcandnotislink(fpath1):
# replace with a link to pyshared
ifnotexists(fpath3):
os.rename(fpath1, fpath3)
relative_symlink(fpath3, fpath1)
eliffcmp(fpath3, fpath1, shallow=False):
os.remove(fpath1)
relative_symlink(fpath3, fpath1)
ifdcisNone: # guess/copy mode
ifislink(fpath1):
# ralative links will work as well, it's always the same level
os.symlink(os.readlink(fpath1), fpath2)
else:
ifexists(fpath3):
# cannot share it, pyshared contains another copy
fcopy(fpath1, fpath2)
else:
# replace with a link to pyshared
os.rename(fpath1, fpath3)
relative_symlink(fpath3, fpath1)
relative_symlink(fpath3, fpath2)
elifexists(fpath2) andexists(fpath3) and \
fcmp(fpath2, fpath3, shallow=False):
os.remove(fpath2)
relative_symlink(fpath3, fpath2)
fordn, dcincommon_dirs:
share_2x(join(dir1, dn), join(dir2, dn), dc)
### PACKAGE DETAILS ############################################
defscan(package, dname=None, clean_dbg_pkg=True):
"""Gather statistics about Python files in given package."""
r= {'requires.txt': set(),
'nsp.txt': set(),
'shebangs': set(),
'public_vers': set(),
'private_dirs': {},
'compile': False,
'ext': set()}
dbg_package=package.endswith('-dbg')
ifnotdname:
proot="debian/%s"%package
ifdnameisFalse:
private_to_check= []
else:
private_to_check= [i%packageforiin
('usr/lib/%s', 'usr/lib/games/%s',
'usr/share/%s', 'usr/share/games/%s')]
else:
# scan private directory *only*
proot=join('debian', package, dname.strip('/'))
private_to_check= [dname[1:]]
forroot, dirs, file_namesinos.walk(proot):
# ignore Python 3.X locations
if'/usr/lib/python3'inrootor\
'/usr/local/lib/python3'inroot:
# warn only once
ifroot[root.find('/lib/python'):].count('/') ==2:
log.warning('Python 3.x location detected, '
'please use dh_python3: %s', root)
continue
bin_dir=private_dir=None
public_dir=PUBLIC_DIR_RE.match(root)
ifpublic_dir:
version=getver(public_dir.group(1))
ifroot.endswith('-packages'):
r['public_vers'].add(version)
else:
# TODO: find a way to specify Python version private
# extension was build for
version=False
foriinprivate_to_check:
ifroot.startswith(join('debian', package, i)):
private_dir='/'+i
break
else: # i.e. not public_dir and not private_dir
iflen(root.split('/', 6)) <6and (\
root.endswith('/sbin') orroot.endswith('/bin') or\
root.endswith('/usr/games')):
# /(s)bin or /usr/(s)bin or /usr/games
bin_dir=root
# handle some EGG related data (.egg-info dirs)
fornameindirs:
ifname.endswith('.egg-info'):
ifdbg_packageandclean_dbg_pkg:
rmtree(join(root, name))
dirs.remove(name)
continue
clean_name=clean_egg_name(name)
ifclean_name!=name:
log.info('renaming %s to %s', name, clean_name)
os.rename(join(root, name), join(root, clean_name))
dirs[dirs.index(name)] =clean_name
ifroot.endswith('.egg-info'):
if'requires.txt'infile_names:
r['requires.txt'].add(join(root, 'requires.txt'))
if'namespace_packages.txt'infile_names:
r['nsp.txt'].add(join(root, 'namespace_packages.txt'))
continue
# check files
forfninsorted(file_names):
# sorted() to make sure .so files are handled before .so.foo
fpath=join(root, fn)
ifnotexists(fpath):
# could be removed while handling .so symlinks
continue
fext=fn.rsplit('.', 1)[-1]
iffextin ('pyc', 'pyo'):
os.remove(fpath)
continue
ifpublic_dir:
iffext=='so'andislink(fpath):
dstfpath=fpath
links=set()
whileislink(dstfpath):
links.add(dstfpath)
dstfpath=join(root, os.readlink(dstfpath))
ifexists(dstfpath) and'.so.'insplit(dstfpath)[-1]:
# rename .so.$FOO symlinks, remove other ones
forlpathinlinks:
log.info('removing symlink: %s', lpath)
os.remove(lpath)
log.info('renaming %s to %s', dstfpath, fn)
os.rename(dstfpath, fpath)
ifdbg_packageandclean_dbg_pkgandfextnotin ('so', 'h'):
os.remove(join(root, fn))
continue
elifprivate_dir:
ifexists(join(root, fn)):
mode=os.stat(join(root, fn))[ST_MODE]
ifmode&S_IXUSRormode&S_IXGRPormode&S_IXOTH:
res=shebang2pyver(join(root, fn))
ifres:
r['private_dirs'].setdefault(private_dir, {})\
.setdefault('shebangs', set()).add(res)
ifpublic_dirorprivate_dir:
iffext=='so':
so_version=so2pyver(join(root, fn))
ifso_version:
ifpublic_dir:
ifversion!=so_version:
log.error('extension linked to libpython%s '
'and shipped in python%s\'s dist-'
'packages: %s', vrepr(so_version),
vrepr(version), fn)
exit(7)
log.warn('public extension linked with '
'libpython%s: %s', vrepr(so_version), fn)
elifnotversion:
version=so_version
(rifpublic_direlse
r['private_dirs'].setdefault(private_dir, {}))\
.setdefault('ext', set()).add(version)
continue
eliffext=='py':
(rifpublic_direlse
r['private_dirs'].setdefault(private_dir, {}))\
['compile'] =True
continue
# .egg-info files
iffn.endswith('.egg-info'):
clean_name=clean_egg_name(fn)
ifclean_name!=fn:
log.info('renaming %s to %s', fn, clean_name)
os.rename(join(root, fn), join(root, clean_name))
continue
# search for scripts in bin dirs
ifbin_dir:
res=shebang2pyver(fpath)
ifres:
r['shebangs'].add(res)
ifdbg_packageandclean_dbg_pkg:
# remove empty directories in -dbg packages
proot=proot+'/usr/lib'
forroot, dirs, file_namesinos.walk(proot, topdown=False):
if'-packages/'inrootandnotfile_names:
try:
os.rmdir(root)
exceptException:
pass
log.debug("package %s details = %s", package, r)
returnr
################################################################
defmain():
usage='%prog -p PACKAGE [-V [X.Y][-][A.B]] DIR [-X REGEXPR]\n'
parser=OptionParser(usage, version='%prog 2.0~beta1',
option_class=Option)
parser.add_option('--no-guessing-versions', action='store_false',
dest='guess_versions', default=True,
help='disable guessing other supported Python versions')
parser.add_option('--no-guessing-deps', action='store_false',
dest='guess_deps', default=True, help='disable guessing dependencies')
parser.add_option('--skip-private', action='store_true', default=False,
help='don\'t check private directories')
parser.add_option('-v', '--verbose', action='store_true', default=False,
help='turn verbose mode on')
# arch=False->arch:all only, arch=True->arch:any only, None->all of them
parser.add_option('-i', '--indep', action='store_false',
dest='arch', default=None,
help='act on architecture independent packages')
parser.add_option('-a', '-s', '--arch', action='store_true',
dest='arch', help='act on architecture dependent packages')
parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
help='be quiet')
parser.add_option('-p', '--package', action='append',
help='act on the package named PACKAGE')
parser.add_option('-N', '--no-package', action='append',
help='do not act on the specified package')
parser.add_option('--compile-all', action='store_true', default=False,
help='compile all files from given private directory in postinst, '
'not just the ones provided by the package')
parser.add_option('-V', type='version_range', dest='vrange',
help='specify list of supported Python versions. '+\
'See pycompile(1) for examples')
parser.add_option('-X', '--exclude', action='append', dest='regexpr',
help='exclude items that match given REGEXPR. You may use this option '
'multiple times to build up a list of things to exclude.')
parser.add_option('--depends', action='append',
help='translate given requirements into Debian dependencies '
'and add them to ${python:Depends}. '
'Use it for missing items in requires.txt.')
parser.add_option('--recommends', action='append',
help='translate given requirements into Debian '
'dependencies and add them to ${python:Recommends}')
parser.add_option('--suggests', action='append',
help='translate given requirements into Debian '
'dependencies and add them to ${python:Suggests}')
parser.add_option('--namespace', action='append', dest='namespaces',
help='recreate __init__.py files for given namespaces at install time')
parser.add_option('--clean-pycentral', action='store_true', default=False,
help='generate maintainer script that will remove pycentral files')
parser.add_option('--ignore-shebangs', action='store_true', default=False,
help='do not translate shebangs into Debian dependencies')
parser.add_option('--ignore-namespace', action='store_true', default=False,
help="ignore Egg's namespace_packages.txt file and --namespace option")
parser.add_option('--no-dbg-cleaning', action='store_false',
dest='clean_dbg_pkg', default=True,
help='do not remove files from debug packages')
# ignore some debhelper options:
parser.add_option('-O', help=SUPPRESS_HELP)
options, args=parser.parse_args(sys.argv[1:] + \
os.environ.get('DH_OPTIONS', '').split())
# regexpr option type is not used so lets check patterns here
forpatterninoptions.regexpror []:
# fail now rather than at runtime
try:
pattern=re.compile(pattern)
exceptException:
log.error('regular expression is not valid: %s', pattern)
exit(1)
ifnotoptions.vrangeandexists('debian/pyversions'):
log.debug('parsing version range from debian/pyversions')
withopen('debian/pyversions') asfp:
forlineinfp:
line=line.strip()
iflineandnotline.startswith('#'):
options.vrange=parse_vrange(line)
break
# disable PyDist if dh_pydeb is used
ifoptions.guess_deps:
try:
rules=open('debian/rules', 'r').read()
exceptIOError:
log.warning('cannot open debian/rules file')
else:
ifre.search('\n\s*dh_pydeb', rules) or \
re.search('\n\s*dh\s+[^#]*--with[^#]+pydeb', rules):
log.warning('dh_pydeb detected, PyDist feature disabled')
options.guess_deps=False
ifnotargs:
private_dir=None
else:
private_dir=args[0]
ifnotprivate_dir.startswith('/'):
# handle usr/share/foo dirs (without leading slash)
private_dir='/'+private_dir
# TODO: support more than one private dir at the same time (see :meth:scan)
ifoptions.skip_private:
private_dir=False
ifoptions.verboseoros.environ.get('DH_VERBOSE') =='1':
log.setLevel(logging.DEBUG)
log.debug('argv: %s', sys.argv)
log.debug('options: %s', options)
log.debug('args: %s', args)
dh=DebHelper(options)
ifnotoptions.vrangeanddh.python_version:
options.vrange=parse_pycentral_vrange(dh.python_version)
forpackage, pdetailsindh.packages.iteritems():
ifoptions.archisFalseandpdetails['arch'] !='all'or \
options.archisTrueandpdetails['arch'] =='all':
continue
log.debug('processing package %s...', package)
ifnotprivate_dir:
ifnotpyinstall(package, options.vrange):
exit(4)
ifnotpyremove(package, options.vrange):
exit(5)
fix_locations(package)
stats=scan(package, private_dir, options.clean_dbg_pkg)
ifnotprivate_dir:
share(package, stats, options)
pyshared_dir="debian/%s/usr/share/pyshared/"%package
ifnotstats['public_vers'] andexists(pyshared_dir):
create_public_links(pyshared_dir, options.vrange)
stats['public_vers'] =get_requested_versions(options.vrange)
stats['compile'] =True
dependencies=Dependencies(package)
dependencies.parse(stats, options)
ifstats['public_vers']:
dh.addsubstvar(package, 'python:Versions', \
', '.join(sorted(vrepr(stats['public_vers']))))
ps=package.split('-', 1)
iflen(ps) >1andps[0] =='python':
dh.addsubstvar(package, 'python:Provides', \
', '.join("python%s-%s"% (i, ps[1])\
foriinsorted(vrepr(stats['public_vers']))))
pyclean_added=False# invoke pyclean only once in maintainer script
ifstats['compile']:
ifoptions.clean_pycentral:
dh.autoscript(package, 'preinst',
'preinst-pycentral-clean', '')
dh.autoscript(package, 'postinst', 'postinst-pycompile', '')
dh.autoscript(package, 'prerm', 'prerm-pyclean', '')
pyclean_added=True
forpdir, detailsinstats['private_dirs'].iteritems():
ifnotdetails.get('compile'):
continue
ifnotpyclean_added:
dh.autoscript(package, 'prerm', 'prerm-pyclean', '')
pyclean_added=True
args=pdir
ext_for=details.get('ext')
ifext_forisNone: # no extension
shebangs=list(vfori, vindetails.get('shebangs', []) ifv)
ifnotoptions.ignore_shebangsandlen(shebangs) ==1:
# only one version from shebang
args+=" -V %s"%vrepr(shebangs[0])
elifoptions.vrangeandoptions.vrange!= (None, None):
args+=" -V %s"%vrange_str(options.vrange)
elifFalseinext_for:
# at least one extension's version not detected
ifoptions.vrangeand'-'notinvrange_str(options.vrange):
ver=vrange_str(options.vrange)
else: # try shebang or default Python version
ver= (list(vfori, vindetails.get('shebangs', [])
ifv) or [None])[0] orDEFAULT
ver=vrepr(ver)
dependencies.depend("python%s"%ver)
args+=" -V %s"%vrepr(ver)
else:
version=ext_for.pop()
args+=" -V %s"%vrepr(version)
dependencies.depend("python%d.%d"%version)
forpatterninoptions.regexpror []:
args+=" -X '%s'"%pattern.replace("'", r"'\''")
dh.autoscript(package, 'postinst', 'postinst-pycompile', args)
dependencies.export_to(dh)
pydist_file=join('debian', "%s.pydist"%package)
ifexists(pydist_file):
ifnotvalidate_pydist(pydist_file):
log.warning("%s.pydist file is invalid", package)
else:
dstdir=join('debian', package, 'usr/share/python/dist/')
ifnotexists(dstdir):
os.makedirs(dstdir)
fcopy(pydist_file, join(dstdir, package))
# namespace feature - recreate __init__.py files at install time
ifoptions.ignore_namespace:
nsp=None
else:
nsp=ns.parse(stats['nsp.txt'], options.namespaces)
# note that pycompile/pyclean is already added to maintainer scripts
# and it should remain there even if __init__.py was the only .py file
ifnsp:
try:
nsp=ns.remove_from_package(package, nsp,
stats['public_vers'])
except (IOError, OSError), e:
log.error('cannot remove __init__.py from package: %s', e)
exit(6)
ifnsp:
dstdir=join('debian', package, 'usr/share/python/ns/')
ifnotexists(dstdir):
os.makedirs(dstdir)
withopen(join(dstdir, package), 'a') asfp:
fp.writelines("%s\n"%iforiinnsp)
pyshared=join('debian', package, 'usr/share/pyshared/')
ifisdir(pyshared) andnotos.listdir(pyshared):
# remove empty pyshared directory
os.rmdir(pyshared)
dh.save()
if__name__=='__main__':
main()