Debian Codegraph @

examples/luasolv

raw
1 #!/usr/bin/lua
2
3 releasever = nil
4 solvcachedir = '/var/cache/solv'
5
6 posix = require("posix")
7 posix.sys.stat = require("posix.sys.stat")
8 require("solv")
9
10 -- helpers
11
12 function parse_ini_file(fn)
13 local sections = {}
14 for line in io.open(fn, 'r'):lines() do
15 local match = line:match('^%[([^%[%]]+)%]$')
16 if match then
17 section = match
18 sections[section] = sections[section] or {}
19 else
20 local param, value = line:match('^([%w|_]+)%s-=%s-(.+)$')
21 if param then sections[section][param] = value end
22 end
23 end
24 return sections
25 end
26
27 function die(str)
28 io.stdout:write(str.."\n")
29 os.exit(1)
30 end
31
32 function isdir(path)
33 local st = posix.sys.stat.stat(path)
34 return st and posix.S_ISDIR(st.st_mode) ~= 0
35 end
36
37 function lsdir(path)
38 local content = posix.dirent.dir(path) or {}
39 table.sort(content)
40 return content
41 end
42
43 function load_stub(repodata)
44 local repo = repodata.repo.appdata
45 if repo then
46 return repo:load_ext(repodata)
47 end
48 return false
49 end
50
51 -- generic repo implementation
52
53 Repo = {}
54
55 function Repo.calc_cookie_filename(filename)
56 chksum = solv.Chksum(solv.REPOKEY_TYPE_SHA256)
57 chksum:add("1.1")
58 chksum:add_stat(filename)
59 return chksum:raw()
60 end
61
62 function Repo.calc_cookie_fp(fp)
63 chksum = solv.Chksum(solv.REPOKEY_TYPE_SHA256)
64 chksum:add("1.1")
65 chksum:add_fp(fp)
66 return chksum:raw()
67 end
68
69 function Repo.calc_cookie_ext(f, cookie)
70 chksum = solv.Chksum(solv.REPOKEY_TYPE_SHA256)
71 chksum:add("1.1")
72 chksum:add(cookie)
73 chksum:add_fstat(f:fileno())
74 return chksum:raw()
75 end
76
77 function Repo:download(file, uncompress, chksum, markincomplete)
78 if not self.baseurl then
79 io.stdout:write(self.alias..": no baseurl\n")
80 return nil
81 end
82 local url = self.baseurl:gsub('/$', '')..'/'..file
83 local tmpfile = io.tmpfile()
84 local fd = posix.stdio.fileno(tmpfile)
85 local status, reason = posix.spawn({'curl', '-f', '-s', '-L', '-o', '/dev/fd/'..fd, '--', url})
86 if posix.unistd.lseek(fd, 0, posix.unistd.SEEK_END) == 0 and (status == 0 or not chksum) then
87 tmpfile:close()
88 return nil
89 end
90 posix.unistd.lseek(fd, 0, posix.unistd.SEEK_SET);
91 if status ~= 0 then
92 print(file..": download error "..status.."\n");
93 tmpfile:close()
94 return nil
95 end
96 if chksum then
97 local fchksum = solv.Chksum(chksum.type);
98 fchksum:add_fd(fd)
99 if fchksum ~= chksum then
100 print(file..": checksum error")
101 if markincomplete then self.incomplete = 1 end
102 return nil
103 end
104 end
105 local ret
106 if uncompress then
107 ret = solv.xfopen_fd(file, fd);
108 else
109 ret = solv.xfopen_fd(nil, fd);
110 end
111 tmpfile:close()
112 return ret
113 end
114
115 function Repo:load(pool)
116 self.handle = pool:add_repo(self.alias)
117 self.handle.appdata = self
118 self.handle.priority = 99 - self.priority
119 if self:usecachedrepo() then
120 io.stdout:write("repo '"..self.alias.."': cached\n")
121 return true
122 end
123 return false
124 end
125
126 function Repo:cachepath(ext)
127 local path = self.alias:gsub('^%.', '_');
128 if ext then
129 path = path .. '_' .. ext ..'.solvx'
130 else
131 path = path ..'.solv'
132 end
133 return '/var/cache/solv/' .. path:gsub('/', '_');
134 end
135
136 function Repo:usecachedrepo(ext, mark)
137 local cookie
138 if ext then
139 cookie = self.extcookie
140 else
141 cookie = self.cookie
142 end
143 local repopath = self:cachepath(ext)
144 local f = io.open(repopath, 'rb')
145 if not f then
146 return false
147 end
148 f:seek('end', -32)
149 local fcookie = f:read(32)
150 if not fcookie or fcookie:len() ~= 32 then
151 f:close()
152 return false
153 end
154 if cookie and cookie ~= fcookie then
155 f:close()
156 return false
157 end
158 local fextcookie
159 if self.type ~= 'system' and not ext then
160 f:seek('end', -64)
161 fextcookie = f:read(32)
162 if not fcookie or fcookie:len() ~= 32 then
163 f:close()
164 return false
165 end
166 end
167 f:seek('set')
168 posix.unistd.lseek(posix.stdio.fileno(f), 0, posix.unistd.SEEK_SET)
169 local ff = solv.xfopen_fd('', posix.stdio.fileno(f))
170 f:close()
171 local flags = 0
172 if ext then
173 flags = flags | solv.Repo.REPO_USE_LOADING|solv.Repo.REPO_EXTEND_SOLVABLES
174 if ext ~= 'DL' then flags = flags | solv.Repo.REPO_LOCALPOOL end
175 end
176 if not self.handle:add_solv(ff, flags) then
177 ff:close()
178 return false
179 end
180 if self.type ~= 'system' and not ext then
181 self.cookie = fcookie
182 self.extcookie = fextcookie
183 end
184 if mark then
185 posix.utime(repopath)
186 end
187 return true
188 end
189
190 function Repo:writecachedrepo(ext, repodata)
191 if self.incomplete then return end
192 if not isdir(solvcachedir) then
193 posix.sys.stat.mkdir(solvcachedir, 7 * 64 + 5 * 8 + 5)
194 end
195 local fd, tmpname = posix.stdlib.mkstemp(solvcachedir..'/.newsolv-XXXXXX')
196 if not fd then
197 return
198 end
199 local ff = solv.xfopen_fd('', fd)
200 if not repodata then
201 self.handle:write(ff)
202 elseif ext then
203 repodata:write(ff)
204 else
205 self.handle:write_first_repodata(ff)
206 end
207 ff:flush()
208 if self.type ~= 'system' and not ext then
209 self.extcookie = self.extcookie or Repo.calc_cookie_ext(ff, self.cookie)
210 ff:write(self.extcookie)
211 end
212 if not ext then
213 ff:write(self.cookie)
214 else
215 ff:write(self.extcookie)
216 end
217 ff:close()
218 os.rename(tmpname, self:cachepath(ext))
219 end
220
221 function Repo:add_ext_keys(ext, repodata, handle)
222 if ext == 'DL' then
223 repodata:add_idarray(handle, solv.REPOSITORY_KEYS, solv.REPOSITORY_DELTAINFO)
224 repodata:add_idarray(handle, solv.REPOSITORY_KEYS, solv.REPOKEY_TYPE_FLEXARRAY)
225 elseif ext == 'DU' then
226 repodata:add_idarray(handle, solv.REPOSITORY_KEYS, solv.SOLVABLE_DISKUSAGE)
227 repodata:add_idarray(handle, solv.REPOSITORY_KEYS, solv.REPOKEY_TYPE_DIRNUMNUMARRAY)
228 elseif ext == 'FL' then
229 repodata:add_idarray(handle, solv.REPOSITORY_KEYS, solv.SOLVABLE_FILELIST)
230 repodata:add_idarray(handle, solv.REPOSITORY_KEYS, solv.REPOKEY_TYPE_DIRSTRARRAY)
231 end
232 end
233
234 -- rpmmd repo implementation
235
236 Repo_rpmmd = {}
237 setmetatable(Repo_rpmmd, {__index = Repo })
238
239 function Repo_rpmmd:find(what)
240 local di = self.handle:Dataiterator_meta(solv.REPOSITORY_REPOMD_TYPE, what, solv.Dataiterator.SEARCH_STRING)
241 di:prepend_keyname(solv.REPOSITORY_REPOMD)
242 for d in di do
243 local dp = d:parentpos()
244 local filename = dp:lookup_str(solv.REPOSITORY_REPOMD_LOCATION)
245 if filename then
246 local chksum = dp:lookup_checksum(solv.REPOSITORY_REPOMD_CHECKSUM)
247 if not chksum then
248 print("no "..filename.." file checksum!\n")
249 return
250 end
251 return filename, chksum
252 end
253 end
254 end
255
256 function Repo_rpmmd:add_ext(repodata, what, ext)
257 local filename, filechksum = self:find(what)
258 if not filename and what == 'deltainfo' then
259 filename, filechksum = self:find('prestodelta')
260 end
261 if filename then
262 local handle = repodata:new_handle()
263 repodata:set_poolstr(handle, solv.REPOSITORY_REPOMD_TYPE, what)
264 repodata:set_str(handle, solv.REPOSITORY_REPOMD_LOCATION, filename)
265 repodata:set_checksum(handle, solv.REPOSITORY_REPOMD_CHECKSUM, filechksum)
266 self:add_ext_keys(ext, repodata, handle)
267 repodata:add_flexarray(solv.SOLVID_META, solv.REPOSITORY_EXTERNAL, handle)
268 end
269 end
270
271 function Repo_rpmmd:add_exts()
272 repodata = self.handle:add_repodata(0)
273 repodata:extend_to_repo()
274 self:add_ext(repodata, 'deltainfo', 'DL')
275 self:add_ext(repodata, 'filelists', 'FL')
276 repodata:internalize()
277 end
278
279 function Repo_rpmmd:load(pool)
280 if Repo.load(self, pool) then return true end
281 io.stdout:write("rpmmd repo '"..self.alias.."': ")
282 local f = self:download("repodata/repomd.xml");
283 if not f then
284 print("no repomd.xml file, skipped");
285 self.handle:free(true)
286 self.handle = nil
287 return false
288 end
289 self.cookie = self.calc_cookie_fp(f)
290 if self:usecachedrepo(nil, True) then
291 print("cached")
292 return true
293 end
294 self.handle:add_repomdxml(f, 0)
295 f:close()
296 print("fetching")
297 local filename, filechksum
298 filename, filechksum = self:find('primary')
299 if filename then
300 f = self:download(filename, true, filechksum, true)
301 if f then
302 self.handle:add_rpmmd(f, nil, 0)
303 f:close()
304 end
305 if self.incomplete then return false end
306 end
307 filename, filechksum = self:find('updateinfo')
308 if filename then
309 f = self:download(filename, true, filechksum, true)
310 if f then
311 self.handle:add_updateinfoxml(f, 0)
312 f:close()
313 end
314 end
315 self:add_exts()
316 self:writecachedrepo()
317 self.handle:create_stubs()
318 return true
319 end
320
321 function Repo_rpmmd:load_ext(repodata)
322 local repomdtype = repodata:lookup_str(solv.SOLVID_META, solv.REPOSITORY_REPOMD_TYPE)
323 local ext
324 if repomdtype == 'filelists' then
325 ext = 'FL'
326 elseif repomdtype == 'deltainfo' then
327 ext = 'DL'
328 else
329 return false
330 end
331 io.stdout:write("["..self.alias..":"..ext..": ")
332 if self:usecachedrepo(ext) then
333 io.stdout:write("cached]\n")
334 return true
335 end
336 io.stdout:write("fetching]\n")
337 local filename = repodata:lookup_str(solv.SOLVID_META, solv.REPOSITORY_REPOMD_LOCATION)
338 local filechksum = repodata:lookup_str(solv.SOLVID_META, solv.REPOSITORY_REPOMD_CHECKSUM)
339 local f = self:download(filename, true, filechksum)
340 if not f then
341 return false
342 end
343 if ext == 'FL' then
344 self.handle:add_rpmmd(f, 'FL', solv.Repo.REPO_USE_LOADING|solv.Repo.REPO_EXTEND_SOLVABLES|solv.Repo.REPO_LOCALPOOL)
345 elseif ext == 'DL' then
346 self.handle:add_deltainfoxml(f, solv.Repo.REPO_USE_LOADING)
347 end
348 self:writecachedrepo(ext, repodata)
349 return true
350 end
351
352 -- susetags repo implementation
353
354 Repo_susetags = {}
355 setmetatable(Repo_susetags, {__index = Repo })
356
357 -- unknown repo implementation
358
359 Repo_unknown = {}
360 setmetatable(Repo_unknown, {__index = Repo })
361
362 function Repo_unknown:load()
363 print("unsupported repo '"..self.alias.."': skipped")
364 return false
365 end
366
367 -- system repo implementation
368
369 Repo_system = {}
370 setmetatable(Repo_system, {__index = Repo })
371
372 function Repo_system:load(pool)
373 self.handle = pool:add_repo(self.alias)
374 self.handle.appdata = self
375 pool.installed = self.handle
376 io.stdout:write("rpm database: ")
377 self.cookie = Repo.calc_cookie_filename("/var/lib/rpm/Packages")
378 if self:usecachedrepo() then
379 print("cached")
380 return true
381 end
382 io.stdout:write("reading\n")
383 local oldf = solv.xfopen(self:cachepath())
384 self.handle:add_rpmdb_reffp(oldf, solv.Repo.REPO_REUSE_REPODATA)
385 self:writecachedrepo()
386 end
387
388 -- main
389
390 cmd = arg[1]
391 if not cmd then die("Usage: luasolv COMMAND [ARGS]") end
392 table.remove(arg, 1)
393
394 cmdabbrev = { ['ls']='list'; ['in']='install'; ['rm']='erase'; ['ve']='verify'; ['se']='search' }
395 cmd = cmdabbrev[cmd] or cmd
396
397 cmdactions = { ['install']=solv.Job.SOLVER_INSTALL; ['erase']=solv.Job.SOLVER_ERASE; ['up']=solv.Job.SOLVER_UPDATE; ['dup']=solv.Job.SOLVER_DISTUPGRADE; ['verify']=solv.Job.SOLVER_VERIFY; ['list']=0; ['info']=0 }
398
399 repos = {}
400 reposdir = {}
401 if isdir('/etc/zypp/repos.d') then
402 table.insert(reposdir, '/etc/zypp/repos.d')
403 elseif isdir('/etc/yum/repos.d') then
404 table.insert(reposdir, '/etc/yum/repos.d')
405 end
406 for _, repodir in ipairs(reposdir) do
407 for _, e in ipairs(lsdir(repodir)) do
408 if e:sub(-5) == '.repo' then
409 sections = parse_ini_file(repodir..'/'..e)
410 for alias, section in pairs(sections) do
411 repo = { ['alias']=alias; ['enabled']=false; ['priority']=99; ['autorefresh']=true; ['type']='rpm-md'; ['metadata_expire']=900 }
412 if section.name then repo.name = section.name end
413 if section.type then repo.type = section.type end
414 if section.baseurl then repo.baseurl = section.baseurl end
415 if section.metadata_expire then repo.metadata_expire = tonumber(section.metadata_expire) end
416 if section.enabled then repo.enabled = tonumber(section.enabled) ~= 0 end
417 if section.autorefresh then repo.autorefresh = tonumber(section.autorefresh) ~= 0 end
418 if section.gpgcheck then repo.gpgcheck = tonumber(section.gpgcheck) ~= 0 end
419 if section.priority then repo.priority = tonumber(section.priority) end
420 if repo.baseurl and releasever then repo.baseurl = repo.baseurl:gsub('$releasever', releasever) end
421 if repo.type == 'rpm-md' then
422 setmetatable(repo , {__index = Repo_rpmmd })
423 elseif repo['type'] == 'yast2' then
424 setmetatable(repo , {__index = Repo_susetags })
425 else
426 setmetatable(repo , {__index = Repo_unknown })
427 end
428 table.insert(repos, repo)
429 end
430 end
431 end
432 end
433
434 local pool = solv.Pool()
435 pool:setarch()
436 pool:set_loadcallback(load_stub)
437
438 sysrepo = { ['alias']='@System', ['type']='system' }
439 setmetatable(sysrepo , {__index = Repo_system })
440 sysrepo:load(pool)
441 for _, repo in ipairs(repos) do
442 if repo.enabled then
443 repo:load(pool)
444 end
445 end
446
447 if cmd == 'search' then
448 pool:createwhatprovides()
449 sel = pool:Selection()
450 di = pool:Dataiterator(solv.SOLVABLE_NAME, arg[1], solv.Dataiterator.SEARCH_SUBSTRING | solv.Dataiterator.SEARCH_NOCASE)
451 for d in di do
452 sel:add_raw(solv.Job.SOLVER_SOLVABLE, d.solvid)
453 end
454 for _, s in ipairs(sel:solvables()) do
455 print(' - '..tostring(s)..' ['..s.repo.name..']: '..s:lookup_str(solv.SOLVABLE_SUMMARY))
456 end
457 os.exit(0)
458 end
459
460 if not cmdactions[cmd] then die(("unknown command '%s'"):format(cmd)) end
461
462 pool:addfileprovides()
463 pool:createwhatprovides()
464
465 jobs = {}
466 for _, a in ipairs(arg) do
467 flags = solv.Selection.SELECTION_NAME | solv.Selection.SELECTION_PROVIDES | solv.Selection.SELECTION_GLOB
468 flags = flags | solv.Selection.SELECTION_CANON | solv.Selection.SELECTION_DOTARCH | solv.Selection.SELECTION_REL
469 if a:sub(1, 1) == '/' then
470 flags = flags | solv.Selection.SELECTION_FILELIST
471 if cmd == 'erase' then
472 flags = flags | solv.Selection.SELECTION_INSTALLED_ONLY
473 end
474 end
475 local sel = pool:select(a, flags)
476 if sel:isempty() then
477 sel = pool:select(a, flags | solv.Selection.SELECTION_NOCASE)
478 if not sel:isempty() then
479 print("[ignoring case for '"..a.."']")
480 end
481 end
482 if (sel.flags & solv.Selection.SELECTION_FILELIST) ~= 0 then
483 print("[using file list match for '"..a.."']")
484 end
485 if (sel.flags & solv.Selection.SELECTION_PROVIDES) ~= 0 then
486 print("[using capability match for '"..a.."']")
487 end
488 for _, j in ipairs(sel:jobs(cmdactions[cmd])) do
489 table.insert(jobs, j)
490 end
491 end
492
493 if #jobs == 0 and (cmd == 'up' or cmd == 'dup' or cmd == 'verify') then
494 for _, j in ipairs(pool:Selection_all():jobs(cmdactions[cmd])) do
495 table.insert(jobs, j)
496 end
497 end
498
499 if #jobs == 0 then die("no package matched.") end
500
501 if cmd == 'list' or cmd == 'info' then
502 for _, job in ipairs(jobs) do
503 for _, s in ipairs(job:solvables()) do
504 if cmd == 'info' then
505 local str
506 print('Name: '..tostring(s))
507 print('Repo: '..s.repo.name)
508 print('Summary: '..s:lookup_str(solv.SOLVABLE_SUMMARY))
509 str = s:lookup_str(solv.SOLVABLE_URL)
510 if str then print('Url: '..str) end
511 str = s:lookup_str(solv.SOLVABLE_LICENSE)
512 if str then print('License: '..str) end
513 print("Description\n"..s:lookup_str(solv.SOLVABLE_DESCRIPTION))
514 print('')
515 else
516 print(' - '..tostring(s)..' ['..s.repo.name..']')
517 print(' '..s:lookup_str(solv.SOLVABLE_SUMMARY))
518 end
519 end
520 end
521 os.exit(0)
522 end
523
524 local solver = pool:Solver()
525 if cmd == 'erase' then
526 solver:set_flag(solv.Solver.SOLVER_FLAG_ALLOW_UNINSTALL, 1)
527 end
528
529 while true do
530 local problems = solver:solve(jobs)
531 if #problems == 0 then break end
532 for _, problem in ipairs(problems) do
533 print(("Problem %d/%d:"):format(problem.id, #problems))
534 print(problem)
535 local solutions = problem:solutions()
536 for _, solution in ipairs(solutions) do
537 print((" Solution %d:"):format(solution.id))
538 local elements = solution:elements(true)
539 for _, element in ipairs(elements) do
540 print((" - %s"):format(element))
541 end
542 print('')
543 end
544 end
545 os.exit(1)
546 end
547
548 local trans = solver:transaction()
549 if trans:isempty() then
550 print("Nothing to do.")
551 os.exit(0)
552 end
553 print('')
554 print("Transaction summary:")
555 print('')
556 for _, cl in ipairs(trans:classify(solv.Transaction.SOLVER_TRANSACTION_SHOW_OBSOLETES | solv.Transaction.SOLVER_TRANSACTION_OBSOLETE_IS_UPGRADE)) do
557 if cl.type == solv.Transaction.SOLVER_TRANSACTION_ERASE then
558 print(("%d erased packages:"):format(cl.count))
559 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_INSTALL then
560 print(("%d installed packages:"):format(cl.count))
561 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_REINSTALLED then
562 print(("%d reinstalled packages:"):format(cl.count))
563 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_DOWNGRADED then
564 print(("%d downgraded packages:"):format(cl.count))
565 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_CHANGED then
566 print(("%d changed packages:"):format(cl.count))
567 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_UPGRADED then
568 print(("%d upgraded packages:"):format(cl.count))
569 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_VENDORCHANGE then
570 print(("%d vendor changes from '%s' to '%s':"):format(cl.count, cl.fromstr, cl.tostr))
571 elseif cl.type == solv.Transaction.SOLVER_TRANSACTION_ARCHCHANGE then
572 print(("%d arch changes from '%s' to '%s':"):format(cl.count, cl.fromstr, cl.tostr))
573 else
574 cl = nil
575 end
576 if cl then
577 for _, p in ipairs(cl:solvables()) do
578 if cl.type == solv.Transaction.SOLVER_TRANSACTION_UPGRADED or cl.type == solv.Transaction.SOLVER_TRANSACTION_DOWNGRADED then
579 print((" - %s -> %s"):format(p, trans:othersolvable(p)))
580 else
581 print((" - %s"):format(p))
582 end
583 end
584 print('')
585 end
586 end
587 print(("install size change: %d K"):format(trans:calc_installsizechange()))
588 print('')
589