|
| 1 | +from typing import Any, List |
| 2 | +import pynvim |
| 3 | +import subprocess |
| 4 | +import os |
| 5 | +from pynvim.api.nvim import Nvim |
| 6 | + |
| 7 | + |
| 8 | +def plug_can_proceed(): |
| 9 | + # plug.vim has these two guards in place. occassionally, if trigger mode is |
| 10 | + # enabled, we can get in a situation where we're calling PlugUpdate when it |
| 11 | + # will throw, causing a nasty error message. instead, we can just duplicate |
| 12 | + # the guards here |
| 13 | + if not os.getcwd(): |
| 14 | + return False |
| 15 | + |
| 16 | + for evar in ["GIT_DIR", "GIT_WORK_TREE"]: |
| 17 | + if os.environ.get(evar) != None: |
| 18 | + return False |
| 19 | + |
| 20 | + return True |
| 21 | + |
| 22 | + |
| 23 | +@pynvim.plugin |
| 24 | +class OutdatedPlugins: |
| 25 | + def __init__(self, vim: Nvim) -> None: |
| 26 | + self.vim = vim |
| 27 | + |
| 28 | + @pynvim.function("CheckOutdatedPlugins") |
| 29 | + def check_for_updates(self, args: List): |
| 30 | + if not plug_can_proceed(): |
| 31 | + return |
| 32 | + |
| 33 | + g_plugs = self.vim.eval("g:plugs") |
| 34 | + |
| 35 | + update_commands = [] |
| 36 | + calculate_updates_commands = [] |
| 37 | + |
| 38 | + for plug in g_plugs.values(): |
| 39 | + update_commands.append("git -C %s remote update > /dev/null" % plug["dir"]) |
| 40 | + calculate_updates_commands.append( |
| 41 | + "git -C %s rev-list HEAD..origin/%s --count" |
| 42 | + % (plug["dir"], plug["branch"] if plug["branch"] else "master") |
| 43 | + ) |
| 44 | + |
| 45 | + update_commands.append("wait") |
| 46 | + update_command = " & ".join(update_commands) |
| 47 | + calculate_updates_command = " && ".join(calculate_updates_commands) |
| 48 | + |
| 49 | + subprocess.run(["bash", "-c", update_command]) |
| 50 | + |
| 51 | + out = subprocess.run( |
| 52 | + ["bash", "-c", calculate_updates_command], stdout=subprocess.PIPE |
| 53 | + ) |
| 54 | + |
| 55 | + plugs_to_update = sum(1 for i in out.stdout.decode().split() if int(i) > 0) |
| 56 | + g_outdated_plugins_silent_mode = self.get_default( |
| 57 | + "g:outdated_plugins_silent_mode", 0 |
| 58 | + ) |
| 59 | + g_outdated_plugins_trigger_mode = self.get_default( |
| 60 | + "g:outdated_plugins_trigger_mode", 0 |
| 61 | + ) |
| 62 | + |
| 63 | + if plugs_to_update > 0: |
| 64 | + self.vim.command(f"echo 'Plugins to update: {plugs_to_update}'") |
| 65 | + if g_outdated_plugins_trigger_mode: |
| 66 | + self.vim.command("PlugUpdate") |
| 67 | + elif not g_outdated_plugins_silent_mode: |
| 68 | + self.vim.command("echo 'All plugins up-to-date'") |
| 69 | + |
| 70 | + def get_default(self, var: str, default: Any) -> Any: |
| 71 | + """ |
| 72 | + Return the value of the vim variable `var` or `default` if it doesn't exist |
| 73 | + """ |
| 74 | + |
| 75 | + try: |
| 76 | + return self.vim.eval(var) |
| 77 | + except: |
| 78 | + return default |
0 commit comments