如何使用LUA转换相对路径中的绝对路径?

时间:2012-11-05 00:58:09

标签: path lua relative absolute

我有两个绝对文件路径(AB)。我想在A的相对路径中转换B。我怎么能用Lua脚本来做呢?

2 个答案:

答案 0 :(得分:3)

执行此操作的算法是:

  1. 将两个路径转换为规范形式。 (即从文件系统根开始,没有尾部斜杠,没有双斜线等)
  2. 从两个路径中删除它们的公共前缀。 (例如,从A="/a/b/c/d.txt" B="/a/b/e/f.txt"转到A="c/d.txt" B="e/f.txt"
  3. 按路径分隔符拆分剩余路径。 (所以你最终会得到A={"c", "d.txt"} B={"e", "f.txt"}
  4. 如果原始路径B指向常规文件,请删除B的最后一个元素。如果它指向一个目录,请保持原样。 (对于我们的示例,您将获得B={"e"}
  5. 对于B中剩余的每个项目,请在..的开头插入A。 (由A={"..", "c", "d.txt"}生成)
  6. 使用路径分隔符加入A的内容以获取最终结果:"../c/d.txt"
  7. 这是一个非常粗略的实现,无需库。它不处理任何边缘情况,如fromto相同,或者一个是另一个的前缀。 (我的意思是在这些情况下函数肯定会破坏,因为mismatch将等于0。)这主要是因为我很懒惰;还因为代码已经变得有点长,这会损害可读性。

    -- to and from have to be in a canonical absolute form at 
    -- this point
    to = "/a/b/c/d.txt"
    from = "/a/b/e/f.txt"
    
    min_len = math.min(to:len(), from:len())
    mismatch = 0
    print(min_len)
    
    for i = 1, min_len do
        if to:sub(i, i) ~= from:sub(i, i) then
            mismatch = i
            break
        end
    end
    
    -- handle edge cases here
    
    -- the parts of `a` and `b` that differ
    to_diff = to:sub(mismatch)
    from_diff = from:sub(mismatch)
    
    from_file = io.open(from)
    from_is_dir = false
    if (from_file) then
        -- check if `from` is a directory
        result, err_msg, err_no = from_file:read(0)
        if (err_no == 21) then -- EISDIR - `from` is a directory
    
    end
    
    result = ""
    for slash in from_diff:gmatch("/") do
        result = result .. "../"
    end
    if from_is_dir then
        result = result .. "../"
    end
    result = result .. to_diff
    
    print(result) --> ../c/d.txt
    

答案 1 :(得分:2)

使用Penlight库中的pl.path.relpathdoc / source)。

相关问题