-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRebasePath.lua
More file actions
67 lines (63 loc) · 1.93 KB
/
RebasePath.lua
File metadata and controls
67 lines (63 loc) · 1.93 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
--TODO: add redirections to accomodate common repository paths
--[[--
Returns a modified version of a pacakge path string
@param table|nil opt a table with options
options:
path: package path to use, defaults to pacakge.path
target: the new path component to use
base: search for this in paths, interpreted as a string pattern, defaults to './'
limit: limit number of substitutions to this number, defaults to 1
anchor: anchor at beginning of path, defaults to true
mode: defaults to 'replace'
append: mix the original and the rebased in place
replace: replace base in place
new: return only the modified paths
simple example: package.path = package.path .. dofile "<pathToThisFile>" {
base = '../MyLibraries/',--mind the trailing slash
mode = 'new',
}
]]
return function ( opt )
opt = opt or {}
local function Escape ( str )
return str:gsub ( '%W', '%%%1' )
end
local Path = opt.path or package.path
local Base = opt.base or './'
local Target = assert ( opt.target, 'No target given' )
local Limit = opt.limit or 1
local Separator = package.config and package.config:match'.\n(.)' or ';'
local BaseSafe = Escape ( Base )
local Anchor = opt.anchor
if Anchor == nil then
Anchor = true
end
if Anchor then
BaseSafe = '^' .. BaseSafe
end
local SeparatorSafe = Escape ( Separator )
local PathPattern = '[^' .. SeparatorSafe ..']+'
local Rebaser
local mode = opt.mode or 'replace'
if mode == 'append' then
function Rebaser ( path )
return path:gsub ( BaseSafe, Target, Limit ) .. Separator .. path
end
elseif mode == 'replace' or mode == 'new' then
function Rebaser ( path )
return path:gsub ( BaseSafe, Target, Limit )
end
end
if mode == 'new' then
local newPaths, i = {}, 1
for path in Path:gmatch ( PathPattern ) do
newPaths [ i ], i = Rebaser ( path ), i + 1
end
return Separator .. table.concat ( newPaths, Separator )
else
return Path:gsub (
PathPattern,
Rebaser
)
end
end