possession.nvim icon indicating copy to clipboard operation
possession.nvim copied to clipboard

[Enhancement] add git branches support

Open mac-hel opened this issue 3 years ago • 1 comments

This is best sessions plugin I have found (better then Persistence/Persisted or auto-session) Cleanest and best configuration, custom session names (all other plugins just save session per working dir, no multiple sessions for single dir allowed)

One thing that may be lacking is command to auto name session after current git branch. Of course I can name session manually, but it would be nice to have this automated - maybe some option added to PossessionSave command It could be even better if configuration option exist to auto load session on branch change

This is just idea, thanks for great plugin

mac-hel avatar Oct 15 '22 20:10 mac-hel

Thanks!

Naming session after current git branch may a nice option, but it probably shouldn't be the default for PossessionSave, maybe we could add a separate PossessionSaveGit command. There is an issue with name duplication as most often the branch is master or main.

You can try the following (uses dir+branch as name):

local function current_git_branch()
    local output = vim.fn.system('git rev-parse --abbrev-ref HEAD ')
    local status = vim.api.nvim_get_vvar('shell_error')
    if status ~= 0 then
        vim.notify('Cannot get current git branch: ' .. output, vim.log.levels.ERROR)
        return
    end

    local lines = vim.split(output, '\n', { plain = true, trimempty = true })
    local words = #lines > 0 and vim.split(vim.trim(lines[1]), '%s+')
    local branch = words and words[1]

    if #lines > 1 or not words or #words > 1 or branch == 'HEAD' then
        vim.notify('Incorrect git branch: ' .. output, vim.log.levels.ERROR)
        return
    end
    return words[1]
end

local function current_dir_name()
    local cwd = vim.fn.getcwd()
    return vim.fn.fnamemodify(cwd, ':t')
end

vim.api.nvim_create_user_command('PossessionSaveGit', function()
    local branch = current_git_branch()
    local repo = current_dir_name()
    if branch then
        branch = branch:gsub('/', '_')
        local session_name = repo .. '-' .. branch
        require('possession.commands').save(session_name)
    end
end, { nargs = 0 })

and if it works well I can add it as separate command.

Regarding auto-changing session on branch change - this seems a bit complicated, it would require setting up some libuv file-watches on .git/ or something like this, and it might be out of scope of this plugin. Maybe some other plugin like fugitive/gitsigns/etc. exposes some autocommand/callback on branch change - then you could try loading the correct session in this callback.

jedrzejboczar avatar Oct 17 '22 11:10 jedrzejboczar