forked from maphew/apt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapt.py
2104 lines (1814 loc) · 74.4 KB
/
apt.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
#!/usr/bin/env python
#@+leo-ver=5-thin
#@+node:maphew.20150327024628.2: * @file apt.py
#@@first
#@@language python
#@@tabwidth -4
#@+<<docstring>>
#@+node:maphew.20100307230644.3846: ** <<docstring>>
'''Apt command line installer and package manager for Osgeo4W.
Examples
--------
Typical daily use::
apt update (fetch up-to-date setup.ini)
apt install gdal gdal-python (install packages "gdal" and "gdal-python", and dependencies)
apt new (show possible upgrades)
apt list (show installed packages)
apt available (show installation candidates)
apt remove xxx yyy (uninstall packages xxx and yyy)
Notes
-----
Apt strives to match Osgeo4wSetup.exe's results as closely as possible, and uses
the same configuration and install manifest files. A prime directive is that
user's should never be put in a position where they feel the need to choose
between the tools and not go back.
That's the aspiration. There's no guarantee it's been achieved.
At the moment apt can only install the 32bit Osgeo4W packages.
References
----------
.. [1] Based on ``cyg-apt`` - "Cygwin installer to keep cygwin root up to date"
(c) 2002--2003 Jan Nieuwenhuizen <[email protected]>
License: GNU GPL
Modified by [email protected] for OSGeo4W,
beginning July 2008
'''
apt_version = '0.4'
#@-<<docstring>>
#@+<<imports>>
#@+node:maphew.20100307230644.3847: ** <<imports>>
import __main__
import getopt
import os
import glob
import re
import shutil
import string
import sys
import urllib
import gzip, tarfile, bz2
import hashlib
import requests
import subprocess
import shlex
import locale
import knownpaths # for fetching Windows special folders
from pkg_resources import parse_version # for version comparing
from datetime import datetime, timedelta
#from attrdict import AttrDict
#@-<<imports>>
#@@language python
#@@tabwidth -4
#@+others
#@+node:maphew.20100223163802.3718: ** usage
def usage ():
print('-={ %s }=-\n'% apt_version)
# better: use parsopt instead, #53 http://trac.osgeo.org/osgeo4w/ticket/53
sys.stdout.write ('''apt [OPTION]... COMMAND [PACKAGE]...
Commands:
available - show packages available to be installed
ball - print full path name of package archive
download - download package
find - package containing file (from installed packages)
hashcheck - check md5 sum of local package vs mirror
help - show help for COMMAND
info - report name, version, category etc. for specified packages
install - download and install packages, including dependencies
list - report installed packages
listfiles - installed with package X
missing - print missing dependencies for X
new - list available upgrades to currently installed packages
remove - uninstall packages
requires - report package dependencies
search - search available packages list for X
setup - skeleton installed packages environment
update - setup.ini
upgrade - all installed packages
url - print package archive path, relative to mirror root
version - print installed version of X
Options:
-b,--bits=32/64 use 32 or 64bit package mirror (only used with `apt setup`)
-d,--download download only
-i,--ini=FILE use setup.ini [%(setup_ini)s]
-m,--mirror=URL use mirror [%(mirror)s]
-r,--root=DIR set osgeo4w root [%(root)s]
-t,--t=NAME set dist name (*curr*, test, prev)
-x,--no-deps ignore dependencies
-s,--start-menu=NAME set the start menu name (OSGeo4W)
--debug display debugging statements
''' % {'setup_ini':setup_ini,'mirror':mirror,'root':root}) #As they were just printing as "%(setup_ini)s" etc...
#@+node:maphew.20121113004545.1577: ** check_env
def check_env(o4w=''):
'''Verify we're running in an Osgeo4W-ready shell'''
#From command line:
if o4w:
OSGEO4W_ROOT = o4w
os.environ['OSGEO4W_ROOT'] = o4w
os.environ['OSGEO4W_ROOT_MSYS'] = OSGEO4W_ROOT # textreplace.exe needs this (post_install)
OSGEO4W_ROOT = OSGEO4W_ROOT.replace('\\', '/')
#From environment:
elif 'OSGEO4W_ROOT' in os.environ.keys():
OSGEO4W_ROOT = os.environ['OSGEO4W_ROOT']
os.putenv('OSGEO4W_ROOT_MSYS', OSGEO4W_ROOT)
OSGEO4W_ROOT = string.replace(OSGEO4W_ROOT, '\\', '/')
else:
sys.stderr.write('error: Please set OSGEO4W_ROOT or use --root=DIR\n')
sys.exit(2)
return OSGEO4W_ROOT
#@+node:maphew.20121111221942.1497: ** check_setup
def check_setup(installed_db, setup_ini):
'''Look to see if the installed packages db and setup.ini are available'''
## for i in (installed_db, setup_ini):
## if not os.path.isfile(i):
## sys.stderr.write('error: %s no such file\n' % i)
## sys.stderr.write('error: set OSGEO4W_ROOT and run "apt setup"\n')
## sys.exit(2)
# AMR66: above changed, because not compatible with osgeo-setup
failed = ""
if not os.path.isfile(installed_db):
failed = installed_db
# search for setup.ini:
if not os.path.isfile(setup_ini):
filename = '%s/%s'%(bits, 'setup.ini')
archive = os.path.join(downloads, filename)
# copy it, like update() does
if os.path.isfile(archive):
shutil.copy(archive, setup_ini)
else:
failed = archive
if failed:
sys.stderr.write('error: %s no such file\n' % failed)
sys.stderr.write('error: set OSGEO4W_ROOT and run "apt setup"\n')
sys.exit(2)
#@+node:maphew.20100302221232.1487: ** Commands
#@+node:maphew.20100223163802.3719: *3* available
def available(dummy):
'''Show packages available on the mirror.
Display packages available on the mirror, with installed packages marked ``*``.
Specify an alternate mirror with ``--mirror=...``
Parameters
----------
dummy : str
Parameter is not used at present.
Returns
-------
list
Package names (without install mark).
'''
# All packages mentioned in setup.ini for the specified distribution
a_list = dists[distname].keys()
# mark installed packages
i_list = list(a_list)
for p in installed[0].keys():
i_list.remove(p)
i_list.append('%s*' % p)
# Report to user, in columns, courtesy of Aaron Digulla,
# http://stackoverflow.com/questions/1524126/how-to-print-a-list-more-nicely
print '\n {} Packages available to install (* = already installed)\n'.format(len(i_list))
i_list.sort()
split = len(i_list)/2
col1 = i_list[0:split]
col2 = i_list[split:]
for key, value in zip(col1,col2):
print '{:<30}{}'.format(key, value)
return a_list
#@+node:maphew.20100223163802.3720: *3* ball
def ball(packages):
'''Print full local path name of package archive
C:\> apt ball shell
shell = d:/temp/o4w-cache/setup/http%3a%2f%2fdownload.osgeo.org%2fosgeo4w%2f/x86
/release/shell/shell-1.0.0-13.tar.bz2
FIXME: This should either return a list of archive filenames,
or there should be a get_ball(p) which returns 1 filename,
or we should rip out all this repetitive code spread across multiple functions,
for the purpose of allowing multiple package input. We need a handler for this instead.
'''
if isinstance(packages, basestring): packages = [packages]
if not packages:
help('ball')
sys.stderr.write("\n*** No package names specified. ***\n")
return
for p in packages:
d = get_info(p)
print "\n%s = %s" % (p, d['local_zip'])
return
#@+node:maphew.20100223163802.3721: *3* download
def download(packages):
'''Download the package(s) from mirror and save in local cache folder:
C:\> apt download shell gdal {...etc}
shell = d:/temp/o4w-cache/setup/http%3a%2f%2fdownload.osgeo.org%2fosgeo4w%2f/x86/release/shell/shell-1.0.0-13.tar.bz2
remote: c38f03d2b7160f891fc36ec776ca4685 shell-1.0.0-13.tar.bz2
local: c38f03d2b7160f891fc36ec776ca4685 shell-1.0.0-13.tar.bz2
gdal = d:/temp/o4w-cache/setup/http%3a%2f%2fdownload.osgeo.org%2fosgeo4w%2f/x86/release/gdal/gdal-1.11.1-4.tar.bz2
remote: 3b60f036f0d29c401d0927a9ae000f0c gdal-1.11.1-4.tar.bz2
local: 3b60f036f0d29c401d0927a9ae000f0c gdal-1.11.1-4.tar.bz2
Use `apt available` to see what is on the mirror for downloading.
'''
if isinstance(packages, basestring): packages = [packages]
if debug:
print '\n### DEBUG: %s ###' % sys._getframe().f_code.co_name
if not packages:
help('download')
sys.stderr.write("\n*** No package names specified. ***\n")
return
print "Preparing to download:", ', '.join(packages)
for p in packages:
do_download(p)
ball(p)
hashcheck(p)
#@+node:maphew.20141101125304.3: *3* info
def info(packages):
'''info - report name, version, category, etc. about the package(s)
B:\> apt info shell
name : shell
version : 1.0.0-13
sdesc : "OSGeo4W Command Shell"
ldesc : "Menu and Desktop icon launch OSGeo4W command shell"
category : Commandline_Utilities
requires : msvcrt setup
zip_path : x86/release/shell/shell-1.0.0-13.tar.bz2
zip_size : 3763
md5 : c38f03d2b7160f891fc36ec776ca4685
local_zip: d:/temp/o4w-cache/setup/http%3.../shell-1.0.0-13.tar.bz2
installed: True
install_v: 1.0.0-11
Notes:
- "local_zip" is best guess based on current mirror. (We don't record which mirror was in use at the time of package install.)
- "version" is from setup.ini, what is available on the mirror server
- "install_v" is the version currently installed
'''
if isinstance(packages, basestring): packages = [packages]
if not packages:
help('info')
sys.stderr.write("\n*** Can't show info, no package names specified. ***\n")
return
for p in packages:
d = get_info(p)
print('')
# WARNING: only prints fields we know about, if something is added
# upstream we'll miss it here
fields = ['name',
'version',
'sdesc',
'ldesc',
'category',
'requires',
'zip_path',
'zip_size',
'md5',
'local_zip',
'installed']
for k in fields:
print('{0:9}: {1}'.format(k,d[k]))
if d['installed']:
print('{0:9}: {1}'.format('install_v',d['install_v']))
if debug:
# This guaranteed to print entire dict contents,
# but not in a logical order.
print '\n----- DEBUG: %s -----' % sys._getframe().f_code.co_name
for k in d.keys():
print('{0:8}:\t{1}'.format(k,d[k]))
print '-' * 36
#@+node:maphew.20100223163802.3722: *3* find
def find(patterns):
'''Search installed packages for filenames matching the specified text string.'''
if not patterns:
sys.stderr.write('\nFind what? Enter a filename to look for (partial is ok).\n')
return
for p in patterns:
print '--- %s:' % p
hits = []
for package in sorted(installed[0].keys()):
for line in get_filelist(package):
if p.lower() in line.lower():
hits.append('%s: /%s' % (package, line))
results = (string.join(hits, '\n'))
if results:
print results
return results
#@+node:maphew.20100223163802.3723: *3* help
def help(*args):
'''Show help for COMMAND'''
action = args[-1] # ([],) --> []
if type(action) is str: action = [action] # convert bare string to list
# Show general usage help when no specific action named
if not (action) or (action == ['help']):
usage()
sys.exit(0)
action = action[-1] # ['help','remove'] --> 'remove'
# display the function's docstring
d = __main__.__dict__
if action in d.keys():
print "\n" + d[action].__doc__
else:
print 'Sorry, function "%s" not found in __main__' % action
#@+node:maphew.20100223163802.3724: *3* install
def install(packages, force=False):
'''Download and install packages, including dependencies
C:\> apt install shell gdal
'''
if isinstance(packages, basestring): packages = [packages]
# where do we get those...?
while '' in packages:
packages.remove('')
if debug: print "--- Found and removed extraneous '' in `packages`"
if debug:
print '\n--- DEBUG: %s ---' % sys._getframe().f_code.co_name
print '--- pkgs:', packages
if not packages:
sys.stderr.write('\n*** No packages specified. Use "apt available" for ideas. ***\n')
help('install')
return
# build list of dependencies
reqs = []
reqs = get_all_dependencies(packages, reqs)
if debug: print 'PKGS: %s, REQS: %s' % (packages, reqs)
print '\nPKGS: Checking install status: {}\n'.format(' '.join(packages))
print '{:20}{:12}({})\n{}'.format('Requirement', 'Installed', 'Available', '-'*43)
delete = []
for p in reqs:
p_installed = get_info(p)['installed']
ini_v = version_to_string(get_version(p))
print '{:19}'.format(p),
if p_installed:
local_v = version_to_string(get_installed_version(p))
if parse_version(local_v) >= parse_version(ini_v):
print '{:12}({})'.format(local_v, ini_v)
delete.append(p)
else:
print '{:12}({})'.format('-', ini_v)
# safety first: delete after loop
reqs = [x for x in reqs if x not in delete]
if reqs:
print '\nREQS: --- To install: {}\n'.format(' '.join(reqs))
for r in reqs:
download(r)
if download_p: # quit if download only flag is set
continue
do_install(r)
else:
print '\nPackages and required dependencies are installed.\n'
version(pkgs_requested)
print ''
version(reqs_requested)
#@+node:maphew.20100510140324.2366: *4* install_next (missing_packages)
def install_next(packages, resolved, seen):
## global packagename
for p in packages:
if p in resolved:
continue
seen.add(p)
dependences = get_missing(p)
dependences.remove(p)
for dep in dependences:
if dep in resolved:
continue
if dep in seen:
raise Exception(
'Required package %s from %s is a circular reference '
'with a previous dependent' % (dep, p))
install_next(dependences, resolved, seen)
if installed[0].has_key(p):
sys.stderr.write('preparing to replace %s %s\n' \
% (p, version_to_string(get_installed_version(p))))
do_uninstall(p)
sys.stderr.write('installing %s %s\n' \
% (p, version_to_string(get_version(p))))
do_install(p)
resolved.add(p)
#@+node:maphew.20150208163633.3: *4* def unique
def unique(L):
'''Remove duplicates and empty items from a list'''
L = list(set(L))
L = [i for i in L if i != '']
return L
#@+node:maphew.20100223163802.3725: *3* list_installed
def list_installed(dummy):
'''List installed packages'''
# fixme: once again, 'dummy' defined but not used. fix after calling structure is refactored
## global packagename
s = '%-20s%-15s' % ('Package', 'Version')
print s
s = '%-20s%-15s' % ('-'*18, '-'*10)
print s
for p in sorted (installed[0].keys()):
ins = get_installed_version(p)
new = 0
if dists[distname].has_key(p) \
and dists[distname][p].has_key(INSTALL):
new = get_version(p)
s = '%-20s%-15s' % (p, version_to_string(ins))
if new and new != ins:
s += '(%s)' % version_to_string(new)
print s
#@+node:mhw.20120404170129.1475: *3* listfiles
def listfiles(packages):
'''List files installed with package X. Multiple packages can be specified.
C:\> apt listfiles shell gdal
----- shell -----
OSGeo4W.bat
OSGeo4W.ico
bin
...etc
----- gdal -----
bin
bin/gdal111.dll
bin/gdaladdo.exe
...etc
'''
if isinstance(packages, basestring): packages = [packages]
if not packages:
help('listfiles')
sys.stderr.write ('\n*** No packages specified. Use "apt list" to see installed packages.***\n')
return
for p in packages:
print "\n----- %s -----" % p
for i in get_filelist(p):
print i
#@+node:maphew.20100223163802.3726: *3* md5
def hashcheck(package):
'''Check if the md5 hash for "package" in local cache matches mirror
> apt hashcheck shell
Returns: True or False for md5 match status
None when cache file not found
If passed a list it only processes the first item.
'''
if not package:
sys.stderr.write('Please specify package to calculate md5 hash value for.')
return
if not isinstance(package, basestring):
package = package[0]
print "--- Verifying local file's md5 hash matches mirror"
match = False
p_info = get_info(package)
try:
localname = p_info['local_zip']
localFile = file(localname, 'rb') #we md5 the *file* not the *filename*
my_md5 = hashlib.md5(localFile.read()).hexdigest()
their_md5 = p_info['md5']
if their_md5 == my_md5:
match = True
except IOError:
sys.stderr.write('*** local {}\'s .bz2 not found ***'.format(package))
return
print('\t%s' % match)
print('\tremote: %s' % their_md5)
print('\tlocal: %s' % my_md5)
return match
#@+node:maphew.20100223163802.3727: *3* missing
def missing(dummy):
'''Display missing dependencies for all installed packages.
`dummy` parameter is ignored
'''
## installed[0] is a dict of {'pkg-name': 'pkg.tar.bz2'}
missing = []
for pkg in installed[0]:
result = string.join(get_missing(pkg))
if result and result not in missing:
missing.append(result)
print "\nThe following packages have been listed as dependencies but are not installed:\n"
for m in missing:
print '\t%s' % m
return missing
#@+node:maphew.20150110091755.3: *4* get_missing
def get_missing(packagename):
'''For package, identify any requirements (dependencies) that are not installed.
Returns a dictionary of {packagname: ['missing_1','missing_2','...']}
'''
if debug:
print '\n### DEBUG: %s ###' % sys._getframe().f_code.co_name
# build list of required packages
reqs = get_info(packagename)['requires'].split()
#depends = get_requires(packagename)
depends = get_all_dependencies(packagename, [])
#debug: #21
# print reqs
# print depends
# determine which requires are not installed
lst = []
for pkg in reqs:
if debug: print 'DEBUG: get_info.reqs.pkg:', pkg
if not pkg in installed[0]:
lst.append(pkg)
# if list exists, and packagename isn't in it,
# something else has listed packagename as a dependency
# fixme: look back up stream and see who asked for it.
if lst and packagename not in lst:
sys.stderr.write('warning: missing package: %s\n' % string.join(lst))
# I think this is out of place. We've only been asked to identify what's missing,
# not if there are new versions available; scope creep.
elif packagename in installed[0]:
ins = get_installed_version(packagename)
new = get_version(packagename)
if ins >= new:
#sys.stderr.write('%s is already the newest version\n' % packagename)
#lst.remove(packagename)
pass
elif packagename not in lst:
lst.append(packagename)
return lst
#@+node:maphew.20100223163802.3728: *3* new
def new(dummy):
'''List available upgrades to currently installed packages'''
print '%-20s%-12s%s' % ('Package', 'Installed', 'Available')
print '%-20s%-12s%s' % ('-'*17, '-'*9, '-'*10)
for p in sorted(get_new()):
print '%-20s%-12s(%s)' % (p,
version_to_string(get_installed_version(p)),
version_to_string(get_version(p)),
)
#@+node:maphew.20100223163802.3729: *3* remove
def remove(packages):
'''Uninstall listed packages'''
if not packages:
sys.stderr.write('No packages specified. Run "apt list" to see installed packages')
return
#AMR66:
if isinstance(packages, basestring): packages = [packages]
#if type(packages) is str: packages = [packages]
for p in packages:
print p
if not installed[0].has_key(p):
sys.stderr.write ('warning: %s not installed\n' % p)
continue
sys.stderr.write('removing %s %s\n' % \
(p, version_to_string(get_installed_version(p))))
do_uninstall(p)
#@+node:maphew.20100223163802.3730: *3* requires
def requires(packages):
''' What packages does X rely on?
Returns dictionary of package names and dependencies.
Reports sub-dependencies, but they aren't in the dict (yet).
'''
if not packages:
sys.stderr.write('Please specify package names to list dependencies for.')
return
if isinstance(packages, basestring): packages = [packages]
for p in packages:
print '----- "%s" requires the following directly to work -----' % p
depends = {p: get_info(p)['requires'].split()}
if p in depends[p]:
depends[p].remove(p) # don't need to list self ;-)
print string.join(depends[p], '\n')
print '----- Sub dependencies are ----'
print string.join(get_all_dependencies(packages, []), '\n')
return depends
#@+node:maphew.20150327024923.2: *3* xrequires
def xrequires(packages):
''' https://github.com/maphew/apt/issues/32 '''
if isinstance(packages, basestring): packages = [packages]
dlist = []
dlist = get_all_dependencies(packages, dlist)
print dlist
#@+node:maphew.20100223163802.3731: *3* search
def search(pattern):
''' Search available packages list and descriptions for X
Returns list of package names
'''
global packagename
packages = []
keys = []
#pattern comes in as a list, we need bare string
pattern = ' '.join(pattern)
if not pattern:
help('search') #stub for when help takes a parameter (print a usage message)
sys.stderr.write("\n*** Missing what to search for ***\n")
return
if distname in dists:
# build list of packagenames
keys = dists[distname].keys()
else:
print '*** this "else:" does not get used???'
# finally understand some of the intent for this block:
# if the distribution name is unknown, dig through all
# dists. Each key should be a package name.
for i in dists.keys():
for j in dists[i].keys():
if not j in keys:
keys.append(j)
#search for the regexp pattern
for i in keys:
pi = get_info(i)
text = '{} {} {}'.format(pi['name'], pi['sdesc'], pi['ldesc'])
# append pkg name (key) when pattern is found in text
if not pattern or re.search(pattern, text):
# Don't understand this if/else at all. It seems to say
# "if True: p.append(i); if False p.append(i)"
if distname in dists:
if dists[distname][i].has_key(INSTALL):
packages.append(i)
else:
packages.append(i)
for packagename in sorted(packages):
pi = get_info(packagename)
print '{:>30} - {}'.format(pi['name'], pi['sdesc'])
return packages
#@+node:maphew.20100223163802.3732: *3* setup
def setup(target):
'''Create skeleton Osgeo4W folders and setup database environment'''
if not bits:
sys.stderr.write('\n*** CPU Architecture not defined. Please use `--bits [32 | 64]`\n')
sys.exit(2)
if not os.path.isdir(root):
sys.stderr.write('Root dir not found, creating %s\n' % root)
os.makedirs(root)
if not os.path.isdir(config):
sys.stderr.write('creating %s\n' % config)
os.makedirs(config)
if not os.path.isfile(installed_db):
sys.stderr.write('creating %s\n' % installed_db)
global installed
installed = {0:{}}
write_installed()
if not os.path.isfile(setup_ini):
sys.stderr.write('getting %s\n' % setup_ini)
update()
print '''
Osgeo4w folders and setup config exist; skeleton environment is complete.
You might try `apt available` and `apt install` next.
'''
#@+node:maphew.20100223163802.3733: *3* update
def update():
'''Fetch updated package list from mirror.
apt update
Specify mirror (web server, windows file share, local disk):
apt --mirror=http://example.com/... update
apt --mirror=file:////server/share/... update
apt --mirror=file://D:/downloads/cache/... update
'''
global bits
if not os.path.exists(downloads):
os.makedirs(downloads)
if not command == 'setup':
bits = get_setup_arch(setup_ini)
# AMR66: changed to uncompressed ini
filename = '%s/%s'%(bits, 'setup.ini')
source = '%s/%s' % (mirror, filename)
archive = os.path.join(downloads, filename)
# backup cached ini archive
if os.path.exists(archive):
shutil.copy(archive, archive + '.bak')
print('Fetching %s' % source)
dodo_download(source, archive)
## print('')
##
## try:
## uncompressedData = bz2.BZ2File(archive).read()
## except:
## raise IOError('\n*** Error decompressing: %s' % archive)
##
# backup existing setup config
if os.path.exists(setup_ini):
shutil.copy(setup_ini, setup_bak)
shutil.copy(archive, setup_ini)
##
## # save uncompressed ini to setup dir
## ini = open(setup_ini, 'w')
## ini.write(uncompressedData)
## ini.close
save_config('last-mirror', mirror)
#@+node:maphew.20100223163802.3734: *3* upgrade
def upgrade(packages):
'''Upgrade named packages.
apt upgrade all
apt upgrade gdal-filegdb qgis-grass-plugin
'''
if not packages:
help('upgrade')
sys.stderr.write('*** No packages specified. Use `apt new` for ideas.\n')
return
if isinstance(packages, basestring): packages = [packages]
if packages[0] == 'all':
packages = get_new()
install(packages)
#@+node:maphew.20100223163802.3735: *3* url
def url(packages):
'''Print remote package archive path, relative to mirror root'''
#AMR66:
if isinstance(packages, basestring): packages = [packages]
#if type(packages) is str: packages = [packages]
if not packages:
help('url')
sys.stderr.write('No package specified. Try running "apt available"')
return
print mirror
for p in packages:
d = get_info(p)
print '\t%s' % d['zip_path']
#@+node:maphew.20100223163802.3736: *3* version
def version(packages):
'''Report installed version of X'''
if isinstance(packages, basestring): packages = [packages]
if not packages:
help('version')
sys.stderr.write('No package specified. Try running "apt list"')
return
for p in packages:
#print '%-20s%-12s' % (p, get_info(p)['version'])
#broken! this reports Setup.ini version!
print '%-20s%-12s' % (p, version_to_string(get_installed_version(p)))
#@+node:maphew.20100302221232.1485: ** Helpers
#@+node:maphew.20141228100517.4: *3* exceptionHandler
def exceptionHandler(exception_type, exception, traceback, debug_hook=sys.excepthook):
'''Print user friendly error messages normally, full traceback if DEBUG on.
Adapted from http://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set
'''
if debug:
print '\n*** Error:'
debug_hook(exception_type, exception, traceback)
else:
print "\n%s: %s" % (exception_type.__name__, exception)
#@+node:maphew.20141110231213.3: *3* class AttrDict
class xAttrDict(dict):
'''Access a dictionary by attributes, like using javascript dotted notation.
dict.mykey <--- same as ---> dict['mykey']
From http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
'''
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
#@+node:maphew.20100223163802.3737: *3* cygpath
def cygpath(path):
# change dos path to unix style path, plus add cygwin prefix
# needs some changes to work for osgeo4w
# adapted from http://cyg-apt.googlecode.com: cygpath()
path = path.replace("\\", "/")
if len(path) == 3:
if path[1] == ":":
path = "/" + path[0].lower()
elif len(path) > 1:
if path[1] == ":":
path = "/" + path[0].lower() + path[2:]
return path
#@+node:maphew.20100223163802.3738: *3* debug_old
def debug_old(s):
# still haven't figured out quite how this is meant to be used
# uncomment the print statement to display contents of parsed setup.ini
s
print s
#@+node:maphew.20150327181149.2: *3* uniq
def uniq(alist):
''' Returns a list with unique items (removes duplicates),
without losing item order.
From @jamylak, http://stackoverflow.com/a/17016257/14420
'''
from collections import OrderedDict
return list(OrderedDict.fromkeys(alist))
#@+node:maphew.20150329144423.2: *3* url_time_to_datetime
def url_time_to_datetime(s):
''' Convert "last-modified" string time from a web server header to a python
datetime object.
Assumes the string looks like "Fri, 27 Mar 2015 08:05:42 GMT". There is
no attempt to use locale or similar, so the function is'nt very robust.
'''
return datetime.strptime(s, '%a, %d %b %Y %X %Z')
#@+node:maphew.20150329144423.3: *3* datetime_to_unixtime
def datetime_to_unixtime(dt, epoch=datetime(1970,1,1)):
''' Convert a datetime object to unix UTC time (seconds since beginning).
Adapted from http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python/
It wants `from __future__ import division`, but that caused issues in other
functions, automatically coverting what used to produce integers into floats
(e.g. "50/2"). It seems to be safe to not use it, but leaving this note just
in case...
'''
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
# FIXME: According to official docs, this should only be necessary in
# py2.6 and earlier # yet it fails for me in py2.7.4! Is osgeo4w's python
# corrupt?
#@+node:maphew.20100308085005.1379: ** Doers
#@+node:maphew.20100223163802.3739: *3* do_download
def do_download(packagename):
'''Download package from mirror and save in local cache folder.
Overwrites existing cached version if md5 sum doesn't match expected from setup.ini.
Returns `path\to\archive.bz2` on success (file downloaded, or file with correct md5 is present),
and http status code if fails.
'''
p_info = get_info(packagename)
# amr66: error with no install-tag, grass71-devel
# if not p_info['zip_path']:
# print "*** no download path for package", p
# return ''
dstFile = p_info['local_zip']
srcFile = p_info['mirror_path']
cacheDir = os.path.dirname(dstFile)
if os.path.exists(dstFile)and hashcheck(packagename):
print 'Skipping download of %s, exists in cache' % p_info['filename']
return
if debug:
print 'do_download():'
print '\tsrcFile:\t', srcFile
print '\tdstFile:\t', dstFile
f = dodo_download(srcFile, dstFile)
return f
#@+node:maphew.20150322125023.13: *4* dodo_download
def dodo_download(url, dstFile):
''' Dumbest name for abstracting downloading
a file to disk with requests module and progress reporting
Returns `path\to\archive.bz2` on success, http status code if fails.
'''
r = requests.head(url)
if not r.ok:
print 'Problem getting %s\nServer returned "%s"' % (url, r.status_code)
return r.status_code
url_time = url_time_to_datetime(r.headers['last-modified'])
if os.path.exists(dstFile):
file_time = datetime.utcfromtimestamp(os.path.getmtime(dstFile))
else:
file_time = datetime(1970, 1, 1)
if debug:
print '\tServer URL Last-modified:\t', r.headers['last-modified']
print '\tDT obj URL Last-modified:\t', url_time
print '\tLocal cache file modified:\t', file_time
if url_time <= file_time:
print "Skipping download - url modified time isn't newer than local file"
print dstFile
return dstFile
if not os.path.exists(os.path.dirname(dstFile)):
os.makedirs(os.path.dirname(dstFile))
with open(dstFile, 'wb') as f:
r = requests.get(url, stream=True)
total_length = int(r.headers.get('content-length'))
block_size = 1024
down_bytes = 0
for block in r.iter_content(block_size):
down_bytes += len(block)
if not block:
break
f.write(block)
down_stat(down_bytes, total_length)
if not r.ok:
print 'Problem getting %s\nServer returned "%s"' % (srcFile, r.status_code)
return r.status_code
# maintain server's file timestamp
tstamp = datetime_to_unixtime(url_time)
os.utime(dstFile, (tstamp, tstamp))
if debug:
print '\tFile timestamp:\t', datetime.utcfromtimestamp(tstamp)
print 'Saved', dstFile
return dstFile
#@+node:maphew.20100223163802.3742: *4* down_stat
def down_stat(downloaded_size, total_size):
''' Report download progress in bar, percent, and bytes.
Each bar stroke '=' is approximately 2%
Adapted from
http://stackoverflow.com/questions/51212/how-to-write-a-download-progress-indicator-in-python
http://stackoverflow.com/questions/15644964/python-progress-bar-and-downloads
'''
percent = int(100 * downloaded_size/total_size)
bar = int(percent/2)
if not 'last_percent' in vars(down_stat):