/
util.py
1707 lines (1455 loc) · 63.6 KB
/
util.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
#
# This module contains most of the code of stdeb.
#
import calendar
import os
import re
import select
import shutil
import sys
import time
import codecs
try:
# Python 2.x
import ConfigParser
except ImportError:
# Python 3.x
import configparser as ConfigParser
import subprocess
import tempfile
import stdeb # noqa: F401
from stdeb import log, __version__ as __stdeb_version__
if hasattr(os, 'link'):
link_func = os.link
else:
# matplotlib deletes link from os namespace, expected distutils workaround
link_func = shutil.copyfile
__all__ = ['DebianInfo', 'build_dsc', 'expand_tarball', 'expand_zip',
'stdeb_cmdline_opts', 'stdeb_cmd_bool_opts', 'recursive_hardlink',
'apply_patch', 'repack_tarball_with_debianized_dirname',
'expand_sdist_file', 'stdeb_cfg_options']
DH_MIN_VERS = '9' # Fundamental to stdeb >= 0.10
DH_DEFAULT_VERS = 9
PYTHON_ALL_MIN_VERS = '2.6.6-3'
try:
# Python 2.x
from exceptions import Exception
except ImportError:
# Python 3.x
pass
class CalledProcessError(Exception):
pass
class CantSatisfyRequirement(Exception):
pass
def check_call(*popenargs, **kwargs):
retcode = subprocess.call(*popenargs, **kwargs)
if retcode == 0:
return
raise CalledProcessError(retcode)
if sys.version_info[0] == 2:
help_str_py2 = 'If True, build package for python 2. (Default=True).'
help_str_py3 = 'If True, build package for python 3. (Default=False).'
else:
assert sys.version_info[0] == 3
help_str_py2 = 'If True, build package for python 2. (Default=False).'
help_str_py3 = 'If True, build package for python 3. (Default=True).'
stdeb_cmdline_opts = [
('dist-dir=', 'd',
"directory to put final built distributions in (default='deb_dist')"),
('patch-already-applied', 'a',
'patch was already applied (used when py2dsc calls sdist_dsc)'),
('default-distribution=', None,
"deprecated (see --suite)"),
('suite=', 'z',
"distribution name to use if not specified in .cfg (default='unstable')"),
('default-maintainer=', None,
'deprecated (see --maintainer)'),
('maintainer=', 'm',
'maintainer name and email to use if not specified in .cfg '
'(default from setup.py)'),
('debian-version=', None, 'debian version (Default: 1)'),
('extra-cfg-file=', 'x',
'additional .cfg file (in addition to stdeb.cfg if present)'),
('patch-file=', 'p',
'patch file applied before setup.py called '
'(incompatible with file specified in .cfg)'),
('patch-level=', 'l',
'patch file applied before setup.py called '
'(incompatible with file specified in .cfg)'),
('patch-posix', 'q',
'apply the patch with --posix mode'),
('remove-expanded-source-dir', 'r',
'remove the expanded source directory'),
('ignore-install-requires', 'i',
'ignore the requirements from requires.txt in the egg-info directory'),
('pycentral-backwards-compatibility=', None,
'This option has no effect, is here for backwards compatibility, and may '
'be removed someday.'),
('workaround-548392=', None,
'This option has no effect, is here for backwards compatibility, and may '
'be removed someday.'),
('no-backwards-compatibility', None,
'This option has no effect, is here for backwards compatibility, and may '
'be removed someday.'),
('guess-conflicts-provides-replaces=', None,
'If True, attempt to guess Conflicts/Provides/Replaces in debian/control '
'based on apt-cache output. (Default=False).'),
('with-python2=', None,
help_str_py2),
('with-python3=', None,
help_str_py3),
('no-python2-scripts=', None,
'If True, do not install scripts for python 2. (Default=False).'),
('no-python3-scripts=', None,
'If True, do not install scripts for python 3. (Default=False).'),
('force-x-python3-version', None,
'Override default minimum python3:any dependency with value from '
'x-python3-version'),
('allow-virtualenv-install-location', None,
'Allow installing into /some/random/virtualenv-path'),
('compat=', 'c',
'Debian compatibility level (Default={})'.format(DH_DEFAULT_VERS)),
('with-dh-virtualenv', None,
'Use dh_virtualenv to build the package instead of python_distutils. '
'This is useful to embed an application with all its dependencies '
'and dont touch to the system libraries.'),
('with-dh-systemd', None,
'Adds the systemd addon that will dh_systemd_enable and'
'dh_systemd_start helpers at the correct time during build.'),
('sign-results', None,
'Use gpg to sign the resulting .dsc and .changes file'),
('ignore-source-changes', None,
'Ignore all changes on source when building source package (add -i.* '
'option to dpkg-source)'),
]
# old entries from stdeb.cfg:
# These should be settable as distutils command options, but in case
# we want to support other packaging methods, they should also be
# settable outside distutils. Consequently, we keep the ability to
# parse ConfigParser files (specified with --extra-cfg-file). TODO:
# Also, some (most, in fact) of the above options should also be
# settable in the ConfigParser file.
stdeb_cfg_options = [
# With defaults
('source=', None,
'debian/control Source: (Default: <source-debianized-setup-name>)'),
('package=', None,
'debian/control Package: (Default: python-<debianized-setup-name>)'),
('package3=', None,
'debian/control Package: (Default: python3-<debianized-setup-name>)'),
('suite=', None,
'suite (e.g. stable, lucid) in changelog (Default: unstable)'),
('suite3=', None,
'suite3 Suites used when building with python3 only (Default: '
'<same-as-suite>)'),
('maintainer=', None,
'debian/control Maintainer: (Default: <setup-maintainer-or-author>)'),
('debian-version=', None, 'debian version (Default: 1)'),
('section=', None, 'debian/control Section: (Default: python)'),
# With no defaults
('epoch=', None, 'version epoch'),
('forced-upstream-version=', None, 'forced upstream version'),
('upstream-version-prefix=', None, 'upstream version prefix'),
('upstream-version-suffix=', None, 'upstream version suffix'),
('uploaders=', None, 'uploaders'),
('copyright-file=', None, 'copyright file'),
('build-depends=', None, 'debian/control Build-Depends:'),
('build-conflicts=', None, 'debian/control Build-Conflicts:'),
('stdeb-patch-file=', None, 'file containing patches for stdeb to apply'),
('stdeb-patch-level=', None, 'patch level provided to patch command'),
('depends=', None, 'debian/control Depends:'),
('depends3=', None, 'debian/control Depends:'),
('suggests=', None, 'debian/control Suggests:'),
('suggests3=', None, 'debian/control Suggests:'),
('recommends=', None, 'debian/control Recommends:'),
('recommends3=', None, 'debian/control Recommends:'),
('xs-python-version=', None, 'debian/control XS-Python-Version:'),
('x-python3-version=', None, 'debian/control X-Python3-Version:'),
('dpkg-shlibdeps-params=', None, 'parameters passed to dpkg-shlibdeps'),
('conflicts=', None, 'debian/control Conflicts:'),
('conflicts3=', None, 'debian/control Conflicts:'),
('breaks=', None, 'debian/control Breaks:'),
('breaks3=', None, 'debian/control Breaks:'),
('provides=', None, 'debian/control Provides:'),
('provides3=', None, 'debian/control Provides3:'),
('replaces=', None, 'debian/control Replaces:'),
('replaces3=', None, 'debian/control Replaces3:'),
('mime-desktop-files=', None, 'MIME desktop files'),
('mime-file=', None, 'MIME file'),
('shared-mime-file=', None, 'shared MIME file'),
('setup-env-vars=', None, 'environment variables passed to setup.py'),
('udev-rules=', None, 'file with rules to install to udev'),
('python2-depends-name=', None,
'Python 2 Debian package name used in ${python:Depends}'),
]
stdeb_cmd_bool_opts = [
'patch-already-applied',
'remove-expanded-source-dir',
'patch-posix',
'ignore-install-requires',
'no-backwards-compatibility',
'force-x-python3-version',
'allow-virtualenv-install-location',
'with-dh-virtualenv',
'with-dh-systemd',
'sign-results',
'ignore-source-changes',
]
class NotGiven:
pass
def process_command(args, cwd=None):
if not isinstance(args, (list, tuple)):
raise RuntimeError("args passed must be in a list")
check_call(args, cwd=cwd)
def recursive_hardlink(src, dst):
dst = os.path.abspath(dst)
orig_dir = os.path.abspath(os.curdir)
os.chdir(src)
try:
for root, dirs, files in os.walk(os.curdir):
for file in files:
fullpath = os.path.normpath(os.path.join(root, file))
dirname, fname = os.path.split(fullpath)
dstdir = os.path.normpath(os.path.join(dst, dirname))
if not os.path.exists(dstdir):
os.makedirs(dstdir)
newpath = os.path.join(dstdir, fname)
if os.path.exists(newpath):
if os.path.samefile(fullpath, newpath):
continue
else:
os.unlink(newpath)
# print 'linking %s -> %s'%(fullpath,newpath)
link_func(fullpath, newpath)
finally:
os.chdir(orig_dir)
def debianize_name(name):
"make name acceptable as a Debian (binary) package name"
name = name.replace('_', '-')
name = name.lower()
return name
def source_debianize_name(name):
"make name acceptable as a Debian source package name"
name = name.replace('_', '-')
name = name.replace('.', '-')
name = name.lower()
return name
def debianize_version(name):
"make name acceptable as a Debian package name"
# XXX should use setuptools' version sorting and do this properly:
name = name.replace('.dev', '~dev')
name = name.lower()
return name
def dpkg_compare_versions(v1, op, v2):
args = ['/usr/bin/dpkg', '--compare-versions', v1, op, v2]
cmd = subprocess.Popen(args)
returncode = cmd.wait()
if returncode:
return False
else:
return True
def get_cmd_stdout(args):
cmd = subprocess.Popen(args, stdout=subprocess.PIPE)
returncode = cmd.wait()
if returncode:
log.error('ERROR running: %s', ' '.join(args))
raise RuntimeError('returncode %d', returncode)
return cmd.stdout.read()
def get_date_822():
"""return output of 822-date command"""
source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH', None)
if source_date_epoch:
t = time.gmtime(int(source_date_epoch))
else:
t = time.localtime()
return time.strftime(
calendar.day_abbr[t.tm_wday] + ", %d " +
calendar.month_abbr[t.tm_mon] + " %Y %H:%M:%S %z", t)
def get_version_str(pkg):
args = ['/usr/bin/dpkg-query', '--show', '--showformat=${Version}', pkg]
stdout = get_cmd_stdout(args)
return stdout.strip().decode('ascii')
def load_module(name, fname):
import imp
suffix = '.py'
found = False
for description in imp.get_suffixes():
if description[0] == suffix:
found = True
break
assert found
fd = open(fname, mode='r')
try:
module = imp.load_module(name, fd, fname, description)
finally:
fd.close()
return module
def get_deb_depends_from_setuptools_requires(requirements, on_failure="warn"):
"""
Suppose you can't confidently figure out a .deb which satisfies a given
requirement. If on_failure == 'warn', then log a warning. If on_failure
== 'raise' then raise CantSatisfyRequirement exception. If on_failure ==
'guess' then guess that python-$FOO will satisfy the dependency and that
the Python version numbers will apply to the Debian packages (in addition
to logging a warning message).
"""
assert on_failure in ("raise", "warn", "guess"), on_failure
import pkg_resources
depends = [] # This will be the return value from this function.
parsed_reqs = []
for extra, reqs in pkg_resources.split_sections(requirements):
if extra:
continue
parsed_reqs.extend(pkg_resources.parse_requirements(reqs))
if not parsed_reqs:
return depends
if not os.path.exists('/usr/bin/apt-file'):
raise ValueError('apt-file not in /usr/bin. Please install '
'with: sudo apt-get install apt-file')
# Ask apt-file for any packages which have a .egg-info file by
# these names.
# Note that apt-file appears to think that some packages
# e.g. setuptools itself have "foo.egg-info/BLAH" files but not a
# "foo.egg-info" directory.
egginfore = (r"(/(%s)(?:-[^/]+)?(?:-py[0-9]\.[0-9.]+)?\.egg-info)"
% '|'.join(
req.project_name.replace('-', '_')
for req in parsed_reqs))
args = ["apt-file", "search", "--ignore-case", "--regexp", egginfore]
if 1:
# do dry run on apt-file
dry_run_args = args[:] + ['--dummy', '--non-interactive']
cmd = subprocess.Popen(dry_run_args, stderr=subprocess.PIPE)
returncode = cmd.wait()
if returncode:
err_output = cmd.stderr.read()
raise RuntimeError('Error running "apt-file search": ' +
err_output.strip())
try:
cmd = subprocess.Popen(args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True)
except Exception as le:
# TODO: catch rc=1 and "E: The cache directory is empty. You need to
# run 'apt-file update' first.", and tell the user to follow those
# instructions.
log.error('ERROR running: %s', ' '.join(args))
raise RuntimeError('exception %s from subprocess %s' % (le, args))
returncode = cmd.wait()
if returncode:
log.error('ERROR running: %s', ' '.join(args))
raise RuntimeError('returncode %d from subprocess %s' % (returncode,
args))
inlines = cmd.stdout.readlines()
dd = {} # {pydistname: {pydist: set(debpackagename)}}
E = re.compile(egginfore, re.I)
D = re.compile("^([^:]*):", re.I)
eggsndebs = set()
for line in inlines:
if line:
emo = E.search(line)
assert emo, line
dmo = D.search(line)
assert dmo, line
eggsndebs.add((emo.group(1), dmo.group(1)))
for (egginfo, debname) in eggsndebs:
pydist = pkg_resources.Distribution.from_filename(egginfo)
try:
dd.setdefault(
pydist.project_name.lower(), {}).setdefault(
pydist, set()).add(debname)
except ValueError as le:
log.warn("I got an error parsing a .egg-info file named \"%s\" "
"from Debian package \"%s\" as a pkg_resources "
"Distribution: %s" % (egginfo, debname, le,))
pass
# Now for each requirement, see if a Debian package satisfies it.
ops = {'<': '<<', '>': '>>', '==': '=', '<=': '<=', '>=': '>='}
for req in parsed_reqs:
reqname = req.project_name.lower()
gooddebs = set()
for pydist, debs in dd.get(reqname, {}).iteritems():
if pydist in req:
# log.info("I found Debian packages \"%s\" which provides "
# "Python package \"%s\", version \"%s\", which "
# "satisfies our version requirements: \"%s\""
# % (', '.join(debs), req.project_name, ver, req)
gooddebs |= (debs)
else:
log.info("I found Debian packages \"%s\" which provides "
"Python package \"%s\" which "
"does not satisfy our version requirements: "
"\"%s\" -- ignoring."
% (', '.join(debs), req.project_name, req))
if not gooddebs:
if on_failure == 'warn':
log.warn(
"I found no Debian package which provides the required "
"Python package \"%s\" with version requirements "
"\"%s\"." % (req.project_name, req.specs))
elif on_failure == "raise":
raise CantSatisfyRequirement(
"I found no Debian package which provides the required "
"Python package \"%s\" with version requirements "
"\"%s\"." % (req.project_name, req.specs), req)
elif on_failure == "guess":
log.warn("I found no Debian package which provides the "
"required Python package \"%s\" with version "
"requirements \"%s\". Guessing blindly that the "
"name \"python-%s\" will be it, and that the Python "
"package version number requirements will apply to "
"the Debian package." % (req.project_name,
req.specs, reqname))
gooddebs.add("python-" + reqname)
elif len(gooddebs) == 1:
log.info("I found a Debian package which provides the require "
"Python package. Python package: \"%s\", "
"Debian package: \"%s\"; adding Depends specifications "
"for the following version(s): \"%s\""
% (req.project_name, tuple(gooddebs)[0], req.specs))
else:
log.warn("I found multiple Debian packages which provide the "
"Python distribution required. I'm listing them all "
"as alternates. Candidate debs which claim to provide "
"the Python package \"%s\" are: \"%s\""
% (req.project_name, ', '.join(gooddebs),))
alts = []
for deb in gooddebs:
added_any_alt = False
for spec in req.specs:
# Here we blithely assume that the Debian package
# versions are enough like the Python package versions
# that the requirement can be ported straight over...
alts.append("%s (%s %s)" % (deb, ops[spec[0]], spec[1]))
added_any_alt = True
if not added_any_alt:
# No alternates were added, but we have the name of a
# good package.
alts.append("%s" % deb)
if len(alts):
depends.append(' | '.join(alts))
return depends
def make_tarball(tarball_fname, directory, cwd=None):
"create a tarball from a directory"
if tarball_fname.endswith('.gz'):
opts = 'czf'
else:
opts = 'cf'
args = ['/bin/tar', opts, tarball_fname, directory]
process_command(args, cwd=cwd)
def expand_tarball(tarball_fname, cwd=None):
"expand a tarball"
if tarball_fname.endswith('.gz'):
opts = 'xzf'
elif tarball_fname.endswith('.bz2'):
opts = 'xjf'
else:
opts = 'xf'
args = ['/bin/tar', opts, tarball_fname]
process_command(args, cwd=cwd)
def expand_zip(zip_fname, cwd=None):
"expand a zip"
unzip_path = '/usr/bin/unzip'
if not os.path.exists(unzip_path):
log.error('ERROR: {} does not exist'.format(unzip_path))
sys.exit(1)
args = [unzip_path, zip_fname]
# Does it have a top dir
res = subprocess.Popen(
[args[0], '-l', args[1]], cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
contents = []
for line in res.stdout.readlines()[3:-2]:
contents.append(line.split(None, 3)[-1])
commonprefix = os.path.commonprefix(contents)
if not commonprefix:
extdir = os.path.join(cwd, os.path.basename(zip_fname[:-4]))
args.extend(['-d', os.path.abspath(extdir)])
process_command(args, cwd=cwd)
def expand_sdist_file(sdist_file, cwd=None):
lower_sdist_file = sdist_file.lower()
if lower_sdist_file.endswith('.zip'):
expand_zip(sdist_file, cwd=cwd)
elif lower_sdist_file.endswith('.tar.bz2'):
expand_tarball(sdist_file, cwd=cwd)
elif lower_sdist_file.endswith('.tar.gz'):
expand_tarball(sdist_file, cwd=cwd)
else:
raise RuntimeError('could not guess format of original sdist file')
def repack_tarball_with_debianized_dirname(orig_sdist_file,
repacked_sdist_file,
debianized_dirname,
original_dirname):
working_dir = tempfile.mkdtemp()
expand_sdist_file(orig_sdist_file, cwd=working_dir)
fullpath_original_dirname = os.path.join(working_dir, original_dirname)
fullpath_debianized_dirname = os.path.join(working_dir, debianized_dirname)
# ensure sdist looks like sdist:
assert os.path.exists(fullpath_original_dirname)
assert len(os.listdir(working_dir)) == 1
if fullpath_original_dirname != fullpath_debianized_dirname:
# rename original dirname to debianized dirname
os.rename(fullpath_original_dirname,
fullpath_debianized_dirname)
make_tarball(repacked_sdist_file, debianized_dirname, cwd=working_dir)
shutil.rmtree(working_dir)
def dpkg_buildpackage(*args, **kwargs):
cwd = kwargs.pop('cwd', None)
if len(kwargs) != 0:
raise ValueError('only kwarg can be "cwd"')
"call dpkg-buildpackage [arg1] [...] [argN]"
args = ['/usr/bin/dpkg-buildpackage']+list(args)
process_command(args, cwd=cwd)
def dpkg_source(b_or_x, arg1, cwd=None):
"call dpkg-source -b|x arg1 [arg2]"
assert b_or_x in ['-b', '-x']
args = ['/usr/bin/dpkg-source', b_or_x, arg1]
process_command(args, cwd=cwd)
def apply_patch(patchfile, cwd=None, posix=False, level=0):
"""call 'patch -p[level] [--posix] < arg1'
posix mode is sometimes necessary. It keeps empty files so that
dpkg-source removes their contents.
"""
if not os.path.exists(patchfile):
raise RuntimeError('patchfile "%s" does not exist' % patchfile)
fd = open(patchfile, mode='r')
level_str = '-p%d' % level
args = ['/usr/bin/patch', level_str]
if posix:
args.append('--posix')
log.info('PATCH COMMAND: %s < %s', ' '.join(args), patchfile)
log.info(' PATCHING in dir: %s', cwd)
# print >> sys.stderr, 'PATCH COMMAND:',' '.join(args),'<',patchfile
# print >> sys.stderr, ' PATCHING in dir:',cwd
res = subprocess.Popen(
args, cwd=cwd,
stdin=fd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
returncode = None
while returncode is None:
returncode = res.poll()
ready = select.select([res.stdout, res.stderr], [], [], 0.1)
# XXX figure out how to do this without reading byte-by-byte
if res.stdout in ready[0]:
sys.stdout.write(res.stdout.read(1))
sys.stdout.flush()
if res.stderr in ready[0]:
sys.stderr.write(res.stderr.read(1))
sys.stderr.flush()
# finish outputting file
sys.stdout.write(res.stdout.read())
sys.stdout.flush()
sys.stderr.write(res.stderr.read())
sys.stderr.flush()
if returncode:
log.error('ERROR running: %s', ' '.join(args))
log.error('ERROR in %s', cwd)
# print >> sys.stderr, 'ERROR running: %s'%(' '.join(args),)
# print >> sys.stderr, 'ERROR in',cwd
raise RuntimeError('returncode %d' % returncode)
def parse_vals(cfg, section, option):
"""parse comma separated values in debian control file style from .cfg"""
try:
vals = cfg.get(section, option)
except ConfigParser.NoSectionError as err:
if section != 'DEFAULT':
vals = cfg.get('DEFAULT', option)
else:
raise err
vals = vals.split('#')[0]
vals = vals.strip()
vals = vals.split(',')
vals = [v.strip() for v in vals]
vals = [v for v in vals if len(v)]
return vals
def parse_val(cfg, section, option):
"""extract a single value from .cfg"""
vals = parse_vals(cfg, section, option)
if len(vals) == 0:
return ''
else:
assert len(vals) == 1, (section, option, vals, type(vals))
return vals[0]
def apt_cache_info(apt_cache_cmd, package_name):
if apt_cache_cmd not in ('showsrc', 'show'):
raise NotImplementedError(
"don't know how to run apt-cache command '%s'" % apt_cache_cmd)
result_list = []
args = ["apt-cache", apt_cache_cmd, package_name]
cmd = subprocess.Popen(args,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
returncode = cmd.wait()
if returncode:
errline = cmd.stderr.read()
if not (
returncode == 100 and errline ==
"E: You must put some 'source' URIs in your sources.list\n"
):
log.error('ERROR running: %s', ' '.join(args))
raise RuntimeError(
'returncode %d from subprocess %s' % (returncode, args))
inlines = cmd.stdout.read()
version_blocks = inlines.split('\n\n')
for version_block in version_blocks:
block_dict = {}
if len(version_block) == 0:
continue
version_lines = version_block.split('\n')
assert version_lines[0].startswith('Package: ')
block_dict['Package'] = version_lines[0][len('Package: '):]
if apt_cache_cmd == 'showsrc':
assert version_lines[1].startswith('Binary: ')
block_dict['Binary'] = version_lines[1][len('Binary: '):]
block_dict['Binary'] = block_dict['Binary'].split(', ')
elif apt_cache_cmd == 'show':
for start in ('Provides: ', 'Conflicts: ', 'Replaces: '):
key = start[:-2]
for line in version_lines[2:]:
if line.startswith(start):
unsplit_line_result = line[len(start):]
split_result = unsplit_line_result.split(', ')
block_dict[key] = split_result
if key not in block_dict:
block_dict[key] = []
result_list.append(block_dict)
return result_list
def check_cfg_files(cfg_files, module_name):
"""check if the configuration files actually specify something
If config files are given, give warning if they don't contain
information. This may indicate a wrong module name name, for
example.
"""
cfg = ConfigParser.SafeConfigParser()
cfg.read(cfg_files)
if cfg.has_section(module_name):
section_items = cfg.items(module_name)
else:
section_items = []
default_items = cfg.items('DEFAULT')
n_items = len(section_items) + len(default_items)
if n_items == 0:
log.warn('configuration files were specified, but no options were '
'found in "%s" or "DEFAULT" sections.' % (module_name,))
class DebianInfo:
"""encapsulate information for Debian distribution system"""
def __init__(self,
cfg_files=NotGiven,
module_name=NotGiven,
default_distribution=NotGiven,
guess_maintainer=NotGiven,
upstream_version=NotGiven,
has_ext_modules=NotGiven,
description=NotGiven,
long_description=NotGiven,
homepage=NotGiven,
patch_file=None,
patch_level=None,
setup_requires=None,
debian_version=None,
use_setuptools=False,
guess_conflicts_provides_replaces=False,
sdist_dsc_command=None,
with_python2=None,
with_python3=None,
no_python2_scripts=None,
no_python3_scripts=None,
force_x_python3_version=False,
allow_virtualenv_install_location=False,
compat=DH_DEFAULT_VERS,
with_dh_virtualenv=False,
with_dh_systemd=False,
):
if cfg_files is NotGiven:
raise ValueError("cfg_files must be supplied")
if module_name is NotGiven:
raise ValueError("module_name must be supplied")
if default_distribution is NotGiven:
raise ValueError("default_distribution must be supplied")
if guess_maintainer is NotGiven:
raise ValueError("guess_maintainer must be supplied")
if upstream_version is NotGiven:
raise ValueError("upstream_version must be supplied")
if has_ext_modules is NotGiven:
raise ValueError("has_ext_modules must be supplied")
if description is NotGiven:
raise ValueError("description must be supplied")
if long_description is NotGiven:
raise ValueError("long_description must be supplied")
if homepage is NotGiven:
raise ValueError("homepage must be supplied")
cfg_defaults = self._make_cfg_defaults(
module_name=module_name,
default_distribution=default_distribution,
guess_maintainer=guess_maintainer,
)
if len(cfg_files):
check_cfg_files(cfg_files, module_name)
cfg = ConfigParser.SafeConfigParser(cfg_defaults)
for cfg_file in cfg_files:
with codecs.open(cfg_file, mode='r', encoding='utf-8') as fd:
cfg.readfp(fd)
if sdist_dsc_command is not None:
# Allow distutils commands to override config files (this lets
# command line options beat file options).
for longopt, shortopt, desc in stdeb_cfg_options:
opt_name = longopt[:-1]
name = opt_name.replace('-', '_')
value = getattr(sdist_dsc_command, name)
if value is not None:
if not cfg.has_section(module_name):
cfg.add_section(module_name)
cfg.set(module_name, opt_name, value)
self.stdeb_version = __stdeb_version__
self.module_name = module_name
self.compat = compat
self.source = parse_val(cfg, module_name, 'Source')
self.package = parse_val(cfg, module_name, 'Package')
self.package3 = parse_val(cfg, module_name, 'Package3')
forced_upstream_version = parse_val(cfg, module_name,
'Forced-Upstream-Version')
if forced_upstream_version == '':
upstream_version_prefix = parse_val(cfg, module_name,
'Upstream-Version-Prefix')
upstream_version_suffix = parse_val(cfg, module_name,
'Upstream-Version-Suffix')
self.upstream_version = (upstream_version_prefix +
debianize_version(upstream_version) +
upstream_version_suffix)
else:
if (
debianize_version(forced_upstream_version) !=
forced_upstream_version
):
raise ValueError(
'forced upstream version ("%s") not a '
'Debian-compatible version (e.g. "%s")' % (
forced_upstream_version,
debianize_version(forced_upstream_version)))
self.upstream_version = forced_upstream_version
self.epoch = parse_val(cfg, module_name, 'Epoch')
if self.epoch != '' and not self.epoch.endswith(':'):
self.epoch = self.epoch + ':'
self.packaging_version = parse_val(cfg, module_name, 'Debian-Version')
if debian_version is not None:
# command-line arg overrides file
self.packaging_version = debian_version
self.dsc_version = '%s-%s' % (
self.upstream_version,
self.packaging_version)
self.full_version = '%s%s-%s' % (
self.epoch,
self.upstream_version,
self.packaging_version)
self.distname = parse_val(cfg, module_name, 'Suite')
self.distname3 = parse_val(cfg, module_name, 'Suite3')
self.maintainer = ', '.join(parse_vals(cfg, module_name, 'Maintainer'))
self.uploaders = parse_vals(cfg, module_name, 'Uploaders')
self.date822 = get_date_822()
build_deps = []
if use_setuptools:
if with_python2:
build_deps.append('python-setuptools (>= 0.6b3)')
if with_python3:
build_deps.append('python3-setuptools')
if setup_requires is not None and len(setup_requires):
build_deps.extend(
get_deb_depends_from_setuptools_requires(setup_requires))
depends = ['${misc:Depends}', '${python:Depends}']
depends3 = ['${misc:Depends}', '${python3:Depends}']
need_custom_binary_target = False
if has_ext_modules:
self.architecture = 'any'
if with_python2:
build_deps.append(
'python-all-dev (>= %s)' % PYTHON_ALL_MIN_VERS)
depends.append('${shlibs:Depends}')
self.architecture3 = 'any'
if with_python3:
build_deps.append('python3-all-dev')
depends3.append('${shlibs:Depends}')
else:
self.architecture = 'all'
if with_python2:
build_deps.append('python-all (>= %s)' % PYTHON_ALL_MIN_VERS)
self.architecture3 = 'all'
if with_python3:
build_deps.append('python3-all')
self.copyright_file = parse_val(cfg, module_name, 'Copyright-File')
self.mime_file = parse_val(cfg, module_name, 'MIME-File')
self.shared_mime_file = parse_val(cfg, module_name, 'Shared-MIME-File')
if self.mime_file == '' and self.shared_mime_file == '':
self.dh_installmime_indep_line = ''
else:
need_custom_binary_target = True
self.dh_installmime_indep_line = '\tdh_installmime'
mime_desktop_files = parse_vals(cfg, module_name, 'MIME-Desktop-Files')
if len(mime_desktop_files):
need_custom_binary_target = True
# E. any mime .desktop files
self.install_file_lines = []
for mime_desktop_file in mime_desktop_files:
self.install_file_lines.append(
'%s usr/share/applications' % mime_desktop_file)
depends.extend(parse_vals(cfg, module_name, 'Depends'))
depends3.extend(parse_vals(cfg, module_name, 'Depends3'))
self.depends = ', '.join(depends)
self.depends3 = ', '.join(depends3)
self.debian_section = parse_val(cfg, module_name, 'Section')
self.description = re.sub(r'\s+', ' ', description).strip()
if long_description != 'UNKNOWN':
ld2 = []
for line in long_description.split('\n'):
ls = line.strip()
if len(ls):
ld2.append(' '+line)
else:
ld2.append(' .')
ld2 = ld2[:20]
self.long_description = '\n'.join(ld2)
else:
self.long_description = ''
build_deps.append('debhelper (>= %s)' % DH_MIN_VERS)
build_deps.extend(parse_vals(cfg, module_name, 'Build-Depends'))
self.build_depends = ', '.join(build_deps)
suggests = ', '.join(parse_vals(cfg, module_name, 'Suggests'))
suggests3 = ', '.join(parse_vals(cfg, module_name, 'Suggests3'))
recommends = ', '.join(parse_vals(cfg, module_name, 'Recommends'))
recommends3 = ', '.join(parse_vals(cfg, module_name, 'Recommends3'))
self.source_stanza_extras = ''
if homepage != 'UNKNOWN':
self.source_stanza_extras += 'Homepage: %s\n' % homepage
build_conflicts = parse_vals(cfg, module_name, 'Build-Conflicts')
if len(build_conflicts):
self.source_stanza_extras += ('Build-Conflicts: ' +
', '.join(build_conflicts)+'\n')
self.patch_file = parse_val(cfg, module_name, 'Stdeb-Patch-File')
if patch_file is not None:
if self.patch_file != '':
raise RuntimeError('A patch file was specified on the command '
'line and in .cfg file.')
else:
self.patch_file = patch_file
self.patch_level = parse_val(cfg, module_name, 'Stdeb-Patch-Level')
if self.patch_level != '':
if patch_level is not None:
raise RuntimeError('A patch level was specified on the '
'command line and in .cfg file.')
else:
self.patch_level = int(self.patch_level)
else:
if patch_level is not None:
self.patch_level = patch_level
else:
self.patch_level = 0
python2_depends_name = parse_val(
cfg, module_name, 'Python2-Depends-Name')
xs_python_version = parse_vals(cfg, module_name, 'XS-Python-Version')
if len(xs_python_version) != 0:
self.source_stanza_extras += ('X-Python-Version: ' +
', '.join(xs_python_version)+'\n')
x_python3_version = parse_vals(cfg, module_name, 'X-Python3-Version')
x_python3_version = [v.strip('"') for v in x_python3_version]
if len(x_python3_version) != 0:
self.source_stanza_extras += ('X-Python3-Version: ' +