From c597d1d6220502cd9ace76207424f2c9ee59bb8c Mon Sep 17 00:00:00 2001 From: skywind3000 Date: Mon, 4 Feb 2019 00:07:38 +0800 Subject: [PATCH] new option: '-b' to jump backwards --- z.lua | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 3 deletions(-) diff --git a/z.lua b/z.lua index 560a7db..ee8ce78 100755 --- a/z.lua +++ b/z.lua @@ -4,7 +4,7 @@ -- z.lua - z.sh implementation in lua, by skywind 2018, 2019 -- Licensed under MIT license. -- --- Version 1.2.1, Last Modified: 2019/02/03 21:15 +-- Version 1.3.0, Last Modified: 2019/02/04 00:06 -- -- * 10x times faster than fasd and autojump -- * 3x times faster than rupa/z @@ -1405,9 +1405,70 @@ end ----------------------------------------------------------------------- --- cd to parent directories which contains keyword +-- find_vcs_root ----------------------------------------------------------------------- -function cd_backward(args, options) +function find_vcs_root(path) + local markers = os.getenv('_ZL_ROOT_MARKERS') + local markers = markers and markers or '.git,.svn,.hg,.root' + local markers = string.split(markers, ',') + path = os.path.absolute(path) + while true do + for _, marker in ipairs(markers) do + local test = os.path.join(path, marker) + if os.path.exists(test) then + return path + end + end + local parent, _ = os.path.split(path) + if path == parent then break end + path = parent + end + return nil +end + + +----------------------------------------------------------------------- +-- cd to parent directories which contains keyword +-- #args == 0 -> returns to vcs root +-- #args == 1 -> returns to parent dir starts with args[1] +-- #args == 2 -> returns string.replace($PWD, args[1], args[2]) +----------------------------------------------------------------------- +function cd_backward(args, options, pwd) + local nargs = #args + local pwd = (pwd ~= nil) and pwd or os.pwd() + if nargs == 0 then + return find_vcs_root(pwd) + elseif nargs == 1 then + local test = windows and pwd:gsub('\\', '/') or pwd + local key = '/' .. args[1] + if not key:match('%u') then + test = test:lower() + end + local pos, _ = test:rfind(key) + if not pos then + return nil + end + local ends = test:find('/', pos + key:len()) + if not ends then + ends = test:len() + end + local path = pwd:sub(1, (not ends) and test:len() or ends) + return os.path.normpath(path) + else + local test = windows and pwd:gsub('\\', '/') or pwd + local src = args[1] + local dst = args[2] + if not src:match('%u') then + test = test:lower() + end + local start, ends = test:rfind(src) + if not start then + return pwd + end + local lhs = pwd:sub(1, start - 1) + local rhs = pwd:sub(ends + 1) + return lhs .. dst .. rhs + end end