-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpacman.py
More file actions
273 lines (231 loc) · 7.87 KB
/
pacman.py
File metadata and controls
273 lines (231 loc) · 7.87 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
"""
python-pacman - (c) Jacob Cook 2015
Licensed under GPLv3
"""
import subprocess, os, shutil
from urllib import request
from shlex import quote
__PACMAN_BIN = shutil.which("pacman") # default to use the system's pacman binary
def get_bin():
'''
Return the current pacman binary being used.
'''
return __PACMAN_BIN
def set_bin(path):
'''
Set a custom pacman binary.
If the pacman binary is set to an AUR helper, this module may also be used to interact with AUR.
'''
global __PACMAN_BIN
if isinstance(path, str) and (os.path.isfile(path) or os.path.isfile(shutil.which(path))):
__PACMAN_BIN = shutil.which(path)
else:
raise IOError("This executable does not exist.")
def install(packages, needed=True):
"""
Install package\n
Parameters::\n
packages <str>
needed <bool>
"""
s = pacman("-S", packages, ["--needed" if needed else None])
if s["code"] != 0:
raise Exception("Failed to install: {0}".format(s["stderr"]))
def refresh():
"""Refresh the local package information database"""
s = pacman("-Sy")
if s["code"] != 0:
raise Exception("Failed to refresh database: {0}".format(s["stderr"]))
def upgrade(packages=[]):
"""
Upgrade packages
Parameters::\n
packages <str> [default = all]
"""
if packages:
install(packages)
else:
s = pacman("-Su")
if s["code"] != 0:
raise Exception("Failed to upgrade packages: {0}".format(s["stderr"]))
def remove(packages, purge=False):
"""
Remove package(s) and purge its files
Parameters ::\n
packages <str>
purge <bool>
"""
s = pacman("-Rc{0}".format("n" if purge else ""), packages)
if s["code"] != 0:
raise Exception("Failed to remove: {0}".format(s["stderr"]))
def get_all():
"""List all packages"""
interim, results = {}, []
s = pacman("-Q")
if s["code"] != 0:
raise Exception(
"Failed to get installed list: {0}".format(s["stderr"])
)
for x in s["stdout"].split('\n'):
if not x.split():
continue
x = x.split(' ')
interim[x[0]] = {
"id": x[0], "version": x[1], "upgradable": False,
"installed": True
}
s = pacman("-Sl")
if s["code"] != 0:
raise Exception(
"Failed to get available list: {0}".format(s["stderr"])
)
for x in s["stdout"].split('\n'):
if not x.split():
continue
x = x.split(' ')
if x[1] in interim:
interim[x[1]]["repo"] = x[0]
if interim[x[1]]["version"] != x[2]:
interim[x[1]]["upgradable"] = x[2]
else:
results.append({
"id": x[1], "repo": x[0], "version": x[2], "upgradable": False,
"installed": False
})
for x in interim:
results.append(interim[x])
return results
def get_installed():
"""List all installed packages"""
interim = {}
s = pacman("-Q")
if s["code"] != 0:
raise Exception(
"Failed to get installed list: {0}".format(s["stderr"])
)
for x in s["stdout"].split('\n'):
if not x.split():
continue
x = x.split(' ')
interim[x[0]] = {
"id": x[0], "version": x[1], "upgradable": False,
"installed": True
}
s = pacman("-Qu")
if s["code"] != 0 and s["stderr"]:
raise Exception(
"Failed to get upgradable list: {0}".format(s["stderr"])
)
for x in s["stdout"].split('\n'):
if not x.split():
continue
x = x.split(' -> ')
name = x[0].split(' ')[0]
if name in interim:
r = interim[name]
r["upgradable"] = x[1]
interim[name] = r
results = []
for x in interim:
results.append(interim[x])
return results
def get_available():
"""List all available packages"""
results = []
s = pacman("-Sl")
if s["code"] != 0:
raise Exception(
"Failed to get available list: {0}".format(s["stderr"])
)
for x in s["stdout"].split('\n'):
if not x.split():
continue
x = x.split(' ')
results.append({"id": x[1], "repo": x[0], "version": x[2]})
return results
def get_info(package):
"""Get package information from database"""
interim = []
s = pacman("-Qi" if is_installed(package) else "-Si", package)
if s["code"] != 0:
raise Exception("Failed to get info: {0}".format(s["stderr"]))
content = s["stdout"].split('\n')
for line_num in range(len(content)-1):
if 'Optional Deps' not in content[line_num]:
if ':' in content[line_num]:
content[line_num] = content[line_num].split(':', 1)
interim.append(
(content[line_num][0].strip(), content[line_num][1].strip()))
else:
opt_dep = {}
i = 0
end_line = [i for i in range(
len(content)) if 'Required By' in content[i]][0]
try :
if ':' in content[line_num]:
content[line_num] = content[line_num].split(':')
opt_dep[content[line_num]
[1].strip()] = content[line_num][2].strip()
except:
pass
line_num += 1
for i in range(line_num, end_line):
if ':' in content[i]:
content[i] = content[i].split(':', 1)
opt_dep[content[i]
[0].strip()] = content[i][1].strip()
line_num = end_line
interim.append(("Optional Dependencies", opt_dep))
result = dict(interim)
return result
def needs_for(packages):
"""Get list of not-yet-installed dependencies of these packages"""
s = pacman("-Sp", packages, ["--print-format", "%n"])
if s["code"] != 0:
raise Exception("Failed to get requirements: {0}".format(s["stderr"]))
return [x for x in s["stdout"].split('\n') if x]
def depends_for(packages):
"""Get list of installed packages that depend on these"""
s = pacman("-Rpc", packages, ["--print-format", "%n"])
if s["code"] != 0:
raise Exception("Failed to get depends: {0}".format(s["stderr"]))
return [x for x in s["stdout"].split('\n') if x]
def is_installed(package):
"""Return True if the specified package is installed"""
return pacman("-Q", package)["code"] == 0
def is_aur(package):
'''
Return True if the given package is an AUR package.
'''
try:
# search in official pacman repo
matched_packages = pacman('-Ssq', package, pacman_bin="pacman").get('stdout').split('\n')
for i in matched_packages:
if i == package:
# find a match in official repo. not aur.
return False
req = request.Request("https://aur.archlinux.org/packages/?O=0&SeB=N&K={}&outdated=&SB=n&SO=a&PP=50&do_Search=Go".format(package), data=b'')
res = request.urlopen(req)
data = res.read()
if b"No packages matched your search criteria." in data:
return False
return True
except Exception as e:
return False
def pacman(flags, pkgs=[], eflgs=[], pacman_bin=__PACMAN_BIN):
"""Subprocess wrapper, get all data"""
if not pkgs:
cmd = [pacman_bin, "--noconfirm", flags]
elif type(pkgs) == list:
cmd = [pacman_bin, "--noconfirm", flags]
cmd += [quote(s) for s in pkgs]
else:
cmd = [pacman_bin, "--noconfirm", flags, pkgs]
if eflgs and any(eflgs):
eflgs = [x for x in eflgs if x]
cmd += eflgs
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
data = p.communicate()
data = {"code": p.returncode, "stdout": data[0].decode(),
"stderr": data[1].rstrip(b'\n').decode()}
return data