bumblebee-status/modules/core/git.py

73 lines
2.2 KiB
Python
Raw Normal View History

2020-04-24 16:28:01 +02:00
# pylint: disable=C0111,R0903
"""Print the branch and git status for the
currently focused window.
Requires:
* xcwd
* Python module 'pygit2'
"""
import os
2020-04-24 16:31:37 +02:00
import pygit2
2020-04-24 16:28:01 +02:00
2020-04-24 16:31:37 +02:00
import core.module
import core.widget
2020-04-24 16:28:01 +02:00
2020-04-24 16:31:37 +02:00
import util.cli
class Module(core.module.Module):
def __init__(self, config, theme):
super().__init__(config, theme, [])
2020-04-24 16:31:37 +02:00
self.__error = False
2020-04-24 16:28:01 +02:00
def hidden(self):
2020-04-24 16:31:37 +02:00
return self.__error
2020-04-24 16:28:01 +02:00
2020-04-24 16:31:37 +02:00
def update(self):
2020-04-24 16:28:01 +02:00
state = {}
new_widgets = []
try:
2020-04-24 16:31:37 +02:00
directory = util.cli.execute("xcwd").strip()
directory = self.__get_git_root(directory)
2020-04-24 16:28:01 +02:00
repo = pygit2.Repository(directory)
2020-04-24 16:31:37 +02:00
new_widgets.append(core.widget.Widget(name='git.main', full_text=repo.head.shorthand))
2020-04-24 16:28:01 +02:00
for filepath, flags in repo.status().items():
if flags == pygit2.GIT_STATUS_WT_NEW or \
flags == pygit2.GIT_STATUS_INDEX_NEW:
state['new'] = True
if flags == pygit2.GIT_STATUS_WT_DELETED or \
flags == pygit2.GIT_STATUS_INDEX_DELETED:
state['deleted'] = True
if flags == pygit2.GIT_STATUS_WT_MODIFIED or \
flags == pygit2.GIT_STATUS_INDEX_MODIFIED:
state['modified'] = True
2020-04-24 16:31:37 +02:00
self.__error = False
2020-04-24 16:28:01 +02:00
if 'new' in state:
2020-04-24 16:31:37 +02:00
new_widgets.append(core.widget.Widget(name='git.new'))
2020-04-24 16:28:01 +02:00
if 'modified' in state:
2020-04-24 16:31:37 +02:00
new_widgets.append(core.widget.Widget(name='git.modified'))
2020-04-24 16:28:01 +02:00
if 'deleted' in state:
2020-04-24 16:31:37 +02:00
new_widgets.append(core.widget.Widget(name='git.deleted'))
2020-04-24 16:28:01 +02:00
2020-04-24 16:31:37 +02:00
self.widgets().clear()
self.widget(new_widgets)
2020-04-24 16:28:01 +02:00
except Exception as e:
2020-04-24 16:31:37 +02:00
self.__error = True
2020-04-24 16:28:01 +02:00
def state(self, widget):
return widget.name.split('.')[1]
2020-04-24 16:31:37 +02:00
def __get_git_root(self, directory):
2020-04-24 16:28:01 +02:00
while len(directory) > 1:
if os.path.exists(os.path.join(directory, ".git")):
return directory
directory = "/".join(directory.split("/")[0:-1])
return "/"
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4