sublime-wakatime/packages/wakatime/projects/git.py

72 lines
2.1 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
"""
wakatime.projects.git
~~~~~~~~~~~~~~~~~~~~~
Information about the git project for a given file.
:copyright: (c) 2013 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
2015-08-25 10:42:37 +03:00
import sys
from .base import BaseProject
2014-09-30 20:27:35 +04:00
from ..compat import u, open
log = logging.getLogger('WakaTime')
class Git(BaseProject):
def process(self):
self.configFile = self._find_git_config_file(self.path)
return self.configFile is not None
def name(self):
base = self._project_base()
if base:
2014-09-30 20:27:35 +04:00
return u(os.path.basename(base))
2015-09-29 13:11:25 +03:00
return None # pragma: nocover
def branch(self):
2013-10-14 03:33:53 +04:00
base = self._project_base()
if base:
head = os.path.join(self._project_base(), '.git', 'HEAD')
try:
2014-09-30 20:27:35 +04:00
with open(head, 'r', encoding='utf-8') as fh:
return self._get_branch_from_head_file(fh.readline())
2015-09-29 13:11:25 +03:00
except UnicodeDecodeError: # pragma: nocover
2015-08-25 10:42:37 +03:00
try:
with open(head, 'r', encoding=sys.getfilesystemencoding()) as fh:
return self._get_branch_from_head_file(fh.readline())
2015-08-25 10:42:37 +03:00
except:
2016-09-02 11:50:54 +03:00
log.traceback(logging.WARNING)
2015-09-29 13:11:25 +03:00
except IOError: # pragma: nocover
2016-09-02 11:50:54 +03:00
log.traceback(logging.WARNING)
2016-05-21 15:28:50 +03:00
return u('master')
def _project_base(self):
if self.configFile:
return os.path.dirname(os.path.dirname(self.configFile))
2016-05-21 15:28:50 +03:00
return None # pragma: nocover
def _find_git_config_file(self, path):
path = os.path.realpath(path)
if os.path.isfile(path):
path = os.path.split(path)[0]
if os.path.isfile(os.path.join(path, '.git', 'config')):
return os.path.join(path, '.git', 'config')
split_path = os.path.split(path)
if split_path[1] == '':
return None
return self._find_git_config_file(split_path[0])
def _get_branch_from_head_file(self, line):
if u(line.strip()).startswith('ref: '):
return u(line.strip().rsplit('/', 1)[-1])
return None