Debian Codegraph @

texk/texlive/linked_scripts/l3sys-query/l3sys-query.lua

raw symbols SCIP
1 #!/usr/bin/env texlua
2
3 --[[
4
5 File l3sys-query.lua Copyright (C) 2024 The LaTeX Project
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in all
15 copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24
25 -----------------------------------------------------------------------
26
27 The development version of the bundle can be found at
28
29 https://github.com/latex3/l3sys-query
30
31 for those people who are interested.
32
33 --]]
34
35 --
36 -- Details of the script itself, etc.
37 --
38 local copyright = "Copyright (C) 2024 The LaTeX Project"
39 local release_date = "2024-04-08"
40 local script_desc = "System queries for LaTeX using Lua\n"
41 local script_name = "l3sys-query"
42
43 --
44 -- Setup for the CLI: commands and options
45 --
46 local cmd_impl = {}
47 local cmd_desc = {}
48
49 local option_list =
50 {
51 exclude =
52 {
53 cmds = {"ls"},
54 desc = "[<xarg>] Exclude entries from directory listing",
55 type = "string"
56 },
57 ["ignore-case"] =
58 {
59 cmds = {"ls"},
60 desc = "Ignore case when sorting directory listing",
61 type = "boolean"
62 },
63 help =
64 {
65 desc = "Prints this message and exits",
66 short = "h",
67 type = "boolean"
68 },
69 pattern =
70 {
71 cmds = {"ls"},
72 desc = "Treat (x)args as a Lua pattern",
73 short = "p",
74 type = "boolean"
75 },
76 recursive =
77 {
78 cmds = {"ls"},
79 desc = "Activates recursive directory listing",
80 short = "r",
81 type = "boolean"
82 },
83 reverse =
84 {
85 cmds = {"ls"},
86 desc = "Reversing sorting order",
87 type = "boolean"
88 },
89 sort =
90 {
91 cmds = {"ls"},
92 desc = "[name|date] Method used to sort directory listing",
93 type = "string"
94 },
95 type =
96 {
97 cmds = {"ls"},
98 desc = "[d|f] Select just the directories or files in a listing",
99 type = "string"
100 },
101 version =
102 {
103 desc = "Prints version information and exits",
104 short = "v",
105 type = "boolean"
106 }
107 }
108
109 --
110 -- Local copies of globals used here
111 --
112 local io = io
113 local stderr = io.stderr
114
115 local lfs = lfs
116 local attributes = lfs.attributes
117 local currentdir = lfs.currentdir
118 local dir = lfs.dir
119
120 local os = os
121 local exit = os.exit
122
123 local string = string
124 local find = string.find
125 local gmatch = string.gmatch
126 local lower = string.lower
127 local match = string.match
128 local rep = string.rep
129 local sub = string.sub
130
131 local table = table
132 local concat = table.concat
133 local insert = table.insert
134 local sort = table.sort
135
136 --
137 -- Support functions and data
138 --
139
140 -- Remove '...' around an entire text:
141 -- we need this to support restricted shell escape on Windows
142 local function dequote(text)
143 if (match(text,"^'") and match(text,"'$")) then
144 return sub(text,2,-2)
145 end
146 return text
147 end
148
149
150 -- A short auxiliary used whever the script bails out
151 local function info_and_quit(s)
152 stderr:write("\n" .. s .. "\nTry '" .. script_name .. " --help' for more information.\n")
153 exit(1)
154 end
155
156 -- Convert a file glob into a pattern for use by e.g. string.gub
157 -- Based on https://github.com/davidm/lua-glob-pattern
158 -- Simplified substantially: "[...]" syntax not supported as is not
159 -- required by the file patterns used by the team. Also note style
160 -- changes to match coding approach in rest of this file.
161 --
162 -- License for original globtopattern
163 --[[
164
165 (c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
166
167 --]]
168 local function glob_to_pattern(glob,skip_convert)
169 if skip_convert then
170 return glob
171 end
172
173 local pattern = "^" -- pattern being built
174 local i = 0 -- index in glob
175 local char -- char at index i in glob
176
177 -- escape pattern char
178 local function escape(char)
179 return match(char,"^%w$") and char or "%" .. char
180 end
181
182 -- Convert tokens.
183 while true do
184 i = i + 1
185 char = sub(glob,i,i)
186 if char == "" then
187 pattern = pattern .. "$"
188 break
189 elseif char == "?" then
190 pattern = pattern .. "."
191 elseif char == "*" then
192 pattern = pattern .. ".*"
193 elseif char == "[" then -- ]
194 -- Ignored
195 info_and_quit("[...] syntax not supported in globs!")
196 elseif char == "\\" then
197 i = i + 1
198 char = sub(glob,i,i)
199 if char == "" then
200 pattern = pattern .. "\\$"
201 break
202 end
203 pattern = pattern .. escape(char)
204 else
205 pattern = pattern .. escape(char)
206 end
207 end
208 return pattern
209 end
210
211
212 -- Initial data for the command line parser
213 local cmd = ""
214 local options = {}
215 local arg_list = ""
216
217 local function parse_args()
218 -- Turn long/short options into two lookup tables
219 local long_options = {}
220 local short_options = {}
221 for k,v in pairs(option_list) do
222 if v.short then
223 short_options[v.short] = k
224 end
225 long_options[k] = k
226 end
227
228 -- Minor speed-up
229 local arg = arg
230
231 -- arg[1] is a special case: must be a command or a very limited
232 -- subset (--help|-h or --version|-v)
233 local a = arg[1]
234 if a then
235 -- No options are allowed in position 1, so filter those out
236 if a == "--version" or a == "-v" then
237 cmd = "version"
238 elseif a == "--help" or a == "-h" then
239 cmd = "help"
240 elseif not match(a,"^%-") then
241 cmd = a
242 end
243 end
244
245 -- Stop here if help or version is required
246 if cmd == "help" or cmd == "version" then
247 return
248 end
249
250 -- An auxiliary to grab all file names into a string:
251 -- this reflects the fact that the use case for l3sys-query doesn't
252 -- allow quoting spaces
253 local function tidy(num)
254 local t = {}
255 for i = num,#arg do
256 insert(t,dequote(arg[i]))
257 end
258 return concat(t," ")
259 end
260
261 -- Examine all other arguments
262 -- Use a while loop rather than for as this makes it easier
263 -- to grab arg for optionals where appropriate
264 local i = 2
265 while i <= #arg do
266 local a = arg[i]
267 -- Terminate search for options
268 if a == "--" then
269 arg_list = tidy(i + 1)
270 return
271 end
272
273 -- Look for optionals
274 local opt
275 local optarg
276 local opts
277 -- Look for and option and get it into a variable
278 if match(a,"^%-") then
279 if match(a,"^%-%-") then
280 opts = long_options
281 local pos = find(a,"=")
282 if pos then
283 opt = sub(a,3,pos - 1)
284 optarg = sub(a,pos + 1)
285 else
286 opt = sub(a,3)
287 end
288 else
289 opts = short_options
290 opt = sub(a,2,2)
291 -- Only set optarg if it is there
292 if #a > 2 then
293 optarg = sub(a,3)
294 end
295 end
296
297 -- Now check that the option is valid and sort out the argument
298 -- if required
299 local optname = opts[opt]
300 if optname then
301 -- Tidy up arguments
302 if option_list[optname].type == "boolean" then
303 if optarg then
304 local opt = "-" .. (match(a,"^%-%-") and "-" or "") .. opt
305 info_and_quit("Value not allowed for option " .. opt)
306 end
307 else
308 if not optarg then
309 optarg = arg[i + 1]
310 if not optarg then
311 info_and_quit("Missing value for option " .. a)
312 end
313 i = i + 1
314 end
315 end
316 else
317 info_and_quit("Unknown option " .. a)
318 end
319
320 -- Store the result
321 if optarg then
322 if option_list[optname].type == "string" then
323 options[optname] = optarg
324 else
325 local opts = options[optname] or {}
326 for hit in gmatch(optarg,"([^,%s]+)") do
327 insert(opts,hit)
328 end
329 options[optname] = opts
330 end
331 else
332 options[optname] = true
333 end
334 i = i + 1
335 end
336
337 -- Collect up the remaining arguments
338 if not opt then
339 arg_list = tidy(i)
340 break
341 end
342 end
343 end
344
345 parse_args()
346
347 --
348 -- The help functions: local only and hard-coded
349 --
350
351 local function help()
352 -- Find the longest entry to pad
353 local function format_list(list)
354 local longest = 0
355 for k,_ in pairs(list) do
356 if k:len() > longest then
357 longest = k:len()
358 end
359 end
360 -- Sort the list
361 local t = {}
362 for k,_ in pairs(list) do
363 insert(t,k)
364 end
365 sort(t)
366 return t,longest
367 end
368
369 -- 'Header' of fixed info
370 print("Usage: " .. script_name .. " <cmd> [<options>] [<args>]\n")
371 print("Valid <cmd>s are:")
372
373 -- Sort the commands, pad the descriptions, print
374 local t,longest = format_list(cmd_desc)
375 for _,k in ipairs(t) do
376 local cmd = cmd_desc[k]
377 local filler = rep(" ",longest - k:len() + 1)
378 print(" " .. k .. filler .. cmd)
379 end
380
381 -- Same for the options
382 print("\nValid <options> are:")
383 t,longest = format_list(option_list)
384 for _,name in ipairs(t) do
385 local opt = option_list[name]
386 local filler = rep(" ",longest - name:len() + 1)
387 if opt.desc then
388 if opt.short then
389 print(" --" .. name .. "|-" .. opt.short .. filler .. opt.desc)
390 else
391 print(" --" .. name .. " " .. filler .. opt.desc)
392 end
393 end
394 end
395
396 -- Postamble
397 print("\nFull manual available via 'texdoc " .. script_name .. "'.\n")
398 print("Repository : https://github.com/latex3/" .. script_name)
399 print("Bug tracker: https://github.com/latex3/" .. script_name .. "/issues")
400 print("\n" .. copyright)
401 end
402
403 local function version()
404 print(script_name .. " " .. release_date)
405 end
406
407 --
408 -- The functions for commands: all held in the table cmd_impl
409 -- with docstrings in the table cmd_desc.
410 --
411
412 -- The aim here is to convert a user file specification (if given) into a
413 -- Lua pattern, and then to do a listing.
414 cmd_desc.ls = "Prints a listing based on the <args> and <options>"
415 function cmd_impl.ls(arg_list)
416 if not arg_list or arg_list == "" or arg_list == "." then
417 arg_list = "*"
418 end
419 -- Look for absolute paths or any trying to leave the confines of the current
420 -- directory: this is not supported.
421 if match(arg_list,"%.%.") or
422 match(arg_list,"^/") or
423 match(arg_list,"^\\") or
424 match(arg_list,"[a-zA-Z]:") then
425 return
426 end
427 -- Tidy up and convert to a pattern.
428 path,glob = match(arg_list,"^(.*)/([^/]*)$")
429 if not path then
430 path = "."
431 glob = arg_list
432 end
433 if path == "" then
434 path = "."
435 end
436 if not match(path,"^%.") then
437 path = "./" .. path
438 end
439 local conv_pattern = options.pattern
440 local pattern = glob_to_pattern(glob,conv_pattern)
441 local exclude_pattern
442 if options.exclude then
443 local exclude = dequote(options.exclude)
444 exclude_pattern = glob_to_pattern(exclude,conv_pattern)
445 end
446 -- A lookup table for attributes: map between lfs- and Unix-type naming
447 local attrib_map = {d = "directory", f = "file"}
448
449 -- A bit of setup to store the sorting data as well as the entry itself
450 local i = 0 -- If no sorting active, just track the order from lfs
451 local entries = {}
452 local sort_mode = options.sort or "none"
453 local function store(entry,full_entry)
454 if not match(entry,pattern)
455 or (exclude_pattern and match(entry,exclude_pattern)) then
456 return
457 end
458 i = i + 1
459 local key = i
460 if sort_mode == "date" then
461 key = attributes(full_entry,"modification")
462 elseif sort_mode == "name" then
463 key = full_entry
464 end
465 entries[key] = full_entry
466 end
467
468 -- Build a table of entries, excluding "." and "..", and return as a string
469 -- with one entry per line.
470 local opt = options.type
471 local is_rec = options.recursive
472 local function browse(path)
473 for entry in dir(path) do
474 if entry ~= "." and entry ~= ".." and not match(entry,"^%.") then
475 local full_entry = path .. "/" .. entry
476 local ft = attributes(full_entry,"mode")
477 if not opt or ft == attrib_map[opt] then
478 store(entry,full_entry)
479 end
480 if is_rec and ft == "directory" then
481 browse(full_entry)
482 end
483 end
484 end
485 end
486 -- Start a search at the top level
487 browse(path)
488
489 -- Extract keys and sort
490 local s = {}
491 for k,_ in pairs(entries) do
492 insert(s,k)
493 end
494
495 -- Setup for case-insensitve sorting
496 local function case(s)
497 return s
498 end
499 if options["ignore-case"] then
500 function case(s)
501 return lower(s)
502 end
503 end
504
505 if options.reverse then
506 sort(s,function(a,b) return case(a) > case(b) end)
507 else
508 sort(s,function(a,b) return case(a) < case(b) end)
509 end
510
511 local result = {}
512 for _,v in ipairs(s) do
513 insert(result,entries[v])
514 end
515
516 return concat(result,"\n")
517 end
518
519 -- A simple rename
520 cmd_desc.pwd = "Prints the present working directory"
521 function cmd_impl.pwd()
522 return currentdir()
523 end
524
525 --
526 -- Execute the given command
527 --
528 if cmd == "help" then
529 help()
530 exit(0)
531 elseif cmd == "version" then
532 version()
533 exit(0)
534 -- Only 'known' commands do anything at all
535 elseif not cmd_impl[cmd] then
536 if cmd == "" then
537 info_and_quit(script_name .. ": No " .. script_name .. " command specified.")
538 else
539 info_and_quit(script_name .. ": '" .. cmd .. "' is not a " .. script_name ..
540 " command.")
541 end
542 exit(1)
543 end
544
545 -- Check options are valid for cmd
546 for k,_ in pairs(options) do
547 local cmds = option_list[k].cmds
548 if k == "help" then
549 help()
550 exit(0)
551 elseif k == "version" then
552 version()
553 exit(0)
554 elseif not cmds then
555 -- Should not be possible:
556 -- everything except --help and --version should have an entry
557 print("Internal error")
558 exit(1)
559 else
560 -- Make a lookup table
561 local t = {}
562 for _,v in pairs(cmds) do
563 t[v] = true
564 end
565 if not t[cmd] then
566 info_and_quit(script_name .. ": Option '" .. k ..
567 "' does not apply to '" .. cmd .. "'")
568 end
569 end
570 end
571
572 local result = cmd_impl[cmd](arg_list)
573
574 if result then
575 print(result)
576 exit(0)
577 else
578 exit(1)
579 end