Debian Codegraph @

texk/texlive/linked_scripts/texfindpkg/texfindpkg.lua

raw symbols SCIP
1 #!/usr/bin/env texlua
2
3 -- Description: Install TeX packages and their dependencies
4 -- Copyright: 2023-2024 (c) Jianrui Lyu <[email protected]>
5 -- Repository: https://github.com/lvjr/texfindpkg
6 -- License: GNU General Public License v3.0
7
8 local tfp = tfp or {}
9
10 tfp.version = "2024A"
11 tfp.date = "2024-11-22"
12
13 local building = tfp.building
14 local tfpresult = ""
15
16 ------------------------------------------------------------
17 --> \section{Some variables and functions}
18 ------------------------------------------------------------
19
20 local lfs = require("lfs")
21
22 local insert = table.insert
23 local remove = table.remove
24 local concat = table.concat
25 local gmatch = string.gmatch
26 local match = string.match
27 local find = string.find
28 local gsub = string.gsub
29 local sub = string.sub
30 local rep = string.rep
31
32 local lookup = kpse.lookup
33 kpse.set_program_name("kpsewhich")
34
35 require(lookup("lualibs.lua"))
36 local json = utilities.json -- for json.tostring and json.tolua
37 local gzip = gzip -- for gzip.compress and gzip.decompress
38
39 local function tfpPrint(msg)
40 msg = "[tfp] " .. msg
41 if building then
42 tfpresult = tfpresult .. msg .. "\n"
43 else
44 print(msg)
45 end
46 end
47
48 local function tfpRealPrint(msg)
49 if not building then
50 print("[tfp] " .. msg)
51 end
52 end
53
54 local showdbg = false
55
56 local function dbgPrint(msg)
57 if showdbg then print("[debug] " .. msg) end
58 end
59
60 local function valueExists(tab, val)
61 for _, v in ipairs(tab) do
62 if v == val then return true end
63 end
64 return false
65 end
66
67 local function getFiles(path, pattern)
68 local files = { }
69 for entry in lfs.dir(path) do
70 if match(entry, pattern) then
71 insert(files, entry)
72 end
73 end
74 return files
75 end
76
77 local function fileRead(input)
78 local f = io.open(input, "rb")
79 local text
80 if f then -- file exists and is readable
81 text = f:read("*all")
82 f:close()
83 --print(#text)
84 return text
85 end
86 -- return nil if file doesn't exists or isn't readable
87 end
88
89 local function fileWrite(text, output)
90 -- using "wb" keeps unix eol characters
91 f = io.open(output, "wb")
92 f:write(text)
93 f:close()
94 end
95
96 local function testDistribution()
97 -- texlive returns "texmf-dist/web2c/updmap.cfg"
98 -- miktex returns nil although there is "texmfs/install/miktex/config/updmap.cfg"
99 local d = lookup("updmap.cfg")
100 if d then
101 return "texlive"
102 else
103 return "miktex"
104 end
105 end
106
107 ------------------------------------------------------------
108 --> \section{Handle TeX Live package database}
109 ------------------------------------------------------------
110
111 local tlpkgtext
112 local tlinspkgtext
113
114 local function tlReadPackageDB()
115 local tlroot = kpse.var_value("TEXMFROOT")
116 if tlroot then
117 tlroot = tlroot .. "/tlpkg"
118 else
119 tfpPrint("error in finding texmf root!")
120 end
121 local list = getFiles(tlroot, "^texlive%.tlpdb%.main")
122 if #list > 0 then
123 tlpkgtext = fileRead(tlroot .. "/" .. list[1])
124 if not tlpkgtext then
125 tfpPrint("error in reading texlive.tlpdb.main file!")
126 end
127 else
128 -- no texlive.tlpdb.main file in a fresh TeX live
129 tfpPrint("error in finding texlive package database!")
130 tfpPrint("please run 'tlmgr update --self' first.")
131 end
132 tlinspkgtext = fileRead(tlroot .. "/texlive.tlpdb")
133 if not tlinspkgtext then
134 tfpPrint("error in reading texlive.tlpdb file!")
135 end
136 end
137
138 local tlfiletopkg = {}
139 local tlpkgtofile = {}
140 local tlinspkgdata = {}
141
142 local function tlExtractFiles(name, desc)
143 -- ignore binary packages
144 -- also ignore latex-dev packages
145 if find(name, "%.") or find(name, "^latex%-[%a]-%-dev") then
146 --print(name)
147 return
148 end
149 -- ignore package files in doc folder
150 desc = match(desc, "\nrunfiles .+") or ""
151 local flist = {}
152 for base, ext in gmatch(desc, "/([%a%d%-%.]+)%.([%a%d]+)\n") do
153 if ext == "sty" or ext == "cls" or ext == "tex" or ext == "ltx" then
154 dbgPrint(name, base .. "." .. ext)
155 tlfiletopkg[base .. "." .. ext] = name
156 insert(flist, base .. "." .. ext)
157 end
158 end
159 tlpkgtofile[name]= flist
160 end
161
162 local function tlExtractPackages(name, desc)
163 tlinspkgdata[name] = true
164 end
165
166 local function tlParsePackageDB(tlpkgtext)
167 gsub(tlpkgtext, "name (.-)\n(.-)\n\n", tlExtractFiles)
168 return tlfiletopkg
169 end
170
171 local function tlParseTwoPackageDB()
172 gsub(tlpkgtext, "name (.-)\n(.-)\n\n", tlExtractFiles)
173 -- texlive.tlpdb might use different eol characters
174 gsub(tlinspkgtext, "name (.-)\r?\n(.-)\r?\n\r?\n", tlExtractPackages)
175 end
176
177 ------------------------------------------------------------
178 --> \section{Handle MiKTeX package database}
179 ------------------------------------------------------------
180
181 local mtpkgtext
182 local mtinspkgtext
183
184 local function mtReadPackageDB()
185 local mtvar = kpse.var_value("TEXMFDIST")
186 if mtvar then
187 mtpkgtext = fileRead(mtvar .. "/miktex/config/package-manifests.ini")
188 if not mtpkgtext then
189 tfpPrint("error in reading package-manifests.ini file!")
190 end
191 mtinspkgtext = fileRead(mtvar .. "/miktex/config/packages.ini")
192 if not mtinspkgtext then
193 tfpPrint("error in reading packages.ini file!")
194 end
195 else
196 tfpPrint("error in finding texmf root!")
197 end
198 end
199
200 local mtfiletopkg = {}
201 local mtpkgtofile = {}
202 local mtinspkgdata = {}
203
204 local function mtExtractFiles(name, desc)
205 -- ignore package files in source or doc folders
206 -- also ignore latex-dev packages
207 if find(name, "_") or find(name, "^latex%-[%a]-%-dev") then
208 --print(name)
209 return
210 end
211 local flist = {}
212 for base, ext in gmatch(desc, "/([%a%d%-%.]+)%.([%a%d]+)\r?\n") do
213 if ext == "sty" or ext == "cls" or ext == "tex" or ext == "ltx" then
214 dbgPrint(name, base .. "." .. ext)
215 mtfiletopkg[base .. "." .. ext] = name
216 insert(flist, base .. "." .. ext)
217 end
218 end
219 mtpkgtofile[name]= flist
220 end
221
222 local function mtExtractPackages(name, desc)
223 mtinspkgdata[name] = true
224 end
225
226 local function mtParsePackageDB(mtpkgtext)
227 -- package-manifests.ini might use different eol characters
228 gsub(mtpkgtext, "%[(.-)%]\r?\n(.-)\r?\n\r?\n", mtExtractFiles)
229 return mtfiletopkg
230 end
231
232 local function mtParseTwoPackageDB()
233 -- package-manifests.ini and packages.ini might use different eol characters
234 gsub(mtpkgtext, "%[(.-)%]\r?\n(.-)\r?\n\r?\n", mtExtractFiles)
235 gsub(mtinspkgtext, "%[(.-)%]\r?\n(.-)\r?\n\r?\n", mtExtractPackages)
236 end
237
238 ------------------------------------------------------------
239 --> \section{Install packages in current TeX distribution}
240 ------------------------------------------------------------
241
242 local dist -- name of current tex distribution
243 local totaldeplist = {} -- list of all depending packages
244 local totalinslist = {} -- list of all missing packages
245 local filecount = 0 -- total number of files found
246
247 local function initPackageDB()
248 dist = testDistribution()
249 tfpPrint("you are using " .. dist)
250 if dist == "texlive" then
251 tlReadPackageDB()
252 tlParseTwoPackageDB()
253 else
254 mtReadPackageDB()
255 mtParseTwoPackageDB()
256 end
257 end
258
259 local function findPackageFromFile(fname)
260 if dist == "texlive" then
261 return tlfiletopkg[fname]
262 else
263 return mtfiletopkg[fname]
264 end
265 end
266
267 local function findFilesInPackage(pkg)
268 if dist == "texlive" then
269 return tlpkgtofile[pkg]
270 else
271 return mtpkgtofile[pkg]
272 end
273 end
274
275 local function checkInsPakage(pkg)
276 if dist == "texlive" then
277 return tlinspkgdata[pkg]
278 else
279 return mtinspkgdata[pkg]
280 end
281 end
282
283 local function tfpExecute(c)
284 if not building then
285 if os.type == "windows" then
286 os.execute(c)
287 else
288 os.execute('sudo env "PATH=$PATH" ' .. c)
289 end
290 end
291 end
292
293 local function installSomePackages(list)
294 if not list then return end
295 if dist == "texlive" then
296 local pkgs = concat(list, " ")
297 if #list > 1 then
298 tfpRealPrint("installing texlive packages: " .. pkgs)
299 else
300 tfpRealPrint("installing texlive package: " .. pkgs)
301 end
302 tfpExecute("tlmgr install " .. pkgs)
303 else
304 -- miktex fails if one of the packages is already installed
305 -- so we install miktex packages one by one
306 for _, p in ipairs(list) do
307 tfpRealPrint("installing miktex package: " .. p)
308 tfpExecute("miktex packages install " .. p)
309 end
310 end
311 end
312
313 local function updateTotalInsList(inslist)
314 if #totalinslist == 0 then
315 totalinslist = inslist
316 else
317 for _, pkg in ipairs(inslist) do
318 if not valueExists(totalinslist, pkg) then
319 insert(totalinslist, pkg)
320 end
321 end
322 end
323 end
324
325 local function listSomePackages(list)
326 if not list then return {} end
327 if #list > 0 then
328 filecount = filecount + 1
329 end
330 table.sort(list)
331 local pkgs = concat(list, " ")
332 if #list == 1 then
333 tfpPrint(dist .. " package needed: " .. pkgs)
334 else
335 tfpPrint(dist .. " packages needed: " .. pkgs)
336 end
337 local inslist = {}
338 for _, p in ipairs(list) do
339 if not checkInsPakage(p) then
340 insert(inslist, p)
341 end
342 end
343 if #inslist == 0 then
344 if #list == 1 then
345 tfpRealPrint("this package is already installed")
346 else
347 tfpRealPrint("these packages are already installed")
348 end
349 else
350 table.sort(inslist)
351 local pkgs = concat(inslist, " ")
352 if #inslist == 1 then
353 tfpRealPrint(dist .. " package not yet installed: " .. pkgs)
354 else
355 tfpRealPrint(dist .. " packages not yet installed: " .. pkgs)
356 end
357 end
358 updateTotalInsList(inslist)
359 end
360
361 ------------------------------------------------------------
362 --> \section{Find dependencies of package files}
363 ------------------------------------------------------------
364
365 local tfptext = "" -- the json text
366 local tfpdata = {} -- the lua object
367 local fnlist = {} -- file name list
368 local pkglist = {} -- package name list
369
370 local function initDependencyDB()
371 local ziptext = fileRead(lookup("texfindpkg.json.gz"))
372 tfptext = gzip.decompress(ziptext)
373 if tfptext then
374 --print(tfptext)
375 tfpdata = json.tolua(tfptext)
376 else
377 tfpPrint("error in reading texfindpkg.json.gz!")
378 end
379 end
380
381 local function printDependency(fname, level)
382 local msg = fname
383 local pkg = findPackageFromFile(fname)
384 if pkg then
385 msg = msg .. " (from " .. pkg .. ")"
386 if not valueExists(pkglist, pkg) then
387 insert(pkglist, pkg)
388 end
389 if not valueExists(totaldeplist, pkg) then
390 insert(totaldeplist, pkg)
391 end
392 else
393 msg = msg .. " (not found)"
394 end
395 if level == 0 then
396 tfpPrint(msg)
397 else
398 tfpPrint(rep(" ", level - 1) .. "|- " .. msg)
399 end
400 end
401
402 local function findDependencies(fname, level)
403 --print(fname)
404 if valueExists(fnlist, fname) then return end
405 local item = tfpdata[fname]
406 if not item then
407 -- no dependency info for fname
408 printDependency(fname, level)
409 return
410 end
411 -- finding dependencies for fname
412 printDependency(fname, level)
413 insert(fnlist, fname)
414 local deps = item.deps
415 if deps then
416 for _, dname in ipairs(deps) do
417 findDependencies(dname, level + 1)
418 end
419 end
420 end
421
422 local function queryByFileName(fname)
423 fnlist, pkglist = {}, {} -- reset the list
424 if not find(fname, "%.") then
425 fname = fname .. ".sty"
426 end
427 tfpPrint("building dependency tree for " .. fname .. ":")
428 tfpPrint(rep("-", 24))
429 findDependencies(fname, 0)
430 tfpPrint(rep("-", 24))
431 if #fnlist == 0 then
432 tfpPrint("could not find any package with file " .. fname)
433 return
434 end
435 if #pkglist == 0 then
436 tfpPrint("error in finding package in " .. dist)
437 return
438 end
439 listSomePackages(pkglist)
440 end
441
442 local function queryByPackageName(pname)
443 local list = findFilesInPackage(pname)
444 if list == nil then
445 tfpPrint(dist .. " package " .. pname .. " doesn't exist")
446 return
447 end
448 if #list > 0 then
449 tfpPrint("finding package files in " .. dist .. " package " .. pname)
450 for _, fname in ipairs(list) do
451 tfpPrint(rep("=", 48))
452 tfpPrint("found package file " .. fname .. " in " .. dist .. " package " .. pname)
453 queryByFileName(fname)
454 end
455 else
456 tfpPrint("could not find any package file in " .. dist .. " package " .. pname)
457 listSomePackages({pname})
458 if not valueExists(totaldeplist, pname) then
459 insert(totaldeplist, pname)
460 end
461 end
462 end
463
464 local function getFileNameFromCmdEnvName(cmdenv, name)
465 --print(name)
466 local flist = {}
467 for line in gmatch(tfptext, "(.-)\n[,}]") do
468 if find(line, '"' .. name .. '"') then
469 --print(line)
470 local fname, fspec = match(line, '"(.-)":(.+)')
471 --print(fname, fspec)
472 local item = json.tolua(fspec)
473 if item[cmdenv] and valueExists(item[cmdenv], name) then
474 insert(flist, fname)
475 end
476 end
477 end
478 return flist
479 end
480
481 local function queryByCommandName(cname)
482 --print(cname)
483 local flist = getFileNameFromCmdEnvName("cmds", cname)
484 if #flist > 0 then
485 for _, fname in ipairs(flist) do
486 tfpPrint(rep("=", 48))
487 tfpPrint("found package file " .. fname .. " with command \\" .. cname)
488 queryByFileName(fname)
489 end
490 else
491 tfpPrint("could not find any package with command \\" .. cname)
492 end
493 end
494
495 local function queryByEnvironmentName(ename)
496 --print(ename)
497 local flist = getFileNameFromCmdEnvName("envs", ename)
498 if #flist > 0 then
499 for _, fname in ipairs(flist) do
500 tfpPrint(rep("=", 48))
501 tfpPrint("found package file " .. fname .. " with environment {" .. ename .. "}")
502 queryByFileName(fname)
503 end
504 else
505 tfpPrint("could not find any package with environment {" .. ename .. "}")
506 end
507 end
508
509 local function queryOne(t, name)
510 if t == "cmd" then
511 queryByCommandName(name)
512 elseif t == "env" then
513 queryByEnvironmentName(name)
514 elseif t == "file" then
515 tfpPrint(rep("=", 48))
516 queryByFileName(name)
517 else -- t == "pkg"
518 tfpPrint(rep("=", 48))
519 queryByPackageName(name)
520 end
521 end
522
523 local outfile = nil
524
525 local function query(namelist)
526 for _, v in ipairs(namelist) do
527 queryOne(v[1], v[2])
528 end
529 if filecount > 1 then
530 tfpRealPrint(rep("=", 48))
531 table.sort(totaldeplist)
532 local pkgs = concat(totaldeplist, " ")
533 if #totaldeplist == 0 then
534 --tfpRealPrint("no packages needed are found")
535 elseif #totaldeplist == 1 then
536 tfpRealPrint(dist .. " package needed in total: " .. pkgs)
537 else
538 tfpRealPrint(dist .. " packages needed in total: " .. pkgs)
539 end
540 tfpRealPrint(rep("=", 48))
541 table.sort(totalinslist)
542 local pkgs = concat(totalinslist, " ")
543 if #totalinslist == 0 then
544 tfpRealPrint("you don't need to install any packages")
545 elseif #totalinslist == 1 then
546 tfpRealPrint(dist .. " package not yet installed in total: " .. pkgs)
547 else
548 tfpRealPrint(dist .. " packages not yet installed in total: " .. pkgs)
549 end
550 if outfile then
551 --print(outfile)
552 pkgs = concat(totaldeplist, "\n")
553 fileWrite(pkgs, outfile)
554 end
555 end
556 end
557
558 local function install(namelist)
559 query(namelist)
560 if #totalinslist > 0 then
561 installSomePackages(totalinslist)
562 end
563 end
564
565 ------------------------------------------------------------
566 --> \section{Parse query or install arguments}
567 ------------------------------------------------------------
568
569 local function parseName(name)
570 local h = sub(name, 1, 1)
571 if h == "\\" then
572 local b = sub(name, 2)
573 return({"cmd", b})
574 elseif h == "{" then
575 if sub(name, -1) == "}" then
576 local b = sub(name, 2, -2)
577 return({"env", b})
578 else
579 error("invalid name '" .. name .. "'")
580 end
581 elseif find(name, "%.") then
582 return({"file", name})
583 else
584 return({"pkg", name})
585 end
586 end
587
588 local function readArgsInFile(list, inname)
589 local intext = fileRead(inname)
590 if not intext then
591 tfpPrint("error in reading input file " .. inname)
592 return list
593 end
594 tfpPrint("reading input file " .. inname)
595 for line in gmatch(intext, "%s*(.-)%s*\r?\n") do
596 line = match(line, "(.-)%s*#") or line
597 --print("|" .. line .. "|")
598 if line ~= "" then
599 insert(list, line)
600 end
601 end
602 return list
603 end
604
605 local function readArgList(arglist)
606 local reallist = {}
607 local isinput = false
608 local isoutput = false
609 for _, v in ipairs(arglist) do
610 if isinput then
611 reallist = readArgsInFile(reallist, v)
612 isinput = false
613 elseif isoutput then
614 outfile = v
615 isoutput = false
616 elseif v == "-i" then
617 isinput = true
618 elseif v == "-o" then
619 isoutput = true
620 else
621 insert(reallist, v)
622 end
623 end
624 return reallist
625 end
626
627 local function parseArgList(arglist)
628 local reallist = readArgList(arglist)
629 local namelist = {}
630 local nametype = nil
631 for _, v in ipairs(reallist) do
632 if v == "-c" then
633 nametype = "cmd"
634 elseif v == "-e" then
635 nametype = "env"
636 elseif v == "-f" then
637 nametype = "file"
638 elseif v == "-p" then
639 nametype = "pkg"
640 else
641 if nametype then
642 insert(namelist, {nametype, v})
643 else
644 insert(namelist, parseName(v))
645 end
646 end
647 end
648 if #namelist == 0 then
649 error("missing the name of file/cmd/env!")
650 else
651 return namelist
652 end
653 end
654
655 local function doQuery(arglist)
656 local namelist = parseArgList(arglist)
657 initPackageDB()
658 initDependencyDB()
659 query(namelist)
660 end
661
662 local function doInstall(arglist)
663 local namelist = parseArgList(arglist)
664 initPackageDB()
665 initDependencyDB()
666 install(namelist)
667 end
668
669 ------------------------------------------------------------
670 --> \section{Print help or version text}
671 ------------------------------------------------------------
672
673 local helptext = [[
674 usage: texfindpkg <action> [<options>] [<name>]
675
676 valid actions are:
677 install Install some package and its dependencies
678 query Query dependencies for some package
679 help Print this message and exit
680 version Print version information and exit
681
682 valid options are:
683 -c Query or install by command name
684 -e Query or install by environment name
685 -f Query or install by file name
686 -p Query or install by package name
687 -i Read arguments line by line from a file
688 -o Write total dependent list to a file
689
690 please report bug at https://github.com/lvjr/texfindpkg
691 ]]
692
693 local function help()
694 print(helptext)
695 end
696
697 local function version()
698 print("TeXFindPkg Version " .. tfp.version .. " (" .. tfp.date .. ")\n")
699 end
700
701 ------------------------------------------------------------
702 --> \section{Respond to user input}
703 ------------------------------------------------------------
704
705 local function tfpMain(tfparg)
706 tfpresult = ""
707 if tfparg[1] == nil then return help() end
708 local action = remove(tfparg, 1)
709 action = match(action, "^%-*(.*)$") -- remove leading dashes
710 --print(action)
711 if action == "query" then
712 doQuery(tfparg)
713 elseif action == "install" then
714 doInstall(tfparg)
715 elseif action == "help" then
716 help()
717 elseif action == "version" then
718 version()
719 else
720 tfpPrint("unknown action '" .. action .. "'")
721 help()
722 end
723 return tfpresult
724 end
725
726 local function main()
727 tfpMain(arg)
728 end
729
730 if building then
731 tfp.tfpMain = tfpMain
732 tfp.showdbg = showdbg
733 tfp.dbgPrint = dbgPrint
734 tfp.tfpPrint = tfpPrint
735 tfp.fileRead = fileRead
736 tfp.fileWrite = fileWrite
737 tfp.getFiles = getFiles
738 tfp.valueExists = valueExists
739 tfp.json = json
740 tfp.gzip = gzip
741 tfp.tlParsePackageDB = tlParsePackageDB
742 tfp.mtParsePackageDB = mtParsePackageDB
743 return tfp
744 else
745 main()
746 end