-
Notifications
You must be signed in to change notification settings - Fork 13
/
upgrade.py
267 lines (225 loc) · 9.67 KB
/
upgrade.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
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
# PKGBUILDer v2.99.4.0
# An AUR helper (and library) in Python 3.
# Copyright © 2011-2013, Kwpolska.
# See /LICENSE for licensing information.
"""
pkgbuilder.upgrade
~~~~~~~~~~~~~~~~~~
Tools for performing upgrades of AUR packages.
:Copyright: © 2011-2013, Kwpolska.
:License: BSD (see /LICENSE).
"""
from . import DS, _, PBError
import pkgbuilder.build
import pkgbuilder.utils
import pyalpm
import datetime
import subprocess
import textwrap
__all__ = ['gather_foreign_pkgs', 'list_upgradable', 'auto_upgrade']
def gather_foreign_pkgs():
"""Gathers a list of all foreign packages."""
localdb = DS.pyc.get_localdb()
# Based on paconky.py.
installed = [p for p in localdb.pkgcache]
repo = []
aur = []
syncdbs = DS.pyc.get_syncdbs()
for sdb in syncdbs:
for pkg in installed:
if sdb.get_pkg(pkg.name):
repo.append(pkg)
aur = set(set(installed) - set(repo))
# Return foreign packages.
return dict([(p.name, p) for p in aur])
def list_upgradable(pkglist, vcsup=False):
"""Compares package versions and returns upgradable ones."""
localdb = DS.pyc.get_localdb()
aurlist = pkgbuilder.utils.info(pkglist)
# It's THAT easy. Oh, and by the way: it is much, MUCH faster
# than others. It makes ONE multiinfo request rather than
# len(installed_packages) info requests.
upgradable = []
downgradable = []
for i in aurlist:
pkg = localdb.get_pkg(i['Name'])
if pkg is not None:
vc = pyalpm.vercmp(i['Version'], pkg.version)
if vc > 0:
upgradable.append([i['Name'], pkg.version, i['Version']])
elif vc < 0:
# If the package version is a date or the name ends in
# -{git,hg,bzr,svn,cvs,darcs}, do not mark it as downgradable.
# BTW: the above is yours truly’s list of VCS preference, if
# you added big a gap between git and hg and then HUGE gaps
# between everything else.
try:
# For epoch packages. Also, cheating here.
v = i['Version'].split(':')[1]
except IndexError:
v = i['Version']
try:
datetime.datetime.strptime(v.split('-')[0], '%Y%m%d')
datever = True
except:
datever = False
dt = datetime.date.today().strftime('%Y%m%d')
if (i['Name'].endswith(('git', 'hg', 'bzr', 'svn', 'cvs',
'darcs'))):
if vcsup:
upgradable.append([i['Name'], pkg.version, dt])
else:
DS.log.warning('{} is -[vcs], ignored for '
'downgrade.'.format(i['Name']))
elif datever:
if vcsup:
upgradable.append([i['Name'], pkg.version, dt])
else:
DS.log.warning('{} version is a date, ignored '
'for downgrade.'.format(i['Name']))
else:
downgradable.append([i['Name'], pkg.version, i['Version']])
return [upgradable, downgradable]
def auto_upgrade(downgrade=False, vcsup=False):
"""
Human friendly upgrade question and output.
Returns packages — should be passed over to builder functions.
"""
DS.log.info('Ran auto_upgrade.')
if DS.pacman:
print(':: ' + _('Synchronizing package databases...'))
else:
DS.fancy_msg(_('Synchronizing package databases...'))
foreign = gather_foreign_pkgs()
gradable = list_upgradable(foreign.keys(), vcsup)
upgradable = gradable[0]
downgradable = gradable[1]
upglen = len(upgradable)
downlen = len(downgradable)
if DS.pacman:
print(':: ' + _('Starting full system upgrade...'))
else:
DS.fancy_msg(_('Starting full system upgrade...'))
if downlen > 0:
for i in downgradable:
if DS.pacman:
print(_('{}: local ({}) is newer than aur '
'({})').format(i[0], i[1], i[2]))
else:
DS.fancy_warning(_('{}: local ({}) is newer than aur '
'({})').format(i[0], i[1], i[2]))
if downgrade:
upglen = upglen + downlen
upgradable = upgradable + downgradable
if upglen == 0:
if DS.pacman:
print(' ' + _('there is nothing to do'))
else:
DS.fancy_msg2(_('there is nothing to do'))
return []
upgnames = [i[0] for i in upgradable]
upgstrings = [i[0] + '-' + i[2] for i in upgradable]
verbosepkglists = False
with open('/etc/pacman.conf') as fh:
for i in fh.read().split('\n'):
if i.strip() == 'VerbosePkgLists':
verbosepkglists = True
break
if upglen > 0:
if 'pkgbuilder' in upgnames or 'pkgbuilder-git' in upgnames:
if 'pkgbuilder' in upgnames:
pkgbname = 'pkgbuilder'
elif 'pkgbuilder-git' in upgnames:
pkgbname = 'pkgbuilder-git'
else:
raise PBError('SANITYERROR GOES HERE')
if DS.pacman:
print('::' + _('The following packages should be upgraded '
'first:'))
print(' {}'.format(pkgbname))
print('::' + _('Do you want to cancel the current operation'))
query = '::' + _('and upgrade these packages now? [Y/n] ')
else:
DS.fancy_warning(_('The following packages should be upgraded '
'first:'))
DS.fancy_msg2(pkgbname)
query = (DS.colors['green'] + '==>' + DS.colors['all_off'] +
DS.colors['bold'] + ' ' +
_('Do you want to cancel the current operation and '
'upgrade these packages now? [Y/n] ') +
DS.colors['all_off'])
yesno = input(query)
if yesno.lower().strip().startswith('y') or yesno.strip() == '':
pkgbuilder.build.safeupgrade(pkgbname)
# The return causes PKGBUILDer.main() to quit and do nothing.
# The else is unnecessary, as we drop to a regular upgrade
# if the luser says “no”.
return []
if DS.pacman:
targetstring = _('Targets ({}): ').format(upglen)
size = subprocess.check_output(['stty', 'size'])
try:
termwidth = int(size.split()[1])
except IndexError:
if verbosepkglists:
# Pacman doesn’t allow tables if the terminal is too small.
# And since we don’t know the size, better safe than sorry.
verbosepkglists = False
DS.log.warning('VerbosePkgLists disabled, cannot '
'determine terminal width')
else:
termwidth = 9001 # Auto-wrap by terminal.
if verbosepkglists:
headers = [_('Name'), _('Old Version'), _('New Version')]
items = upgradable # Magical.
sizes = [len(i) for i in headers]
for n, ov, nv in items:
if len(n) > sizes[0]:
sizes[0] = len(n)
if len(ov) > sizes[1]:
sizes[1] = len(ov)
if len(nv) > sizes[2]:
sizes[2] = len(nv)
fstring = ('{{i[0]:<{s[0]}}} {{i[1]:<{s[1]}}} '
'{{i[2]:<{s[2]}}}').format(s=sizes)
if len(fstring.format(i=4 * ['n'])) > termwidth:
verbosepkglists = False
DS.log.warning('VerbosePkgLists disabled, terminal is '
'not wide enough')
else:
print('\n{0}\n'.format(targetstring.strip()))
print(fstring.format(i=headers))
print()
for i in items:
print(fstring.format(i=i))
# Not using else because there is a fallback if the terminal
# is too small.
if not verbosepkglists:
nowrap = targetstring + ' '.join(upgstrings)
wrapv = textwrap.wrap(nowrap, termwidth,
break_on_hyphens=False)
wrap0 = wrapv[0]
wraprest = textwrap.wrap('\n'.join(wrapv[1:]), termwidth -
len(targetstring),
break_on_hyphens=False)
wraprest = [i.replace(' ', ' ').replace(' ', ' ') for i
in wraprest]
print(wrap0)
for i in wraprest:
print(len(targetstring) * ' ' + i)
print()
query = _('Proceed with installation? [Y/n] ')
else:
DS.fancy_msg(_('Targets ({}): ').format(upglen))
DS.fancy_msg2(' '.join(upgstrings))
query = (DS.colors['green'] + '==>' + DS.colors['all_off'] +
DS.colors['bold'] + ' ' +
_('Proceed with installation? [Y/n] ') +
DS.colors['all_off'])
yesno = input(query)
if yesno.lower().strip().startswith('y') or yesno.strip() == '':
return upgnames
else:
return []