1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
|
from __future__ import annotations
import time
from qtpy import QtGui
from qtpy.QtCore import QMimeData, QModelIndex, Qt
from qtpy.QtCore import Signal
from .. import gitcmds
from .. import core
from .. import icons
from .. import utils
from .. import qtutils
from ..git import STDOUT
from ..i18n import N_
class Columns:
"""Defines columns in the worktree browser"""
NAME = 0
STATUS = 1
MESSAGE = 2
AUTHOR = 3
AGE = 4
ALL = (NAME, STATUS, MESSAGE, AUTHOR, AGE)
ATTRS = ('name', 'status', 'message', 'author', 'age')
TEXT: list[str] = []
@classmethod
def init(cls) -> None:
cls.TEXT.extend(
[N_('Name'), N_('Status'), N_('Message'), N_('Author'), N_('Age')]
)
@classmethod
def text_values(cls) -> list[str]:
if not cls.TEXT:
cls.init()
return cls.TEXT
@classmethod
def text(cls, column: int) -> str:
try:
value = cls.TEXT[column]
except IndexError:
# Defer translation until runtime
cls.init()
value = cls.TEXT[column]
return value
@classmethod
def attr(cls, column: int) -> str:
"""Return the attribute for the column"""
return cls.ATTRS[column]
class GitRepoModel(QtGui.QStandardItemModel):
"""Provides an interface into a git repository for browsing purposes."""
restore = Signal()
def __init__(self, context, parent) -> None:
QtGui.QStandardItemModel.__init__(self, parent)
self.setColumnCount(len(Columns.ALL))
self.context = context
self.model = context.model
self.entries = {}
cfg = context.cfg
self.turbo = cfg.get('cola.turbo', False)
self.default_author = cfg.get('user.name', N_('Author'))
self._interesting_paths = set()
self._interesting_files = set()
self._runtask = qtutils.RunTask(parent=parent)
self.model.updated.connect(self.refresh, type=Qt.QueuedConnection)
self.file_icon = icons.file_text()
self.dir_icon = icons.directory()
def mimeData(self, indexes: list[QModelIndex]) -> QMimeData:
paths = qtutils.paths_from_indexes(
self, indexes, item_type=GitRepoNameItem.TYPE
)
return qtutils.mimedata_from_paths(self.context, paths)
def mimeTypes(self) -> list[str]:
return qtutils.path_mimetypes()
def clear(self) -> None:
self.entries.clear()
super().clear()
def hasChildren(self, index: QModelIndex) -> bool:
if index.isValid():
item = self.itemFromIndex(index)
result = item.hasChildren()
else:
result = True
return result
def get(self, path: str, default=None):
if not path:
item = self.invisibleRootItem()
else:
item = self.entries.get(path, default)
return item
def create_row(
self, path: str, create: bool = True, is_dir: bool = False
) -> list[GitRepoNameItem | GitRepoItem]:
try:
row = self.entries[path]
except KeyError:
if create:
column = create_column
row = self.entries[path] = [
column(c, path, is_dir) for c in Columns.ALL
]
else:
row = None
return row
def populate(self, item: GitRepoItem) -> None:
self.populate_dir(item, item.path + '/')
def add_directory(self, parent: GitRepoItem, path: str) -> GitRepoItem:
"""Add a directory entry to the model."""
# First, try returning an existing item
current_item = self.get(path)
if current_item is not None:
return current_item[0]
# Create model items
row_items = self.create_row(path, is_dir=True)
# Use a standard directory icon
name_item = row_items[0]
name_item.setIcon(self.dir_icon)
parent.appendRow(row_items)
return name_item
def add_file(self, parent: GitRepoItem, path: str) -> GitRepoItem:
"""Add a file entry to the model."""
file_entry = self.get(path)
if file_entry is not None:
return file_entry
# Create model items
row_items = self.create_row(path)
name_item = row_items[0]
# Use a standard file icon for the name field
name_item.setIcon(self.file_icon)
# Add file paths at the end of the list
parent.appendRow(row_items)
return name_item
def populate_dir(self, parent: GitRepoItem, path: str) -> None:
"""Populate a subtree"""
context = self.context
dirs, paths = gitcmds.listdir(context, path)
# Insert directories before file paths
for dirname in dirs:
dir_parent = parent
if '/' in dirname:
dir_parent = self.add_parent_directories(parent, dirname)
self.add_directory(dir_parent, dirname)
self.update_entry(dirname)
for filename in paths:
file_parent = parent
if '/' in filename:
file_parent = self.add_parent_directories(parent, filename)
self.add_file(file_parent, filename)
self.update_entry(filename)
def add_parent_directories(self, parent: GitRepoItem, dirname: str) -> GitRepoItem:
"""Ensure that all parent directory entries exist"""
sub_parent = parent
parent_dir = utils.dirname(dirname)
for path in utils.pathset(parent_dir):
sub_parent = self.add_directory(sub_parent, path)
return sub_parent
def path_is_interesting(self, path: str) -> bool:
"""Return True if path has a status."""
return path in self._interesting_paths
def get_paths(self, files=None) -> set[str]:
"""Return paths of interest; e.g. paths with a status."""
if files is None:
files = self.get_files()
return utils.add_parents(files)
def get_files(self):
model = self.model
return set(model.staged + model.unstaged)
def refresh(self) -> None:
old_files = self._interesting_files
old_paths = self._interesting_paths
new_files = self.get_files()
new_paths = self.get_paths(files=new_files)
if new_files != old_files or not old_paths:
self.clear()
self._initialize()
self.restore.emit()
# Existing items
for path in sorted(new_paths.union(old_paths)):
self.update_entry(path)
self._interesting_files = new_files
self._interesting_paths = new_paths
def _initialize(self) -> None:
self.setHorizontalHeaderLabels(Columns.text_values())
self.entries = {}
self._interesting_files = files = self.get_files()
self._interesting_paths = self.get_paths(files=files)
root = self.invisibleRootItem()
self.populate_dir(root, './')
def update_entry(self, path: str) -> None:
if self.turbo or path not in self.entries:
return # entry doesn't currently exist
context = self.context
task = GitRepoInfoTask(context, path, self.default_author)
task.connect(self.apply_data)
self._runtask.start(task)
def apply_data(self, data: list[str]) -> None:
entry = self.get(data[0])
if entry:
entry[1].set_status(data[1])
entry[2].setText(data[2])
entry[3].setText(data[3])
entry[4].setText(data[4])
def create_column(col, path: str, is_dir: bool) -> GitRepoNameItem | GitRepoItem:
"""Creates a StandardItem for use in a treeview cell."""
# GitRepoNameItem is the only one that returns a custom type()
# and is used to infer selections.
if col == Columns.NAME:
item = GitRepoNameItem(path, is_dir)
else:
item = GitRepoItem(path)
return item
class GitRepoInfoTask(qtutils.Task):
"""Handles expensive git lookups for a path."""
def __init__(self, context, path: str, default_author: str) -> None:
qtutils.Task.__init__(self)
self.context = context
self.path = path
self._default_author = default_author
self._data = {}
def data(self, key: str) -> str:
"""Return git data for a path
Supported keys are 'date', 'message', and 'author'
"""
git = self.context.git
if not self._data:
log_line = git.log(
'-1',
'--',
self.path,
no_color=True,
pretty=r'format:%ar%x01%s%x01%an',
_readonly=True,
)[STDOUT]
if log_line:
date, message, author = log_line.split(chr(0x01), 2)
self._data['date'] = date
self._data['message'] = message
self._data['author'] = author
else:
self._data['date'] = self.date()
self._data['message'] = '-'
self._data['author'] = self._default_author
return self._data[key]
def date(self) -> str:
"""Returns a relative date for a file path
This is typically used for new entries that do not have
'git log' information.
"""
try:
st = core.stat(self.path)
except OSError:
return N_('%d minutes ago') % 0
elapsed = time.time() - st.st_mtime
minutes = int(elapsed / 60)
if minutes < 60:
return N_('%d minutes ago') % minutes
hours = int(elapsed / 60 / 60)
if hours < 24:
return N_('%d hours ago') % hours
return N_('%d days ago') % int(elapsed / 60 / 60 / 24)
def status(self) -> tuple[str | None, str]:
"""Return the status for the entry's path."""
model = self.context.model
unmerged = utils.add_parents(model.unmerged)
modified = utils.add_parents(model.modified)
staged = utils.add_parents(model.staged)
untracked = utils.add_parents(model.untracked)
upstream_changed = utils.add_parents(model.upstream_changed)
path = self.path
if path in unmerged:
status = (icons.modified_name(), N_('Unmerged'))
elif path in modified and self.path in staged:
status = (icons.partial_name(), N_('Partially Staged'))
elif path in modified:
status = (icons.modified_name(), N_('Modified'))
elif path in staged:
status = (icons.staged_name(), N_('Staged'))
elif path in upstream_changed:
status = (icons.upstream_name(), N_('Changed Upstream'))
elif path in untracked:
status = (None, '?')
else:
status = (None, '')
return status
def task(self) -> tuple[str, tuple[str | None, str], str, str, str]:
"""Perform expensive lookups and post corresponding events."""
data = (
self.path,
self.status(),
self.data('message'),
self.data('author'),
self.data('date'),
)
return data
class GitRepoItem(QtGui.QStandardItem):
"""Represents a cell in a treeview.
Many GitRepoItems map to a single repository path.
Each GitRepoItem manages a different cell in the tree view.
One is created for each column -- Name, Status, Age, etc.
"""
def __init__(self, path: str) -> None:
QtGui.QStandardItem.__init__(self)
self.path = path
self.cached = False
self.setDragEnabled(False)
self.setEditable(False)
def set_status(self, data: tuple[str | None, str]) -> None:
icon, txt = data
if icon:
self.setIcon(QtGui.QIcon(icon))
else:
self.setIcon(QtGui.QIcon())
self.setText(txt)
class GitRepoNameItem(GitRepoItem):
"""Subclass GitRepoItem to provide a custom type()."""
TYPE = qtutils.standard_item_type_value(1)
def __init__(self, path: str, is_dir: bool) -> None:
GitRepoItem.__init__(self, path)
self.is_dir: bool = is_dir
self.setDragEnabled(True)
self.setText(utils.basename(path))
def type(self):
"""
Indicate that this item is of a special user-defined type.
'name' is the only column that registers a user-defined type.
This is done to allow filtering out other columns when determining
which paths are selected.
"""
return self.TYPE
def hasChildren(self) -> bool:
return self.is_dir
|