summaryrefslogtreecommitdiff
path: root/macros/latex/contrib/l3build/l3build-file-functions.lua
blob: 841c05571ae45e20090f3c802503ecbd33cf71c5 (plain)
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
--[[

File l3build-file-functions.lua Copyright (C) 2018-2022 The LaTeX Project

It may be distributed and/or modified under the conditions of the
LaTeX Project Public License (LPPL), either version 1.3c of this
license or (at your option) any later version.  The latest version
of this license is in the file

   http://www.latex-project.org/lppl.txt

This file is part of the "l3build bundle" (The Work in LPPL)
and all files in that bundle must be distributed together.

-----------------------------------------------------------------------

The development version of the bundle can be found at

   https://github.com/latex3/l3build

for those people who are interested.

--]]

local pairs            = pairs
local print            = print

local open             = io.open

local attributes       = lfs.attributes
local currentdir       = lfs.currentdir
local chdir            = lfs.chdir
local lfs_dir          = lfs.dir

local execute          = os.execute
local exit             = os.exit
local getenv           = os.getenv
local remove           = os.remove
local os_type          = os.type

local luatex_revision  = status.luatex_revision
local luatex_version   = status.luatex_version

local match            = string.match
local sub              = string.sub
local gmatch           = string.gmatch
local gsub             = string.gsub

local insert           = table.insert

-- Convert a file glob into a pattern for use by e.g. string.gub
-- Based on https://github.com/davidm/lua-glob-pattern
-- Simplified substantially: "[...]" syntax not supported as is not
-- required by the file patterns used by the team. Also note style
-- changes to match coding approach in rest of this file.
--
-- License for original globtopattern
--[[

   (c) 2008-2011 David Manura.  Licensed under the same terms as Lua (MIT).

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  (end license)

--]]
function glob_to_pattern(glob)

  local pattern = "^" -- pattern being built
  local i = 0 -- index in glob
  local char -- char at index i in glob

  -- escape pattern char
  local function escape(char)
    return match(char, "^%w$") and char or "%" .. char
  end

  -- Convert tokens.
  while true do
    i = i + 1
    char = sub(glob, i, i)
    if char == "" then
      pattern = pattern .. "$"
      break
    elseif char == "?" then
      pattern = pattern .. "."
    elseif char == "*" then
      pattern = pattern .. ".*"
    elseif char == "[" then
      -- Ignored
      print("[...] syntax not supported in globs!")
    elseif char == "\\" then
      i = i + 1
      char = sub(glob, i, i)
      if char == "" then
        pattern = pattern .. "\\$"
        break
      end
      pattern = pattern .. escape(char)
    else
      pattern = pattern .. escape(char)
    end
  end
  return pattern
end

-- Detect the operating system in use
-- Support items are defined here for cases where a single string can cover
-- both Windows and Unix cases: more complex situations are handled inside
-- the support functions
os_concat  = ";"
os_null    = "/dev/null"
os_pathsep = ":"
os_setenv  = "export"
os_yes     = "printf 'y\\n%.0s' {1..300}"

os_ascii   = "echo \"\""
os_cmpexe  = getenv("cmpexe") or "cmp"
os_cmpext  = getenv("cmpext") or ".cmp"
os_diffext = getenv("diffext") or ".diff"
os_diffexe = getenv("diffexe") or "diff -c --strip-trailing-cr"
os_grepexe = "grep"
os_newline = "\n"

if os_type == "windows" then
  os_ascii   = "@echo."
  os_cmpexe  = getenv("cmpexe") or "fc /b"
  os_cmpext  = getenv("cmpext") or ".cmp"
  os_concat  = "&"
  os_diffext = getenv("diffext") or ".fc"
  os_diffexe = getenv("diffexe") or "fc /n"
  os_grepexe = "findstr /r"
  os_newline = "\n"
  if tonumber(luatex_version) < 100 or
     (tonumber(luatex_version) == 100
       and tonumber(luatex_revision) < 4) then
    os_newline = "\r\n"
  end
  os_null    = "nul"
  os_pathsep = ";"
  os_setenv  = "set"
  os_yes     = "for /l %I in (1,1,300) do @echo y"
end

-- Deal with the fact that Windows and Unix use different path separators
local function unix_to_win(path)
  return gsub(path, "/", "\\")
end

function normalize_path(path)
  if os_type == "windows" then
    return unix_to_win(path)
  end
  return path
end

-- Return an absolute path from a relative one
-- Due to chdir, path must exist and be accessible.
function abspath(path)
  local oldpwd = currentdir()
  local ok, msg = chdir(path)
  if ok then
    local result = currentdir()
    chdir(oldpwd)
    return escapepath(gsub(gsub(result,"^\\\\%?\\",""), "\\", "/"))
  end
  error(msg)
end

-- TODO: Fix the cross platform problem
function escapepath(path)
  if os_type == "windows" then
    local path,count = gsub(path,'"','')
    if count % 2 ~= 0 then
      print("Unbalanced quotes in path")
      exit(0)
    else
      if match(path," ") then
        return '"' .. path .. '"'
      end
      return path
    end
  else
    path = gsub(path,"\\ ","[PATH-SPACE]")
    path = gsub(path," ","\\ ")
    return gsub(path,"%[PATH%-SPACE%]","\\ ")
  end
end

-- For cleaning out a directory, which also ensures that it exists
function cleandir(dir)
  local errorlevel = mkdir(dir)
  if errorlevel ~= 0 then
    return errorlevel
  end
  return rm(dir, "**")
end

function direxists(dir)
  return attributes(dir, "mode") == "directory"
end

function fileexists(file)
  local f = open(file, "r")
  if f ~= nil then
    f:close()
    return true
  else
    return false -- also file exits and is not readable
  end
end

-- Copy files 'quietly'
function cp(glob, source, dest)
  local errorlevel
  for _,p in ipairs(tree(source, glob)) do
    -- p_src is a path relative to `source` whereas
    -- p_cwd is the counterpart relative to the current working directory
    if os_type == "windows" then
      if direxists(p.cwd) then
        errorlevel = execute(
          'xcopy /y /e /i "' .. unix_to_win(p.cwd) .. '" '
             .. unix_to_win(dest .. '/' .. escapepath(p.src)) .. ' > nul'
        ) and 0 or 1
      else
        errorlevel = execute(
          'xcopy /y "' .. unix_to_win(p.cwd) .. '" '
             .. unix_to_win(dest .. '/') .. ' > nul'
        ) and 0 or 1
      end
    else
      -- Ensure we get similar behavior on all platforms
      if not direxists(dirname(dest)) then
        errorlevel = mkdir(dirname(dest))
        if errorlevel ~=0 then return errorlevel end
      end
      errorlevel = execute(
        "cp -RLf '" .. p.cwd .. "' " .. dest
      ) and 0 or 1
    end
    if errorlevel ~=0 then
      return errorlevel
    end
  end
  return 0
end

-- Generate a table containing all file names of the given glob or all files
-- if absent
function filelist(path, glob)
  local files = { }
  local pattern
  if glob then
    pattern = glob_to_pattern(glob)
  end
  if direxists(path) then
    for entry in lfs_dir(path) do
      if pattern then
        if match(entry, pattern) then
          insert(files, entry)
        end
      else
        if entry ~= "." and entry ~= ".." then
          insert(files, entry)
        end
      end
    end
  end
  return files
end
function ordered_filelist(...)
  local files = filelist(...)
  table.sort(files)
  return files
end

---@class tree_entry_t
---@field src string path relative to the source directory
---@field cwd string path counterpart relative to the current working directory

---Does what filelist does, but can also glob subdirectories.
---In the returned table, the keys are paths relative to the given source path,
---the values are their counterparts relative to the current working directory.
---@param src_path string
---@param glob string
---@return table<integer,tree_entry_t>
function tree(src_path, glob)
  local function cropdots(path)
    return path:gsub( "^%./", ""):gsub("/%./", "/")
  end
  src_path = cropdots(src_path)
  glob = cropdots(glob)
  local function always_true()
    return true
  end
  ---@type table<integer,tree_entry_t>
  local result = { {
    src = ".",
    cwd = src_path,
  } }
  for glob_part, sep in glob:gmatch("([^/]+)(/?)/*") do
    local accept = sep == "/" and direxists or always_true
    ---Feeds the given table according to `glob_part`
    ---@param p tree_entry_t path counterpart relative to the current working directory
    ---@param table table
    local function fill(p, table)
      for _,file in ipairs(filelist(p.cwd, glob_part)) do
        if file ~= "." and file ~= ".." then
          local pp = {
            src = p.src .. "/" .. file,
            cwd = p.cwd .. "/" .. file,
          }
          if pp.cwd ~= builddir -- TODO: ensure that `builddir` is properly formatted
          and accept(pp.cwd)
          then
            insert(table, pp)
          end
        end
      end
    end
    local new_result = {}
    if glob_part == "**" then
      local i = 1
      while true do
        local p = result[i]
        i = i + 1
        if not p then
          break
        end
        insert(new_result, p) -- shorter path
        fill(p, result)       -- after longer
      end
    else
      for _,p in ipairs(result) do
        fill(p, new_result)
      end
    end
    result = new_result
  end
  return result
end

function remove_duplicates(a)
  -- Return array with duplicate entries removed from input array `a`.

  local uniq = {}
  local hash = {}

  for _,v in ipairs(a) do
    if (not hash[v]) then
      hash[v] = true
      uniq[#uniq+1] = v
    end
  end

  return uniq
end

function mkdir(dir)
  dir = escapepath(dir)
  if os_type == "windows" then
    -- Windows (with the extensions) will automatically make directory trees
    -- but issues a warning if the dir already exists: avoid by including a test
    dir = unix_to_win(dir)
    return execute(
      "if not exist "  .. dir .. "\\nul " .. "mkdir " .. dir
    )
  else
    return execute("mkdir -p " .. dir)
  end
end

-- Rename
function ren(dir, source, dest)
  dir = dir .. "/"
  if os_type == "windows" then
    source = gsub(source, "^%.+/", "")
    dest = gsub(dest, "^%.+/", "")
    return execute("ren " .. unix_to_win(dir) .. source .. " " .. dest)
  else
    return execute("mv " .. dir .. source .. " " .. dir .. dest)
  end
end

-- Remove file(s) based on a glob
function rm(source, glob)
  for _,p in ipairs(tree(source, glob)) do
    rmfile(source,p.src)
  end
  -- os.remove doesn't give a sensible errorlevel
  return 0
end

-- Remove file
function rmfile(source, file)
  remove(source .. "/" .. file)
  -- os.remove doesn't give a sensible errorlevel
  return 0
end

-- Remove a directory tree
function rmdir(dir)
  -- First, make sure it exists to avoid any errors
  mkdir(dir)
  if os_type == "windows" then
    return execute("rmdir /s /q " .. unix_to_win(dir))
  else
    return execute("rm -r " .. dir)
  end
end

-- Run a command in a given directory
function run(dir, cmd)
  return execute("cd " .. dir .. os_concat .. cmd)
end

-- Split a path into file and directory component
function splitpath(file)
  local path, name = match(file, "^(.*)/([^/]*)$")
  if path then
    return path, name
  else
    return ".", file
  end
end

-- Arguably clearer names
function basename(file)
  return(select(2, splitpath(file)))
end

function dirname(file)
  return(select(1, splitpath(file)))
end

-- Strip the extension from a file name (if present)
function jobname(file)
  local name = match(basename(file), "^(.*)%.")
  return name or file
end

-- Look for files, directory by directory, and return the first existing
function locate(dirs, names)
  for _,i in ipairs(dirs) do
    for _,j in ipairs(names) do
      local path = i .. "/" .. j
      if fileexists(path) then
        return path
      end
    end
  end
end