id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
100 | filelist.py | git-cola_git-cola/cola/widgets/filelist.py | from qtpy import QtWidgets
from qtpy.QtCore import Signal
from qtpy.QtCore import QSize
from qtpy.QtCore import Qt
from .. import cmds
from .. import hotkeys
from .. import qtutils
from ..i18n import N_
from .standard import TreeWidget
class FileWidget(TreeWidget):
files_selected = Signal(object)
difftool_selected = Signal(object)
histories_selected = Signal(object)
grab_file = Signal(object)
grab_file_from_parent = Signal(object)
remark_toggled = Signal(object, object)
def __init__(self, context, parent, remarks=False):
TreeWidget.__init__(self, parent)
self.context = context
labels = [N_('Filename'), N_('Additions'), N_('Deletions')]
self.setHeaderLabels(labels)
self.show_history_action = qtutils.add_action(
self, N_('Show History'), self.show_history, hotkeys.HISTORY
)
self.launch_difftool_action = qtutils.add_action(
self, N_('Launch Diff Tool'), self.show_diff
)
self.launch_editor_action = qtutils.add_action(
self, N_('Launch Editor'), self.edit_paths, hotkeys.EDIT
)
self.grab_file_action = qtutils.add_action(
self, N_('Grab File...'), self._grab_file
)
self.grab_file_from_parent_action = qtutils.add_action(
self, N_('Grab File from Parent Commit...'), self._grab_file_from_parent
)
if remarks:
self.toggle_remark_actions = tuple(
qtutils.add_action(
self,
r,
lambda remark=r: self.toggle_remark(remark),
hotkeys.hotkey(Qt.CTRL | getattr(Qt, 'Key_' + r)),
)
for r in map(str, range(10))
)
else:
self.toggle_remark_actions = tuple()
self.itemSelectionChanged.connect(self.selection_changed)
def selection_changed(self):
items = self.selected_items()
self.files_selected.emit([i.path for i in items])
def commits_selected(self, commits):
if not commits:
self.clear()
return
git = self.context.git
paths = []
if len(commits) > 1:
# Get a list of changed files for a commit range.
start = commits[0].oid + '~'
end = commits[-1].oid
status, out, _ = git.diff(start, end, z=True, numstat=True, no_renames=True)
if status == 0:
paths = [f for f in out.rstrip('\0').split('\0') if f]
else:
# Get the list of changed files in a single commit.
commit = commits[0]
oid = commit.oid
status, out, _ = git.show(
oid, z=True, numstat=True, oneline=True, no_renames=True
)
if status == 0:
paths = [f for f in out.rstrip('\0').split('\0') if f]
if paths:
paths = paths[1:] # Skip over the summary on the first line.
self.list_files(paths)
def list_files(self, files_log):
self.clear()
if not files_log:
return
files = []
for filename in files_log:
item = FileTreeWidgetItem(filename)
files.append(item)
self.insertTopLevelItems(0, files)
def adjust_columns(self, size, old_size):
if size.isValid() and old_size.isValid():
width = self.columnWidth(0) + size.width() - old_size.width()
self.setColumnWidth(0, width)
else:
width = self.width()
two_thirds = (width * 2) // 3
one_sixth = width // 6
self.setColumnWidth(0, two_thirds)
self.setColumnWidth(1, one_sixth)
self.setColumnWidth(2, one_sixth)
def show(self):
self.adjust_columns(QSize(), QSize())
def resizeEvent(self, event):
self.adjust_columns(event.size(), event.oldSize())
def contextMenuEvent(self, event):
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.grab_file_action)
menu.addAction(self.grab_file_from_parent_action)
menu.addAction(self.show_history_action)
menu.addAction(self.launch_difftool_action)
menu.addAction(self.launch_editor_action)
if self.toggle_remark_actions:
menu_toggle_remark = menu.addMenu(N_('Toggle remark of touching commits'))
tuple(map(menu_toggle_remark.addAction, self.toggle_remark_actions))
menu.exec_(self.mapToGlobal(event.pos()))
def show_diff(self):
self.difftool_selected.emit(self.selected_paths())
def _grab_file(self):
for path in self.selected_paths():
self.grab_file.emit(path)
def _grab_file_from_parent(self):
for path in self.selected_paths():
self.grab_file_from_parent.emit(path)
def selected_paths(self):
return [i.path for i in self.selected_items()]
def edit_paths(self):
cmds.do(cmds.Edit, self.context, self.selected_paths())
def show_history(self):
items = self.selected_items()
paths = [i.path for i in items]
self.histories_selected.emit(paths)
def toggle_remark(self, remark):
items = self.selected_items()
paths = tuple(i.path for i in items)
self.remark_toggled.emit(remark, paths)
class FileTreeWidgetItem(QtWidgets.QTreeWidgetItem):
def __init__(self, file_log, parent=None):
QtWidgets.QTreeWidgetItem.__init__(self, parent)
texts = file_log.split('\t')
self.path = path = texts[2]
self.setText(0, path)
self.setText(1, texts[0])
self.setText(2, texts[1])
| 5,736 | Python | .py | 140 | 31.178571 | 88 | 0.595798 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
101 | compare.py | git-cola_git-cola/cola/widgets/compare.py | """Provides dialogs for comparing branches and commits."""
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from .. import difftool
from .. import gitcmds
from .. import icons
from .. import qtutils
from ..i18n import N_
from ..qtutils import connect_button
from . import defs
from . import standard
class FileItem(QtWidgets.QTreeWidgetItem):
def __init__(self, path, icon):
QtWidgets.QTreeWidgetItem.__init__(self, [path])
self.path = path
self.setIcon(0, icon)
def compare_branches(context):
"""Launches a dialog for comparing a pair of branches"""
view = CompareBranchesDialog(context, qtutils.active_window())
view.show()
return view
class CompareBranchesDialog(standard.Dialog):
def __init__(self, context, parent):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.BRANCH_POINT = N_('*** Branch Point ***')
self.SANDBOX = N_('*** Sandbox ***')
self.LOCAL = N_('Local')
self.diff_arg = ()
self.use_sandbox = False
self.start = None
self.end = None
self.setWindowTitle(N_('Branch Diff Viewer'))
self.remote_branches = gitcmds.branch_list(context, remote=True)
self.local_branches = gitcmds.branch_list(context, remote=False)
self.top_widget = QtWidgets.QWidget()
self.bottom_widget = QtWidgets.QWidget()
self.left_combo = QtWidgets.QComboBox()
self.left_combo.addItem(N_('Local'))
self.left_combo.addItem(N_('Remote'))
self.left_combo.setCurrentIndex(0)
self.right_combo = QtWidgets.QComboBox()
self.right_combo.addItem(N_('Local'))
self.right_combo.addItem(N_('Remote'))
self.right_combo.setCurrentIndex(1)
self.left_list = QtWidgets.QListWidget()
self.right_list = QtWidgets.QListWidget()
Expanding = QtWidgets.QSizePolicy.Expanding
Minimum = QtWidgets.QSizePolicy.Minimum
self.button_spacer = QtWidgets.QSpacerItem(1, 1, Expanding, Minimum)
self.button_compare = qtutils.create_button(
text=N_('Compare'), icon=icons.diff()
)
self.button_close = qtutils.close_button()
self.diff_files = standard.TreeWidget()
self.diff_files.headerItem().setText(0, N_('File Differences'))
self.top_grid_layout = qtutils.grid(
defs.no_margin,
defs.spacing,
(self.left_combo, 0, 0, 1, 1),
(self.left_list, 1, 0, 1, 1),
(self.right_combo, 0, 1, 1, 1),
(self.right_list, 1, 1, 1, 1),
)
self.top_widget.setLayout(self.top_grid_layout)
self.bottom_grid_layout = qtutils.grid(
defs.no_margin,
defs.button_spacing,
(self.diff_files, 0, 0, 1, 4),
(self.button_spacer, 1, 0, 1, 1),
(self.button_close, 1, 2, 1, 1),
(self.button_compare, 1, 3, 1, 1),
)
self.bottom_widget.setLayout(self.bottom_grid_layout)
self.splitter = qtutils.splitter(
Qt.Vertical, self.top_widget, self.bottom_widget
)
self.main_layout = qtutils.vbox(defs.margin, defs.spacing, self.splitter)
self.setLayout(self.main_layout)
connect_button(self.button_close, self.accept)
connect_button(self.button_compare, self.compare)
self.diff_files.itemDoubleClicked.connect(lambda _: self.compare())
self.left_combo.currentIndexChanged.connect(
lambda x: self.update_combo_boxes(left=True)
)
self.right_combo.currentIndexChanged.connect(
lambda x: self.update_combo_boxes(left=False)
)
self.left_list.itemSelectionChanged.connect(self.update_diff_files)
self.right_list.itemSelectionChanged.connect(self.update_diff_files)
self.update_combo_boxes(left=True)
self.update_combo_boxes(left=False)
# Pre-select the 0th elements
item = self.left_list.item(0)
if item:
self.left_list.setCurrentItem(item)
item.setSelected(True)
item = self.right_list.item(0)
if item:
self.right_list.setCurrentItem(item)
item.setSelected(True)
self.init_size(parent=parent)
def selection(self):
left_item = self.left_list.currentItem()
if left_item and left_item.isSelected():
left_item = left_item.text()
else:
left_item = None
right_item = self.right_list.currentItem()
if right_item and right_item.isSelected():
right_item = right_item.text()
else:
right_item = None
return (left_item, right_item)
def update_diff_files(self):
"""Updates the list of files whenever the selection changes"""
# Left and Right refer to the comparison pair (l,r)
left_item, right_item = self.selection()
if not left_item or not right_item or left_item == right_item:
self.set_diff_files([])
return
left_item = self.remote_ref(left_item)
right_item = self.remote_ref(right_item)
# If any of the selection includes sandbox then we
# generate the same diff, regardless. This means we don't
# support reverse diffs against sandbox aka worktree.
if self.SANDBOX in (left_item, right_item):
self.use_sandbox = True
if left_item == self.SANDBOX:
self.diff_arg = (right_item,)
else:
self.diff_arg = (left_item,)
else:
self.diff_arg = (left_item, right_item)
self.use_sandbox = False
# start and end as in 'git diff start end'
self.start = left_item
self.end = right_item
context = self.context
if len(self.diff_arg) == 1:
files = gitcmds.diff_index_filenames(context, self.diff_arg[0])
else:
files = gitcmds.diff_filenames(context, *self.diff_arg)
self.set_diff_files(files)
def set_diff_files(self, files):
mk = FileItem
icon = icons.file_code()
self.diff_files.clear()
self.diff_files.addTopLevelItems([mk(f, icon) for f in files])
def remote_ref(self, branch):
"""Returns the remote ref for 'git diff [local] [remote]'"""
context = self.context
if branch == self.BRANCH_POINT:
# Compare against the branch point so find the merge-base
branch = gitcmds.current_branch(context)
tracked_branch = gitcmds.tracked_branch(context)
if tracked_branch:
return gitcmds.merge_base(context, branch, tracked_branch)
remote_branches = gitcmds.branch_list(context, remote=True)
remote_branch = 'origin/%s' % branch
if remote_branch in remote_branches:
return gitcmds.merge_base(context, branch, remote_branch)
if 'origin/main' in remote_branches:
return gitcmds.merge_base(context, branch, 'origin/main')
if 'origin/master' in remote_branches:
return gitcmds.merge_base(context, branch, 'origin/master')
return 'HEAD'
# Compare against the remote branch
return branch
def update_combo_boxes(self, left=False):
"""Update listwidgets from the combobox selection
Update either the left or right listwidgets
to reflect the available items.
"""
if left:
which = self.left_combo.currentText()
widget = self.left_list
else:
which = self.right_combo.currentText()
widget = self.right_list
if not which:
return
# If we're looking at "local" stuff then provide the
# sandbox as a valid choice. If we're looking at
# "remote" stuff then also include the branch point.
if which == self.LOCAL:
new_list = [self.SANDBOX] + self.local_branches
else:
new_list = [self.BRANCH_POINT] + self.remote_branches
widget.clear()
widget.addItems(new_list)
if new_list:
item = widget.item(0)
widget.setCurrentItem(item)
item.setSelected(True)
def compare(self):
"""Shows the diff for a specific file"""
tree_widget = self.diff_files
item = tree_widget.currentItem()
if item and item.isSelected():
self.compare_file(item.path)
def compare_file(self, filename):
"""Initiates the difftool session"""
if self.use_sandbox:
left = self.diff_arg[0]
if len(self.diff_arg) > 1:
right = self.diff_arg[1]
else:
right = None
else:
left, right = self.start, self.end
context = self.context
difftool.difftool_launch(context, left=left, right=right, paths=[filename])
| 9,020 | Python | .py | 213 | 32.525822 | 83 | 0.613076 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
102 | action.py | git-cola_git-cola/cola/widgets/action.py | """Actions widget"""
from functools import partial
from qtpy import QtCore
from qtpy import QtWidgets
from .. import cmds
from .. import qtutils
from ..i18n import N_
from ..widgets import defs
from ..widgets import remote
from ..widgets import stash
from ..qtutils import create_button
from ..qtutils import connect_button
class QFlowLayoutWidget(QtWidgets.QFrame):
_horizontal = QtWidgets.QBoxLayout.LeftToRight
_vertical = QtWidgets.QBoxLayout.TopToBottom
def __init__(self, parent):
QtWidgets.QFrame.__init__(self, parent)
self._direction = self._vertical
self._layout = layout = QtWidgets.QBoxLayout(self._direction)
layout.setSpacing(defs.spacing)
qtutils.set_margin(layout, defs.margin)
self.setLayout(layout)
policy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum
)
self.setSizePolicy(policy)
self.setMinimumSize(QtCore.QSize(10, 10))
self.aspect_ratio = 0.8
def resizeEvent(self, event):
size = event.size()
if size.width() * self.aspect_ratio < size.height():
dxn = self._vertical
else:
dxn = self._horizontal
if dxn != self._direction:
self._direction = dxn
self.layout().setDirection(dxn)
def tooltip_button(text, layout, tooltip=''):
"""Convenience wrapper around qtutils.create_button()"""
return create_button(text, layout=layout, tooltip=tooltip)
class ActionButtons(QFlowLayoutWidget):
def __init__(self, context, parent=None):
QFlowLayoutWidget.__init__(self, parent)
layout = self.layout()
self.context = context
self.stage_button = tooltip_button(
N_('Stage'), layout, tooltip=N_('Stage changes using "git add"')
)
self.unstage_button = tooltip_button(
N_('Unstage'), layout, tooltip=N_('Unstage changes using "git reset"')
)
self.refresh_button = tooltip_button(N_('Refresh'), layout)
self.fetch_button = tooltip_button(
N_('Fetch...'),
layout,
tooltip=N_('Fetch from one or more remotes using "git fetch"'),
)
self.push_button = tooltip_button(
N_('Push...'), layout, N_('Push to one or more remotes using "git push"')
)
self.pull_button = tooltip_button(
N_('Pull...'), layout, tooltip=N_('Integrate changes using "git pull"')
)
self.stash_button = tooltip_button(
N_('Stash...'),
layout,
tooltip=N_('Temporarily stash away uncommitted changes using "git stash"'),
)
self.exit_diff_mode_button = tooltip_button(
N_('Exit Diff'), layout, tooltip=N_('Exit Diff mode')
)
self.exit_diff_mode_button.setVisible(False)
self.aspect_ratio = 0.4
layout.addStretch()
self.setMinimumHeight(30)
# Add callbacks
connect_button(self.refresh_button, cmds.run(cmds.Refresh, context))
connect_button(self.fetch_button, partial(remote.fetch, context))
connect_button(self.push_button, partial(remote.push, context))
connect_button(self.pull_button, partial(remote.pull, context))
connect_button(self.stash_button, partial(stash.view, context))
connect_button(self.stage_button, cmds.run(cmds.StageSelected, context))
connect_button(self.exit_diff_mode_button, cmds.run(cmds.ResetMode, context))
connect_button(self.unstage_button, self.unstage)
def unstage(self):
"""Unstage selected files, or all files if no selection exists."""
context = self.context
paths = context.selection.staged
if not paths:
cmds.do(cmds.UnstageAll, context)
else:
cmds.do(cmds.Unstage, context, paths)
def set_mode(self, mode):
"""Respond to changes to the diff mode"""
diff_mode = mode == self.context.model.mode_diff
self.exit_diff_mode_button.setVisible(diff_mode)
| 4,086 | Python | .py | 96 | 34.291667 | 87 | 0.644115 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
103 | toolbarcmds.py | git-cola_git-cola/cola/widgets/toolbarcmds.py | from .. import cmds
from .. import difftool
from .. import guicmds
from ..widgets import archive
from ..widgets import browse
from ..widgets import compare
from ..widgets import createbranch
from ..widgets import createtag
from ..widgets import dag
from ..widgets import diff
from ..widgets import editremotes
from ..widgets import finder
from ..widgets import grep
from ..widgets import merge
from ..widgets import recent
from ..widgets import remote
from ..widgets import search
from ..widgets import stash
COMMANDS = {
'Others::LaunchEditor': {
'title': 'Launch Editor',
'action': cmds.run(cmds.LaunchEditor),
'icon': 'edit',
},
'Others::RevertUnstagedEdits': {
'title': 'Revert Unstaged Edits...',
'action': cmds.run(cmds.RevertUnstagedEdits),
'icon': 'undo',
},
'File::QuickOpen': {
'title': 'Quick Open...',
'action': guicmds.open_quick_repo_search,
'icon': 'search',
},
'File::NewRepo': {
'title': 'New Repository...',
'action': guicmds.open_new_repo,
'icon': 'new',
},
'File::OpenRepo': {
'title': 'Open...',
'action': guicmds.open_repo,
'icon': 'folder',
},
'File::OpenRepoNewWindow': {
'title': 'Open in New Window...',
'action': guicmds.open_repo_in_new_window,
'icon': 'folder',
},
# 'File::CloneRepo': {
# 'title': 'Clone...',
# 'action': guicmds.spawn_clone,
# 'icon': 'repo'
# },
'File::Refresh': {
'title': 'Refresh...',
'action': cmds.run(cmds.Refresh),
'icon': 'sync',
},
'File::FindFiles': {
'title': 'Find Files',
'action': finder.finder,
'icon': 'zoom_in',
},
'File::EditRemotes': {
'title': 'Edit Remotes...',
'action': editremotes.editor,
'icon': 'edit',
},
'File::RecentModified': {
'title': 'Recently Modified Files...',
'action': recent.browse_recent_files,
'icon': 'edit',
},
'File::ApplyPatches': {
'title': 'Apply Patches...',
'action': diff.apply_patches,
'icon': 'diff',
},
'File::ExportPatches': {
'title': 'Export Patches...',
'action': guicmds.export_patches,
'icon': 'save',
},
'File::SaveAsTarZip': {
'title': 'Save As Tarball/Zip...',
'action': archive.save_archive,
'icon': 'file_zip',
},
# 'File::Preferences': {
# 'title': 'Preferences',
# 'action': prefs.preferences,
# 'icon': 'configure'
# },
'Actions::Fetch': {'title': 'Fetch...', 'action': remote.fetch, 'icon': 'download'},
'Actions::Pull': {'title': 'Pull...', 'action': remote.pull, 'icon': 'pull'},
'Actions::Push': {'title': 'Push...', 'action': remote.push, 'icon': 'push'},
'Actions::Stash': {'title': 'Stash...', 'action': stash.view, 'icon': 'commit'},
'Actions::CreateTag': {
'title': 'Create Tag...',
'action': createtag.create_tag,
'icon': 'tag',
},
'Actions::CherryPick': {
'title': 'Cherry-Pick...',
'action': guicmds.cherry_pick,
'icon': 'cherry_pick',
},
'Actions::Merge': {
'title': 'Merge...',
'action': merge.local_merge,
'icon': 'merge',
},
'Actions::AbortMerge': {
'title': 'Abort Merge...',
'action': cmds.run(cmds.AbortMerge),
'icon': 'undo',
},
'Actions::UpdateSubmodules': {
'title': 'Update All Submodules...',
'action': cmds.run(cmds.SubmodulesUpdate),
'icon': 'sync',
},
'Actions::ResetSoft': {
'title': 'Reset Branch (Soft)',
'action': guicmds.reset_soft,
'icon': 'style_dialog_reset',
'tooltip': cmds.ResetSoft.tooltip('<commit>'),
},
'Actions::ResetMixed': {
'title': 'Reset Branch and Stage (Mixed)',
'action': guicmds.reset_mixed,
'icon': 'style_dialog_reset',
'tooltip': cmds.ResetMixed.tooltip('<commit>'),
},
'Actions::RestoreWorktree': {
'title': 'Restore Worktree',
'action': guicmds.restore_worktree,
'icon': 'edit',
'tooltip': cmds.RestoreWorktree.tooltip('<commit>'),
},
'Actions::ResetKeep': {
'title': 'Restore Worktree and Reset All (Keep Unstaged Changes)',
'action': guicmds.reset_keep,
'icon': 'style_dialog_reset',
'tooltip': cmds.ResetKeep.tooltip('<commit>'),
},
'Actions::ResetHard': {
'title': 'Restore Worktre and Reset All (Hard)',
'action': guicmds.reset_hard,
'icon': 'style_dialog_reset',
'tooltip': cmds.ResetHard.tooltip('<commit>'),
},
'Actions::Grep': {
'title': 'Grep',
'action': grep.grep,
'icon': 'search',
},
'Actions::Search': {
'title': 'Search...',
'action': search.search,
'icon': 'search',
},
'Commit::Stage': {
'title': 'Stage',
'action': cmds.run(cmds.StageOrUnstage),
'icon': 'add',
},
'Commit::AmendLast': {
'title': 'Amend Last Commit',
'action': cmds.run(cmds.AmendMode),
'icon': 'edit',
},
'Commit::UndoLastCommit': {
'title': 'Undo Last Commit',
'action': cmds.run(cmds.UndoLastCommit),
'icon': 'style_dialog_discard',
},
'Commit::StageModified': {
'title': 'Stage Modified',
'action': cmds.run(cmds.StageModified),
'icon': 'add',
},
'Commit::StageUntracked': {
'title': 'Stage Untracked',
'action': cmds.run(cmds.StageUntracked),
'icon': 'add',
},
'Commit::UnstageAll': {
'title': 'Unstage All',
'action': cmds.run(cmds.UnstageAll),
'icon': 'remove',
},
'Commit::Unstage': {
'title': 'Unstage',
'action': cmds.run(cmds.UnstageSelected),
'icon': 'remove',
},
'Commit::LoadCommitMessage': {
'title': 'Load Commit Message...',
'action': guicmds.load_commitmsg,
'icon': 'file_text',
},
'Commit::GetCommitMessageTemplate': {
'title': 'Get Commit Message Template',
'action': cmds.run(cmds.LoadCommitMessageFromTemplate),
'icon': 'style_dialog_apply',
},
'Diff::Difftool': {
'title': 'Launch Diff tool',
'action': cmds.run(difftool.LaunchDifftool),
'icon': 'diff',
},
'Diff::Expression': {
'title': 'Expression...',
'action': guicmds.diff_expression,
'icon': 'compare',
},
'Diff::Branches': {
'title': 'Branches...',
'action': compare.compare_branches,
'icon': 'compare',
},
'Diff::Diffstat': {
'title': 'Diffstat',
'action': cmds.run(cmds.Diffstat),
'icon': 'diff',
},
'Branch::Review': {
'title': 'Review...',
'action': guicmds.review_branch,
'icon': 'compare',
},
'Branch::Create': {
'title': 'Create...',
'action': createbranch.create_new_branch,
'icon': 'branch',
},
'Branch::Checkout': {
'title': 'Checkout...',
'action': guicmds.checkout_branch,
'icon': 'branch',
},
'Branch::Delete': {
'title': 'Delete...',
'action': guicmds.delete_branch,
'icon': 'discard',
},
'Branch::DeleteRemote': {
'title': 'Delete Remote Branch...',
'action': guicmds.delete_remote_branch,
'icon': 'discard',
},
'Branch::Rename': {
'title': 'Rename Branch...',
'action': guicmds.rename_branch,
'icon': 'edit',
},
'Branch::BrowseCurrent': {
'title': 'Browse Current Branch...',
'action': guicmds.browse_current,
'icon': 'directory',
},
'Branch::BrowseOther': {
'title': 'Browse Other Branch...',
'action': guicmds.browse_other,
'icon': 'directory',
},
'Branch::VisualizeCurrent': {
'title': 'Visualize Current Branch...',
'action': cmds.run(cmds.VisualizeCurrent),
'icon': 'visualize',
},
'Branch::VisualizeAll': {
'title': 'Visualize All Branches...',
'action': cmds.run(cmds.VisualizeAll),
'icon': 'visualize',
},
'View::FileBrowser': {
'title': 'File Browser...',
'action': browse.worktree_browser,
'icon': 'cola',
},
'View::DAG': {'title': 'DAG...', 'action': dag.git_dag, 'icon': 'cola'},
}
# 'Rebase::StartInteractive': {
# 'title': 'Start Interactive Rebase...',
# 'action': lambda: app().activeWindow().rebase_start(),
# 'icon': None
# },
# 'Rebase::Edit': {
# 'title': 'Edit...',
# 'action': lambda: cmds.rebase_edit_todo(),
# 'icon': None
# },
# 'Rebase::Continue': {
# 'title': 'Continue',
# 'action': lambda: cmds.rebase_continue(),
# 'icon': None
# },
# 'Rebase::SkipCurrentPatch': {
# 'title': 'Skip Current Patch',
# 'action': lambda: cmds.rebase_skip(),
# 'icon': None
# },
# 'Rebase::Abort': {
# 'title': 'Abort',
# 'action': lambda: cmds.rebase_abort(),
# 'icon': None
# }
| 9,295 | Python | .py | 310 | 23.6 | 88 | 0.53573 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
104 | createbranch.py | git-cola_git-cola/cola/widgets/createbranch.py | from qtpy import QtWidgets
from qtpy import QtCore
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..i18n import N_
from ..interaction import Interaction
from ..qtutils import get
from .. import gitcmds
from .. import icons
from .. import qtutils
from . import defs
from . import completion
from . import standard
def create_new_branch(context, revision=''):
"""Launches a dialog for creating a new branch"""
view = CreateBranchDialog(context, parent=qtutils.active_window())
if revision:
view.set_revision(revision)
view.show()
return view
class CreateOpts:
def __init__(self, context):
self.context = context
self.reset = False
self.track = False
self.fetch = True
self.checkout = True
self.revision = 'HEAD'
self.branch = ''
class CreateThread(QtCore.QThread):
command = Signal(object, object, object)
result = Signal(object)
def __init__(self, opts, parent):
QtCore.QThread.__init__(self, parent)
self.opts = opts
def run(self):
branch = self.opts.branch
revision = self.opts.revision
reset = self.opts.reset
checkout = self.opts.checkout
track = self.opts.track
context = self.opts.context
git = context.git
model = context.model
results = []
status = 0
if track and '/' in revision:
remote = revision.split('/', 1)[0]
status, out, err = git.fetch(remote)
self.command.emit(status, out, err)
results.append(('fetch', status, out, err))
if status == 0:
status, out, err = model.create_branch(
branch, revision, force=reset, track=track
)
self.command.emit(status, out, err)
results.append(('branch', status, out, err))
if status == 0 and checkout:
status, out, err = git.checkout(branch)
self.command.emit(status, out, err)
results.append(('checkout', status, out, err))
model.update_status()
self.result.emit(results)
class CreateBranchDialog(standard.Dialog):
"""A dialog for creating branches."""
def __init__(self, context, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.setWindowTitle(N_('Create Branch'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.context = context
self.model = context.model
self.opts = CreateOpts(context)
self.thread = CreateThread(self.opts, self)
self.progress = None
self.branch_name_label = QtWidgets.QLabel()
self.branch_name_label.setText(N_('Branch Name'))
self.branch_name = completion.GitCreateBranchLineEdit(context)
self.branch_validator = completion.BranchValidator(
context.git, parent=self.branch_name
)
self.branch_name.setValidator(self.branch_validator)
self.rev_label = QtWidgets.QLabel()
self.rev_label.setText(N_('Starting Revision'))
self.revision = completion.GitRefLineEdit(context)
current = gitcmds.current_branch(context)
if current:
self.revision.setText(current)
self.local_radio = qtutils.radio(text=N_('Local branch'), checked=True)
self.remote_radio = qtutils.radio(text=N_('Tracking branch'))
self.tag_radio = qtutils.radio(text=N_('Tag'))
self.branch_list = QtWidgets.QListWidget()
self.update_existing_label = QtWidgets.QLabel()
self.update_existing_label.setText(N_('Update Existing Branch:'))
self.no_update_radio = qtutils.radio(text=N_('No'))
self.ffwd_only_radio = qtutils.radio(text=N_('Fast Forward Only'), checked=True)
self.reset_radio = qtutils.radio(text=N_('Reset'))
text = N_('Fetch Tracking Branch')
self.fetch_checkbox = qtutils.checkbox(text=text, checked=True)
text = N_('Checkout After Creation')
self.checkout_checkbox = qtutils.checkbox(text=text, checked=True)
icon = icons.branch()
self.create_button = qtutils.create_button(
text=N_('Create Branch'), icon=icon, default=True
)
self.close_button = qtutils.close_button()
self.options_checkbox_layout = qtutils.hbox(
defs.margin,
defs.spacing,
self.fetch_checkbox,
self.checkout_checkbox,
qtutils.STRETCH,
)
self.branch_name_layout = qtutils.hbox(
defs.margin, defs.spacing, self.branch_name_label, self.branch_name
)
self.rev_radio_group = qtutils.buttongroup(
self.local_radio, self.remote_radio, self.tag_radio
)
self.rev_radio_layout = qtutils.hbox(
defs.margin,
defs.spacing,
self.local_radio,
self.remote_radio,
self.tag_radio,
qtutils.STRETCH,
)
self.rev_start_textinput_layout = qtutils.hbox(
defs.no_margin, defs.spacing, self.rev_label, defs.spacing, self.revision
)
self.rev_start_layout = qtutils.vbox(
defs.no_margin,
defs.spacing,
self.rev_radio_layout,
self.branch_list,
self.rev_start_textinput_layout,
)
self.options_radio_group = qtutils.buttongroup(
self.no_update_radio, self.ffwd_only_radio, self.reset_radio
)
self.options_radio_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.update_existing_label,
self.no_update_radio,
self.ffwd_only_radio,
self.reset_radio,
qtutils.STRETCH,
)
self.buttons_layout = qtutils.hbox(
defs.margin,
defs.spacing,
qtutils.STRETCH,
self.close_button,
self.create_button,
)
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.branch_name_layout,
self.rev_start_layout,
defs.button_spacing,
self.options_radio_layout,
self.options_checkbox_layout,
self.buttons_layout,
)
self.setLayout(self.main_layout)
qtutils.add_close_action(self)
qtutils.connect_button(self.close_button, self.close)
qtutils.connect_button(self.create_button, self.create_branch)
qtutils.connect_toggle(self.local_radio, self.display_model)
qtutils.connect_toggle(self.remote_radio, self.display_model)
qtutils.connect_toggle(self.tag_radio, self.display_model)
branches = self.branch_list
branches.itemSelectionChanged.connect(self.branch_item_changed)
thread = self.thread
thread.command.connect(Interaction.log_status, type=Qt.QueuedConnection)
thread.result.connect(self.thread_result, type=Qt.QueuedConnection)
self.init_size(settings=context.settings, parent=parent)
self.display_model()
def set_revision(self, revision):
self.revision.setText(revision)
def getopts(self):
self.opts.revision = get(self.revision)
self.opts.branch = get(self.branch_name)
self.opts.checkout = get(self.checkout_checkbox)
self.opts.reset = get(self.reset_radio)
self.opts.fetch = get(self.fetch_checkbox)
self.opts.track = get(self.remote_radio)
def create_branch(self):
"""Creates a branch; called by the "Create Branch" button"""
context = self.context
self.getopts()
revision = self.opts.revision
branch = self.opts.branch
no_update = get(self.no_update_radio)
ffwd_only = get(self.ffwd_only_radio)
existing_branches = gitcmds.branch_list(context)
check_branch = False
if not branch or not revision:
Interaction.critical(
N_('Missing Data'),
N_('Please provide both a branch name and revision expression.'),
)
return
if branch in existing_branches:
if no_update:
msg = N_('Branch "%s" already exists.') % branch
Interaction.critical(N_('Branch Exists'), msg)
return
# Whether we should prompt the user for lost commits
commits = gitcmds.rev_list_range(context, revision, branch)
check_branch = bool(commits)
if check_branch:
msg = N_('Resetting "%(branch)s" to "%(revision)s" will lose commits.') % {
'branch': branch,
'revision': revision,
}
if ffwd_only:
Interaction.critical(N_('Branch Exists'), msg)
return
lines = [msg]
for idx, commit in enumerate(commits):
subject = commit[1][0 : min(len(commit[1]), 16)]
if len(subject) < len(commit[1]):
subject += '...'
lines.append('\t' + commit[0][:8] + '\t' + subject)
if idx >= 5:
skip = len(commits) - 5
lines.append('\t(%s)' % (N_('%d skipped') % skip))
break
line = N_('Recovering lost commits may not be easy.')
lines.append(line)
info_text = N_('Reset "%(branch)s" to "%(revision)s"?') % {
'branch': branch,
'revision': revision,
}
if not Interaction.confirm(
N_('Reset Branch?'),
'\n'.join(lines),
info_text,
N_('Reset Branch'),
default=False,
icon=icons.undo(),
):
return
title = N_('Create Branch')
label = N_('Updating')
self.progress = standard.progress(title, label, self)
self.progress.show()
self.thread.start()
def thread_result(self, results):
self.progress.hide()
del self.progress
for cmd, status, _, _ in results:
if status != 0:
Interaction.critical(
N_('Error Creating Branch'),
(
N_('"%(command)s" returned exit status "%(status)d"')
% {
'command': 'git ' + cmd,
'status': status,
}
),
)
return
self.accept()
def branch_item_changed(self, *rest):
"""This callback is called when the branch selection changes"""
# When the branch selection changes then we should update
# the "Revision Expression" accordingly.
qlist = self.branch_list
remote_branch = qtutils.selected_item(qlist, self.branch_sources())
if not remote_branch:
return
# Update the model with the selection
self.revision.setText(remote_branch)
# Set the branch field if we're branching from a remote branch.
if not get(self.remote_radio):
return
branch = gitcmds.strip_remote(self.model.remotes, remote_branch)
if branch == 'HEAD':
return
# Signal that we've clicked on a remote branch
self.branch_name.set_value(branch)
def display_model(self):
"""Sets the branch list to the available branches"""
branches = self.branch_sources()
qtutils.set_items(self.branch_list, branches)
def branch_sources(self):
"""Get the list of items for populating the branch root list."""
if get(self.local_radio):
value = self.model.local_branches
elif get(self.remote_radio):
value = self.model.remote_branches
elif get(self.tag_radio):
value = self.model.tags
else:
value = []
return value
def dispose(self):
self.branch_name.dispose()
self.revision.dispose()
| 12,176 | Python | .py | 304 | 29.266447 | 88 | 0.585287 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
105 | grep.py | git-cola_git-cola/cola/widgets/grep.py | from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..i18n import N_
from ..utils import Group
from .. import cmds
from .. import core
from .. import hotkeys
from .. import utils
from .. import qtutils
from ..qtutils import get
from .standard import Dialog
from .text import HintedLineEdit
from .text import VimHintedPlainTextEdit
from .text import VimTextBrowser
from . import defs
def grep(context):
"""Prompt and use 'git grep' to find the content."""
widget = new_grep(context, parent=qtutils.active_window())
widget.show()
return widget
def new_grep(context, text=None, parent=None):
"""Construct a new Grep dialog"""
widget = Grep(context, parent=parent)
if text:
widget.search_for(text)
return widget
def parse_grep_line(line):
"""Parse a grep result line into (filename, line_number, content)"""
try:
filename, line_number, contents = line.split(':', 2)
result = (filename, line_number, contents)
except ValueError:
result = None
return result
def goto_grep(context, line):
"""Called when Search -> Grep's right-click 'goto' action."""
parsed_line = parse_grep_line(line)
if parsed_line:
filename, line_number, _ = parsed_line
cmds.do(
cmds.Edit,
context,
[filename],
line_number=line_number,
background_editor=True,
)
class GrepThread(QtCore.QThread):
"""Gather `git grep` results in a background thread"""
result = Signal(object, object, object)
def __init__(self, context, parent):
QtCore.QThread.__init__(self, parent)
self.context = context
self.query = None
self.shell = False
self.regexp_mode = '--basic-regexp'
def run(self):
if self.query is None:
return
git = self.context.git
query = self.query
if self.shell:
args = utils.shell_split(query)
else:
args = [query]
status, out, err = git.grep(self.regexp_mode, n=True, _readonly=True, *args)
if query == self.query:
self.result.emit(status, out, err)
else:
self.run()
class Grep(Dialog):
"""A dialog for searching content using `git grep`"""
def __init__(self, context, parent=None):
Dialog.__init__(self, parent)
self.context = context
self.grep_result = ''
self.setWindowTitle(N_('Search'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.edit_action = qtutils.add_action(self, N_('Edit'), self.edit, hotkeys.EDIT)
self.refresh_action = qtutils.add_action(
self, N_('Refresh'), self.search, *hotkeys.REFRESH_HOTKEYS
)
self.input_label = QtWidgets.QLabel('git grep')
self.input_label.setFont(qtutils.diff_font(context))
self.input_txt = HintedLineEdit(
context, N_('command-line arguments'), parent=self
)
self.regexp_combo = combo = QtWidgets.QComboBox()
combo.setToolTip(N_('Choose the "git grep" regular expression mode'))
items = [N_('Basic Regexp'), N_('Extended Regexp'), N_('Fixed String')]
combo.addItems(items)
combo.setCurrentIndex(0)
combo.setEditable(False)
tooltip0 = N_('Search using a POSIX basic regular expression')
tooltip1 = N_('Search using a POSIX extended regular expression')
tooltip2 = N_('Search for a fixed string')
combo.setItemData(0, tooltip0, Qt.ToolTipRole)
combo.setItemData(1, tooltip1, Qt.ToolTipRole)
combo.setItemData(2, tooltip2, Qt.ToolTipRole)
combo.setItemData(0, '--basic-regexp', Qt.UserRole)
combo.setItemData(1, '--extended-regexp', Qt.UserRole)
combo.setItemData(2, '--fixed-strings', Qt.UserRole)
self.result_txt = GrepTextView(context, N_('grep result...'), self)
self.preview_txt = PreviewTextView(context, self)
self.preview_txt.setFocusProxy(self.result_txt)
self.edit_button = qtutils.edit_button(default=True)
qtutils.button_action(self.edit_button, self.edit_action)
self.refresh_button = qtutils.refresh_button()
qtutils.button_action(self.refresh_button, self.refresh_action)
text = N_('Shell arguments')
tooltip = N_(
'Parse arguments using a shell.\n'
'Queries with spaces will require "double quotes".'
)
self.shell_checkbox = qtutils.checkbox(
text=text, tooltip=tooltip, checked=False
)
self.close_button = qtutils.close_button()
self.refresh_group = Group(self.refresh_action, self.refresh_button)
self.refresh_group.setEnabled(False)
self.edit_group = Group(self.edit_action, self.edit_button)
self.edit_group.setEnabled(False)
self.input_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.input_label,
self.input_txt,
self.regexp_combo,
)
self.bottom_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.refresh_button,
self.shell_checkbox,
qtutils.STRETCH,
self.close_button,
self.edit_button,
)
self.splitter = qtutils.splitter(Qt.Vertical, self.result_txt, self.preview_txt)
self.mainlayout = qtutils.vbox(
defs.margin,
defs.no_spacing,
self.input_layout,
self.splitter,
self.bottom_layout,
)
self.setLayout(self.mainlayout)
thread = self.worker_thread = GrepThread(context, self)
thread.result.connect(self.process_result, type=Qt.QueuedConnection)
self.input_txt.textChanged.connect(lambda s: self.search())
self.regexp_combo.currentIndexChanged.connect(lambda x: self.search())
self.result_txt.leave.connect(self.input_txt.setFocus)
self.result_txt.cursorPositionChanged.connect(self.update_preview)
qtutils.add_action(
self.input_txt,
'Focus Results',
self.focus_results,
hotkeys.DOWN,
*hotkeys.ACCEPT
)
qtutils.add_action(self, 'Focus Input', self.focus_input, hotkeys.FOCUS)
qtutils.connect_toggle(self.shell_checkbox, lambda x: self.search())
qtutils.connect_button(self.close_button, self.close)
qtutils.add_close_action(self)
self.init_size(parent=parent)
def focus_input(self):
"""Focus the grep input field and select the text"""
self.input_txt.setFocus()
self.input_txt.selectAll()
def focus_results(self):
"""Give focus to the results window"""
self.result_txt.setFocus()
def regexp_mode(self):
"""Return the selected grep regex mode"""
idx = self.regexp_combo.currentIndex()
return self.regexp_combo.itemData(idx, Qt.UserRole)
def search(self):
"""Initiate a search by starting the GrepThread"""
self.edit_group.setEnabled(False)
self.refresh_group.setEnabled(False)
query = get(self.input_txt)
if len(query) < 2:
self.result_txt.clear()
self.preview_txt.clear()
return
self.worker_thread.query = query
self.worker_thread.shell = get(self.shell_checkbox)
self.worker_thread.regexp_mode = self.regexp_mode()
self.worker_thread.start()
def search_for(self, txt):
"""Set the initial value of the input text"""
self.input_txt.set_value(txt)
def text_scroll(self):
"""Return the scrollbar value for the results window"""
scrollbar = self.result_txt.verticalScrollBar()
if scrollbar:
return get(scrollbar)
return None
def set_text_scroll(self, scroll):
"""Set the scrollbar value for the results window"""
scrollbar = self.result_txt.verticalScrollBar()
if scrollbar and scroll is not None:
scrollbar.setValue(scroll)
def text_offset(self):
"""Return the cursor's offset within the result text"""
return self.result_txt.textCursor().position()
def set_text_offset(self, offset):
"""Set the text cursor from an offset"""
cursor = self.result_txt.textCursor()
cursor.setPosition(offset)
self.result_txt.setTextCursor(cursor)
def process_result(self, status, out, err):
"""Apply the results from grep to the widgets"""
if status == 0:
value = out + err
elif out + err:
value = 'git grep: ' + out + err
else:
value = ''
# save scrollbar and text cursor
scroll = self.text_scroll()
offset = min(len(value), self.text_offset())
self.grep_result = value
self.result_txt.set_value(value)
# restore
self.set_text_scroll(scroll)
self.set_text_offset(offset)
enabled = status == 0
self.edit_group.setEnabled(enabled)
self.refresh_group.setEnabled(True)
if not value:
self.preview_txt.clear()
def update_preview(self):
"""Update the file preview window"""
parsed_line = parse_grep_line(self.result_txt.selected_line())
if parsed_line:
filename, line_number, _ = parsed_line
self.preview_txt.preview(filename, line_number)
def edit(self):
"""Launch an editor on the currently selected line"""
goto_grep(self.context, self.result_txt.selected_line())
def export_state(self):
"""Export persistent settings"""
state = super().export_state()
state['sizes'] = get(self.splitter)
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = super().apply_state(state)
try:
self.splitter.setSizes(state['sizes'])
except (AttributeError, KeyError, ValueError, TypeError):
result = False
return result
class GrepTextView(VimHintedPlainTextEdit):
"""A text view with hotkeys for launching editors"""
def __init__(self, context, hint, parent):
VimHintedPlainTextEdit.__init__(self, context, hint, parent=parent)
self.context = context
self.goto_action = qtutils.add_action(self, 'Launch Editor', self.edit)
self.goto_action.setShortcut(hotkeys.EDIT)
self.menu_actions.append(self.goto_action)
def edit(self):
goto_grep(self.context, self.selected_line())
class PreviewTask(qtutils.Task):
"""Asynchronous task for loading file content"""
def __init__(self, filename, line_number):
qtutils.Task.__init__(self)
self.content = ''
self.filename = filename
self.line_number = line_number
def task(self):
try:
self.content = core.read(self.filename, errors='ignore')
except OSError:
pass
return (self.filename, self.content, self.line_number)
class PreviewTextView(VimTextBrowser):
"""Preview window for file contents"""
def __init__(self, context, parent):
VimTextBrowser.__init__(self, context, parent)
self.filename = None
self.content = None
self.runtask = qtutils.RunTask(parent=self)
def preview(self, filename, line_number):
"""Preview a file at the specified line number"""
if filename != self.filename:
request = PreviewTask(filename, line_number)
self.runtask.start(request, finish=self.show_preview)
else:
self.scroll_to_line(line_number)
def clear(self):
self.filename = ''
self.content = ''
super().clear()
def show_preview(self, task):
"""Show the results of the asynchronous file read"""
filename = task.filename
content = task.content
line_number = task.line_number
if filename != self.filename:
self.filename = filename
self.content = content
self.set_value(content)
self.scroll_to_line(line_number)
def scroll_to_line(self, line_number):
"""Scroll to the specified line number"""
try:
line_num = int(line_number) - 1
except ValueError:
return
self.numbers.set_highlighted(line_num)
cursor = self.textCursor()
cursor.setPosition(0)
self.setTextCursor(cursor)
self.ensureCursorVisible()
cursor.movePosition(cursor.Down, cursor.MoveAnchor, line_num)
cursor.movePosition(cursor.EndOfLine, cursor.KeepAnchor)
self.setTextCursor(cursor)
self.ensureCursorVisible()
scrollbar = self.verticalScrollBar()
step = scrollbar.pageStep() // 2
position = scrollbar.sliderPosition() + step
scrollbar.setSliderPosition(position)
self.ensureCursorVisible()
| 13,141 | Python | .py | 327 | 31.406728 | 88 | 0.632166 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
106 | commitmsg.py | git-cola_git-cola/cola/widgets/commitmsg.py | import datetime
from functools import partial
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from .. import actions
from .. import cmds
from .. import core
from .. import gitcmds
from .. import hotkeys
from .. import icons
from .. import textwrap
from .. import qtutils
from .. import spellcheck
from ..interaction import Interaction
from ..gitcmds import commit_message_path
from ..i18n import N_
from ..models import dag
from ..models import prefs
from ..qtutils import get
from ..utils import Group
from . import defs
from . import standard
from .selectcommits import select_commits
from .spellcheck import SpellCheckLineEdit, SpellCheckTextEdit
from .text import anchor_mode
class CommitMessageEditor(QtWidgets.QFrame):
commit_finished = Signal(object)
cursor_changed = Signal(int, int)
down = Signal()
up = Signal()
def __init__(self, context, parent):
QtWidgets.QFrame.__init__(self, parent)
cfg = context.cfg
self.context = context
self.model = model = context.model
self.spellcheck_initialized = False
self.spellcheck = spellcheck.NorvigSpellCheck()
self.spellcheck.set_dictionary(cfg.get('cola.dictionary', None))
self._linebreak = None
self._textwidth = None
self._tabwidth = None
self._last_commit_datetime = None # The most recently selected commit date.
self._git_commit_date = None # Overrides the commit date when committing.
# Actions
self.signoff_action = qtutils.add_action(
self, cmds.SignOff.name(), cmds.run(cmds.SignOff, context), hotkeys.SIGNOFF
)
self.signoff_action.setIcon(icons.style_dialog_apply())
self.signoff_action.setToolTip(N_('Sign off on this commit'))
self.commit_action = qtutils.add_action(
self, N_('Commit@@verb'), self.commit, hotkeys.APPLY
)
self.commit_action.setIcon(icons.commit())
self.commit_action.setToolTip(N_('Commit staged changes'))
self.clear_action = qtutils.add_action(self, N_('Clear...'), self.clear)
self.launch_editor = actions.launch_editor_at_line(context, self)
self.launch_difftool = actions.launch_difftool(context, self)
self.move_up = actions.move_up(self)
self.move_down = actions.move_down(self)
# Menu actions
self.menu_actions = menu_actions = [
self.signoff_action,
self.commit_action,
None,
self.launch_editor,
self.launch_difftool,
None,
self.move_up,
self.move_down,
None,
]
# Widgets
self.summary = CommitSummaryLineEdit(context, check=self.spellcheck)
self.summary.setMinimumHeight(defs.tool_button_height)
self.summary.menu_actions.extend(menu_actions)
self.description = CommitMessageTextEdit(
context, check=self.spellcheck, parent=self
)
self.description.menu_actions.extend(menu_actions)
commit_button_tooltip = N_('Commit staged changes\nShortcut: Ctrl+Enter')
self.commit_button = qtutils.create_button(
text=N_('Commit@@verb'), tooltip=commit_button_tooltip, icon=icons.commit()
)
self.commit_group = Group(self.commit_action, self.commit_button)
self.commit_progress_bar = standard.progress_bar(
self,
disable=(self.commit_button, self.summary, self.description),
)
self.commit_progress_bar.setMaximumHeight(defs.small_icon)
self.actions_menu = qtutils.create_menu(N_('Actions'), self)
self.actions_button = qtutils.create_toolbutton(
icon=icons.configure(), tooltip=N_('Actions...')
)
self.actions_button.setMenu(self.actions_menu)
self.actions_menu.addAction(self.signoff_action)
self.actions_menu.addAction(self.commit_action)
self.actions_menu.addSeparator()
# Amend checkbox
self.amend_action = self.actions_menu.addAction(N_('Amend Last Commit'))
self.amend_action.setIcon(icons.edit())
self.amend_action.setCheckable(True)
self.amend_action.setShortcuts(hotkeys.AMEND)
self.amend_action.setShortcutContext(Qt.ApplicationShortcut)
# Commit Date
self.commit_date_action = self.actions_menu.addAction(N_('Set Commit Date'))
self.commit_date_action.setCheckable(True)
self.commit_date_action.setChecked(False)
qtutils.connect_action_bool(self.commit_date_action, self.set_commit_date)
# Bypass hooks
self.bypass_commit_hooks_action = self.actions_menu.addAction(
N_('Bypass Commit Hooks')
)
self.bypass_commit_hooks_action.setCheckable(True)
self.bypass_commit_hooks_action.setChecked(False)
# Sign commits
self.sign_action = self.actions_menu.addAction(N_('Create Signed Commit'))
self.sign_action.setCheckable(True)
signcommits = cfg.get('cola.signcommits', default=False)
self.sign_action.setChecked(signcommits)
# Spell checker
self.check_spelling_action = self.actions_menu.addAction(N_('Check Spelling'))
self.check_spelling_action.setCheckable(True)
spell_check = prefs.spellcheck(context)
self.check_spelling_action.setChecked(spell_check)
self.toggle_check_spelling(spell_check)
# Line wrapping
self.autowrap_action = self.actions_menu.addAction(N_('Auto-Wrap Lines'))
self.autowrap_action.setCheckable(True)
self.autowrap_action.setChecked(prefs.linebreak(context))
# Commit message
self.actions_menu.addSeparator()
self.load_commitmsg_menu = self.actions_menu.addMenu(
N_('Load Previous Commit Message')
)
self.load_commitmsg_menu.aboutToShow.connect(self.build_commitmsg_menu)
self.fixup_commit_menu = self.actions_menu.addMenu(N_('Fixup Previous Commit'))
self.fixup_commit_menu.aboutToShow.connect(self.build_fixup_menu)
self.toplayout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.actions_button,
self.summary,
self.commit_button,
)
self.toplayout.setContentsMargins(
defs.margin, defs.no_margin, defs.no_margin, defs.no_margin
)
self.mainlayout = qtutils.vbox(
defs.no_margin, defs.spacing, self.toplayout, self.description
)
self.setLayout(self.mainlayout)
qtutils.connect_button(self.commit_button, self.commit)
# Broadcast the amend mode
qtutils.connect_action_bool(
self.amend_action, partial(cmds.run(cmds.AmendMode), context)
)
qtutils.connect_action_bool(
self.check_spelling_action, self.toggle_check_spelling
)
# Handle the one-off auto-wrapping
qtutils.connect_action_bool(self.autowrap_action, self.set_linebreak)
self.summary.accepted.connect(self.focus_description)
self.summary.down_pressed.connect(self.summary_cursor_down)
self.model.commit_message_changed.connect(
self.set_commit_message, type=Qt.QueuedConnection
)
self.commit_finished.connect(self._commit_finished, type=Qt.QueuedConnection)
self.summary.cursor_changed.connect(self.cursor_changed.emit)
self.description.cursor_changed.connect(
# description starts at line 2
lambda row, col: self.cursor_changed.emit(row + 2, col)
)
self.summary.textChanged.connect(self.commit_summary_changed)
self.description.textChanged.connect(self._commit_message_changed)
self.description.leave.connect(self.focus_summary)
self.commit_group.setEnabled(False)
self.set_expandtab(prefs.expandtab(context))
self.set_tabwidth(prefs.tabwidth(context))
self.set_textwidth(prefs.textwidth(context))
self.set_linebreak(prefs.linebreak(context))
# Loading message
commit_msg = ''
commit_msg_path = commit_message_path(context)
if commit_msg_path:
commit_msg = core.read(commit_msg_path)
model.set_commitmsg(commit_msg)
# Allow tab to jump from the summary to the description
self.setTabOrder(self.summary, self.description)
self.setFont(qtutils.diff_font(context))
self.setFocusProxy(self.summary)
cfg.user_config_changed.connect(self.config_changed)
def config_changed(self, key, value):
if key != prefs.SPELL_CHECK:
return
if get(self.check_spelling_action) == value:
return
self.check_spelling_action.setChecked(value)
self.toggle_check_spelling(value)
def set_initial_size(self):
self.setMaximumHeight(133)
QtCore.QTimer.singleShot(1, self.restore_size)
def restore_size(self):
self.setMaximumHeight(2**13)
def focus_summary(self):
self.summary.setFocus()
def focus_description(self):
self.description.setFocus()
def summary_cursor_down(self):
"""Handle the down key in the summary field
If the cursor is at the end of the line then focus the description.
Otherwise, move the cursor to the end of the line so that a
subsequence "down" press moves to the end of the line.
"""
self.focus_description()
def commit_message(self, raw=True):
"""Return the commit message as a Unicode string"""
summary = get(self.summary)
if raw:
description = get(self.description)
else:
description = self.formatted_description()
if summary and description:
return summary + '\n\n' + description
if summary:
return summary
if description:
return '\n\n' + description
return ''
def formatted_description(self):
text = get(self.description)
if not self._linebreak:
return text
return textwrap.word_wrap(text, self._tabwidth, self._textwidth)
def commit_summary_changed(self):
"""Respond to changes to the `summary` field
Newlines can enter the `summary` field when pasting, which is
undesirable. Break the pasted value apart into the separate
(summary, description) values and move the description over to the
"extended description" field.
"""
value = self.summary.value()
if '\n' in value:
summary, description = value.split('\n', 1)
description = description.lstrip('\n')
cur_description = get(self.description)
if cur_description:
description = description + '\n' + cur_description
# this callback is triggered by changing `summary`
# so disable signals for `summary` only.
self.summary.set_value(summary, block=True)
self.description.set_value(description)
self._commit_message_changed()
def _commit_message_changed(self, _value=None):
"""Update the model when values change"""
message = self.commit_message()
self.model.set_commitmsg(message, notify=False)
self.refresh_palettes()
self.update_actions()
def clear(self):
if not Interaction.confirm(
N_('Clear commit message?'),
N_('The commit message will be cleared.'),
N_('This cannot be undone. Clear commit message?'),
N_('Clear commit message'),
default=True,
icon=icons.discard(),
):
return
self.model.set_commitmsg('')
def update_actions(self):
commit_enabled = bool(get(self.summary))
self.commit_group.setEnabled(commit_enabled)
def refresh_palettes(self):
"""Update the color palette for the hint text"""
self.summary.hint.refresh()
self.description.hint.refresh()
def set_commit_message(self, message):
"""Set the commit message to match the observed model"""
# Parse the "summary" and "description" fields
lines = message.splitlines()
num_lines = len(lines)
if num_lines == 0:
# Message is empty
summary = ''
description = ''
elif num_lines == 1:
# Message has a summary only
summary = lines[0]
description = ''
elif num_lines == 2:
# Message has two lines; this is not a common case
summary = lines[0]
description = lines[1]
else:
# Summary and several description lines
summary = lines[0]
if lines[1]:
# We usually skip this line but check just in case
description_lines = lines[1:]
else:
description_lines = lines[2:]
description = '\n'.join(description_lines)
focus_summary = not summary
focus_description = not description
# Update summary
self.summary.set_value(summary, block=True)
# Update description
self.description.set_value(description, block=True)
# Update text color
self.refresh_palettes()
# Focus the empty summary or description
if focus_summary:
self.summary.setFocus()
elif focus_description:
self.description.setFocus()
else:
self.summary.cursor_position.emit()
self.update_actions()
def set_expandtab(self, value):
self.description.set_expandtab(value)
def set_tabwidth(self, width):
self._tabwidth = width
self.description.set_tabwidth(width)
def set_textwidth(self, width):
self._textwidth = width
self.description.set_textwidth(width)
def set_linebreak(self, brk):
self._linebreak = brk
self.description.set_linebreak(brk)
with qtutils.BlockSignals(self.autowrap_action):
self.autowrap_action.setChecked(brk)
def setFont(self, font):
"""Pass the setFont() calls down to the text widgets"""
self.summary.setFont(font)
self.description.setFont(font)
def set_mode(self, mode):
can_amend = not self.model.is_merging
checked = mode == self.model.mode_amend
with qtutils.BlockSignals(self.amend_action):
self.amend_action.setEnabled(can_amend)
self.amend_action.setChecked(checked)
def commit(self):
"""Attempt to create a commit from the index and commit message."""
context = self.context
if not bool(get(self.summary)):
# Describe a good commit message
error_msg = N_(
'Please supply a commit message.\n\n'
'A good commit message has the following format:\n\n'
'- First line: Describe in one sentence what you did.\n'
'- Second line: Blank\n'
'- Remaining lines: Describe why this change is good.\n'
)
Interaction.log(error_msg)
Interaction.information(N_('Missing Commit Message'), error_msg)
return
msg = self.commit_message(raw=False)
# We either need to have something staged, or be merging.
# If there was a merge conflict resolved, there may not be anything
# to stage, but we still need to commit to complete the merge.
if not (self.model.staged or self.model.is_merging):
error_msg = N_(
'No changes to commit.\n\n'
'You must stage at least 1 file before you can commit.'
)
if self.model.modified:
informative_text = N_(
'Would you like to stage and commit all modified files?'
)
if not Interaction.confirm(
N_('Stage and commit?'),
error_msg,
informative_text,
N_('Stage and Commit'),
default=True,
icon=icons.save(),
):
return
else:
Interaction.information(N_('Nothing to commit'), error_msg)
return
cmds.do(cmds.StageModified, context)
# Warn that amending published commits is generally bad
amend = get(self.amend_action)
check_published = prefs.check_published_commits(context)
if (
amend
and check_published
and self.model.is_commit_published()
and not Interaction.confirm(
N_('Rewrite Published Commit?'),
N_(
'This commit has already been published.\n'
'This operation will rewrite published history.\n'
"You probably don't want to do this."
),
N_('Amend the published commit?'),
N_('Amend Commit'),
default=False,
icon=icons.save(),
)
):
return
sign = get(self.sign_action)
no_verify = get(self.bypass_commit_hooks_action)
self.bypass_commit_hooks_action.setChecked(False)
if self.commit_date_action.isChecked():
self.commit_date_action.setChecked(False)
date = self._git_commit_date
else:
date = None
task = qtutils.SimpleTask(
cmds.run(
cmds.Commit,
context,
amend,
msg,
sign,
no_verify=no_verify,
date=date,
)
)
self.context.runtask.start(
task,
finish=self.commit_finished.emit,
progress=self.commit_progress_bar,
)
def _commit_finished(self, task):
"""Reset widget state on completion of the commit task"""
title = N_('Commit failed')
status, out, err = task.result
Interaction.command(title, 'git commit', status, out, err)
self.setFocus()
def build_fixup_menu(self):
self.build_commits_menu(
cmds.LoadFixupMessage,
self.fixup_commit_menu,
self.choose_fixup_commit,
prefix='fixup! ',
)
def build_commitmsg_menu(self):
self.build_commits_menu(
cmds.LoadCommitMessageFromOID,
self.load_commitmsg_menu,
self.choose_commit_message,
)
def build_commits_menu(self, cmd, menu, chooser, prefix=''):
context = self.context
params = dag.DAG('HEAD', 6)
commits = dag.RepoReader(context, params)
menu_commits = []
for idx, commit in enumerate(commits.get()):
menu_commits.insert(0, commit)
if idx > 5:
continue
menu.clear()
for commit in menu_commits:
menu.addAction(prefix + commit.summary, cmds.run(cmd, context, commit.oid))
if len(commits) == 6:
menu.addSeparator()
menu.addAction(N_('More...'), chooser)
def choose_commit(self, cmd):
context = self.context
revs, summaries = gitcmds.log_helper(context)
oids = select_commits(
context, N_('Select Commit'), revs, summaries, multiselect=False
)
if not oids:
return
oid = oids[0]
cmds.do(cmd, context, oid)
def choose_commit_message(self):
self.choose_commit(cmds.LoadCommitMessageFromOID)
def choose_fixup_commit(self):
self.choose_commit(cmds.LoadFixupMessage)
def toggle_check_spelling(self, enabled):
spell_check = self.spellcheck
cfg = self.context.cfg
if prefs.spellcheck(self.context) != enabled:
cfg.set_user(prefs.SPELL_CHECK, enabled)
if enabled and not self.spellcheck_initialized:
# Add our name to the dictionary
self.spellcheck_initialized = True
user_name = cfg.get('user.name')
if user_name:
for part in user_name.split():
spell_check.add_word(part)
# Add our email address to the dictionary
user_email = cfg.get('user.email')
if user_email:
for part in user_email.split('@'):
for elt in part.split('.'):
spell_check.add_word(elt)
# git jargon
spell_check.add_word('Acked')
spell_check.add_word('Signed')
spell_check.add_word('Closes')
spell_check.add_word('Fixes')
self.summary.highlighter.enable(enabled)
self.description.highlighter.enable(enabled)
def set_commit_date(self, enabled):
"""Choose the date and time that is used when authoring commits"""
if not enabled:
self._git_commit_date = None
return
widget = CommitDateDialog(self, commit_datetime=self._last_commit_datetime)
if widget.exec_() == QtWidgets.QDialog.Accepted:
commit_date = widget.commit_date()
Interaction.log(N_('Setting commit date to %s') % commit_date)
self._git_commit_date = commit_date
self._last_commit_datetime = CommitDateDialog.tick_time(widget.datetime())
else:
self.commit_date_action.setChecked(False)
class CommitDateDialog(QtWidgets.QDialog):
"""Choose the date and time used when authoring commits"""
slider_range = 500
def __init__(self, parent, commit_datetime=None):
QtWidgets.QDialog.__init__(self, parent)
slider_range = self.slider_range
self._calendar_widget = calendar_widget = QtWidgets.QCalendarWidget()
self._time_widget = time_widget = QtWidgets.QTimeEdit()
time_widget.setDisplayFormat('hh:mm:ss AP')
# Horizontal slider moves the date and time backwards and forwards.
self._slider = slider = QtWidgets.QSlider(Qt.Horizontal)
slider.setRange(0, slider_range) # Mapped from 00:00:00 to 23:59:59
self._tick_backward = tick_backward = qtutils.create_toolbutton_with_callback(
partial(self._adjust_slider, -1), '-', None, N_('Decrement')
)
self._tick_forward = tick_forward = qtutils.create_toolbutton_with_callback(
partial(self._adjust_slider, 1), '+', None, N_('Increment')
)
cancel_button = QtWidgets.QPushButton(N_('Cancel'))
cancel_button.setIcon(icons.close())
set_commit_time_button = QtWidgets.QPushButton(N_('Set Date and Time'))
set_commit_time_button.setDefault(True)
set_commit_time_button.setIcon(icons.ok())
button_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
cancel_button,
qtutils.STRETCH,
set_commit_time_button,
)
slider_layout = qtutils.hbox(
defs.no_margin,
defs.no_spacing,
tick_backward,
tick_forward,
slider,
time_widget,
)
layout = qtutils.vbox(
defs.small_margin,
defs.spacing,
calendar_widget,
slider_layout,
defs.button_spacing,
button_layout,
)
self.setLayout(layout)
self.setWindowTitle(N_('Set Commit Date'))
self.setWindowModality(Qt.ApplicationModal)
if commit_datetime is None:
commit_datetime = datetime.datetime.now()
time_widget.setTime(commit_datetime.time())
calendar_widget.setSelectedDate(commit_datetime.date())
self._update_slider_from_datetime(commit_datetime)
time_widget.timeChanged.connect(self._update_slider_from_time_signal)
slider.valueChanged.connect(self._update_time_from_slider)
calendar_widget.activated.connect(lambda _: self.accept())
cancel_button.clicked.connect(self.reject)
set_commit_time_button.clicked.connect(self.accept)
@classmethod
def tick_time(cls, commit_datetime):
"""Tick time forward"""
seconds_per_day = 86400
one_tick = seconds_per_day // cls.slider_range # 172 seconds (2m52s)
return commit_datetime + datetime.timedelta(seconds=one_tick)
def datetime(self):
"""Return the calculated datetime value"""
# We take the date from the calendar widget and the time from the datetime widget.
time_value = self._time_widget.time().toPyTime()
date_value = self._calendar_widget.selectedDate().toPyDate()
date_time = datetime.datetime(
date_value.year,
date_value.month,
date_value.day,
time_value.hour,
time_value.minute,
time_value.second,
)
return date_time.astimezone()
def commit_date(self):
"""Return the selected datetime as a string for use by Git"""
return self.datetime().strftime('%a %b %d %H:%M:%S %Y %z')
def _update_time_from_slider(self, value):
"""Map the slider value to an offset corresponding to the current time.
The passed-in value will be between 0 and range.
"""
seconds_per_day = 86400
seconds_range = seconds_per_day - 1
ratio = value / self.slider_range
delta = datetime.timedelta(seconds=int(ratio * seconds_range))
now = datetime.datetime.now()
midnight = datetime.datetime(1999, 12, 31)
new_time = (midnight + delta).time()
self._time_widget.setTime(new_time)
def _adjust_slider(self, amount):
"""Adjust the slider forward or backwards"""
new_value = self._slider.value() + amount
self._slider.setValue(new_value)
def _update_slider_from_time_signal(self, new_time):
"""Update the time slider to match the new time"""
self._update_slider_from_time(new_time.toPyTime())
def _update_slider_from_datetime(self, commit_datetime):
"""Update the time slider to match the specified datetime"""
commit_time = commit_datetime.time()
self._update_slider_from_time(commit_time)
def _update_slider_from_time(self, commit_time):
"""Update the slider to match the specified time."""
seconds_since_midnight = (
60 * 60 * commit_time.hour +
60 * commit_time.minute +
commit_time.second
)
seconds_per_day = 86400
seconds_range = seconds_per_day - 1
ratio = seconds_since_midnight / seconds_range
value = int(self.slider_range * ratio)
with qtutils.BlockSignals(self._slider):
self._slider.setValue(value)
class CommitSummaryLineEdit(SpellCheckLineEdit):
"""Text input field for the commit summary"""
down_pressed = Signal()
accepted = Signal()
def __init__(self, context, check=None, parent=None):
hint = N_('Commit summary')
SpellCheckLineEdit.__init__(self, context, hint, check=check, parent=parent)
self._comment_char = None
self._refresh_config()
self.textChanged.connect(self._update_summary_text, Qt.QueuedConnection)
context.cfg.updated.connect(self._refresh_config, type=Qt.QueuedConnection)
def _refresh_config(self):
"""Update comment char in response to config changes"""
self._comment_char = prefs.comment_char(self.context)
def _update_summary_text(self):
"""Prevent commit messages from starting with comment characters"""
value = self.value()
if self._comment_char and value.startswith(self._comment_char):
cursor = self.textCursor()
position = cursor.position()
value = value.lstrip()
if self._comment_char:
value = value.lstrip(self._comment_char).lstrip()
self.set_value(value, block=True)
value = self.value()
if position > 1:
position = max(0, min(position - 1, len(value) - 1))
cursor.setPosition(position)
self.setTextCursor(cursor)
def keyPressEvent(self, event):
"""Allow "Enter" to focus into the extended description field"""
event_key = event.key()
if event_key in (
Qt.Key_Enter,
Qt.Key_Return,
):
self.accepted.emit()
return
SpellCheckLineEdit.keyPressEvent(self, event)
class CommitMessageTextEdit(SpellCheckTextEdit):
leave = Signal()
def __init__(self, context, check=None, parent=None):
hint = N_('Extended description...')
SpellCheckTextEdit.__init__(self, context, hint, check=check, parent=parent)
self.action_emit_leave = qtutils.add_action(
self, 'Shift Tab', self.leave.emit, hotkeys.LEAVE
)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Up:
cursor = self.textCursor()
position = cursor.position()
if position == 0:
# The cursor is at the beginning of the line.
# If we have selection then simply reset the cursor.
# Otherwise, emit a signal so that the parent can
# change focus.
if cursor.hasSelection():
self.set_cursor_position(0)
else:
self.leave.emit()
event.accept()
return
text_before = self.toPlainText()[:position]
lines_before = text_before.count('\n')
if lines_before == 0:
# If we're on the first line, but not at the
# beginning, then move the cursor to the beginning
# of the line.
if event.modifiers() & Qt.ShiftModifier:
mode = QtGui.QTextCursor.KeepAnchor
else:
mode = QtGui.QTextCursor.MoveAnchor
cursor.setPosition(0, mode)
self.setTextCursor(cursor)
event.accept()
return
elif event.key() == Qt.Key_Down:
cursor = self.textCursor()
position = cursor.position()
all_text = self.toPlainText()
text_after = all_text[position:]
lines_after = text_after.count('\n')
if lines_after == 0:
select = event.modifiers() & Qt.ShiftModifier
mode = anchor_mode(select)
cursor.setPosition(len(all_text), mode)
self.setTextCursor(cursor)
event.accept()
return
SpellCheckTextEdit.keyPressEvent(self, event)
def setFont(self, font):
SpellCheckTextEdit.setFont(self, font)
width, height = qtutils.text_size(font, 'MMMM')
self.setMinimumSize(QtCore.QSize(width, height * 2))
| 31,246 | Python | .py | 728 | 32.410714 | 90 | 0.614342 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
107 | completion.py | git-cola_git-cola/cola/widgets/completion.py | import re
import time
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..models import prefs
from .. import core
from .. import gitcmds
from .. import icons
from .. import qtutils
from .. import utils
from . import defs
from .text import HintedLineEdit
class ValidateRegex:
def __init__(self, regex):
self.regex = re.compile(regex) # regex to scrub
def validate(self, string, idx):
"""Scrub and validate the user-supplied input"""
state = QtGui.QValidator.Acceptable
if self.regex.search(string):
string = self.regex.sub('', string) # scrub matching bits
idx = min(idx - 1, len(string))
return (state, string, idx)
class RemoteValidator(QtGui.QValidator):
"""Prevent invalid remote names"""
def __init__(self, parent=None):
super().__init__(parent)
self._validate = ValidateRegex(r'[ \t\\/]')
def validate(self, string, idx):
return self._validate.validate(string, idx)
class BranchValidator(QtGui.QValidator):
"""Prevent invalid branch names"""
def __init__(self, git, parent=None):
super().__init__(parent)
self._git = git
self._validate = ValidateRegex(r'[ \t\\]') # forward-slash is okay
def validate(self, string, idx):
"""Scrub and validate the user-supplied input"""
state, string, idx = self._validate.validate(string, idx)
if string: # Allow empty strings
status, _, _ = self._git.check_ref_format(string, branch=True)
if status != 0:
# The intermediate string, when deleting characters, might
# end in a name that is invalid to Git, but we must allow it
# otherwise we won't be able to delete it using backspace.
if string.endswith('/') or string.endswith('.'):
state = self.Intermediate
else:
state = self.Invalid
return (state, string, idx)
def _is_case_sensitive(text):
return bool([char for char in text if char.isupper()])
class CompletionLineEdit(HintedLineEdit):
"""A lineedit with advanced completion abilities"""
activated = Signal()
changed = Signal()
cleared = Signal()
enter = Signal()
up = Signal()
down = Signal()
# Activation keys will cause a selected completion item to be chosen
ACTIVATION_KEYS = (Qt.Key_Return, Qt.Key_Enter)
# Navigation keys trigger signals that widgets can use for customization
NAVIGATION_KEYS = {
Qt.Key_Return: 'enter',
Qt.Key_Enter: 'enter',
Qt.Key_Up: 'up',
Qt.Key_Down: 'down',
}
def __init__(
self, context, model_factory, hint='', show_all_completions=False, parent=None
):
HintedLineEdit.__init__(self, context, hint, parent=parent)
# Tracks when the completion popup was active during key events
self.context = context
# The most recently selected completion item
self._selection = None
self._show_all_completions = show_all_completions
# Create a completion model
completion_model = model_factory(context, self)
completer = Completer(completion_model, self)
completer.setWidget(self)
self._completer = completer
self._completion_model = completion_model
# The delegate highlights matching completion text in the popup widget
self._delegate = HighlightDelegate(self)
completer.popup().setItemDelegate(self._delegate)
self.textChanged.connect(self._text_changed)
self._completer.activated.connect(self.choose_completion)
self._completion_model.updated.connect(
self._completions_updated, type=Qt.QueuedConnection
)
self.destroyed.connect(self.dispose)
def __del__(self):
self.dispose()
def dispose(self, *args):
self._completer.dispose()
def completion_selection(self):
"""Return the last completion's selection"""
return self._selection
def complete(self):
"""Trigger the completion popup to appear and offer completions"""
self._completer.complete()
def refresh(self):
"""Refresh the completion model"""
return self._completer.model().update()
def popup(self):
"""Return the completer's popup"""
return self._completer.popup()
def _text_changed(self, full_text):
match_text = self._last_word()
self._do_text_changed(full_text, match_text)
self.complete_last_word()
def _do_text_changed(self, full_text, match_text):
case_sensitive = _is_case_sensitive(match_text)
if case_sensitive:
self._completer.setCaseSensitivity(Qt.CaseSensitive)
else:
self._completer.setCaseSensitivity(Qt.CaseInsensitive)
self._delegate.set_highlight_text(match_text, case_sensitive)
self._completer.set_match_text(full_text, match_text, case_sensitive)
def update_matches(self):
text = self._last_word()
case_sensitive = _is_case_sensitive(text)
self._completer.setCompletionPrefix(text)
self._completer.model().update_matches(case_sensitive)
def choose_completion(self, completion):
"""
This is the event handler for the QCompleter.activated(QString) signal,
it is called when the user selects an item in the completer popup.
"""
if not completion:
self._do_text_changed('', '')
return
words = self._words()
if words and not self._ends_with_whitespace():
words.pop()
words.append(completion)
text = core.list2cmdline(words)
self.setText(text)
self.changed.emit()
self._do_text_changed(text, '')
self.popup().hide()
def _words(self):
return utils.shell_split(self.value())
def _ends_with_whitespace(self):
value = self.value()
return value != value.rstrip()
def _last_word(self):
if self._ends_with_whitespace():
return ''
words = self._words()
if not words:
return self.value()
if not words[-1]:
return ''
return words[-1]
def complete_last_word(self):
self.update_matches()
self.complete()
def close_popup(self):
"""Close the completion popup"""
self.popup().close()
def _completions_updated(self):
"""Select the first completion item when completions are updated"""
popup = self.popup()
if self._completion_model.rowCount() == 0:
popup.hide()
return
if not popup.isVisible():
if not self.hasFocus() or not self._show_all_completions:
return
self.select_first_completion()
def select_first_completion(self):
"""Select the first item in the completion model"""
idx = self._completion_model.index(0, 0)
mode = (
QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.SelectCurrent
)
self.popup().selectionModel().setCurrentIndex(idx, mode)
def selected_completion(self):
"""Return the selected completion item"""
popup = self.popup()
if not popup.isVisible():
return None
model = popup.selectionModel()
indexes = model.selectedIndexes()
if not indexes:
return None
idx = indexes[0]
item = self._completion_model.itemFromIndex(idx)
if not item:
return None
return item.text()
def select_completion(self):
"""Choose the selected completion option from the completion popup"""
result = False
visible = self.popup().isVisible()
if visible:
selection = self.selected_completion()
if selection:
self.choose_completion(selection)
result = True
return result
def show_popup(self):
"""Display the completion popup"""
self.refresh()
x_val = self.x()
y_val = self.y() + self.height()
point = QtCore.QPoint(x_val, y_val)
mapped = self.parent().mapToGlobal(point)
popup = self.popup()
popup.move(mapped.x(), mapped.y())
popup.show()
# Qt overrides
def event(self, event):
"""Override QWidget::event() for tab completion"""
event_type = event.type()
if (
event_type == QtCore.QEvent.KeyPress
and event.key() == Qt.Key_Tab
and self.select_completion()
):
return True
# Make sure the popup goes away during teardown
if event_type == QtCore.QEvent.Close:
self.close_popup()
elif event_type == QtCore.QEvent.Hide:
self.popup().hide()
return super().event(event)
def keyPressEvent(self, event):
"""Process completion and navigation events"""
super().keyPressEvent(event)
popup = self.popup()
visible = popup.isVisible()
# Hide the popup when the field becomes empty.
is_empty = not self.value()
if is_empty and event.modifiers() != Qt.ControlModifier:
self.cleared.emit()
if visible:
popup.hide()
# Activation keys select the completion when pressed and emit the
# activated signal. Navigation keys have lower priority, and only
# emit when it wasn't already handled as an activation event.
key = event.key()
if key in self.ACTIVATION_KEYS and visible:
if self.select_completion():
self.activated.emit()
return
navigation = self.NAVIGATION_KEYS.get(key, None)
if navigation:
signal = getattr(self, navigation)
signal.emit()
return
# Show the popup when Ctrl-Space is pressed.
if (
not visible
and key == Qt.Key_Space
and event.modifiers() == Qt.ControlModifier
):
self.show_popup()
class GatherCompletionsThread(QtCore.QThread):
items_gathered = Signal(object)
def __init__(self, model):
QtCore.QThread.__init__(self)
self.model = model
self.case_sensitive = False
self.running = False
def dispose(self):
self.running = False
utils.catch_runtime_error(self.wait)
def run(self):
text = None
items = []
self.running = True
# Loop when the matched text changes between the start and end time.
# This happens when gather_matches() takes too long and the
# model's match_text changes in-between.
while self.running and text != self.model.match_text:
text = self.model.match_text
items = self.model.gather_matches(self.case_sensitive)
if self.running and text is not None:
self.items_gathered.emit(items)
class HighlightDelegate(QtWidgets.QStyledItemDelegate):
"""A delegate used for auto-completion to give formatted completion"""
def __init__(self, parent):
QtWidgets.QStyledItemDelegate.__init__(self, parent)
self.widget = parent
self.highlight_text = ''
self.case_sensitive = False
self.doc = QtGui.QTextDocument()
# older PyQt4 does not have setDocumentMargin
if hasattr(self.doc, 'setDocumentMargin'):
self.doc.setDocumentMargin(0)
def set_highlight_text(self, text, case_sensitive):
"""Sets the text that will be made bold when displayed"""
self.highlight_text = text
self.case_sensitive = case_sensitive
def paint(self, painter, option, index):
"""Overloaded Qt method for custom painting of a model index"""
if not self.highlight_text:
QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
return
text = index.data()
if self.case_sensitive:
html = text.replace(
self.highlight_text, '<strong>%s</strong>' % self.highlight_text
)
else:
match = re.match(
r'(.*)(%s)(.*)' % re.escape(self.highlight_text), text, re.IGNORECASE
)
if match:
start = match.group(1) or ''
middle = match.group(2) or ''
end = match.group(3) or ''
html = start + ('<strong>%s</strong>' % middle) + end
else:
html = text
self.doc.setHtml(html)
# Painting item without text, Text Document will paint the text
params = QtWidgets.QStyleOptionViewItem(option)
self.initStyleOption(params, index)
params.text = ''
style = QtWidgets.QApplication.style()
style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, params, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
# Highlighting text if item is selected
if params.state & QtWidgets.QStyle.State_Selected:
color = params.palette.color(
QtGui.QPalette.Active, QtGui.QPalette.HighlightedText
)
ctx.palette.setColor(QtGui.QPalette.Text, color)
# translate the painter to where the text is drawn
item_text = QtWidgets.QStyle.SE_ItemViewItemText
rect = style.subElementRect(item_text, params, self.widget)
painter.save()
start = rect.topLeft() + QtCore.QPoint(defs.margin, 0)
painter.translate(start)
# tell the text document to draw the html for us
self.doc.documentLayout().draw(painter, ctx)
painter.restore()
def ref_sort_key(ref):
"""Sort key function that causes shorter refs to sort first, but
alphabetizes refs of equal length (in order to make local branches sort
before remote ones)."""
return len(ref), ref
class CompletionModel(QtGui.QStandardItemModel):
updated = Signal()
items_gathered = Signal(object)
model_updated = Signal()
def __init__(self, context, parent):
QtGui.QStandardItemModel.__init__(self, parent)
self.context = context
self.match_text = ''
self.full_text = ''
self.case_sensitive = False
self.update_thread = GatherCompletionsThread(self)
self.update_thread.items_gathered.connect(
self.apply_matches, type=Qt.QueuedConnection
)
def update(self):
case_sensitive = self.update_thread.case_sensitive
self.update_matches(case_sensitive)
def set_match_text(self, full_text, match_text, case_sensitive):
self.full_text = full_text
self.match_text = match_text
self.update_matches(case_sensitive)
def update_matches(self, case_sensitive):
self.case_sensitive = case_sensitive
self.update_thread.case_sensitive = case_sensitive
if not self.update_thread.isRunning():
self.update_thread.start()
def gather_matches(self, case_sensitive):
return ((), (), set())
def apply_matches(self, match_tuple):
"""Build widgets for all of the matching items"""
if not match_tuple:
# Results from background tasks may arrive after the widget
# has been destroyed.
utils.catch_runtime_error(self.set_items, [])
return
matched_refs, matched_paths, dirs = match_tuple
QStandardItem = QtGui.QStandardItem
dir_icon = icons.directory()
git_icon = icons.cola()
items = []
for ref in matched_refs:
item = QStandardItem()
item.setText(ref)
item.setIcon(git_icon)
items.append(item)
from_filename = icons.from_filename
for match in matched_paths:
item = QStandardItem()
item.setText(match)
if match in dirs:
item.setIcon(dir_icon)
else:
item.setIcon(from_filename(match))
items.append(item)
# Results from background tasks can arrive after the widget has been destroyed.
utils.catch_runtime_error(self.set_items, items)
def set_items(self, items):
"""Clear the widget and add items to the model"""
self.clear()
self.invisibleRootItem().appendRows(items)
self.updated.emit()
def dispose(self):
self.update_thread.dispose()
def _identity(value):
return value
def _lower(value):
return value.lower()
def filter_matches(match_text, candidates, case_sensitive, sort_key=None):
"""Filter candidates and return the matches"""
if case_sensitive:
case_transform = _identity
else:
case_transform = _lower
if match_text:
match_text = case_transform(match_text)
matches = [r for r in candidates if match_text in case_transform(r)]
else:
matches = list(candidates)
if case_sensitive:
if sort_key is None:
matches.sort()
else:
matches.sort(key=sort_key)
else:
if sort_key is None:
matches.sort(key=_lower)
else:
matches.sort(key=lambda x: sort_key(_lower(x)))
return matches
def filter_path_matches(match_text, file_list, case_sensitive):
"""Return matching completions from a list of candidate files"""
files = set(file_list)
files_and_dirs = utils.add_parents(files)
dirs = files_and_dirs.difference(files)
paths = filter_matches(match_text, files_and_dirs, case_sensitive)
return (paths, dirs)
class Completer(QtWidgets.QCompleter):
def __init__(self, model, parent):
QtWidgets.QCompleter.__init__(self, parent)
self._model = model
self.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion)
self.setCaseSensitivity(Qt.CaseInsensitive)
self.setFilterMode(QtCore.Qt.MatchContains)
model.model_updated.connect(self.update, type=Qt.QueuedConnection)
self.setModel(model)
def update(self):
self._model.update()
def dispose(self):
self._model.dispose()
def set_match_text(self, full_text, match_text, case_sensitive):
self._model.set_match_text(full_text, match_text, case_sensitive)
class GitCompletionModel(CompletionModel):
def __init__(self, context, parent):
CompletionModel.__init__(self, context, parent)
self.context = context
context.model.updated.connect(self.model_updated, type=Qt.QueuedConnection)
def gather_matches(self, case_sensitive):
refs = filter_matches(
self.match_text, self.matches(), case_sensitive, sort_key=ref_sort_key
)
return (refs, (), set())
def matches(self):
return []
class GitRefCompletionModel(GitCompletionModel):
"""Completer for branches and tags"""
def __init__(self, context, parent):
GitCompletionModel.__init__(self, context, parent)
context.model.refs_updated.connect(self.model_updated, type=Qt.QueuedConnection)
def matches(self):
model = self.context.model
return model.local_branches + model.remote_branches + model.tags
def find_potential_branches(model):
remotes = model.remotes
remote_branches = model.remote_branches
ambiguous = set()
allnames = set(model.local_branches)
potential = []
for remote_branch in remote_branches:
branch = gitcmds.strip_remote(remotes, remote_branch)
if branch in allnames or branch == remote_branch:
ambiguous.add(branch)
continue
potential.append(branch)
allnames.add(branch)
potential_branches = [p for p in potential if p not in ambiguous]
return potential_branches
class GitCreateBranchCompletionModel(GitCompletionModel):
"""Completer for naming new branches"""
def matches(self):
model = self.context.model
potential_branches = find_potential_branches(model)
return model.local_branches + potential_branches + model.tags
class GitCheckoutBranchCompletionModel(GitCompletionModel):
"""Completer for git checkout <branch>"""
def matches(self):
model = self.context.model
potential_branches = find_potential_branches(model)
return (
model.local_branches
+ potential_branches
+ model.remote_branches
+ model.tags
)
class GitBranchCompletionModel(GitCompletionModel):
"""Completer for local branches"""
def __init__(self, context, parent):
GitCompletionModel.__init__(self, context, parent)
def matches(self):
model = self.context.model
return model.local_branches
class GitRemoteBranchCompletionModel(GitCompletionModel):
"""Completer for remote branches"""
def __init__(self, context, parent):
GitCompletionModel.__init__(self, context, parent)
def matches(self):
model = self.context.model
return model.remote_branches
class GitPathCompletionModel(GitCompletionModel):
"""Base class for path completion"""
def __init__(self, context, parent):
GitCompletionModel.__init__(self, context, parent)
def candidate_paths(self):
return []
def gather_matches(self, case_sensitive):
paths, dirs = filter_path_matches(
self.match_text, self.candidate_paths(), case_sensitive
)
return ((), paths, dirs)
class GitStatusFilterCompletionModel(GitPathCompletionModel):
"""Completer for modified files and folders for status filtering"""
def __init__(self, context, parent):
GitPathCompletionModel.__init__(self, context, parent)
def candidate_paths(self):
model = self.context.model
return model.staged + model.unmerged + model.modified + model.untracked
class GitTrackedCompletionModel(GitPathCompletionModel):
"""Completer for tracked files and folders"""
def __init__(self, context, parent):
GitPathCompletionModel.__init__(self, context, parent)
self.model_updated.connect(self.gather_paths, type=Qt.QueuedConnection)
self._paths = []
def gather_paths(self):
context = self.context
self._paths = gitcmds.tracked_files(context)
def gather_matches(self, case_sensitive):
if not self._paths:
self.gather_paths()
refs = []
paths, dirs = filter_path_matches(self.match_text, self._paths, case_sensitive)
return (refs, paths, dirs)
class GitLogCompletionModel(GitRefCompletionModel):
"""Completer for arguments suitable for git-log like commands"""
def __init__(self, context, parent):
GitRefCompletionModel.__init__(self, context, parent)
self._paths = []
self._model = context.model
self._runtask = qtutils.RunTask(parent=self)
self._time = 0.0 # ensure that the first event runs a task.
self.model_updated.connect(
self._start_gathering_paths, type=Qt.QueuedConnection
)
def matches(self):
"""Return candidate values for completion"""
matches = super().matches()
return [
'--all',
'--all-match',
'--author',
'--after=two.days.ago',
'--basic-regexp',
'--before=two.days.ago',
'--branches',
'--committer',
'--exclude',
'--extended-regexp',
'--find-object',
'--first-parent',
'--fixed-strings',
'--full-diff',
'--grep',
'--invert-grep',
'--merges',
'--no-merges',
'--not',
'--perl-regexp',
'--pickaxe-all',
'--pickaxe-regex',
'--regexp-ignore-case',
'--tags',
'-D',
'-E',
'-F',
'-G',
'-P',
'-S',
'@{upstream}',
] + matches
def _start_gathering_paths(self):
"""Gather paths when the model changes"""
# Debounce updates that land within 1 second of each other.
if time.time() - self._time > 1.0:
self._runtask.start(qtutils.SimpleTask(self.gather_paths))
self._time = time.time()
def gather_paths(self):
"""Gather paths and store them in the model"""
self._time = time.time()
if self._model.cfg.get(prefs.AUTOCOMPLETE_PATHS, True):
self._paths = gitcmds.tracked_files(self.context)
else:
self._paths = []
self._time = time.time()
def gather_matches(self, case_sensitive):
"""Filter paths and refs to find matching entries"""
if not self._paths:
self.gather_paths()
refs = filter_matches(
self.match_text, self.matches(), case_sensitive, sort_key=ref_sort_key
)
paths, dirs = filter_path_matches(self.match_text, self._paths, case_sensitive)
has_doubledash = (
self.match_text == '--'
or self.full_text.startswith('-- ')
or ' -- ' in self.full_text
)
if has_doubledash:
refs = []
elif refs and paths:
paths.insert(0, '--')
return (refs, paths, dirs)
def bind_lineedit(model, hint='', show_all_completions=False):
"""Create a line edit bound against a specific model"""
class BoundLineEdit(CompletionLineEdit):
def __init__(self, context, hint=hint, parent=None):
CompletionLineEdit.__init__(
self,
context,
model,
hint=hint,
show_all_completions=show_all_completions,
parent=parent,
)
self.context = context
return BoundLineEdit
# Concrete classes
GitLogLineEdit = bind_lineedit(GitLogCompletionModel, hint='<ref>')
GitRefLineEdit = bind_lineedit(GitRefCompletionModel, hint='<ref>')
GitCheckoutBranchLineEdit = bind_lineedit(
GitCheckoutBranchCompletionModel,
hint='<branch>',
show_all_completions=True,
)
GitCreateBranchLineEdit = bind_lineedit(GitCreateBranchCompletionModel, hint='<branch>')
GitBranchLineEdit = bind_lineedit(GitBranchCompletionModel, hint='<branch>')
GitRemoteBranchLineEdit = bind_lineedit(
GitRemoteBranchCompletionModel, hint='<remote-branch>'
)
GitStatusFilterLineEdit = bind_lineedit(GitStatusFilterCompletionModel, hint='<path>')
GitTrackedLineEdit = bind_lineedit(GitTrackedCompletionModel, hint='<path>')
class GitDialog(QtWidgets.QDialog):
# The "lineedit" argument is provided by the derived class constructor.
def __init__(self, lineedit, context, title, text, parent, icon=None):
QtWidgets.QDialog.__init__(self, parent)
self.context = context
self.setWindowTitle(title)
self.setWindowModality(Qt.WindowModal)
self.setMinimumWidth(333)
self.label = QtWidgets.QLabel()
self.label.setText(title)
self.lineedit = lineedit(context)
self.ok_button = qtutils.ok_button(text, icon=icon, enabled=False)
self.close_button = qtutils.close_button()
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
qtutils.STRETCH,
self.close_button,
self.ok_button,
)
self.main_layout = qtutils.vbox(
defs.margin, defs.spacing, self.label, self.lineedit, self.button_layout
)
self.setLayout(self.main_layout)
self.lineedit.textChanged.connect(self.text_changed)
self.lineedit.enter.connect(self.accept)
qtutils.connect_button(self.ok_button, self.accept)
qtutils.connect_button(self.close_button, self.reject)
self.setFocusProxy(self.lineedit)
self.lineedit.setFocus()
def text(self):
return self.lineedit.text()
def text_changed(self, _txt):
self.ok_button.setEnabled(bool(self.text()))
def set_text(self, ref):
self.lineedit.setText(ref)
@classmethod
def get(cls, context, title, text, parent, default=None, icon=None):
dlg = cls(context, title, text, parent, icon=icon)
if default:
dlg.set_text(default)
dlg.show()
QtCore.QTimer().singleShot(250, dlg.lineedit.show_popup)
if dlg.exec_() == cls.Accepted:
return dlg.text()
return None
class GitRefDialog(GitDialog):
def __init__(self, context, title, text, parent, icon=None):
GitDialog.__init__(
self, GitRefLineEdit, context, title, text, parent, icon=icon
)
class GitCheckoutBranchDialog(GitDialog):
def __init__(self, context, title, text, parent, icon=None):
GitDialog.__init__(
self, GitCheckoutBranchLineEdit, context, title, text, parent, icon=icon
)
class GitBranchDialog(GitDialog):
def __init__(self, context, title, text, parent, icon=None):
GitDialog.__init__(
self, GitBranchLineEdit, context, title, text, parent, icon=icon
)
class GitRemoteBranchDialog(GitDialog):
def __init__(self, context, title, text, parent, icon=None):
GitDialog.__init__(
self, GitRemoteBranchLineEdit, context, title, text, parent, icon=icon
)
| 29,623 | Python | .py | 733 | 31.515689 | 88 | 0.629019 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
108 | diff.py | git-cola_git-cola/cola/widgets/diff.py | from functools import partial
import os
import re
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..i18n import N_
from ..editpatch import edit_patch
from ..interaction import Interaction
from ..models import main
from ..models import prefs
from ..qtutils import get
from .. import actions
from .. import cmds
from .. import core
from .. import diffparse
from .. import gitcmds
from .. import gravatar
from .. import hotkeys
from .. import icons
from .. import utils
from .. import qtutils
from .text import TextDecorator
from .text import VimHintedPlainTextEdit
from .text import PlainTextLabel
from .text import RichTextLabel
from .text import TextSearchWidget
from . import defs
from . import standard
from . import imageview
class DiffSyntaxHighlighter(QtGui.QSyntaxHighlighter):
"""Implements the diff syntax highlighting"""
INITIAL_STATE = -1
DEFAULT_STATE = 0
DIFFSTAT_STATE = 1
DIFF_FILE_HEADER_STATE = 2
DIFF_STATE = 3
SUBMODULE_STATE = 4
END_STATE = 5
DIFF_FILE_HEADER_START_RGX = re.compile(r'diff --git a/.* b/.*')
DIFF_HUNK_HEADER_RGX = re.compile(
r'(?:@@ -[0-9,]+ \+[0-9,]+ @@)|(?:@@@ (?:-[0-9,]+ ){2}\+[0-9,]+ @@@)'
)
BAD_WHITESPACE_RGX = re.compile(r'\s+$')
def __init__(self, context, doc, whitespace=True, is_commit=False):
QtGui.QSyntaxHighlighter.__init__(self, doc)
self.whitespace = whitespace
self.enabled = True
self.is_commit = is_commit
QPalette = QtGui.QPalette
cfg = context.cfg
palette = QPalette()
disabled = palette.color(QPalette.Disabled, QPalette.Text)
header = qtutils.rgb_hex(disabled)
dark = palette.color(QPalette.Base).lightnessF() < 0.5
self.color_text = qtutils.rgb_triple(cfg.color('text', '030303'))
self.color_add = qtutils.rgb_triple(
cfg.color('add', '77aa77' if dark else 'd2ffe4')
)
self.color_remove = qtutils.rgb_triple(
cfg.color('remove', 'aa7777' if dark else 'fee0e4')
)
self.color_header = qtutils.rgb_triple(cfg.color('header', header))
self.diff_header_fmt = qtutils.make_format(foreground=self.color_header)
self.bold_diff_header_fmt = qtutils.make_format(
foreground=self.color_header, bold=True
)
self.diff_add_fmt = qtutils.make_format(
foreground=self.color_text, background=self.color_add
)
self.diff_remove_fmt = qtutils.make_format(
foreground=self.color_text, background=self.color_remove
)
self.bad_whitespace_fmt = qtutils.make_format(background=Qt.red)
self.setCurrentBlockState(self.INITIAL_STATE)
def set_enabled(self, enabled):
self.enabled = enabled
def highlightBlock(self, text):
"""Highlight the current text block"""
if not self.enabled or not text:
return
formats = []
state = self.get_next_state(text)
if state == self.DIFFSTAT_STATE:
state, formats = self.get_formats_for_diffstat(state, text)
elif state == self.DIFF_FILE_HEADER_STATE:
state, formats = self.get_formats_for_diff_header(state, text)
elif state == self.DIFF_STATE:
state, formats = self.get_formats_for_diff_text(state, text)
for start, end, fmt in formats:
self.setFormat(start, end, fmt)
self.setCurrentBlockState(state)
def get_next_state(self, text):
"""Transition to the next state based on the input text"""
state = self.previousBlockState()
if state == DiffSyntaxHighlighter.INITIAL_STATE:
if text.startswith('Submodule '):
state = DiffSyntaxHighlighter.SUBMODULE_STATE
elif text.startswith('diff --git '):
state = DiffSyntaxHighlighter.DIFFSTAT_STATE
elif self.is_commit:
state = DiffSyntaxHighlighter.DEFAULT_STATE
else:
state = DiffSyntaxHighlighter.DIFFSTAT_STATE
return state
def get_formats_for_diffstat(self, state, text):
"""Returns (state, [(start, end, fmt), ...]) for highlighting diffstat text"""
formats = []
if self.DIFF_FILE_HEADER_START_RGX.match(text):
state = self.DIFF_FILE_HEADER_STATE
end = len(text)
fmt = self.diff_header_fmt
formats.append((0, end, fmt))
elif self.DIFF_HUNK_HEADER_RGX.match(text):
state = self.DIFF_STATE
end = len(text)
fmt = self.bold_diff_header_fmt
formats.append((0, end, fmt))
elif '|' in text:
offset = text.index('|')
formats.append((0, offset, self.bold_diff_header_fmt))
formats.append((offset, len(text) - offset, self.diff_header_fmt))
else:
formats.append((0, len(text), self.diff_header_fmt))
return state, formats
def get_formats_for_diff_header(self, state, text):
"""Returns (state, [(start, end, fmt), ...]) for highlighting diff headers"""
formats = []
if self.DIFF_HUNK_HEADER_RGX.match(text):
state = self.DIFF_STATE
formats.append((0, len(text), self.bold_diff_header_fmt))
else:
formats.append((0, len(text), self.diff_header_fmt))
return state, formats
def get_formats_for_diff_text(self, state, text):
"""Return (state, [(start, end fmt), ...]) for highlighting diff text"""
formats = []
if self.DIFF_FILE_HEADER_START_RGX.match(text):
state = self.DIFF_FILE_HEADER_STATE
formats.append((0, len(text), self.diff_header_fmt))
elif self.DIFF_HUNK_HEADER_RGX.match(text):
formats.append((0, len(text), self.bold_diff_header_fmt))
elif text.startswith('-'):
if text == '-- ':
state = self.END_STATE
else:
formats.append((0, len(text), self.diff_remove_fmt))
elif text.startswith('+'):
formats.append((0, len(text), self.diff_add_fmt))
if self.whitespace:
match = self.BAD_WHITESPACE_RGX.search(text)
if match is not None:
start = match.start()
formats.append((start, len(text) - start, self.bad_whitespace_fmt))
return state, formats
class DiffTextEdit(VimHintedPlainTextEdit):
"""A textedit for interacting with diff text"""
def __init__(
self, context, parent, is_commit=False, whitespace=True, numbers=False
):
VimHintedPlainTextEdit.__init__(self, context, '', parent=parent)
# Diff/patch syntax highlighter
self.highlighter = DiffSyntaxHighlighter(
context, self.document(), is_commit=is_commit, whitespace=whitespace
)
if numbers:
self.numbers = DiffLineNumbers(context, self)
self.numbers.hide()
else:
self.numbers = None
self.scrollvalue = None
self.copy_diff_action = qtutils.add_action_with_icon(
self,
icons.copy(),
N_('Copy Diff'),
self.copy_diff,
hotkeys.COPY_DIFF,
)
self.copy_diff_action.setEnabled(False)
self.menu_actions.append(self.copy_diff_action)
self.cursorPositionChanged.connect(self._cursor_changed)
self.selectionChanged.connect(self._selection_changed)
def setFont(self, font):
"""Override setFont() so that we can use a custom "block" cursor"""
super().setFont(font)
if prefs.block_cursor(self.context):
width = qtutils.text_width(font, 'M')
self.setCursorWidth(width)
def _cursor_changed(self):
"""Update the line number display when the cursor changes"""
line_number = max(0, self.textCursor().blockNumber())
if self.numbers is not None:
self.numbers.set_highlighted(line_number)
def _selection_changed(self):
"""Respond to selection changes"""
selected = bool(self.selected_text())
self.copy_diff_action.setEnabled(selected)
def resizeEvent(self, event):
super().resizeEvent(event)
if self.numbers:
self.numbers.refresh_size()
def save_scrollbar(self):
"""Save the scrollbar value, but only on the first call"""
if self.scrollvalue is None:
scrollbar = self.verticalScrollBar()
if scrollbar:
scrollvalue = get(scrollbar)
else:
scrollvalue = None
self.scrollvalue = scrollvalue
def restore_scrollbar(self):
"""Restore the scrollbar and clear state"""
scrollbar = self.verticalScrollBar()
scrollvalue = self.scrollvalue
if scrollbar and scrollvalue is not None:
scrollbar.setValue(scrollvalue)
self.scrollvalue = None
def set_loading_message(self):
"""Add a pending loading message in the diff view"""
self.hint.set_value('+++ ' + N_('Loading...'))
self.set_value('')
def set_diff(self, diff):
"""Set the diff text, but save the scrollbar"""
diff = diff.rstrip('\n') # diffs include two empty newlines
self.save_scrollbar()
self.hint.set_value('')
if self.numbers:
self.numbers.set_diff(diff)
self.set_value(diff)
self.restore_scrollbar()
def selected_diff_stripped(self):
"""Return the selected diff stripped of any diff characters"""
sep, selection = self.selected_text_lines()
return sep.join(_strip_diff(line) for line in selection)
def copy_diff(self):
"""Copy the selected diff text stripped of any diff prefix characters"""
text = self.selected_diff_stripped()
qtutils.set_clipboard(text)
def selected_lines(self):
"""Return selected lines"""
cursor = self.textCursor()
selection_start = cursor.selectionStart()
selection_end = max(selection_start, cursor.selectionEnd() - 1)
first_line_idx = -1
last_line_idx = -1
line_idx = 0
line_start = 0
for line_idx, line in enumerate(get(self, default='').splitlines()):
line_end = line_start + len(line)
if line_start <= selection_start <= line_end:
first_line_idx = line_idx
if line_start <= selection_end <= line_end:
last_line_idx = line_idx
break
line_start = line_end + 1
if first_line_idx == -1:
first_line_idx = line_idx
if last_line_idx == -1:
last_line_idx = line_idx
return first_line_idx, last_line_idx
def selected_text_lines(self):
"""Return selected lines and the CRLF / LF separator"""
first_line_idx, last_line_idx = self.selected_lines()
text = get(self, default='')
sep = _get_sep(text)
lines = []
for line_idx, line in enumerate(text.split(sep)):
if first_line_idx <= line_idx <= last_line_idx:
lines.append(line)
return sep, lines
def _get_sep(text):
"""Return either CRLF or LF based on the content"""
if '\r\n' in text:
sep = '\r\n'
else:
sep = '\n'
return sep
def _strip_diff(value):
"""Remove +/-/<space> from a selection"""
if value.startswith(('+', '-', ' ')):
return value[1:]
return value
class DiffLineNumbers(TextDecorator):
def __init__(self, context, parent):
TextDecorator.__init__(self, parent)
self.highlight_line = -1
self.lines = None
self.parser = diffparse.DiffLines()
self.formatter = diffparse.FormatDigits()
font = qtutils.diff_font(context)
self.setFont(font)
self._char_width = qtutils.text_width(font, 'M')
QPalette = QtGui.QPalette
self._palette = palette = self.palette()
self._base = palette.color(QtGui.QPalette.Base)
self._highlight = palette.color(QPalette.Highlight)
self._highlight.setAlphaF(0.3)
self._highlight_text = palette.color(QPalette.HighlightedText)
self._window = palette.color(QPalette.Window)
self._disabled = palette.color(QPalette.Disabled, QPalette.Text)
def set_diff(self, diff):
self.lines = self.parser.parse(diff)
self.formatter.set_digits(self.parser.digits())
def width_hint(self):
if not self.isVisible():
return 0
parser = self.parser
if parser.merge:
columns = 3
extra = 3 # one space in-between, one space after
else:
columns = 2
extra = 2 # one space in-between, one space after
digits = parser.digits() * columns
return defs.margin + (self._char_width * (digits + extra))
def set_highlighted(self, line_number):
"""Set the line to highlight"""
self.highlight_line = line_number
def current_line(self):
lines = self.lines
if lines and self.highlight_line >= 0:
# Find the next valid line
for i in range(self.highlight_line, len(lines)):
# take the "new" line number: last value in tuple
line_number = lines[i][-1]
if line_number > 0:
return line_number
# Find the previous valid line
for i in range(self.highlight_line - 1, -1, -1):
# take the "new" line number: last value in tuple
if i < len(lines):
line_number = lines[i][-1]
if line_number > 0:
return line_number
return None
def paintEvent(self, event):
"""Paint the line number"""
if not self.lines:
return
painter = QtGui.QPainter(self)
painter.fillRect(event.rect(), self._base)
editor = self.editor
content_offset = editor.contentOffset()
block = editor.firstVisibleBlock()
width = self.width()
text_width = width - (defs.margin * 2)
text_flags = Qt.AlignRight | Qt.AlignVCenter
event_rect_bottom = event.rect().bottom()
highlight_line = self.highlight_line
highlight = self._highlight
highlight_text = self._highlight_text
disabled = self._disabled
fmt = self.formatter
lines = self.lines
num_lines = len(lines)
while block.isValid():
block_number = block.blockNumber()
if block_number >= num_lines:
break
block_geom = editor.blockBoundingGeometry(block)
rect = block_geom.translated(content_offset).toRect()
if not block.isVisible() or rect.top() >= event_rect_bottom:
break
if block_number == highlight_line:
painter.fillRect(rect.x(), rect.y(), width, rect.height(), highlight)
painter.setPen(highlight_text)
else:
painter.setPen(disabled)
line = lines[block_number]
if len(line) == 2:
a, b = line
text = fmt.value(a, b)
elif len(line) == 3:
old, base, new = line
text = fmt.merge_value(old, base, new)
painter.drawText(
rect.x(),
rect.y(),
text_width,
rect.height(),
text_flags,
text,
)
block = block.next()
class Viewer(QtWidgets.QFrame):
"""Text and image diff viewers"""
INDEX_TEXT = 0
INDEX_IMAGE = 1
def __init__(self, context, parent=None):
super().__init__(parent)
self.context = context
self.model = model = context.model
self.images = []
self.pixmaps = []
self.options = options = Options(self)
self.filename = PlainTextLabel(parent=self)
self.filename.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
font = self.font()
font.setItalic(True)
self.filename.setFont(font)
self.filename.elide()
self.text = DiffEditor(context, options, self)
self.image = imageview.ImageView(parent=self)
self.image.setFocusPolicy(Qt.NoFocus)
self.search_widget = TextSearchWidget(self.text, self)
self.search_widget.hide()
self._drag_has_patches = False
self.setAcceptDrops(True)
self.setFocusProxy(self.text)
stack = self.stack = QtWidgets.QStackedWidget(self)
stack.addWidget(self.text)
stack.addWidget(self.image)
self.main_layout = qtutils.vbox(
defs.no_margin,
defs.no_spacing,
self.stack,
self.search_widget,
)
self.setLayout(self.main_layout)
# Observe images
model.images_changed.connect(self.set_images, type=Qt.QueuedConnection)
# Observe the diff type
model.diff_type_changed.connect(self.set_diff_type, type=Qt.QueuedConnection)
# Observe the file type
model.file_type_changed.connect(self.set_file_type, type=Qt.QueuedConnection)
# Observe the image mode combo box
options.image_mode.currentIndexChanged.connect(lambda _: self.render())
options.zoom_mode.currentIndexChanged.connect(lambda _: self.render())
self.search_action = qtutils.add_action(
self,
N_('Search in Diff'),
self.show_search_diff,
hotkeys.SEARCH,
)
def dragEnterEvent(self, event):
"""Accepts drops if the mimedata contains patches"""
super().dragEnterEvent(event)
patches = get_patches_from_mimedata(event.mimeData())
if patches:
event.acceptProposedAction()
self._drag_has_patches = True
def dragLeaveEvent(self, event):
"""End the drag+drop interaction"""
super().dragLeaveEvent(event)
if self._drag_has_patches:
event.accept()
else:
event.ignore()
self._drag_has_patches = False
def dropEvent(self, event):
"""Apply patches when dropped onto the widget"""
if not self._drag_has_patches:
event.ignore()
return
event.setDropAction(Qt.CopyAction)
super().dropEvent(event)
self._drag_has_patches = False
patches = get_patches_from_mimedata(event.mimeData())
if patches:
apply_patches(self.context, patches=patches)
event.accept() # must be called after dropEvent()
def show_search_diff(self):
"""Show a dialog for searching diffs"""
# The diff search is only active in text mode.
if self.stack.currentIndex() != self.INDEX_TEXT:
return
if not self.search_widget.isVisible():
self.search_widget.show()
self.search_widget.setFocus()
def export_state(self, state):
state['show_diff_line_numbers'] = self.options.show_line_numbers.isChecked()
state['show_diff_filenames'] = self.options.show_filenames.isChecked()
state['image_diff_mode'] = self.options.image_mode.currentIndex()
state['image_zoom_mode'] = self.options.zoom_mode.currentIndex()
state['word_wrap'] = self.options.enable_word_wrapping.isChecked()
return state
def apply_state(self, state):
diff_numbers = bool(state.get('show_diff_line_numbers', False))
self.set_line_numbers(diff_numbers, update=True)
show_filenames = bool(state.get('show_diff_filenames', True))
self.set_show_filenames(show_filenames, update=True)
image_mode = utils.asint(state.get('image_diff_mode', 0))
self.options.image_mode.set_index(image_mode)
zoom_mode = utils.asint(state.get('image_zoom_mode', 0))
self.options.zoom_mode.set_index(zoom_mode)
word_wrap = bool(state.get('word_wrap', True))
self.set_word_wrapping(word_wrap, update=True)
return True
def set_diff_type(self, diff_type):
"""Manage the image and text diff views when selection changes"""
# The "diff type" is whether the diff viewer is displaying an image.
self.options.set_diff_type(diff_type)
if diff_type == main.Types.IMAGE:
self.stack.setCurrentWidget(self.image)
self.search_widget.hide()
self.render()
else:
self.stack.setCurrentWidget(self.text)
def set_file_type(self, file_type):
"""Manage the diff options when the file type changes"""
# The "file type" is whether the file itself is an image.
self.options.set_file_type(file_type)
def enable_filename_tracking(self):
"""Enable displaying the currently selected filename"""
self.context.selection.selection_changed.connect(
self.update_filename, type=Qt.QueuedConnection
)
def update_filename(self):
"""Update the filename display when the selection changes"""
filename = self.context.selection.filename()
self.filename.set_text(filename or '')
def update_options(self):
"""Emit a signal indicating that options have changed"""
self.text.update_options()
show_filenames = get(self.options.show_filenames)
self.set_show_filenames(show_filenames)
def set_show_filenames(self, enabled, update=False):
"""Enable/disable displaying the selected filename"""
self.filename.setVisible(enabled)
if update:
with qtutils.BlockSignals(self.options.show_filenames):
self.options.show_filenames.setChecked(enabled)
def set_line_numbers(self, enabled, update=False):
"""Enable/disable line numbers in the text widget"""
self.text.set_line_numbers(enabled, update=update)
def set_word_wrapping(self, enabled, update=False):
"""Enable/disable word wrapping in the text widget"""
self.text.set_word_wrapping(enabled, update=update)
def reset(self):
self.image.pixmap = QtGui.QPixmap()
self.cleanup()
def cleanup(self):
for image, unlink in self.images:
if unlink and core.exists(image):
os.unlink(image)
self.images = []
def set_images(self, images):
self.images = images
self.pixmaps = []
if not images:
self.reset()
return False
# In order to comp, we first have to load all the images
all_pixmaps = [QtGui.QPixmap(image[0]) for image in images]
pixmaps = [pixmap for pixmap in all_pixmaps if not pixmap.isNull()]
if not pixmaps:
self.reset()
return False
self.pixmaps = pixmaps
self.render()
self.cleanup()
return True
def render(self):
# Update images
if self.pixmaps:
mode = self.options.image_mode.currentIndex()
if mode == self.options.SIDE_BY_SIDE:
image = self.render_side_by_side()
elif mode == self.options.DIFF:
image = self.render_diff()
elif mode == self.options.XOR:
image = self.render_xor()
elif mode == self.options.PIXEL_XOR:
image = self.render_pixel_xor()
else:
image = self.render_side_by_side()
else:
image = QtGui.QPixmap()
self.image.pixmap = image
# Apply zoom
zoom_mode = self.options.zoom_mode.currentIndex()
zoom_factor = self.options.zoom_factors[zoom_mode][1]
if zoom_factor > 0.0:
self.image.resetTransform()
self.image.scale(zoom_factor, zoom_factor)
poly = self.image.mapToScene(self.image.viewport().rect())
self.image.last_scene_roi = poly.boundingRect()
def render_side_by_side(self):
# Side-by-side lineup comp
pixmaps = self.pixmaps
width = sum(pixmap.width() for pixmap in pixmaps)
height = max(pixmap.height() for pixmap in pixmaps)
image = create_image(width, height)
# Paint each pixmap
painter = create_painter(image)
x = 0
for pixmap in pixmaps:
painter.drawPixmap(x, 0, pixmap)
x += pixmap.width()
painter.end()
return image
def render_comp(self, comp_mode):
# Get the max size to use as the render canvas
pixmaps = self.pixmaps
if len(pixmaps) == 1:
return pixmaps[0]
width = max(pixmap.width() for pixmap in pixmaps)
height = max(pixmap.height() for pixmap in pixmaps)
image = create_image(width, height)
painter = create_painter(image)
for pixmap in (pixmaps[0], pixmaps[-1]):
x = (width - pixmap.width()) // 2
y = (height - pixmap.height()) // 2
painter.drawPixmap(x, y, pixmap)
painter.setCompositionMode(comp_mode)
painter.end()
return image
def render_diff(self):
comp_mode = QtGui.QPainter.CompositionMode_Difference
return self.render_comp(comp_mode)
def render_xor(self):
comp_mode = QtGui.QPainter.CompositionMode_Xor
return self.render_comp(comp_mode)
def render_pixel_xor(self):
comp_mode = QtGui.QPainter.RasterOp_SourceXorDestination
return self.render_comp(comp_mode)
def create_image(width, height):
size = QtCore.QSize(width, height)
image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32_Premultiplied)
image.fill(Qt.transparent)
return image
def create_painter(image):
painter = QtGui.QPainter(image)
painter.fillRect(image.rect(), Qt.transparent)
return painter
class Options(QtWidgets.QWidget):
"""Provide the options widget used by the editor
Actions are registered on the parent widget.
"""
# mode combobox indexes
SIDE_BY_SIDE = 0
DIFF = 1
XOR = 2
PIXEL_XOR = 3
def __init__(self, parent):
super().__init__(parent)
# Create widgets
self.widget = parent
self.ignore_space_at_eol = self.add_option(
N_('Ignore changes in whitespace at EOL')
)
self.ignore_space_change = self.add_option(
N_('Ignore changes in amount of whitespace')
)
self.ignore_all_space = self.add_option(N_('Ignore all whitespace'))
self.function_context = self.add_option(
N_('Show whole surrounding functions of changes')
)
self.show_line_numbers = qtutils.add_action_bool(
self, N_('Show line numbers'), self.set_line_numbers, True
)
self.show_filenames = self.add_option(N_('Show filenames'))
self.enable_word_wrapping = qtutils.add_action_bool(
self, N_('Enable word wrapping'), self.set_word_wrapping, True
)
self.options = qtutils.create_action_button(
tooltip=N_('Diff Options'), icon=icons.configure()
)
self.toggle_image_diff = qtutils.create_action_button(
tooltip=N_('Toggle image diff'), icon=icons.visualize()
)
self.toggle_image_diff.hide()
self.image_mode = qtutils.combo(
[N_('Side by side'), N_('Diff'), N_('XOR'), N_('Pixel XOR')]
)
self.zoom_factors = (
(N_('Zoom to Fit'), 0.0),
(N_('25%'), 0.25),
(N_('50%'), 0.5),
(N_('100%'), 1.0),
(N_('200%'), 2.0),
(N_('400%'), 4.0),
(N_('800%'), 8.0),
)
zoom_modes = [factor[0] for factor in self.zoom_factors]
self.zoom_mode = qtutils.combo(zoom_modes, parent=self)
self.menu = menu = qtutils.create_menu(N_('Diff Options'), self.options)
self.options.setMenu(menu)
menu.addAction(self.ignore_space_at_eol)
menu.addAction(self.ignore_space_change)
menu.addAction(self.ignore_all_space)
menu.addSeparator()
menu.addAction(self.function_context)
menu.addAction(self.show_line_numbers)
menu.addAction(self.show_filenames)
menu.addSeparator()
menu.addAction(self.enable_word_wrapping)
# Layouts
layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.image_mode,
self.zoom_mode,
self.options,
self.toggle_image_diff,
)
self.setLayout(layout)
# Policies
self.image_mode.setFocusPolicy(Qt.NoFocus)
self.zoom_mode.setFocusPolicy(Qt.NoFocus)
self.options.setFocusPolicy(Qt.NoFocus)
self.toggle_image_diff.setFocusPolicy(Qt.NoFocus)
self.setFocusPolicy(Qt.NoFocus)
def set_file_type(self, file_type):
"""Set whether we are viewing an image file type"""
is_image = file_type == main.Types.IMAGE
self.toggle_image_diff.setVisible(is_image)
def set_diff_type(self, diff_type):
"""Toggle between image and text diffs"""
is_text = diff_type == main.Types.TEXT
is_image = diff_type == main.Types.IMAGE
self.options.setVisible(is_text)
self.image_mode.setVisible(is_image)
self.zoom_mode.setVisible(is_image)
if is_image:
self.toggle_image_diff.setIcon(icons.diff())
else:
self.toggle_image_diff.setIcon(icons.visualize())
def add_option(self, title):
"""Add a diff option which calls update_options() on change"""
action = qtutils.add_action(self, title, self.update_options)
action.setCheckable(True)
return action
def update_options(self):
"""Update diff options in response to UI events"""
space_at_eol = get(self.ignore_space_at_eol)
space_change = get(self.ignore_space_change)
all_space = get(self.ignore_all_space)
function_context = get(self.function_context)
gitcmds.update_diff_overrides(
space_at_eol, space_change, all_space, function_context
)
self.widget.update_options()
def set_line_numbers(self, value):
"""Enable / disable line numbers"""
self.widget.set_line_numbers(value, update=False)
def set_word_wrapping(self, value):
"""Respond to Qt action callbacks"""
self.widget.set_word_wrapping(value, update=False)
def hide_advanced_options(self):
"""Hide advanced options that are not applicable to the DiffWidget"""
self.show_filenames.setVisible(False)
self.show_line_numbers.setVisible(False)
self.ignore_space_at_eol.setVisible(False)
self.ignore_space_change.setVisible(False)
self.ignore_all_space.setVisible(False)
self.function_context.setVisible(False)
class DiffEditor(DiffTextEdit):
up = Signal()
down = Signal()
options_changed = Signal()
def __init__(self, context, options, parent):
DiffTextEdit.__init__(self, context, parent, numbers=True)
self.context = context
self.model = model = context.model
self.selection_model = selection_model = context.selection
# "Diff Options" tool menu
self.options = options
self.action_apply_selection = qtutils.add_action(
self,
'Apply',
self.apply_selection,
hotkeys.STAGE_DIFF,
hotkeys.STAGE_DIFF_ALT,
)
self.action_revert_selection = qtutils.add_action(
self, 'Revert', self.revert_selection, hotkeys.REVERT, hotkeys.REVERT_ALT
)
self.action_revert_selection.setIcon(icons.undo())
self.action_edit_and_apply_selection = qtutils.add_action(
self,
'Edit and Apply',
partial(self.apply_selection, edit=True),
hotkeys.EDIT_AND_STAGE_DIFF,
)
self.action_edit_and_revert_selection = qtutils.add_action(
self,
'Edit and Revert',
partial(self.revert_selection, edit=True),
hotkeys.EDIT_AND_REVERT,
)
self.action_edit_and_revert_selection.setIcon(icons.undo())
self.launch_editor = actions.launch_editor_at_line(
context, self, hotkeys.EDIT_SHORT, *hotkeys.ACCEPT
)
self.launch_difftool = actions.launch_difftool(context, self)
self.stage_or_unstage = actions.stage_or_unstage(context, self)
# Emit up/down signals so that they can be routed by the main widget
self.move_up = actions.move_up(self)
self.move_down = actions.move_down(self)
model.diff_text_updated.connect(self.set_diff, type=Qt.QueuedConnection)
selection_model.selection_changed.connect(
self.refresh, type=Qt.QueuedConnection
)
# Update the selection model when the cursor changes
self.cursorPositionChanged.connect(self._update_line_number)
qtutils.connect_button(options.toggle_image_diff, self.toggle_diff_type)
def toggle_diff_type(self):
cmds.do(cmds.ToggleDiffType, self.context)
def refresh(self):
enabled = False
s = self.selection_model.selection()
model = self.model
if model.is_partially_stageable():
item = s.modified[0] if s.modified else None
if item in model.submodules:
pass
elif item not in model.unstaged_deleted:
enabled = True
self.action_revert_selection.setEnabled(enabled)
def set_line_numbers(self, enabled, update=False):
"""Enable/disable the diff line number display"""
self.numbers.setVisible(enabled)
if update:
with qtutils.BlockSignals(self.options.show_line_numbers):
self.options.show_line_numbers.setChecked(enabled)
# Refresh the display. Not doing this results in the display not
# correctly displaying the line numbers widget until the text scrolls.
self.set_value(self.value())
def update_options(self):
self.options_changed.emit()
def create_context_menu(self, event_pos):
"""Override create_context_menu() to display a completely custom menu"""
menu = super().create_context_menu(event_pos)
context = self.context
model = self.model
s = self.selection_model.selection()
filename = self.selection_model.filename()
# These menu actions will be inserted at the start of the widget.
current_actions = menu.actions()
menu_actions = []
add_action = menu_actions.append
edit_actions_added = False
stage_action_added = False
if s.staged and model.is_unstageable():
item = s.staged[0]
if item not in model.submodules and item not in model.staged_deleted:
if self.has_selection():
apply_text = N_('Unstage Selected Lines')
else:
apply_text = N_('Unstage Diff Hunk')
self.action_apply_selection.setText(apply_text)
self.action_apply_selection.setIcon(icons.remove())
add_action(self.action_apply_selection)
stage_action_added = self._add_stage_or_unstage_action(
menu, add_action, stage_action_added
)
if model.is_partially_stageable():
item = s.modified[0] if s.modified else None
if item in model.submodules:
path = core.abspath(item)
action = qtutils.add_action_with_icon(
menu,
icons.add(),
cmds.Stage.name(),
cmds.run(cmds.Stage, context, s.modified),
hotkeys.STAGE_SELECTION,
)
add_action(action)
stage_action_added = self._add_stage_or_unstage_action(
menu, add_action, stage_action_added
)
action = qtutils.add_action_with_icon(
menu,
icons.cola(),
N_('Launch git-cola'),
cmds.run(cmds.OpenRepo, context, path),
)
add_action(action)
elif item and item not in model.unstaged_deleted:
if self.has_selection():
apply_text = N_('Stage Selected Lines')
edit_and_apply_text = N_('Edit Selected Lines to Stage...')
revert_text = N_('Revert Selected Lines...')
edit_and_revert_text = N_('Edit Selected Lines to Revert...')
else:
apply_text = N_('Stage Diff Hunk')
edit_and_apply_text = N_('Edit Diff Hunk to Stage...')
revert_text = N_('Revert Diff Hunk...')
edit_and_revert_text = N_('Edit Diff Hunk to Revert...')
self.action_apply_selection.setText(apply_text)
self.action_apply_selection.setIcon(icons.add())
add_action(self.action_apply_selection)
self.action_revert_selection.setText(revert_text)
add_action(self.action_revert_selection)
stage_action_added = self._add_stage_or_unstage_action(
menu, add_action, stage_action_added
)
# Do not show the "edit" action when the file does not exist.
add_action(qtutils.menu_separator(menu))
if filename and core.exists(filename):
add_action(self.launch_editor)
# Removed files can still be diffed.
add_action(self.launch_difftool)
edit_actions_added = True
add_action(qtutils.menu_separator(menu))
self.action_edit_and_apply_selection.setText(edit_and_apply_text)
self.action_edit_and_apply_selection.setIcon(icons.add())
add_action(self.action_edit_and_apply_selection)
self.action_edit_and_revert_selection.setText(edit_and_revert_text)
add_action(self.action_edit_and_revert_selection)
if s.staged and model.is_unstageable():
item = s.staged[0]
if item in model.submodules:
path = core.abspath(item)
action = qtutils.add_action_with_icon(
menu,
icons.remove(),
cmds.Unstage.name(),
cmds.run(cmds.Unstage, context, s.staged),
hotkeys.STAGE_SELECTION,
)
add_action(action)
stage_action_added = self._add_stage_or_unstage_action(
menu, add_action, stage_action_added
)
qtutils.add_action_with_icon(
menu,
icons.cola(),
N_('Launch git-cola'),
cmds.run(cmds.OpenRepo, context, path),
)
add_action(action)
elif item not in model.staged_deleted:
# Do not show the "edit" action when the file does not exist.
add_action(qtutils.menu_separator(menu))
if filename and core.exists(filename):
add_action(self.launch_editor)
# Removed files can still be diffed.
add_action(self.launch_difftool)
add_action(qtutils.menu_separator(menu))
edit_actions_added = True
if self.has_selection():
edit_and_apply_text = N_('Edit Selected Lines to Unstage...')
else:
edit_and_apply_text = N_('Edit Diff Hunk to Unstage...')
self.action_edit_and_apply_selection.setText(edit_and_apply_text)
self.action_edit_and_apply_selection.setIcon(icons.remove())
add_action(self.action_edit_and_apply_selection)
if not edit_actions_added and (model.is_stageable() or model.is_unstageable()):
add_action(qtutils.menu_separator(menu))
# Do not show the "edit" action when the file does not exist.
# Untracked files exist by definition.
if filename and core.exists(filename):
add_action(self.launch_editor)
# Removed files can still be diffed.
add_action(self.launch_difftool)
add_action(qtutils.menu_separator(menu))
_add_patch_actions(self, self.context, menu)
# Add the Previous/Next File actions, which improves discoverability
# of their associated shortcuts
add_action(qtutils.menu_separator(menu))
add_action(self.move_up)
add_action(self.move_down)
add_action(qtutils.menu_separator(menu))
if current_actions:
first_action = current_actions[0]
else:
first_action = None
menu.insertActions(first_action, menu_actions)
return menu
def _add_stage_or_unstage_action(self, menu, add_action, already_added):
"""Add the Stage / Unstage menu action"""
if already_added:
return True
model = self.context.model
s = self.selection_model.selection()
if model.is_stageable() or model.is_unstageable():
if (model.is_amend_mode() and s.staged) or not self.model.is_stageable():
self.stage_or_unstage.setText(N_('Unstage'))
self.stage_or_unstage.setIcon(icons.remove())
else:
self.stage_or_unstage.setText(N_('Stage'))
self.stage_or_unstage.setIcon(icons.add())
add_action(qtutils.menu_separator(menu))
add_action(self.stage_or_unstage)
return True
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
# Intercept right-click to move the cursor to the current position.
# setTextCursor() clears the selection so this is only done when
# nothing is selected.
if not self.has_selection():
cursor = self.cursorForPosition(event.pos())
self.setTextCursor(cursor)
return super().mousePressEvent(event)
def setPlainText(self, text):
"""setPlainText(str) while retaining scrollbar positions"""
model = self.model
mode = model.mode
highlight = mode not in (
model.mode_none,
model.mode_display,
model.mode_untracked,
)
self.highlighter.set_enabled(highlight)
scrollbar = self.verticalScrollBar()
if scrollbar:
scrollvalue = get(scrollbar)
else:
scrollvalue = None
if text is None:
return
DiffTextEdit.setPlainText(self, text)
if scrollbar and scrollvalue is not None:
scrollbar.setValue(scrollvalue)
def apply_selection(self, *, edit=False):
model = self.model
s = self.selection_model.single_selection()
if model.is_partially_stageable() and (s.modified or s.untracked):
self.process_diff_selection(edit=edit)
elif model.is_unstageable():
self.process_diff_selection(reverse=True, edit=edit)
def revert_selection(self, *, edit=False):
"""Destructively revert selected lines or hunk from a worktree file."""
if not edit:
if self.has_selection():
title = N_('Revert Selected Lines?')
ok_text = N_('Revert Selected Lines')
else:
title = N_('Revert Diff Hunk?')
ok_text = N_('Revert Diff Hunk')
if not Interaction.confirm(
title,
N_(
'This operation drops uncommitted changes.\n'
'These changes cannot be recovered.'
),
N_('Revert the uncommitted changes?'),
ok_text,
default=True,
icon=icons.undo(),
):
return
self.process_diff_selection(reverse=True, apply_to_worktree=True, edit=edit)
def extract_patch(self, reverse=False):
first_line_idx, last_line_idx = self.selected_lines()
patch = diffparse.Patch.parse(self.model.filename, self.model.diff_text)
if self.has_selection():
return patch.extract_subset(first_line_idx, last_line_idx, reverse=reverse)
return patch.extract_hunk(first_line_idx, reverse=reverse)
def patch_encoding(self):
if isinstance(self.model.diff_text, core.UStr):
# original encoding must prevail
return self.model.diff_text.encoding
return self.context.cfg.file_encoding(self.model.filename)
def process_diff_selection(
self, reverse=False, apply_to_worktree=False, edit=False
):
"""Implement un/staging of the selected line(s) or hunk."""
if self.selection_model.is_empty():
return
patch = self.extract_patch(reverse)
if not patch.has_changes():
return
patch_encoding = self.patch_encoding()
if edit:
patch = edit_patch(
patch,
patch_encoding,
self.context,
reverse=reverse,
apply_to_worktree=apply_to_worktree,
)
if not patch.has_changes():
return
cmds.do(
cmds.ApplyPatch,
self.context,
patch,
patch_encoding,
apply_to_worktree,
)
def _update_line_number(self):
"""Update the selection model when the cursor changes"""
self.selection_model.line_number = self.numbers.current_line()
def _add_patch_actions(widget, context, menu):
"""Add actions for manipulating patch files"""
patches_menu = menu.addMenu(N_('Patches'))
patches_menu.setIcon(icons.diff())
export_action = qtutils.add_action(
patches_menu,
N_('Export Patch'),
lambda: _export_patch(widget, context),
)
export_action.setIcon(icons.save())
patches_menu.addAction(export_action)
# Build the "Append Patch" menu dynamically.
append_menu = patches_menu.addMenu(N_('Append Patch'))
append_menu.setIcon(icons.add())
append_menu.aboutToShow.connect(
lambda: _build_patch_append_menu(widget, context, append_menu)
)
def _build_patch_append_menu(widget, context, menu):
"""Build the "Append Patch" sub-menu"""
# Build the menu when first displayed only. This initial check avoids
# re-populating the menu with duplicate actions.
menu_actions = menu.actions()
if menu_actions:
return
choose_patch_action = qtutils.add_action(
menu,
N_('Choose Patch...'),
lambda: _export_patch(widget, context, append=True),
)
choose_patch_action.setIcon(icons.diff())
menu.addAction(choose_patch_action)
subdir_menus = {}
path = prefs.patches_directory(context)
patches = get_patches_from_dir(path)
for patch in patches:
relpath = os.path.relpath(patch, start=path)
sub_menu = _add_patch_subdirs(menu, subdir_menus, relpath)
patch_basename = os.path.basename(relpath)
append_action = qtutils.add_action(
sub_menu,
patch_basename,
lambda patch_file=patch: _append_patch(widget, patch_file),
)
append_action.setIcon(icons.save())
sub_menu.addAction(append_action)
def _add_patch_subdirs(menu, subdir_menus, relpath):
"""Build menu leading up to the patch"""
# If the path contains no directory separators then add it to the
# root of the menu.
if os.sep not in relpath:
return menu
# Loop over each directory component and build a menu if it doesn't already exist.
components = []
for dirname in os.path.dirname(relpath).split(os.sep):
components.append(dirname)
current_dir = os.sep.join(components)
try:
menu = subdir_menus[current_dir]
except KeyError:
menu = subdir_menus[current_dir] = menu.addMenu(dirname)
menu.setIcon(icons.folder())
return menu
def _export_patch(diff_editor, context, append=False):
"""Export the selected diff to a patch file"""
if diff_editor.selection_model.is_empty():
return
patch = diff_editor.extract_patch(reverse=False)
if not patch.has_changes():
return
directory = prefs.patches_directory(context)
if append:
filename = qtutils.existing_file(directory, title=N_('Append Patch...'))
else:
default_filename = os.path.join(directory, 'diff.patch')
filename = qtutils.save_as(default_filename)
if not filename:
return
_write_patch_to_file(diff_editor, patch, filename, append=append)
def _append_patch(diff_editor, filename):
"""Append diffs to the specified patch file"""
if diff_editor.selection_model.is_empty():
return
patch = diff_editor.extract_patch(reverse=False)
if not patch.has_changes():
return
_write_patch_to_file(diff_editor, patch, filename, append=True)
def _write_patch_to_file(diff_editor, patch, filename, append=False):
"""Write diffs from the Diff Editor to the specified patch file"""
encoding = diff_editor.patch_encoding()
content = patch.as_text()
try:
core.write(filename, content, encoding=encoding, append=append)
except OSError as exc:
_, details = utils.format_exception(exc)
title = N_('Error writing patch')
msg = N_('Unable to write patch to "%s". Check permissions?' % filename)
Interaction.critical(title, message=msg, details=details)
return
Interaction.log('Patch written to "%s"' % filename)
class ObjectIdLabel(PlainTextLabel):
"""Interactive object IDs"""
def __init__(self, context, oid='', parent=None):
super().__init__(parent=parent)
self.context = context
self.oid = oid
self.setCursor(Qt.PointingHandCursor)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.setFocusPolicy(Qt.NoFocus)
self.setToolTip(N_('Click to Copy'))
self.customContextMenuRequested.connect(self._context_menu)
self._copy_short_action = qtutils.add_action_with_icon(
self,
icons.copy(),
N_('Copy Commit (Short)'),
self._copy_short,
hotkeys.COPY,
)
self._copy_long_action = qtutils.add_action_with_icon(
self,
icons.copy(),
N_('Copy Commit'),
self._copy_long,
hotkeys.COPY_COMMIT_ID,
)
self._select_all_action = qtutils.add_action(
self, N_('Select All'), self._select_all, hotkeys.SELECT_ALL
)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(200)
self.timer.setSingleShot(True)
self.timer.timeout.connect(self._timeout)
def _timeout(self):
"""Clear the selection"""
self.setSelection(0, 0)
def set_oid(self, oid):
"""Record the object ID and update the display"""
self.oid = oid
self.set_text(oid)
def _copy_short(self, clicked=False):
"""Copy the abbreviated commit ID"""
abbrev = prefs.abbrev(self.context)
qtutils.set_clipboard(self.oid[:abbrev])
self._select_all()
if not self.timer.isActive():
self.timer.start()
def _copy_long(self):
"""Copy the full commit ID"""
qtutils.set_clipboard(self.oid)
self._select_all()
if not self.timer.isActive():
self.timer.start()
def _select_all(self):
"""Select the text"""
length = len(self.get())
self.setSelection(0, length)
def mousePressEvent(self, event):
"""Copy the commit ID when clicked"""
if event.button() == Qt.LeftButton:
# This behavior makes it impossible to select text by clicking and dragging,
# but it's okay because this also makes copying text a single-click affair.
self._copy_short(clicked=True)
return super().mousePressEvent(event)
def _context_menu(self, pos):
"""Display a custom context menu"""
menu = QtWidgets.QMenu(self)
menu.addAction(self._copy_short_action)
menu.addAction(self._copy_long_action)
menu.addAction(self._select_all_action)
menu.exec_(self.mapToGlobal(pos))
class DiffWidget(QtWidgets.QWidget):
"""Display commit metadata and text diffs"""
def __init__(self, context, parent, is_commit=False, options=None):
QtWidgets.QWidget.__init__(self, parent)
self.context = context
self.oid = 'HEAD'
self.oid_start = None
self.oid_end = None
self.options = options
author_font = QtGui.QFont(self.font())
author_font.setPointSize(int(author_font.pointSize() * 1.1))
summary_font = QtGui.QFont(author_font)
summary_font.setWeight(QtGui.QFont.Bold)
self.gravatar_label = gravatar.GravatarLabel(self.context, parent=self)
self.oid_label = ObjectIdLabel(context, parent=self)
self.oid_label.setAlignment(Qt.AlignBottom)
self.oid_label.elide()
self.author_label = RichTextLabel(selectable=False, parent=self)
self.author_label.setFont(author_font)
self.author_label.setAlignment(Qt.AlignTop)
self.author_label.elide()
self.date_label = PlainTextLabel(parent=self)
self.date_label.setAlignment(Qt.AlignTop)
self.date_label.elide()
self.summary_label = PlainTextLabel(parent=self)
self.summary_label.setFont(summary_font)
self.summary_label.setAlignment(Qt.AlignTop)
self.summary_label.elide()
self.diff = DiffTextEdit(context, self, is_commit=is_commit, whitespace=False)
self.setFocusProxy(self.diff)
self.info_layout = qtutils.vbox(
defs.no_margin,
defs.no_spacing,
self.oid_label,
self.author_label,
self.date_label,
self.summary_label,
)
self.logo_layout = qtutils.hbox(
defs.no_margin, defs.button_spacing, self.gravatar_label, self.info_layout
)
self.logo_layout.setContentsMargins(defs.margin, 0, defs.margin, 0)
self.main_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.logo_layout, self.diff
)
self.setLayout(self.main_layout)
self.set_tabwidth(prefs.tabwidth(context))
def set_tabwidth(self, width):
self.diff.set_tabwidth(width)
def set_word_wrapping(self, enabled, update=False):
"""Enable and disable word wrapping"""
self.diff.set_word_wrapping(enabled, update=update)
def set_options(self, options):
"""Register an options widget"""
self.options = options
self.diff.set_options(options)
def start_diff_task(self, task):
"""Clear the display and start a diff-gathering task"""
self.diff.save_scrollbar()
self.diff.set_loading_message()
self.context.runtask.start(task, result=self.set_diff)
def set_diff_oid(self, oid, filename=None):
"""Set the diff from a single commit object ID"""
task = DiffInfoTask(self.context, oid, filename)
self.start_diff_task(task)
def set_diff_range(self, start, end, filename=None):
task = DiffRangeTask(self.context, start + '~', end, filename)
self.start_diff_task(task)
def commits_selected(self, commits):
"""Display an appropriate diff when commits are selected"""
if not commits:
self.clear()
return
commit = commits[-1]
oid = commit.oid
author = commit.author or ''
email = commit.email or ''
date = commit.authdate or ''
summary = commit.summary or ''
self.set_details(oid, author, email, date, summary)
self.oid = oid
if len(commits) > 1:
start, end = commits[0], commits[-1]
self.set_diff_range(start.oid, end.oid)
self.oid_start = start
self.oid_end = end
else:
self.set_diff_oid(oid)
self.oid_start = None
self.oid_end = None
def set_diff(self, diff):
"""Set the diff text"""
self.diff.set_diff(diff)
def set_details(self, oid, author, email, date, summary):
template_args = {'author': author, 'email': email, 'summary': summary}
author_text = (
"""%(author)s <"""
"""<a href="mailto:%(email)s">"""
"""%(email)s</a>>""" % template_args
)
author_template = '%(author)s <%(email)s>' % template_args
self.date_label.set_text(date)
self.date_label.setVisible(bool(date))
self.oid_label.set_oid(oid)
self.author_label.set_template(author_text, author_template)
self.summary_label.set_text(summary)
self.gravatar_label.set_email(email)
def clear(self):
self.date_label.set_text('')
self.oid_label.set_oid('')
self.author_label.set_text('')
self.summary_label.set_text('')
self.gravatar_label.clear()
self.diff.clear()
def files_selected(self, filenames):
"""Update the view when a filename is selected"""
oid_start = self.oid_start
oid_end = self.oid_end
extra_args = {}
if filenames:
extra_args['filename'] = filenames[0]
if oid_start and oid_end:
self.set_diff_range(oid_start.oid, oid_end.oid, **extra_args)
else:
self.set_diff_oid(self.oid, **extra_args)
class DiffPanel(QtWidgets.QWidget):
"""A combined diff + search panel"""
def __init__(self, diff_widget, text_widget, parent):
super().__init__(parent)
self.diff_widget = diff_widget
self.search_widget = TextSearchWidget(text_widget, self)
self.search_widget.hide()
layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.diff_widget, self.search_widget
)
self.setLayout(layout)
self.setFocusProxy(self.diff_widget)
self.search_action = qtutils.add_action(
self,
N_('Search in Diff'),
self.show_search,
hotkeys.SEARCH,
)
def show_search(self):
"""Show a dialog for searching diffs"""
# The diff search is only active in text mode.
if not self.search_widget.isVisible():
self.search_widget.show()
self.search_widget.setFocus()
class DiffInfoTask(qtutils.Task):
"""Gather diffs for a single commit"""
def __init__(self, context, oid, filename):
qtutils.Task.__init__(self)
self.context = context
self.oid = oid
self.filename = filename
def task(self):
context = self.context
oid = self.oid
return gitcmds.diff_info(context, oid, filename=self.filename)
class DiffRangeTask(qtutils.Task):
"""Gather diffs for a range of commits"""
def __init__(self, context, start, end, filename):
qtutils.Task.__init__(self)
self.context = context
self.start = start
self.end = end
self.filename = filename
def task(self):
context = self.context
return gitcmds.diff_range(context, self.start, self.end, filename=self.filename)
def apply_patches(context, patches=None):
"""Open the ApplyPatches dialog"""
parent = qtutils.active_window()
dlg = new_apply_patches(context, patches=patches, parent=parent)
dlg.show()
dlg.raise_()
return dlg
def new_apply_patches(context, patches=None, parent=None):
"""Create a new instances of the ApplyPatches dialog"""
dlg = ApplyPatches(context, parent=parent)
if patches:
dlg.add_paths(patches)
return dlg
def get_patches_from_paths(paths):
"""Returns all patches beneath a given path"""
paths = [core.decode(p) for p in paths]
patches = [p for p in paths if core.isfile(p) and p.endswith(('.patch', '.mbox'))]
dirs = [p for p in paths if core.isdir(p)]
dirs.sort()
for d in dirs:
patches.extend(get_patches_from_dir(d))
return patches
def get_patches_from_mimedata(mimedata):
"""Extract path files from a QMimeData payload"""
urls = mimedata.urls()
if not urls:
return []
paths = [x.path() for x in urls]
return get_patches_from_paths(paths)
def get_patches_from_dir(path):
"""Find patches in a subdirectory"""
patches = []
for root, _, files in core.walk(path):
for name in [f for f in files if f.endswith(('.patch', '.mbox'))]:
patches.append(core.decode(os.path.join(root, name)))
return patches
class ApplyPatches(standard.Dialog):
def __init__(self, context, parent=None):
super().__init__(parent=parent)
self.context = context
self.setWindowTitle(N_('Apply Patches'))
self.setAcceptDrops(True)
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.curdir = core.getcwd()
self.inner_drag = False
self.usage = QtWidgets.QLabel()
self.usage.setText(
N_(
"""
<p>
Drag and drop or use the <strong>Add</strong> button to add
patches to the list
</p>
"""
)
)
self.tree = PatchTreeWidget(parent=self)
self.tree.setHeaderHidden(True)
self.tree.itemSelectionChanged.connect(self._tree_selection_changed)
self.diffwidget = DiffWidget(context, self, is_commit=True)
self.add_button = qtutils.create_toolbutton(
text=N_('Add'), icon=icons.add(), tooltip=N_('Add patches (+)')
)
self.remove_button = qtutils.create_toolbutton(
text=N_('Remove'),
icon=icons.remove(),
tooltip=N_('Remove selected (Delete)'),
)
self.apply_button = qtutils.create_button(text=N_('Apply'), icon=icons.ok())
self.close_button = qtutils.close_button()
self.add_action = qtutils.add_action(
self, N_('Add'), self.add_files, hotkeys.ADD_ITEM
)
self.remove_action = qtutils.add_action(
self,
N_('Remove'),
self.tree.remove_selected,
hotkeys.DELETE,
hotkeys.BACKSPACE,
hotkeys.REMOVE_ITEM,
)
self.top_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.add_button,
self.remove_button,
qtutils.STRETCH,
self.usage,
)
self.bottom_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
qtutils.STRETCH,
self.close_button,
self.apply_button,
)
self.splitter = qtutils.splitter(Qt.Vertical, self.tree, self.diffwidget)
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.top_layout,
self.splitter,
self.bottom_layout,
)
self.setLayout(self.main_layout)
qtutils.connect_button(self.add_button, self.add_files)
qtutils.connect_button(self.remove_button, self.tree.remove_selected)
qtutils.connect_button(self.apply_button, self.apply_patches)
qtutils.connect_button(self.close_button, self.close)
self.init_state(None, self.resize, 720, 480)
def apply_patches(self):
items = self.tree.items()
if not items:
return
context = self.context
patches = [i.data(0, Qt.UserRole) for i in items]
cmds.do(cmds.ApplyPatches, context, patches)
self.accept()
def add_files(self):
files = qtutils.open_files(
N_('Select patch file(s)...'),
directory=self.curdir,
filters='Patches (*.patch *.mbox)',
)
if not files:
return
self.curdir = os.path.dirname(files[0])
self.add_paths([core.relpath(f) for f in files])
def dragEnterEvent(self, event):
"""Accepts drops if the mimedata contains patches"""
super().dragEnterEvent(event)
patches = get_patches_from_mimedata(event.mimeData())
if patches:
event.acceptProposedAction()
def dropEvent(self, event):
"""Add dropped patches"""
event.accept()
patches = get_patches_from_mimedata(event.mimeData())
if not patches:
return
self.add_paths(patches)
def add_paths(self, paths):
self.tree.add_paths(paths)
def _tree_selection_changed(self):
items = self.tree.selected_items()
if not items:
return
item = items[-1] # take the last item
path = item.data(0, Qt.UserRole)
if not core.exists(path):
return
commit = parse_patch(path)
self.diffwidget.set_details(
commit.oid, commit.author, commit.email, commit.date, commit.summary
)
self.diffwidget.set_diff(commit.diff)
def export_state(self):
"""Export persistent settings"""
state = super().export_state()
state['sizes'] = get(self.splitter)
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = super().apply_state(state)
try:
self.splitter.setSizes(state['sizes'])
except (AttributeError, KeyError, ValueError, TypeError):
pass
return result
class PatchTreeWidget(standard.DraggableTreeWidget):
def add_paths(self, paths):
patches = get_patches_from_paths(paths)
if not patches:
return
items = []
icon = icons.file_text()
for patch in patches:
item = QtWidgets.QTreeWidgetItem()
flags = item.flags() & ~Qt.ItemIsDropEnabled
item.setFlags(flags)
item.setIcon(0, icon)
item.setText(0, os.path.basename(patch))
item.setData(0, Qt.UserRole, patch)
item.setToolTip(0, patch)
items.append(item)
self.addTopLevelItems(items)
def remove_selected(self):
idxs = self.selectedIndexes()
rows = [idx.row() for idx in idxs]
for row in reversed(sorted(rows)):
self.invisibleRootItem().takeChild(row)
class Commit:
"""Container for commit details"""
def __init__(self):
self.content = ''
self.author = ''
self.email = ''
self.oid = ''
self.summary = ''
self.diff = ''
self.date = ''
def parse_patch(path):
content = core.read(path)
commit = Commit()
parse(content, commit)
return commit
def parse(content, commit):
"""Parse commit details from a patch"""
from_rgx = re.compile(r'^From (?P<oid>[a-f0-9]{40}) .*$')
author_rgx = re.compile(r'^From: (?P<author>[^<]+) <(?P<email>[^>]+)>$')
date_rgx = re.compile(r'^Date: (?P<date>.*)$')
subject_rgx = re.compile(r'^Subject: (?P<summary>.*)$')
commit.content = content
lines = content.splitlines()
for idx, line in enumerate(lines):
match = from_rgx.match(line)
if match:
commit.oid = match.group('oid')
continue
match = author_rgx.match(line)
if match:
commit.author = match.group('author')
commit.email = match.group('email')
continue
match = date_rgx.match(line)
if match:
commit.date = match.group('date')
continue
match = subject_rgx.match(line)
if match:
commit.summary = match.group('summary')
commit.diff = '\n'.join(lines[idx + 1 :])
break
| 68,723 | Python | .py | 1,652 | 31.533293 | 88 | 0.604794 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
109 | selectcommits.py | git-cola_git-cola/cola/widgets/selectcommits.py | """A GUI for selecting commits"""
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from .. import gitcmds
from .. import qtutils
from ..i18n import N_
from ..icons import folder
from ..interaction import Interaction
from ..models import prefs
from . import completion
from . import defs
from .diff import DiffTextEdit
from .standard import Dialog
def select_commits(context, title, revs, summaries, multiselect=True):
"""Use the SelectCommits to select commits from a list."""
model = Model(revs, summaries)
parent = qtutils.active_window()
dialog = SelectCommits(context, model, parent, title, multiselect=multiselect)
return dialog.select_commits()
def select_commits_and_output(context, title, revs, summaries, multiselect=True):
"""Select commits from a list and output path"""
model = Model(revs, summaries)
parent = qtutils.active_window()
dialog = SelectCommitsAndOutput(
context, model, parent, title, multiselect=multiselect
)
return dialog.select_commits_and_output()
class Model:
def __init__(self, revs, summaries):
self.revisions = revs
self.summaries = summaries
class SelectCommits(Dialog):
def __init__(self, context, model, parent=None, title=None, multiselect=True):
Dialog.__init__(self, parent)
self.context = context
self.model = model
if title:
self.setWindowTitle(title)
if multiselect:
mode = QtWidgets.QAbstractItemView.ExtendedSelection
else:
mode = QtWidgets.QAbstractItemView.SingleSelection
commits = self.commits = QtWidgets.QListWidget()
commits.setSelectionMode(mode)
commits.setAlternatingRowColors(True)
self.commit_text = DiffTextEdit(context, self, whitespace=False)
self.revision_label = QtWidgets.QLabel()
self.revision_label.setText(N_('Revision Expression:'))
self.revision = completion.GitRefLineEdit(context)
self.revision.setReadOnly(True)
self.search_label = QtWidgets.QLabel()
self.search_label.setText(N_('Search:'))
self.search = QtWidgets.QLineEdit()
self.search.setReadOnly(False)
self.search.textChanged.connect(self.search_list)
self.select_button = qtutils.ok_button(N_('Select'), enabled=False)
# Make the list widget slightly larger
self.splitter = qtutils.splitter(Qt.Vertical, self.commits, self.commit_text)
self.splitter.setSizes([100, 150])
self.input_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.search_label,
self.search,
qtutils.STRETCH,
self.revision_label,
self.revision,
self.select_button,
)
self.main_layout = qtutils.vbox(
defs.margin, defs.margin, self.input_layout, self.splitter
)
self.setLayout(self.main_layout)
commits.itemSelectionChanged.connect(self.commit_oid_selected)
commits.itemDoubleClicked.connect(self.commit_oid_double_clicked)
qtutils.connect_button(self.select_button, self.accept)
self.init_state(None, self.resize_widget, parent)
def resize_widget(self, parent):
"""Set the initial size of the widget"""
width, height = qtutils.default_size(parent, 720, 480)
self.resize(width, height)
def selected_commit(self):
return qtutils.selected_item(self.commits, self.model.revisions)
def selected_commits(self):
return qtutils.selected_items(self.commits, self.model.revisions)
def select_commits(self):
summaries = self.model.summaries
if not summaries:
msg = N_('No commits exist in this branch.')
Interaction.log(msg)
return []
qtutils.set_items(self.commits, summaries)
self.show()
if self.exec_() != QtWidgets.QDialog.Accepted:
return []
return self.selected_commits()
def commit_oid_selected(self):
context = self.context
oid = self.selected_commit()
selected = oid is not None
self.select_button.setEnabled(selected)
if not selected:
self.commit_text.set_value('')
self.revision.setText('')
return
self.revision.setText(oid)
self.revision.selectAll()
# Display the oid's commit
commit_diff = gitcmds.commit_diff(context, oid)
self.commit_text.setText(commit_diff)
def commit_oid_double_clicked(self, _item):
oid = self.selected_commit()
if oid:
self.accept()
def search_list(self, text):
if text:
for i in range(self.commits.count()):
self.commits.item(i).setHidden(True)
search_items = self.commits.findItems(text, Qt.MatchContains)
for items in search_items:
items.setHidden(False)
class SelectCommitsAndOutput(SelectCommits):
def __init__(self, context, model, parent=None, title=None, multiselect=True):
SelectCommits.__init__(self, context, model, parent, title, multiselect)
self.output_dir = prefs.patches_directory(context)
self.select_output = qtutils.create_button(
tooltip=N_('Select output dir'), icon=folder()
)
self.output_text = QtWidgets.QLineEdit()
self.output_text.setReadOnly(True)
self.output_text.setText(self.output_dir)
output_layout = qtutils.hbox(
defs.no_margin, defs.no_spacing, self.select_output, self.output_text
)
self.input_layout.insertLayout(1, output_layout)
qtutils.connect_button(self.select_output, self.show_output_dialog)
def select_commits_and_output(self):
to_export = SelectCommits.select_commits(self)
output = self.output_dir
return {'to_export': to_export, 'output': output}
def show_output_dialog(self):
self.output_dir = qtutils.opendir_dialog(
N_('Select output directory'), self.output_dir
)
if not self.output_dir:
return
self.output_text.setText(self.output_dir)
| 6,213 | Python | .py | 147 | 33.857143 | 85 | 0.663128 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
110 | remote.py | git-cola_git-cola/cola/widgets/remote.py | """Widgets for Fetch, Push, and Pull"""
import fnmatch
import time
import os
try:
import notifypy
except (ImportError, ModuleNotFoundError):
notifypy = None
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from ..i18n import N_
from ..interaction import Interaction
from ..models import main
from ..models import prefs
from ..models.main import FETCH, FETCH_HEAD, PULL, PUSH
from ..qtutils import connect_button
from ..qtutils import get
from .. import core
from .. import display
from .. import git
from .. import gitcmds
from .. import icons
from .. import resources
from .. import qtutils
from .. import utils
from . import defs
from . import log
from . import standard
def fetch(context):
"""Fetch from remote repositories"""
return run(context, Fetch)
def push(context):
"""Push to remote repositories"""
return run(context, Push)
def pull(context):
"""Pull from remote repositories"""
return run(context, Pull)
def run(context, RemoteDialog):
"""Launches fetch/push/pull dialogs."""
# Copy global stuff over to speedup startup
parent = qtutils.active_window()
view = RemoteDialog(context, parent=parent)
view.show()
return view
def combine(result, prev):
"""Combine multiple (status, out, err) tuples into a combined tuple
The current state is passed in via `prev`.
The status code is a max() over all the subprocess status codes.
Individual (out, err) strings are sequentially concatenated together.
"""
if isinstance(prev, (tuple, list)):
if len(prev) != 3:
raise AssertionError('combine() with length %d' % len(prev))
combined = (
max(prev[0], result[0]),
combine(prev[1], result[1]),
combine(prev[2], result[2]),
)
elif prev and result:
combined = prev + '\n\n' + result
elif prev:
combined = prev
else:
combined = result
return combined
def uncheck(value, *checkboxes):
"""Uncheck the specified checkboxes if value is True"""
if value:
for checkbox in checkboxes:
checkbox.setChecked(False)
def strip_remotes(remote_branches):
"""Strip the <remote>/ prefixes from branches
e.g. "origin/main" becomes "main".
"""
branches = [utils.strip_one(branch) for branch in remote_branches]
return [branch for branch in branches if branch != 'HEAD']
def get_default_remote(context):
"""Get the name of the default remote to use for pushing.
This will be the remote the branch is set to track, if it is set. If it
is not, remote.pushDefault will be used (or origin if not set)
"""
upstream_remote = gitcmds.upstream_remote(context)
return upstream_remote or context.cfg.get('remote.pushDefault', default='origin')
class ActionTask(qtutils.Task):
"""Run actions asynchronously"""
def __init__(self, model_action, remote, kwargs):
qtutils.Task.__init__(self)
self.model_action = model_action
self.remote = remote
self.kwargs = kwargs
def task(self):
"""Runs the model action and captures the result"""
return self.model_action(self.remote, **self.kwargs)
def _emit_push_notification(
context, selected_remotes, pushed_remotes, unpushed_remotes
):
"""Emit desktop notification when pushing remotes"""
total = len(selected_remotes)
count = len(pushed_remotes)
scope = {
'total': total,
'count': count,
}
title = N_('Pushed %(count)s / %(total)s remotes') % scope
pushed_message = N_('Pushed: %s') % ', '.join(pushed_remotes)
unpushed_message = N_('Not pushed: %s') % ', '.join(unpushed_remotes)
success_icon = resources.icon_path('git-cola-ok.svg')
error_icon = resources.icon_path('git-cola-error.svg')
if unpushed_remotes:
icon = error_icon
else:
icon = success_icon
if pushed_remotes and unpushed_remotes:
message = unpushed_message + '\t\t' + pushed_message
elif pushed_remotes:
message = pushed_message
else:
message = unpushed_message
display.notify(context.app_name, title, message, icon)
class RemoteActionDialog(standard.Dialog):
"""Interface for performing remote operations"""
def __init__(self, context, action, title, parent=None, icon=None):
"""Customize the dialog based on the remote action"""
standard.Dialog.__init__(self, parent=parent)
self.setWindowTitle(title)
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.context = context
self.model = model = context.model
self.action = action
self.filtered_remote_branches = []
self.selected_remotes = []
self.selected_remotes_by_worktree = {}
self.last_updated = 0.0
self.runtask = qtutils.RunTask(parent=self)
self.local_label = QtWidgets.QLabel()
self.local_label.setText(N_('Local Branch'))
self.local_branch = QtWidgets.QLineEdit()
self.local_branch.textChanged.connect(self.local_branch_text_changed)
local_branches = self.get_local_branches()
qtutils.add_completer(self.local_branch, local_branches)
self.local_branches = QtWidgets.QListWidget()
self.local_branches.addItems(local_branches)
self.remote_label = QtWidgets.QLabel()
self.remote_label.setText(N_('Remote'))
self.remote_name = QtWidgets.QLineEdit()
qtutils.add_completer(self.remote_name, model.remotes)
self.remote_name.editingFinished.connect(self.remote_name_edited)
self.remote_name.textEdited.connect(lambda _: self.remote_name_edited())
self.remotes = QtWidgets.QListWidget()
if action == PUSH:
mode = QtWidgets.QAbstractItemView.ExtendedSelection
self.remotes.setSelectionMode(mode)
self.remotes.addItems(model.remotes)
self.remote_branch_label = QtWidgets.QLabel()
self.remote_branch_label.setText(N_('Remote Branch'))
self.remote_branch = QtWidgets.QLineEdit()
self.remote_branch.textChanged.connect(lambda _: self.update_command_display())
remote_branches = strip_remotes(model.remote_branches)
qtutils.add_completer(self.remote_branch, remote_branches)
self.remote_branches = QtWidgets.QListWidget()
self.remote_branches.addItems(model.remote_branches)
text = N_('Prompt on creation')
tooltip = N_('Prompt when pushing creates new remote branches')
self.prompt_checkbox = qtutils.checkbox(
checked=True, text=text, tooltip=tooltip
)
text = N_('Show remote messages')
tooltip = N_('Display remote messages in a separate dialog')
self.remote_messages_checkbox = qtutils.checkbox(
checked=False, text=text, tooltip=tooltip
)
text = N_('Fast-forward only')
tooltip = N_(
'Refuse to merge unless the current HEAD is already up-'
'to-date or the merge can be resolved as a fast-forward'
)
self.ff_only_checkbox = qtutils.checkbox(
checked=True, text=text, tooltip=tooltip
)
self.ff_only_checkbox.toggled.connect(self.update_command_display)
text = N_('No fast-forward')
tooltip = N_(
'Create a merge commit even when the merge resolves as a fast-forward'
)
self.no_ff_checkbox = qtutils.checkbox(
checked=False, text=text, tooltip=tooltip
)
self.no_ff_checkbox.toggled.connect(self.update_command_display)
text = N_('Force')
tooltip = N_(
'Allow non-fast-forward updates. Using "force" can '
'cause the remote repository to lose commits; '
'use it with care'
)
self.force_checkbox = qtutils.checkbox(
checked=False, text=text, tooltip=tooltip
)
self.force_checkbox.toggled.connect(self.update_command_display)
self.tags_checkbox = qtutils.checkbox(text=N_('Include tags '))
self.tags_checkbox.toggled.connect(self.update_command_display)
tooltip = N_(
'Remove remote-tracking branches that no longer exist on the remote'
)
self.prune_checkbox = qtutils.checkbox(text=N_('Prune '), tooltip=tooltip)
self.prune_checkbox.toggled.connect(self.update_command_display)
tooltip = N_('Rebase the current branch instead of merging')
self.rebase_checkbox = qtutils.checkbox(text=N_('Rebase'), tooltip=tooltip)
self.rebase_checkbox.toggled.connect(self.update_command_display)
text = N_('Set upstream')
tooltip = N_('Configure the remote branch as the the new upstream')
self.upstream_checkbox = qtutils.checkbox(text=text, tooltip=tooltip)
self.upstream_checkbox.toggled.connect(self.update_command_display)
text = N_('Close on completion')
tooltip = N_('Close dialog when completed')
self.close_on_completion_checkbox = qtutils.checkbox(
checked=True, text=text, tooltip=tooltip
)
self.action_button = qtutils.ok_button(title, icon=icon)
self.close_button = qtutils.close_button()
self.buttons_group = utils.Group(self.close_button, self.action_button)
self.inputs_group = utils.Group(
self.close_on_completion_checkbox,
self.force_checkbox,
self.ff_only_checkbox,
self.local_branch,
self.local_branches,
self.tags_checkbox,
self.prune_checkbox,
self.rebase_checkbox,
self.remote_name,
self.remotes,
self.remote_branch,
self.remote_branches,
self.upstream_checkbox,
self.prompt_checkbox,
self.remote_messages_checkbox,
)
self.progress = standard.progress_bar(
self,
disable=(self.buttons_group, self.inputs_group),
)
self.command_display = log.LogWidget(self.context, display_usage=False)
self.local_branch_layout = qtutils.hbox(
defs.small_margin, defs.spacing, self.local_label, self.local_branch
)
self.remote_layout = qtutils.hbox(
defs.small_margin, defs.spacing, self.remote_label, self.remote_name
)
self.remote_branch_layout = qtutils.hbox(
defs.small_margin,
defs.spacing,
self.remote_branch_label,
self.remote_branch,
)
self.options_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.force_checkbox,
self.ff_only_checkbox,
self.no_ff_checkbox,
self.tags_checkbox,
self.prune_checkbox,
self.rebase_checkbox,
self.upstream_checkbox,
self.prompt_checkbox,
self.close_on_completion_checkbox,
self.remote_messages_checkbox,
qtutils.STRETCH,
self.progress,
self.close_button,
self.action_button,
)
self.remote_input_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.remote_layout, self.remotes
)
self.local_branch_input_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.local_branch_layout, self.local_branches
)
self.remote_branch_input_layout = qtutils.vbox(
defs.no_margin,
defs.spacing,
self.remote_branch_layout,
self.remote_branches,
)
if action == PUSH:
widgets = (
self.remote_input_layout,
self.local_branch_input_layout,
self.remote_branch_input_layout,
)
else: # fetch and pull
widgets = (
self.remote_input_layout,
self.remote_branch_input_layout,
self.local_branch_input_layout,
)
self.top_layout = qtutils.hbox(defs.no_margin, defs.spacing, *widgets)
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.top_layout,
self.command_display,
self.options_layout,
)
self.main_layout.setStretchFactor(self.top_layout, 2)
self.setLayout(self.main_layout)
default_remote = get_default_remote(context)
remotes = model.remotes
if default_remote in remotes:
idx = remotes.index(default_remote)
if self.select_remote(idx):
self.set_remote_name(default_remote)
else:
if self.select_first_remote():
self.set_remote_name(remotes[0])
# Trim the remote list to just the default remote
self.update_remotes(update_command_display=False)
# Setup signals and slots
self.remotes.itemSelectionChanged.connect(self.update_remotes)
local = self.local_branches
local.itemSelectionChanged.connect(self.update_local_branches)
remote = self.remote_branches
remote.itemSelectionChanged.connect(self.update_remote_branches)
self.no_ff_checkbox.toggled.connect(
lambda x: uncheck(x, self.ff_only_checkbox, self.rebase_checkbox)
)
self.ff_only_checkbox.toggled.connect(
lambda x: uncheck(x, self.no_ff_checkbox, self.rebase_checkbox)
)
self.rebase_checkbox.toggled.connect(
lambda x: uncheck(x, self.no_ff_checkbox, self.ff_only_checkbox)
)
connect_button(self.action_button, self.action_callback)
connect_button(self.close_button, self.close)
qtutils.add_action(
self, N_('Close'), self.close, QtGui.QKeySequence.Close, 'Esc'
)
if action != FETCH:
self.prune_checkbox.hide()
if action != PUSH:
# Push-only options
self.upstream_checkbox.hide()
self.prompt_checkbox.hide()
if action == PULL:
# Fetch and Push-only options
self.force_checkbox.hide()
self.tags_checkbox.hide()
self.local_label.hide()
self.local_branch.hide()
self.local_branches.hide()
else:
# Pull-only options
self.rebase_checkbox.hide()
self.no_ff_checkbox.hide()
self.ff_only_checkbox.hide()
self.init_size(parent=parent)
self.set_field_defaults()
def set_rebase(self, value):
"""Check the rebase checkbox"""
self.rebase_checkbox.setChecked(value)
def set_field_defaults(self):
"""Set sensible initial defaults"""
# Default to "git fetch origin main"
action = self.action
if action == FETCH:
self.set_local_branch('')
self.set_remote_branch('')
if action == PULL: # Nothing to do when fetching.
pass
# Select the current branch by default for push
if action == PUSH:
branch = self.model.currentbranch
try:
idx = self.model.local_branches.index(branch)
except ValueError:
return
self.select_local_branch(idx)
self.set_remote_branch(branch)
self.update_command_display()
def update_command_display(self):
"""Display the git commands that will be run"""
commands = ['']
for remote in self.selected_remotes:
cmd = ['git', self.action]
_, kwargs = self.common_args()
args, kwargs = main.remote_args(self.context, remote, self.action, **kwargs)
cmd.extend(git.transform_kwargs(**kwargs))
cmd.extend(args)
commands.append(core.list2cmdline(cmd))
self.command_display.set_output('\n'.join(commands))
def local_branch_text_changed(self, value):
"""Update the remote branch field in response to local branch text edits"""
if self.action == PUSH:
self.remote_branches.clearSelection()
self.set_remote_branch(value)
self.update_command_display()
def set_remote_name(self, remote_name):
"""Set the remote name"""
self.remote_name.setText(remote_name)
def set_local_branch(self, branch):
"""Set the local branch name"""
self.local_branch.setText(branch)
if branch:
self.local_branch.selectAll()
def set_remote_branch(self, branch):
"""Set the remote branch name"""
self.remote_branch.setText(branch)
if branch:
self.remote_branch.selectAll()
def set_remote_branches(self, branches):
"""Set the list of remote branches"""
self.remote_branches.clear()
self.remote_branches.addItems(branches)
self.filtered_remote_branches = branches
qtutils.add_completer(self.remote_branch, strip_remotes(branches))
def select_first_remote(self):
"""Select the first remote in the list view"""
return self.select_remote(0)
def select_remote(self, idx, make_current=True):
"""Select a remote by index"""
item = self.remotes.item(idx)
if item:
item.setSelected(True)
if make_current:
self.remotes.setCurrentItem(item)
self.set_remote_name(item.text())
result = True
else:
result = False
return result
def select_remote_by_name(self, remote, make_current=True):
"""Select a remote by name"""
remotes = self.model.remotes
if remote in remotes:
idx = remotes.index(remote)
result = self.select_remote(idx, make_current=make_current)
else:
result = False
return result
def set_selected_remotes(self, remotes):
"""Set the list of selected remotes
Return True if all remotes were found and selected.
"""
# Invalid remote names are ignored.
# This handles a remote going away between sessions.
# The selection is unchanged when none of the specified remotes exist.
found = False
for remote in remotes:
if remote in self.model.remotes:
found = True
break
if found:
# Only clear the selection if the specified remotes exist
self.remotes.clearSelection()
found = all(self.select_remote_by_name(x) for x in remotes)
return found
def select_local_branch(self, idx):
"""Selects a local branch by index in the list view"""
item = self.local_branches.item(idx)
if item:
item.setSelected(True)
self.local_branches.setCurrentItem(item)
self.set_local_branch(item.text())
result = True
else:
result = False
return result
def select_remote_branch(self, idx):
"""Selects a remote branch by index in the list view"""
item = self.remote_branches.item(idx)
if item:
item.setSelected(True)
self.remote_branches.setCurrentItem(item)
remote_branch = item.text()
branch = remote_branch.split('/', 1)[-1]
self.set_remote_branch(branch)
result = True
else:
result = False
return result
def display_remotes(self, widget):
"""Display the available remotes in a listwidget"""
displayed = []
for remote_name in self.model.remotes:
url = self.model.remote_url(remote_name, self.action)
display_text = '{}\t({})'.format(remote_name, N_('URL: %s') % url)
displayed.append(display_text)
qtutils.set_items(widget, displayed)
def update_remotes(self, update_command_display=True):
"""Update the remote name when a remote from the list is selected"""
widget = self.remotes
remotes = self.model.remotes
selection = qtutils.selected_item(widget, remotes)
if not selection:
self.selected_remotes = []
return
self.set_remote_name(selection)
self.selected_remotes = qtutils.selected_items(self.remotes, self.model.remotes)
self.set_remote_to(selection, self.selected_remotes)
worktree = self.context.git.worktree()
self.selected_remotes_by_worktree[worktree] = self.selected_remotes
if update_command_display:
self.update_command_display()
def set_remote_to(self, _remote, selected_remotes):
context = self.context
all_branches = gitcmds.branch_list(context, remote=True)
branches = []
patterns = []
remote = ''
for remote_name in selected_remotes:
remote = remote or remote_name # Use the first remote when prepopulating.
patterns.append(remote_name + '/*')
for branch in all_branches:
for pat in patterns:
if fnmatch.fnmatch(branch, pat):
branches.append(branch)
break
if branches:
self.set_remote_branches(branches)
else:
self.set_remote_branches(all_branches)
if self.action == FETCH:
self.set_remote_branch('')
elif self.action in (PUSH, PULL):
branch = ''
current_branch = (
self.local_branch.text() or self.context.model.currentbranch
)
remote_branch = f'{remote}/{current_branch}'
if branches and remote_branch in branches:
branch = current_branch
try:
idx = self.filtered_remote_branches.index(remote_branch)
except ValueError:
pass
self.select_remote_branch(idx)
return
self.set_remote_branch(branch)
def remote_name_edited(self):
"""Update the current remote when the remote name is typed manually"""
remote = self.remote_name.text()
self.update_selected_remotes(remote)
self.set_remote_to(remote, self.selected_remotes)
self.update_command_display()
def get_local_branches(self):
"""Calculate the list of local branches"""
if self.action == FETCH:
branches = self.model.local_branches + [FETCH_HEAD]
else:
branches = self.model.local_branches
return branches
def update_local_branches(self):
"""Update the local/remote branch names when a branch is selected"""
branches = self.get_local_branches()
widget = self.local_branches
selection = qtutils.selected_item(widget, branches)
if not selection:
return
self.set_local_branch(selection)
if self.action == FETCH and selection != FETCH_HEAD:
self.set_remote_branch(selection)
self.update_command_display()
def update_remote_branches(self):
"""Update the remote branch name when a branch is selected"""
widget = self.remote_branches
branches = self.filtered_remote_branches
selection = qtutils.selected_item(widget, branches)
if not selection:
return
branch = utils.strip_one(selection)
if branch == 'HEAD':
return
self.set_remote_branch(branch)
self.update_command_display()
def common_args(self):
"""Returns git arguments common to fetch/push/pull"""
remote_name = self.remote_name.text()
local_branch = self.local_branch.text()
remote_branch = self.remote_branch.text()
ff_only = get(self.ff_only_checkbox)
force = get(self.force_checkbox)
no_ff = get(self.no_ff_checkbox)
rebase = get(self.rebase_checkbox)
set_upstream = get(self.upstream_checkbox)
tags = get(self.tags_checkbox)
prune = get(self.prune_checkbox)
return (
remote_name,
{
'ff_only': ff_only,
'force': force,
'local_branch': local_branch,
'no_ff': no_ff,
'rebase': rebase,
'remote_branch': remote_branch,
'set_upstream': set_upstream,
'tags': tags,
'prune': prune,
},
)
# Actions
def push_to_all(self, _remote, *args, **kwargs):
"""Push to all selected remotes"""
selected_remotes = self.selected_remotes
all_results = None
pushed_remotes = []
unpushed_remotes = []
for remote in selected_remotes:
result = self.model.push(remote, *args, **kwargs)
if result[0] == 0:
pushed_remotes.append(remote)
else:
unpushed_remotes.append(remote)
all_results = combine(result, all_results)
if prefs.notify_on_push(self.context):
_emit_push_notification(
self.context, selected_remotes, pushed_remotes, unpushed_remotes
)
return all_results
def action_callback(self):
"""Perform the actual fetch/push/pull operation"""
action = self.action
remote_messages = get(self.remote_messages_checkbox)
if action == FETCH:
model_action = self.model.fetch
elif action == PUSH:
model_action = self.push_to_all
else: # if action == PULL:
model_action = self.model.pull
remote_name = self.remote_name.text()
if not remote_name:
errmsg = N_('No repository selected.')
Interaction.log(errmsg)
return
remote, kwargs = self.common_args()
self.update_selected_remotes(remote)
# Check if we're about to create a new branch and warn.
remote_branch = self.remote_branch.text()
local_branch = self.local_branch.text()
if action == PUSH and not remote_branch:
branch = local_branch
candidate = f'{remote}/{branch}'
prompt = get(self.prompt_checkbox)
if prompt and candidate not in self.model.remote_branches:
title = N_('Push')
args = {
'branch': branch,
'remote': remote,
}
msg = (
N_(
'Branch "%(branch)s" does not exist in "%(remote)s".\n'
'A new remote branch will be published.'
)
% args
)
info_txt = N_('Create a new remote branch?')
ok_text = N_('Create Remote Branch')
if not Interaction.confirm(
title, msg, info_txt, ok_text, icon=icons.cola()
):
return
if get(self.force_checkbox):
if action == FETCH:
title = N_('Force Fetch?')
msg = N_('Non-fast-forward fetch overwrites local history!')
info_txt = N_('Force fetching from %s?') % remote
ok_text = N_('Force Fetch')
elif action == PUSH:
title = N_('Force Push?')
msg = N_(
'Non-fast-forward push overwrites published '
'history!\n(Did you pull first?)'
)
info_txt = N_('Force push to %s?') % remote
ok_text = N_('Force Push')
else: # pull: shouldn't happen since the controls are hidden
return
if not Interaction.confirm(
title, msg, info_txt, ok_text, default=False, icon=icons.discard()
):
return
self.progress.setMaximumHeight(
self.action_button.height() - defs.small_margin * 2
)
# Use a thread to update in the background
task = ActionTask(model_action, remote, kwargs)
if remote_messages:
result = log.show_remote_messages(self, self.context)
else:
result = None
self.runtask.start(
task,
progress=self.progress,
finish=self.action_completed,
result=result,
)
def update_selected_remotes(self, remote):
"""Update the selected remotes when an ad-hoc remote is typed in"""
self.selected_remotes = qtutils.selected_items(self.remotes, self.model.remotes)
if remote not in self.selected_remotes:
self.selected_remotes = [remote]
worktree = self.context.git.worktree()
self.selected_remotes_by_worktree[worktree] = self.selected_remotes
def action_completed(self, task):
"""Grab the results of the action and finish up"""
if not task.result or not isinstance(task.result, (list, tuple)):
return
status, out, err = task.result
command = 'git %s' % self.action
message = Interaction.format_command_status(command, status)
details = Interaction.format_out_err(out, err)
log_message = message
if details:
log_message += '\n\n' + details
Interaction.log(log_message)
if status == 0:
close_on_completion = get(self.close_on_completion_checkbox)
if close_on_completion:
self.accept()
return
if self.action == PUSH:
message += '\n\n'
message += N_('Have you rebased/pulled lately?')
Interaction.critical(self.windowTitle(), message=message, details=details)
def export_state(self):
"""Export persistent settings"""
state = standard.Dialog.export_state(self)
state['close_on_completion'] = get(self.close_on_completion_checkbox)
state['remote_messages'] = get(self.remote_messages_checkbox)
state['selected_remotes'] = self.selected_remotes_by_worktree
state['last_updated'] = self.last_updated
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = standard.Dialog.apply_state(self, state)
# Restore the "close on completion" checkbox
close_on_completion = bool(state.get('close_on_completion', True))
self.close_on_completion_checkbox.setChecked(close_on_completion)
# Restore the "show remote messages" checkbox
remote_messages = bool(state.get('remote_messages', False))
self.remote_messages_checkbox.setChecked(remote_messages)
# Restore the selected remotes.
self.selected_remotes_by_worktree = state.get('selected_remotes', {})
self.last_updated = state.get('last_updated', 0.0)
current_time = time.time()
one_month = 60.0 * 60.0 * 24.0 * 31.0 # one month is ~31 days.
if (current_time - self.last_updated) > one_month:
self._prune_selected_remotes()
self.last_updated = current_time
# Selected remotes are stored per-worktree.
worktree = self.context.git.worktree()
selected_remotes = self.selected_remotes_by_worktree.get(worktree, [])
if selected_remotes:
# Restore the stored selection. We stash away the current selection so that
# we can restore it in case we are unable to apply the stored selection.
current_selection = self.remotes.selectedItems()
self.remotes.clearSelection()
selected = False
for idx, remote in enumerate(selected_remotes):
make_current = idx == 0 or not selected
if self.select_remote_by_name(remote, make_current=make_current):
selected = True
# Restore the original selection if nothing was selected.
if not selected:
for item in current_selection:
item.setSelected(True)
return result
def _prune_selected_remotes(self):
"""Prune stale worktrees from the persistent selected_remotes_by_worktree"""
worktrees = list(self.selected_remotes_by_worktree.keys())
for worktree in worktrees:
if not os.path.exists(worktree):
self.selected_remotes_by_worktree.pop(worktree, None)
# Use distinct classes so that each saves its own set of preferences
class Fetch(RemoteActionDialog):
"""Fetch from remote repositories"""
def __init__(self, context, parent=None):
super().__init__(context, FETCH, N_('Fetch'), parent=parent, icon=icons.repo())
def export_state(self):
"""Export persistent settings"""
state = RemoteActionDialog.export_state(self)
state['tags'] = get(self.tags_checkbox)
state['prune'] = get(self.prune_checkbox)
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = RemoteActionDialog.apply_state(self, state)
tags = bool(state.get('tags', False))
self.tags_checkbox.setChecked(tags)
prune = bool(state.get('prune', False))
self.prune_checkbox.setChecked(prune)
return result
class Push(RemoteActionDialog):
"""Push to remote repositories"""
def __init__(self, context, parent=None):
super().__init__(context, PUSH, N_('Push'), parent=parent, icon=icons.push())
def export_state(self):
"""Export persistent settings"""
state = RemoteActionDialog.export_state(self)
state['prompt'] = get(self.prompt_checkbox)
state['tags'] = get(self.tags_checkbox)
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = RemoteActionDialog.apply_state(self, state)
# Restore the "prompt on creation" checkbox
prompt = bool(state.get('prompt', True))
self.prompt_checkbox.setChecked(prompt)
# Restore the "tags" checkbox
tags = bool(state.get('tags', False))
self.tags_checkbox.setChecked(tags)
return result
class Pull(RemoteActionDialog):
"""Pull from remote repositories"""
def __init__(self, context, parent=None):
super().__init__(context, PULL, N_('Pull'), parent=parent, icon=icons.pull())
def apply_state(self, state):
"""Apply persistent settings"""
result = RemoteActionDialog.apply_state(self, state)
# Rebase has the highest priority
rebase = bool(state.get('rebase', False))
self.rebase_checkbox.setChecked(rebase)
ff_only = not rebase and bool(state.get('ff_only', False))
no_ff = not rebase and not ff_only and bool(state.get('no_ff', False))
self.no_ff_checkbox.setChecked(no_ff)
# Allow users coming from older versions that have rebase=False to
# pickup the new ff_only=True default by only setting ff_only False
# when it either exists in the config or when rebase=True.
if 'ff_only' in state or rebase:
self.ff_only_checkbox.setChecked(ff_only)
return result
def export_state(self):
"""Export persistent settings"""
state = RemoteActionDialog.export_state(self)
state['ff_only'] = get(self.ff_only_checkbox)
state['no_ff'] = get(self.no_ff_checkbox)
state['rebase'] = get(self.rebase_checkbox)
return state
| 35,646 | Python | .py | 841 | 32.268728 | 88 | 0.613391 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
111 | main.py | git-cola_git-cola/cola/widgets/main.py | """Main UI for authoring commits and other Git Cola interactions"""
import os
from functools import partial
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..compat import uchr
from ..compat import WIN32
from ..i18n import N_
from ..interaction import Interaction
from ..models import prefs
from ..qtutils import get
from .. import cmds
from .. import core
from .. import guicmds
from .. import git
from .. import gitcmds
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import resources
from .. import utils
from .. import version
from . import about
from . import action
from . import archive
from . import bookmarks
from . import branch
from . import submodules
from . import browse
from . import cfgactions
from . import clone
from . import commitmsg
from . import common
from . import compare
from . import createbranch
from . import createtag
from . import dag
from . import defs
from . import diff
from . import finder
from . import editremotes
from . import grep
from . import log
from . import merge
from . import prefs as prefs_widget
from . import recent
from . import remote
from . import search
from . import standard
from . import status
from . import stash
from . import toolbar
class MainView(standard.MainWindow):
config_actions_changed = Signal(object)
def __init__(self, context, parent=None):
standard.MainWindow.__init__(self, parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.context = context
self.git = context.git
self.dag = None
self.model = context.model
self.prefs_model = prefs_model = prefs.PreferencesModel(context)
self.toolbar_state = toolbar.ToolBarState(context, self)
# The widget version is used by import/export_state().
# Change this whenever dockwidgets are removed.
self.widget_version = 2
create_dock = qtutils.create_dock
cfg = context.cfg
self.browser_dockable = cfg.get('cola.browserdockable')
if self.browser_dockable:
browser = browse.worktree_browser(
context, parent=self, show=False, update=False
)
self.browserdock = create_dock(
'Browser', N_('Browser'), self, widget=browser
)
# "Actions" widget
self.actionswidget = action.ActionButtons(context, self)
self.actionsdock = create_dock(
'Actions', N_('Actions'), self, widget=self.actionswidget
)
qtutils.hide_dock(self.actionsdock)
# "Repository Status" widget
self.statusdock = create_dock(
'Status',
N_('Status'),
self,
func=lambda dock: status.StatusWidget(context, dock.titleBarWidget(), dock),
)
self.statuswidget = self.statusdock.widget()
# "Switch Repository" widgets
self.bookmarksdock = create_dock(
'Favorites',
N_('Favorites'),
self,
func=lambda dock: bookmarks.bookmark(context, dock),
)
bookmarkswidget = self.bookmarksdock.widget()
qtutils.hide_dock(self.bookmarksdock)
self.recentdock = create_dock(
'Recent',
N_('Recent'),
self,
func=lambda dock: bookmarks.recent(context, dock),
)
recentwidget = self.recentdock.widget()
qtutils.hide_dock(self.recentdock)
bookmarkswidget.connect_to(recentwidget)
# "Branch" widgets
self.branchdock = create_dock(
'Branches',
N_('Branches'),
self,
func=partial(branch.BranchesWidget, context),
)
self.branchwidget = self.branchdock.widget()
titlebar = self.branchdock.titleBarWidget()
titlebar.add_corner_widget(self.branchwidget.filter_button)
titlebar.add_corner_widget(self.branchwidget.sort_order_button)
# "Submodule" widgets
self.submodulesdock = create_dock(
'Submodules',
N_('Submodules'),
self,
func=partial(submodules.SubmodulesWidget, context),
)
self.submoduleswidget = self.submodulesdock.widget()
# "Commit Message Editor" widget
self.position_label = QtWidgets.QLabel()
self.position_label.setAlignment(Qt.AlignCenter)
font = qtutils.default_monospace_font()
font.setPointSize(int(font.pointSize() * 0.8))
self.position_label.setFont(font)
# make the position label fixed size to avoid layout issues
text_width = qtutils.text_width(font, '99:999')
width = text_width + defs.spacing
self.position_label.setMinimumWidth(width)
editor = commitmsg.CommitMessageEditor(context, self)
self.commiteditor = editor
self.commitdock = create_dock('Commit', N_('Commit'), self, widget=editor)
titlebar = self.commitdock.titleBarWidget()
titlebar.add_title_widget(self.commiteditor.commit_progress_bar)
titlebar.add_corner_widget(self.position_label)
# "Console" widget
self.logwidget = log.LogWidget(context)
self.logdock = create_dock(
'Console', N_('Console'), self, widget=self.logwidget
)
qtutils.hide_dock(self.logdock)
# "Diff Viewer" widget
self.diffdock = create_dock(
'Diff',
N_('Diff'),
self,
func=lambda dock: diff.Viewer(context, parent=dock),
)
self.diffviewer = self.diffdock.widget()
self.diffviewer.set_diff_type(self.model.diff_type)
self.diffviewer.enable_filename_tracking()
self.diffeditor = self.diffviewer.text
titlebar = self.diffdock.titleBarWidget()
titlebar.add_title_widget(self.diffviewer.filename)
titlebar.add_corner_widget(self.diffviewer.options)
# All Actions
add_action = qtutils.add_action
add_action_bool = qtutils.add_action_bool
self.commit_amend_action = add_action_bool(
self,
N_('Amend Last Commit'),
partial(cmds.do, cmds.AmendMode, context),
False,
)
self.commit_amend_action.setIcon(icons.edit())
self.commit_amend_action.setShortcuts(hotkeys.AMEND)
self.commit_amend_action.setShortcutContext(Qt.WidgetShortcut)
# Make Cmd-M minimize the window on macOS.
if utils.is_darwin():
self.minimize_action = add_action(
self, N_('Minimize Window'), self.showMinimized, hotkeys.MACOS_MINIMIZE
)
self.unstage_all_action = add_action(
self, N_('Unstage All'), cmds.run(cmds.UnstageAll, context)
)
self.unstage_all_action.setIcon(icons.remove())
self.undo_commit_action = add_action(
self, N_('Undo Last Commit'), cmds.run(cmds.UndoLastCommit, context)
)
self.undo_commit_action.setIcon(icons.style_dialog_discard())
self.unstage_selected_action = add_action(
self, N_('Unstage'), cmds.run(cmds.UnstageSelected, context)
)
self.unstage_selected_action.setIcon(icons.remove())
self.show_diffstat_action = add_action(
self, N_('Diffstat'), self.statuswidget.select_header, hotkeys.DIFFSTAT
)
self.show_diffstat_action.setIcon(icons.diff())
self.stage_modified_action = add_action(
self,
cmds.StageModified.name(),
cmds.run(cmds.StageModified, context),
hotkeys.STAGE_MODIFIED,
)
self.stage_modified_action.setIcon(icons.add())
self.stage_untracked_action = add_action(
self,
cmds.StageUntracked.name(),
cmds.run(cmds.StageUntracked, context),
hotkeys.STAGE_UNTRACKED,
)
self.stage_untracked_action.setIcon(icons.add())
self.apply_patches_action = add_action(
self, N_('Apply Patches...'), partial(diff.apply_patches, context)
)
self.apply_patches_action.setIcon(icons.diff())
self.apply_patches_abort_action = qtutils.add_action_with_tooltip(
self,
N_('Abort Applying Patches...'),
N_('Abort the current "git am" patch session'),
cmds.run(cmds.AbortApplyPatch, context),
)
self.apply_patches_abort_action.setIcon(icons.style_dialog_discard())
self.apply_patches_continue_action = qtutils.add_action_with_tooltip(
self,
N_('Continue Applying Patches'),
N_('Commit the current state and continue applying patches'),
cmds.run(cmds.ApplyPatchesContinue, context),
)
self.apply_patches_continue_action.setIcon(icons.commit())
self.apply_patches_skip_action = qtutils.add_action_with_tooltip(
self,
N_('Skip Current Patch'),
N_('Skip applying the current patch and continue applying patches'),
cmds.run(cmds.ApplyPatchesContinue, context),
)
self.apply_patches_skip_action.setIcon(icons.discard())
self.export_patches_action = add_action(
self,
N_('Export Patches...'),
partial(guicmds.export_patches, context),
hotkeys.EXPORT,
)
self.export_patches_action.setIcon(icons.save())
self.new_repository_action = add_action(
self, N_('New Repository...'), partial(guicmds.open_new_repo, context)
)
self.new_repository_action.setIcon(icons.new())
self.new_bare_repository_action = add_action(
self, N_('New Bare Repository...'), partial(guicmds.new_bare_repo, context)
)
self.new_bare_repository_action.setIcon(icons.new())
prefs_func = partial(
prefs_widget.preferences, context, parent=self, model=prefs_model
)
self.preferences_action = add_action(
self, N_('Preferences'), prefs_func, QtGui.QKeySequence.Preferences
)
self.preferences_action.setIcon(icons.configure())
self.edit_remotes_action = add_action(
self, N_('Edit Remotes...'), partial(editremotes.editor, context)
)
self.edit_remotes_action.setIcon(icons.edit())
self.rescan_action = add_action(
self,
cmds.Refresh.name(),
cmds.run(cmds.Refresh, context),
*hotkeys.REFRESH_HOTKEYS,
)
self.rescan_action.setIcon(icons.sync())
self.find_files_action = add_action(
self,
N_('Find Files'),
partial(finder.finder, context),
hotkeys.FINDER,
)
self.find_files_action.setIcon(icons.search())
self.browse_recently_modified_action = add_action(
self,
N_('Recently Modified Files...'),
partial(recent.browse_recent_files, context),
hotkeys.EDIT_SECONDARY,
)
self.browse_recently_modified_action.setIcon(icons.directory())
self.cherry_pick_action = add_action(
self,
N_('Cherry-Pick...'),
partial(guicmds.cherry_pick, context),
hotkeys.CHERRY_PICK,
)
self.cherry_pick_action.setIcon(icons.cherry_pick())
self.cherry_pick_abort_action = add_action(
self, N_('Abort Cherry-Pick...'), cmds.run(cmds.AbortCherryPick, context)
)
self.cherry_pick_abort_action.setIcon(icons.style_dialog_discard())
self.load_commitmsg_action = add_action(
self, N_('Load Commit Message...'), partial(guicmds.load_commitmsg, context)
)
self.load_commitmsg_action.setIcon(icons.file_text())
self.prepare_commitmsg_hook_action = add_action(
self,
N_('Prepare Commit Message'),
cmds.run(cmds.PrepareCommitMessageHook, context),
hotkeys.PREPARE_COMMIT_MESSAGE,
)
self.save_tarball_action = add_action(
self, N_('Save As Tarball/Zip...'), partial(archive.save_archive, context)
)
self.save_tarball_action.setIcon(icons.file_zip())
self.quit_action = add_action(self, N_('Quit'), self.close, hotkeys.QUIT)
self.grep_action = add_action(
self, N_('Grep'), partial(grep.grep, context), hotkeys.GREP
)
self.grep_action.setIcon(icons.search())
self.merge_local_action = add_action(
self, N_('Merge...'), partial(merge.local_merge, context), hotkeys.MERGE
)
self.merge_local_action.setIcon(icons.merge())
self.merge_abort_action = add_action(
self, N_('Abort Merge...'), cmds.run(cmds.AbortMerge, context)
)
self.merge_abort_action.setIcon(icons.style_dialog_discard())
self.update_submodules_action = add_action(
self,
N_('Update All Submodules...'),
cmds.run(cmds.SubmodulesUpdate, context),
)
self.update_submodules_action.setIcon(icons.sync())
self.add_submodule_action = add_action(
self,
N_('Add Submodule...'),
partial(submodules.add_submodule, context, parent=self),
)
self.add_submodule_action.setIcon(icons.add())
self.fetch_action = qtutils.add_action_with_tooltip(
self,
N_('Fetch...'),
N_('Fetch from one or more remotes using "git fetch"'),
partial(remote.fetch, context),
hotkeys.FETCH,
)
self.fetch_action.setIcon(icons.download())
self.push_action = qtutils.add_action_with_tooltip(
self,
N_('Push...'),
N_('Push to one or more remotes using "git push"'),
partial(remote.push, context),
hotkeys.PUSH,
)
self.push_action.setIcon(icons.push())
self.pull_action = qtutils.add_action_with_tooltip(
self,
N_('Pull...'),
N_('Integrate changes using "git pull"'),
partial(remote.pull, context),
hotkeys.PULL,
)
self.pull_action.setIcon(icons.pull())
self.open_repo_action = add_action(
self, N_('Open...'), partial(guicmds.open_repo, context), hotkeys.OPEN
)
self.open_repo_action.setIcon(icons.folder())
self.open_repo_new_action = add_action(
self,
N_('Open in New Window...'),
partial(guicmds.open_repo_in_new_window, context),
)
self.open_repo_new_action.setIcon(icons.folder())
self.stash_action = qtutils.add_action_with_tooltip(
self,
N_('Stash...'),
N_('Temporarily stash away uncommitted changes using "git stash"'),
partial(stash.view, context),
hotkeys.STASH,
)
self.stash_action.setIcon(icons.commit())
self.reset_soft_action = qtutils.add_action_with_tooltip(
self,
N_('Reset Branch (Soft)'),
cmds.ResetSoft.tooltip('<commit>'),
partial(guicmds.reset_soft, context),
)
self.reset_soft_action.setIcon(icons.style_dialog_reset())
self.reset_mixed_action = qtutils.add_action_with_tooltip(
self,
N_('Reset Branch and Stage (Mixed)'),
cmds.ResetMixed.tooltip('<commit>'),
partial(guicmds.reset_mixed, context),
)
self.reset_mixed_action.setIcon(icons.style_dialog_reset())
self.reset_keep_action = qtutils.add_action_with_tooltip(
self,
N_('Restore Worktree and Reset All (Keep Unstaged Changes)'),
cmds.ResetKeep.tooltip('<commit>'),
partial(guicmds.reset_keep, context),
)
self.reset_keep_action.setIcon(icons.style_dialog_reset())
self.reset_merge_action = qtutils.add_action_with_tooltip(
self,
N_('Restore Worktree and Reset All (Merge)'),
cmds.ResetMerge.tooltip('<commit>'),
partial(guicmds.reset_merge, context),
)
self.reset_merge_action.setIcon(icons.style_dialog_reset())
self.reset_hard_action = qtutils.add_action_with_tooltip(
self,
N_('Restore Worktree and Reset All (Hard)'),
cmds.ResetHard.tooltip('<commit>'),
partial(guicmds.reset_hard, context),
)
self.reset_hard_action.setIcon(icons.style_dialog_reset())
self.restore_worktree_action = qtutils.add_action_with_tooltip(
self,
N_('Restore Worktree'),
cmds.RestoreWorktree.tooltip('<commit>'),
partial(guicmds.restore_worktree, context),
)
self.restore_worktree_action.setIcon(icons.edit())
self.clone_repo_action = add_action(
self, N_('Clone...'), partial(clone.clone, context)
)
self.clone_repo_action.setIcon(icons.repo())
self.help_docs_action = add_action(
self,
N_('Documentation'),
resources.show_html_docs,
QtGui.QKeySequence.HelpContents,
)
self.help_shortcuts_action = add_action(
self, N_('Keyboard Shortcuts'), about.show_shortcuts, hotkeys.QUESTION
)
self.visualize_current_action = add_action(
self,
N_('Visualize Current Branch...'),
cmds.run(cmds.VisualizeCurrent, context),
)
self.visualize_current_action.setIcon(icons.visualize())
self.visualize_all_action = add_action(
self, N_('Visualize All Branches...'), cmds.run(cmds.VisualizeAll, context)
)
self.visualize_all_action.setIcon(icons.visualize())
self.search_commits_action = add_action(
self, N_('Search...'), partial(search.search, context)
)
self.search_commits_action.setIcon(icons.search())
self.browse_branch_action = add_action(
self,
N_('Browse Current Branch...'),
partial(guicmds.browse_current, context),
)
self.browse_branch_action.setIcon(icons.directory())
self.browse_other_branch_action = add_action(
self, N_('Browse Other Branch...'), partial(guicmds.browse_other, context)
)
self.browse_other_branch_action.setIcon(icons.directory())
self.load_commitmsg_template_action = add_action(
self,
N_('Get Commit Message Template'),
cmds.run(cmds.LoadCommitMessageFromTemplate, context),
)
self.load_commitmsg_template_action.setIcon(icons.style_dialog_apply())
self.help_about_action = add_action(
self, N_('About'), partial(about.about_dialog, context)
)
self.diff_against_commit_action = add_action(
self,
N_('Against Commit... (Diff Mode)'),
partial(guicmds.diff_against_commit, context),
)
self.diff_against_commit_action.setIcon(icons.compare())
self.exit_diff_mode_action = add_action(
self, N_('Exit Diff Mode'), cmds.run(cmds.ResetMode, context)
)
self.exit_diff_mode_action.setIcon(icons.compare())
self.diff_expression_action = add_action(
self, N_('Expression...'), partial(guicmds.diff_expression, context)
)
self.diff_expression_action.setIcon(icons.compare())
self.branch_compare_action = add_action(
self, N_('Branches...'), partial(compare.compare_branches, context)
)
self.branch_compare_action.setIcon(icons.compare())
self.create_tag_action = add_action(
self,
N_('Create Tag...'),
partial(createtag.create_tag, context),
)
self.create_tag_action.setIcon(icons.tag())
self.create_branch_action = add_action(
self,
N_('Create...'),
partial(createbranch.create_new_branch, context),
hotkeys.BRANCH,
)
self.create_branch_action.setIcon(icons.branch())
self.delete_branch_action = add_action(
self, N_('Delete...'), partial(guicmds.delete_branch, context)
)
self.delete_branch_action.setIcon(icons.discard())
self.delete_remote_branch_action = add_action(
self,
N_('Delete Remote Branch...'),
partial(guicmds.delete_remote_branch, context),
)
self.delete_remote_branch_action.setIcon(icons.discard())
self.rename_branch_action = add_action(
self, N_('Rename Branch...'), partial(guicmds.rename_branch, context)
)
self.rename_branch_action.setIcon(icons.edit())
self.checkout_branch_action = add_action(
self,
N_('Checkout...'),
partial(guicmds.checkout_branch, context),
hotkeys.CHECKOUT,
)
self.checkout_branch_action.setIcon(icons.branch())
self.branch_review_action = add_action(
self, N_('Review...'), partial(guicmds.review_branch, context)
)
self.branch_review_action.setIcon(icons.compare())
self.browse_action = add_action(
self, N_('File Browser...'), partial(browse.worktree_browser, context)
)
self.browse_action.setIcon(icons.cola())
self.dag_action = add_action(self, N_('DAG...'), self.git_dag)
self.dag_action.setIcon(icons.cola())
self.rebase_start_action = add_action(
self,
N_('Start Interactive Rebase...'),
cmds.run(cmds.Rebase, context),
hotkeys.REBASE_START_AND_CONTINUE,
)
self.rebase_start_action.setIcon(icons.play())
self.rebase_edit_todo_action = add_action(
self, N_('Edit...'), cmds.run(cmds.RebaseEditTodo, context)
)
self.rebase_edit_todo_action.setIcon(icons.edit())
self.rebase_continue_action = add_action(
self,
N_('Continue'),
cmds.run(cmds.RebaseContinue, context),
hotkeys.REBASE_START_AND_CONTINUE,
)
self.rebase_continue_action.setIcon(icons.play())
self.rebase_skip_action = add_action(
self, N_('Skip Current Patch'), cmds.run(cmds.RebaseSkip, context)
)
self.rebase_skip_action.setIcon(icons.delete())
self.rebase_abort_action = add_action(
self, N_('Abort'), cmds.run(cmds.RebaseAbort, context)
)
self.rebase_abort_action.setIcon(icons.close())
# For "Start Rebase" only, reverse the first argument to setEnabled()
# so that we can operate on it as a group.
# We can do this because can_rebase == not is_rebasing
self.rebase_start_action_proxy = utils.Proxy(
self.rebase_start_action,
setEnabled=lambda x: self.rebase_start_action.setEnabled(not x),
)
self.rebase_group = utils.Group(
self.rebase_start_action_proxy,
self.rebase_edit_todo_action,
self.rebase_continue_action,
self.rebase_skip_action,
self.rebase_abort_action,
)
self.annex_init_action = qtutils.add_action(
self, N_('Initialize Git Annex'), cmds.run(cmds.AnnexInit, context)
)
self.lfs_init_action = qtutils.add_action(
self, N_('Initialize Git LFS'), cmds.run(cmds.LFSInstall, context)
)
self.lock_layout_action = add_action_bool(
self, N_('Lock Layout'), self.set_lock_layout, False
)
self.reset_layout_action = add_action(
self, N_('Reset Layout'), self.reset_layout
)
self.quick_repository_search = add_action(
self,
N_('Quick Open...'),
lambda: guicmds.open_quick_repo_search(self.context, parent=self),
hotkeys.OPEN_REPO_SEARCH,
)
self.quick_repository_search.setIcon(icons.search())
self.terminal_action = common.terminal_action(
context, self, hotkey=hotkeys.TERMINAL
)
# Create the application menu
self.menubar = QtWidgets.QMenuBar(self)
self.setMenuBar(self.menubar)
# File Menu
add_menu = qtutils.add_menu
self.file_menu = add_menu(N_('&File'), self.menubar)
self.file_menu.addAction(self.quick_repository_search)
# File->Open Recent menu
self.open_recent_menu = self.file_menu.addMenu(N_('Open Recent'))
self.open_recent_menu.setIcon(icons.folder())
self.file_menu.addAction(self.open_repo_action)
self.file_menu.addAction(self.open_repo_new_action)
self.file_menu.addSeparator()
self.file_menu.addAction(self.new_repository_action)
self.file_menu.addAction(self.new_bare_repository_action)
self.file_menu.addAction(self.clone_repo_action)
self.file_menu.addSeparator()
self.file_menu.addAction(self.rescan_action)
self.file_menu.addAction(self.find_files_action)
self.file_menu.addAction(self.edit_remotes_action)
self.file_menu.addAction(self.browse_recently_modified_action)
self.file_menu.addSeparator()
self.file_menu.addAction(self.save_tarball_action)
self.patches_menu = self.file_menu.addMenu(N_('Patches'))
self.patches_menu.setIcon(icons.diff())
self.patches_menu.addAction(self.export_patches_action)
self.patches_menu.addAction(self.apply_patches_action)
self.patches_menu.addAction(self.apply_patches_continue_action)
self.patches_menu.addAction(self.apply_patches_skip_action)
self.patches_menu.addAction(self.apply_patches_abort_action)
# Git Annex / Git LFS
annex = core.find_executable('git-annex')
lfs = core.find_executable('git-lfs')
if annex or lfs:
self.file_menu.addSeparator()
if annex:
self.file_menu.addAction(self.annex_init_action)
if lfs:
self.file_menu.addAction(self.lfs_init_action)
self.file_menu.addSeparator()
self.file_menu.addAction(self.preferences_action)
self.file_menu.addAction(self.quit_action)
# Edit Menu
self.edit_proxy = edit_proxy = FocusProxy(
editor, editor.summary, editor.description
)
copy_widgets = (
self,
editor.summary,
editor.description,
self.diffeditor,
bookmarkswidget.tree,
recentwidget.tree,
)
select_widgets = copy_widgets + (self.statuswidget.tree,)
edit_proxy.override('copy', copy_widgets)
edit_proxy.override('selectAll', select_widgets)
edit_menu = self.edit_menu = add_menu(N_('&Edit'), self.menubar)
undo = add_action(edit_menu, N_('Undo'), edit_proxy.undo, hotkeys.UNDO)
undo.setIcon(icons.undo())
redo = add_action(edit_menu, N_('Redo'), edit_proxy.redo, hotkeys.REDO)
redo.setIcon(icons.redo())
edit_menu.addSeparator()
cut = add_action(edit_menu, N_('Cut'), edit_proxy.cut, hotkeys.CUT)
cut.setIcon(icons.cut())
copy = add_action(edit_menu, N_('Copy'), edit_proxy.copy, hotkeys.COPY)
copy.setIcon(icons.copy())
paste = add_action(edit_menu, N_('Paste'), edit_proxy.paste, hotkeys.PASTE)
paste.setIcon(icons.paste())
delete = add_action(edit_menu, N_('Delete'), edit_proxy.delete, hotkeys.DELETE)
delete.setIcon(icons.delete())
edit_menu.addSeparator()
select_all = add_action(
edit_menu, N_('Select All'), edit_proxy.selectAll, hotkeys.SELECT_ALL
)
select_all.setIcon(icons.select_all())
edit_menu.addSeparator()
qtutils.add_menu_actions(edit_menu, self.commiteditor.menu_actions)
# Actions menu
self.actions_menu = add_menu(N_('Actions'), self.menubar)
if self.terminal_action is not None:
self.actions_menu.addAction(self.terminal_action)
self.actions_menu.addAction(self.fetch_action)
self.actions_menu.addAction(self.push_action)
self.actions_menu.addAction(self.pull_action)
self.actions_menu.addAction(self.stash_action)
self.actions_menu.addSeparator()
self.actions_menu.addAction(self.create_tag_action)
self.actions_menu.addAction(self.cherry_pick_action)
self.actions_menu.addAction(self.cherry_pick_abort_action)
self.actions_menu.addAction(self.merge_local_action)
self.actions_menu.addAction(self.merge_abort_action)
self.actions_menu.addSeparator()
self.actions_menu.addAction(self.update_submodules_action)
self.actions_menu.addAction(self.add_submodule_action)
self.actions_menu.addSeparator()
self.actions_menu.addAction(self.grep_action)
self.actions_menu.addAction(self.search_commits_action)
# Commit Menu
self.commit_menu = add_menu(N_('Commit@@verb'), self.menubar)
self.commit_menu.setTitle(N_('Commit@@verb'))
self.commit_menu.addAction(self.commiteditor.commit_action)
self.commit_menu.addAction(self.commit_amend_action)
self.commit_menu.addAction(self.undo_commit_action)
self.commit_menu.addSeparator()
self.commit_menu.addAction(self.statuswidget.tree.process_selection_action)
self.commit_menu.addAction(self.statuswidget.tree.stage_or_unstage_all_action)
self.commit_menu.addAction(self.stage_modified_action)
self.commit_menu.addAction(self.stage_untracked_action)
self.commit_menu.addSeparator()
self.commit_menu.addAction(self.unstage_all_action)
self.commit_menu.addAction(self.unstage_selected_action)
self.commit_menu.addSeparator()
self.commit_menu.addAction(self.load_commitmsg_action)
self.commit_menu.addAction(self.load_commitmsg_template_action)
self.commit_menu.addAction(self.prepare_commitmsg_hook_action)
# Diff Menu
self.diff_menu = add_menu(N_('Diff'), self.menubar)
self.diff_menu.addAction(self.diff_expression_action)
self.diff_menu.addAction(self.branch_compare_action)
self.diff_menu.addAction(self.show_diffstat_action)
self.diff_menu.addSeparator()
self.diff_menu.addAction(self.diff_against_commit_action)
self.diff_menu.addAction(self.exit_diff_mode_action)
# Branch Menu
self.branch_menu = add_menu(N_('Branch'), self.menubar)
self.branch_menu.addAction(self.branch_review_action)
self.branch_menu.addSeparator()
self.branch_menu.addAction(self.create_branch_action)
self.branch_menu.addAction(self.checkout_branch_action)
self.branch_menu.addAction(self.delete_branch_action)
self.branch_menu.addAction(self.delete_remote_branch_action)
self.branch_menu.addAction(self.rename_branch_action)
self.branch_menu.addSeparator()
self.branch_menu.addAction(self.browse_branch_action)
self.branch_menu.addAction(self.browse_other_branch_action)
self.branch_menu.addSeparator()
self.branch_menu.addAction(self.visualize_current_action)
self.branch_menu.addAction(self.visualize_all_action)
# Rebase menu
self.rebase_menu = add_menu(N_('Rebase'), self.menubar)
self.rebase_menu.addAction(self.rebase_start_action)
self.rebase_menu.addAction(self.rebase_edit_todo_action)
self.rebase_menu.addSeparator()
self.rebase_menu.addAction(self.rebase_continue_action)
self.rebase_menu.addAction(self.rebase_skip_action)
self.rebase_menu.addSeparator()
self.rebase_menu.addAction(self.rebase_abort_action)
# Reset menu
self.reset_menu = add_menu(N_('Reset'), self.menubar)
self.reset_menu.addAction(self.unstage_all_action)
self.reset_menu.addAction(self.undo_commit_action)
self.reset_menu.addSeparator()
self.reset_menu.addAction(self.reset_soft_action)
self.reset_menu.addAction(self.reset_mixed_action)
self.reset_menu.addAction(self.restore_worktree_action)
self.reset_menu.addSeparator()
self.reset_menu.addAction(self.reset_keep_action)
self.reset_menu.addAction(self.reset_merge_action)
self.reset_menu.addAction(self.reset_hard_action)
# View Menu
self.view_menu = add_menu(N_('View'), self.menubar)
self.view_menu.aboutToShow.connect(lambda: self.build_view_menu(self.view_menu))
self.setup_dockwidget_view_menu()
if utils.is_darwin():
# The native macOS menu doesn't show empty entries.
self.build_view_menu(self.view_menu)
# Help Menu
self.help_menu = add_menu(N_('Help'), self.menubar)
self.help_menu.addAction(self.help_docs_action)
self.help_menu.addAction(self.help_shortcuts_action)
self.help_menu.addAction(self.help_about_action)
# Arrange dock widgets
bottom = Qt.BottomDockWidgetArea
top = Qt.TopDockWidgetArea
self.addDockWidget(top, self.statusdock)
self.addDockWidget(top, self.commitdock)
if self.browser_dockable:
self.addDockWidget(top, self.browserdock)
self.tabifyDockWidget(self.browserdock, self.commitdock)
self.addDockWidget(top, self.branchdock)
self.addDockWidget(top, self.submodulesdock)
self.addDockWidget(top, self.bookmarksdock)
self.addDockWidget(top, self.recentdock)
self.tabifyDockWidget(self.branchdock, self.submodulesdock)
self.tabifyDockWidget(self.submodulesdock, self.bookmarksdock)
self.tabifyDockWidget(self.bookmarksdock, self.recentdock)
self.branchdock.raise_()
self.addDockWidget(bottom, self.diffdock)
self.addDockWidget(bottom, self.actionsdock)
self.addDockWidget(bottom, self.logdock)
self.tabifyDockWidget(self.actionsdock, self.logdock)
# Listen for model notifications
self.model.updated.connect(self.refresh, type=Qt.QueuedConnection)
self.model.mode_changed.connect(
lambda mode: self.refresh(), type=Qt.QueuedConnection
)
prefs_model.config_updated.connect(self._config_updated)
# Set a default value
self.show_cursor_position(1, 0)
self.commit_menu.aboutToShow.connect(self.update_menu_actions)
self.open_recent_menu.aboutToShow.connect(self.build_recent_menu)
self.commiteditor.cursor_changed.connect(self.show_cursor_position)
self.diffeditor.options_changed.connect(self.statuswidget.refresh)
self.diffeditor.up.connect(self.statuswidget.move_up)
self.diffeditor.down.connect(self.statuswidget.move_down)
self.commiteditor.up.connect(self.statuswidget.move_up)
self.commiteditor.down.connect(self.statuswidget.move_down)
self.config_actions_changed.connect(
lambda names_and_shortcuts: _install_config_actions(
context,
self.actions_menu,
names_and_shortcuts,
),
type=Qt.QueuedConnection,
)
self.init_state(context.settings, self.set_initial_size)
# Route command output here
Interaction.log_status = self.logwidget.log_status
Interaction.log = self.logwidget.log
# Focus the status widget; this must be deferred
QtCore.QTimer.singleShot(0, self.initialize)
def initialize(self):
context = self.context
git_version = version.git_version_str(context)
if git_version:
ok = True
Interaction.log(
git_version + '\n' + N_('git cola version %s') % version.version()
)
else:
ok = False
error_msg = N_('error: unable to execute git')
Interaction.log(error_msg)
if ok:
self.statuswidget.setFocus()
else:
title = N_('error: unable to execute git')
msg = title
details = ''
if WIN32:
details = git.win32_git_error_hint()
Interaction.critical(title, message=msg, details=details)
self.context.app.exit(2)
def set_initial_size(self):
# Default size; this is thrown out when save/restore is used
width, height = qtutils.desktop_size()
self.resize((width * 3) // 4, height)
self.statuswidget.set_initial_size()
self.commiteditor.set_initial_size()
def set_filter(self, txt):
self.statuswidget.set_filter(txt)
# Qt overrides
def closeEvent(self, event):
"""Save state in the settings"""
commit_msg = self.commiteditor.commit_message(raw=True)
self.model.save_commitmsg(msg=commit_msg)
for browser in list(self.context.browser_windows):
browser.close()
standard.MainWindow.closeEvent(self, event)
def create_view_menu(self):
menu = qtutils.create_menu(N_('View'), self)
self.build_view_menu(menu)
return menu
def build_view_menu(self, menu):
menu.clear()
if utils.is_darwin():
menu.addAction(self.minimize_action)
menu.addAction(self.browse_action)
menu.addAction(self.dag_action)
menu.addSeparator()
popup_menu = self.createPopupMenu()
for menu_action in popup_menu.actions():
menu_action.setParent(menu)
menu.addAction(menu_action)
context = self.context
menu_action = menu.addAction(
N_('New Toolbar'), partial(toolbar.add_toolbar, context, self)
)
menu_action.setIcon(icons.add())
menu.addSeparator()
dockwidgets = [
self.logdock,
self.commitdock,
self.statusdock,
self.diffdock,
self.actionsdock,
self.bookmarksdock,
self.recentdock,
self.branchdock,
self.submodulesdock,
]
if self.browser_dockable:
dockwidgets.append(self.browserdock)
for dockwidget in dockwidgets:
# Associate the action with the shortcut
toggleview = dockwidget.toggleViewAction()
menu.addAction(toggleview)
menu.addSeparator()
menu.addAction(self.lock_layout_action)
menu.addAction(self.reset_layout_action)
return menu
def contextMenuEvent(self, event):
menu = self.create_view_menu()
menu.exec_(event.globalPos())
def build_recent_menu(self):
cmd = cmds.OpenRepo
context = self.context
settings = context.settings
settings.load()
menu = self.open_recent_menu
menu.clear()
worktree = context.git.worktree()
for entry in settings.recent:
directory = entry['path']
if directory == worktree:
# Omit the current worktree from the "Open Recent" menu.
continue
name = entry['name']
text = f'{name} {uchr(0x2192)} {directory}'
menu.addAction(text, cmds.run(cmd, context, directory))
# Accessors
mode = property(lambda self: self.model.mode)
def _config_updated(self, _source, config, value):
if config == prefs.FONTDIFF:
# The diff font
font = QtGui.QFont()
if not font.fromString(value):
return
self.logwidget.setFont(font)
self.diffeditor.setFont(font)
self.commiteditor.setFont(font)
elif config == prefs.TABWIDTH:
# This can be set locally or globally, so we have to use the
# effective value otherwise we'll update when we shouldn't.
# For example, if this value is overridden locally, and the
# global value is tweaked, we should not update.
value = prefs.tabwidth(self.context)
self.diffeditor.set_tabwidth(value)
self.commiteditor.set_tabwidth(value)
elif config == prefs.EXPANDTAB:
self.commiteditor.set_expandtab(value)
elif config == prefs.LINEBREAK:
# enables automatic line breaks
self.commiteditor.set_linebreak(value)
elif config == prefs.SORT_BOOKMARKS:
self.bookmarksdock.widget().reload_bookmarks()
elif config == prefs.TEXTWIDTH:
# Use the effective value for the same reason as tabwidth.
value = prefs.textwidth(self.context)
self.commiteditor.set_textwidth(value)
elif config == prefs.SHOW_PATH:
# the path in the window title was toggled
self.refresh_window_title()
def start(self, context):
"""Do the expensive "get_config_actions()" call in the background"""
# Install .git-config-defined actions
task = qtutils.SimpleTask(self.get_config_actions)
context.runtask.start(task)
def get_config_actions(self):
actions = cfgactions.get_config_actions(self.context)
self.config_actions_changed.emit(actions)
def refresh(self):
"""Update the title with the current branch and directory name."""
curbranch = self.model.currentbranch
is_merging = self.model.is_merging
is_rebasing = self.model.is_rebasing
is_applying_patch = self.model.is_applying_patch
is_cherry_picking = self.model.is_rebasing
curdir = core.getcwd()
msg = N_('Repository: %s') % curdir
msg += '\n'
msg += N_('Branch: %s') % curbranch
if is_rebasing:
msg += '\n\n'
msg += N_(
'This repository is currently being rebased.\n'
'Resolve conflicts, commit changes, and run:\n'
' Rebase > Continue'
)
elif is_applying_patch:
msg += '\n\n'
msg += N_(
'This repository has unresolved conflicts after applying a patch.\n'
'Resolve conflicts and commit changes.'
)
elif is_cherry_picking:
msg += '\n\n'
msg += N_(
'This repository is in the middle of a cherry-pick.\n'
'Resolve conflicts and commit changes.'
)
elif is_merging:
msg += '\n\n'
msg += N_(
'This repository is in the middle of a merge.\n'
'Resolve conflicts and commit changes.'
)
self.refresh_window_title()
if self.mode == self.model.mode_amend:
self.commit_amend_action.setChecked(True)
else:
self.commit_amend_action.setChecked(False)
self.commitdock.setToolTip(msg)
self.actionswidget.set_mode(self.mode)
self.commiteditor.set_mode(self.mode)
self.statuswidget.set_mode(self.mode)
self.update_actions()
def refresh_window_title(self):
"""Refresh the window title when state changes"""
alerts = []
project = self.model.project
curbranch = self.model.currentbranch
is_cherry_picking = self.model.is_cherry_picking
is_merging = self.model.is_merging
is_rebasing = self.model.is_rebasing
is_applying_patch = self.model.is_applying_patch
is_diff_mode = self.model.is_diff_mode()
is_amend_mode = self.mode == self.model.mode_amend
prefix = uchr(0xAB)
suffix = uchr(0xBB)
if is_amend_mode:
alerts.append(N_('Amending'))
elif is_diff_mode:
alerts.append(N_('Diff Mode'))
elif is_cherry_picking:
alerts.append(N_('Cherry-picking'))
elif is_merging:
alerts.append(N_('Merging'))
elif is_rebasing:
alerts.append(N_('Rebasing'))
elif is_applying_patch:
alerts.append(N_('Applying Patch'))
if alerts:
alert_text = (prefix + ' %s ' + suffix + ' ') % ', '.join(alerts)
else:
alert_text = ''
if self.model.cfg.get(prefs.SHOW_PATH, True):
path_text = self.git.worktree()
else:
path_text = ''
title = f'{project}: {curbranch} {alert_text}{path_text}'
self.setWindowTitle(title)
def update_actions(self):
is_rebasing = self.model.is_rebasing
self.rebase_group.setEnabled(is_rebasing)
enabled = not self.model.is_empty_repository()
self.rename_branch_action.setEnabled(enabled)
self.delete_branch_action.setEnabled(enabled)
self.annex_init_action.setEnabled(not self.model.annex)
self.lfs_init_action.setEnabled(not self.model.lfs)
self.merge_abort_action.setEnabled(self.model.is_merging)
self.cherry_pick_abort_action.setEnabled(self.model.is_cherry_picking)
self.apply_patches_continue_action.setEnabled(self.model.is_applying_patch)
self.apply_patches_skip_action.setEnabled(self.model.is_applying_patch)
self.apply_patches_abort_action.setEnabled(self.model.is_applying_patch)
diff_mode = self.model.mode == self.model.mode_diff
self.exit_diff_mode_action.setEnabled(diff_mode)
def update_menu_actions(self):
# Enable the Prepare Commit Message action if the hook exists
hook = gitcmds.prepare_commit_message_hook(self.context)
enabled = os.path.exists(hook)
self.prepare_commitmsg_hook_action.setEnabled(enabled)
def export_state(self):
state = standard.MainWindow.export_state(self)
show_status_filter = self.statuswidget.filter_widget.isVisible()
state['show_status_filter'] = show_status_filter
state['toolbars'] = self.toolbar_state.export_state()
state['ref_sort'] = self.model.ref_sort
self.diffviewer.export_state(state)
return state
def apply_state(self, state):
"""Imports data for save/restore"""
base_ok = standard.MainWindow.apply_state(self, state)
lock_layout = state.get('lock_layout', False)
self.lock_layout_action.setChecked(lock_layout)
show_status_filter = state.get('show_status_filter', False)
self.statuswidget.filter_widget.setVisible(show_status_filter)
toolbars = state.get('toolbars', [])
self.toolbar_state.apply_state(toolbars)
sort_key = state.get('ref_sort', 0)
self.model.set_ref_sort(sort_key)
diff_ok = self.diffviewer.apply_state(state)
return base_ok and diff_ok
def setup_dockwidget_view_menu(self):
# Hotkeys for toggling the dock widgets
if utils.is_darwin():
optkey = 'Meta'
else:
optkey = 'Ctrl'
dockwidgets = (
(optkey + '+0', self.logdock),
(optkey + '+1', self.commitdock),
(optkey + '+2', self.statusdock),
(optkey + '+3', self.diffdock),
(optkey + '+4', self.actionsdock),
(optkey + '+5', self.bookmarksdock),
(optkey + '+6', self.recentdock),
(optkey + '+7', self.branchdock),
(optkey + '+8', self.submodulesdock),
)
for shortcut, dockwidget in dockwidgets:
# Associate the action with the shortcut
toggleview = dockwidget.toggleViewAction()
toggleview.setShortcut('Shift+' + shortcut)
def showdock(show, dockwidget=dockwidget):
if show:
dockwidget.raise_()
dockwidget.widget().setFocus()
else:
self.setFocus()
self.addAction(toggleview)
qtutils.connect_action_bool(toggleview, showdock)
# Create a new shortcut Shift+<shortcut> that gives focus
toggleview = QtWidgets.QAction(self)
toggleview.setShortcut(shortcut)
def focusdock(dockwidget=dockwidget):
focus_dock(dockwidget)
self.addAction(toggleview)
qtutils.connect_action(toggleview, focusdock)
# These widgets warrant home-row hotkey status
qtutils.add_action(
self,
'Focus Commit Message',
lambda: focus_dock(self.commitdock),
hotkeys.FOCUS,
)
qtutils.add_action(
self,
'Focus Status Window',
lambda: focus_dock(self.statusdock),
hotkeys.FOCUS_STATUS,
)
qtutils.add_action(
self,
'Focus Diff Editor',
lambda: focus_dock(self.diffdock),
hotkeys.FOCUS_DIFF,
)
def git_dag(self):
self.dag = dag.git_dag(self.context, existing_view=self.dag)
def show_cursor_position(self, rows, cols):
display_content = '%02d:%02d' % (rows, cols)
css = """
<style>
.good {
}
.first-warning {
color: black;
background-color: yellow;
}
.second-warning {
color: black;
background-color: #f83;
}
.error {
color: white;
background-color: red;
}
</style>
"""
if cols > 78:
cls = 'error'
elif cols > 72:
cls = 'second-warning'
elif cols > 64:
cls = 'first-warning'
else:
cls = 'good'
div = f'<div class="{cls}">{display_content}</div>'
self.position_label.setText(css + div)
class FocusProxy:
"""Proxy over child widgets and operate on the focused widget"""
def __init__(self, *widgets):
self.widgets = widgets
self.overrides = {}
def override(self, name, widgets):
self.overrides[name] = widgets
def focus(self, name):
"""Return the currently focused widget"""
widgets = self.overrides.get(name, self.widgets)
# The parent must be the parent of all the proxied widgets
parent = widgets[0]
# The first widget is used as a fallback
fallback = widgets[1]
# We ignore the parent when delegating to child widgets
widgets = widgets[1:]
focus = parent.focusWidget()
if focus not in widgets:
focus = fallback
return focus
def __getattr__(self, name):
"""Return a callback that calls a common child method"""
def callback():
focus = self.focus(name)
func = getattr(focus, name, None)
if func:
func()
return callback
def delete(self):
"""Specialized delete() to deal with QLineEdit vs. QTextEdit"""
focus = self.focus('delete')
if hasattr(focus, 'del_'):
focus.del_()
elif hasattr(focus, 'textCursor'):
focus.textCursor().deleteChar()
def show_dock(dockwidget):
dockwidget.raise_()
dockwidget.widget().setFocus()
def focus_dock(dockwidget):
if get(dockwidget.toggleViewAction()):
show_dock(dockwidget)
else:
dockwidget.toggleViewAction().trigger()
def _install_config_actions(context, menu, names_and_shortcuts):
"""Install .gitconfig-defined actions"""
if not names_and_shortcuts:
return
menu.addSeparator()
cache = {}
for name, shortcut in names_and_shortcuts:
sub_menu, action_name = build_menus(name, menu, cache)
callback = cmds.run(cmds.RunConfigAction, context, name)
menu_action = sub_menu.addAction(action_name, callback)
if shortcut:
menu_action.setShortcut(shortcut)
def build_menus(name, menu, cache):
"""Create a chain of QMenu entries parented under a root QMenu
A name of "a/b/c" create a menu chain of menu -> QMenu("a") -> QMenu("b")
and returns a tuple of (QMenu("b"), "c").
:param name: The full entry path, ex: "a/b/c" where "a/b" is the menu chain.
:param menu: The root menu under which to create the menu chain.
:param cache: A dict cache of previously created menus to avoid duplicates.
"""
# NOTE: utils.split() and friends are used instead of os.path.split() because
# slash '/' is the only supported "<menu>/name" separator. Use of os.path.split()
# would introduce differences in behavior across platforms.
# If the menu_path is empty then no parent menus need to be created.
# The action will be added to the root menu.
menu_path, text = utils.split(utils.normalize_slash(name))
if not menu_path:
return (menu, text)
# When menu_path contains ex: "a/b" we will create two menus: "a" and "b".
# The root menu is the parent of "a" and "a" is the parent of "b".
# The menu returned to the caller is "b".
#
# Loop over the individual menu basenames alongside the full subpath returned by
# pathset(). The subpath is a cache key for finding previously created menus.
menu_names = utils.splitpath(menu_path) # ['a', 'b']
menu_pathset = utils.pathset(menu_path) # ['a', 'a/b']
for menu_name, menu_id in zip(menu_names, menu_pathset):
try:
menu = cache[menu_id]
except KeyError:
menu = cache[menu_id] = menu.addMenu(menu_name)
return (menu, text)
| 53,761 | Python | .py | 1,245 | 33.163855 | 88 | 0.622436 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
112 | common.py | git-cola_git-cola/cola/widgets/common.py | import functools
from ..i18n import N_
from .. import cmds
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import utils
def cmd_action(parent, cmd, context, func, *keys):
"""Wrap a standard Command object in a QAction
This function assumes that :func:`func()` takes no arguments,
that `cmd` has a :func:`name()` method, and that the `cmd`
constructor takes a single argument, as returned by `func`.
"""
return qtutils.add_action(
parent, cmd.name(), lambda: cmds.do(cmd, context, func()), *keys
)
def default_app_action(context, parent, func):
"""Open paths with the OS-default app -> QAction"""
action = cmd_action(
parent, cmds.OpenDefaultApp, context, func, hotkeys.PRIMARY_ACTION
)
action.setIcon(icons.default_app())
return action
def edit_action(context, parent, *keys):
"""Launch an editor -> QAction"""
action = qtutils.add_action_with_tooltip(
parent,
cmds.LaunchEditor.name(),
N_('Edit selected paths'),
cmds.run(cmds.LaunchEditor, context),
hotkeys.EDIT,
*keys
)
action.setIcon(icons.edit())
return action
def parent_dir_action(context, parent, func):
"""Open the parent directory of paths -> QAction"""
hotkey = hotkeys.SECONDARY_ACTION
action = cmd_action(parent, cmds.OpenParentDir, context, func, hotkey)
action.setIcon(icons.folder())
return action
def worktree_dir_action(context, parent, *keys):
"""Open the repository worktree -> QAction"""
# lambda: None is a no-op.
action = cmd_action(parent, cmds.OpenWorktree, context, lambda: None, *keys)
action.setIcon(icons.folder())
return action
def refresh_action(context, parent):
"""Refresh the repository state -> QAction"""
return qtutils.add_action(
parent, cmds.Refresh.name(), cmds.run(cmds.Refresh, context), hotkeys.REFRESH
)
def terminal_action(context, parent, func=None, hotkey=None):
"""Launch a terminal -> QAction"""
action = None
if cmds.LaunchTerminal.is_available(context):
if func is None:
func = functools.partial(lambda: None)
action = cmd_action(
parent,
cmds.LaunchTerminal,
context,
lambda: utils.select_directory(func()),
)
action.setIcon(icons.terminal())
if hotkey is not None:
action.setShortcut(hotkey)
return action
| 2,474 | Python | .py | 68 | 30.426471 | 85 | 0.666388 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
113 | gitignore.py | git-cola_git-cola/cola/widgets/gitignore.py | """Provides the StashView dialog."""
from qtpy import QtCore
from qtpy import QtWidgets
from .. import cmds
from .. import qtutils
from ..i18n import N_
from . import defs
from .standard import Dialog
def gitignore_view(context):
"""Launches a gitignore dialog"""
view = AddToGitIgnore(context, parent=qtutils.active_window())
view.show()
return view
class AddToGitIgnore(Dialog):
def __init__(self, context, parent=None):
Dialog.__init__(self, parent=parent)
self.context = context
self.selection = context.selection
if parent is not None:
self.setWindowModality(QtCore.Qt.WindowModal)
self.setWindowTitle(N_('Add to exclusions'))
# Create text
self.text_description = QtWidgets.QLabel()
self.text_description.setText(N_('Ignore filename or pattern'))
# Create edit filename
self.edit_filename = QtWidgets.QLineEdit()
self.check_filename()
self.filename_layt = qtutils.vbox(
defs.no_margin, defs.spacing, self.text_description, self.edit_filename
)
# Create radio options
self.radio_filename = qtutils.radio(
text=N_('Ignore exact filename'), checked=True
)
self.radio_pattern = qtutils.radio(text=N_('Ignore custom pattern'))
self.name_radio_group = qtutils.buttongroup(
self.radio_filename, self.radio_pattern
)
self.name_radio_layt = qtutils.vbox(
defs.no_margin, defs.spacing, self.radio_filename, self.radio_pattern
)
self.radio_in_repo = qtutils.radio(text=N_('Add to .gitignore'), checked=True)
self.radio_local = qtutils.radio(text=N_('Add to local .git/info/exclude'))
self.location_radio_group = qtutils.buttongroup(
self.radio_in_repo, self.radio_local
)
self.location_radio_layt = qtutils.vbox(
defs.no_margin, defs.spacing, self.radio_in_repo, self.radio_local
)
# Create buttons
self.button_apply = qtutils.ok_button(text=N_('Add'))
self.button_close = qtutils.close_button()
self.btn_layt = qtutils.hbox(
defs.no_margin,
defs.spacing,
qtutils.STRETCH,
self.button_close,
self.button_apply,
)
# Layout
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.name_radio_layt,
defs.button_spacing,
self.filename_layt,
defs.button_spacing,
self.location_radio_layt,
qtutils.STRETCH,
self.btn_layt,
)
self.setLayout(self.main_layout)
# Connect actions
qtutils.connect_toggle(self.radio_pattern, self.check_pattern)
qtutils.connect_toggle(self.radio_filename, self.check_filename)
qtutils.connect_button(self.button_apply, self.apply)
qtutils.connect_button(self.button_close, self.close)
self.init_state(None, self.resize_widget, parent)
def resize_widget(self, parent):
"""Set the initial size of the widget"""
width, height = qtutils.default_size(parent, 720, 400)
self.resize(width, max(400, height // 2))
def check_pattern(self):
self.edit_filename.setDisabled(False)
def check_filename(self):
self.edit_filename.setText('/' + ';/'.join(self.selection.untracked))
self.edit_filename.setDisabled(True)
def close(self):
self.reject()
def apply(self):
context = self.context
cmds.do(
cmds.Ignore,
context,
self.edit_filename.text().split(';'),
self.radio_local.isChecked(),
)
self.accept()
| 3,795 | Python | .py | 98 | 29.72449 | 86 | 0.626326 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
114 | filetree.py | git-cola_git-cola/cola/widgets/filetree.py | from qtpy import QtCore
from qtpy import QtWidgets
from .. import icons
from . import standard
class FileTree(standard.TreeWidget):
def __init__(self, parent=None):
standard.TreeWidget.__init__(self, parent=parent)
self.setSelectionMode(self.ExtendedSelection)
self.setHeaderHidden(True)
def set_filenames(self, filenames, select=False):
self.clear()
if not filenames:
return
items = []
from_filename = icons.from_filename
for filename in filenames:
icon = from_filename(filename)
item = QtWidgets.QTreeWidgetItem()
item.setIcon(0, icon)
item.setText(0, filename)
item.setData(0, QtCore.Qt.UserRole, filename)
items.append(item)
self.addTopLevelItems(items)
if select and items:
items[0].setSelected(True)
def has_selection(self):
return bool(self.selectedItems())
def selected_filenames(self):
items = self.selectedItems()
if not items:
return []
return [filename_from_item(i) for i in items]
def filename_from_item(item):
return item.data(0, QtCore.Qt.UserRole)
| 1,212 | Python | .py | 34 | 27.352941 | 57 | 0.64188 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
115 | browse.py | git-cola_git-cola/cola/models/browse.py | import time
from qtpy import QtGui
from qtpy.QtCore import 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 = []
@classmethod
def init(cls):
cls.TEXT.extend(
[N_('Name'), N_('Status'), N_('Message'), N_('Author'), N_('Age')]
)
@classmethod
def text_values(cls):
if not cls.TEXT:
cls.init()
return cls.TEXT
@classmethod
def text(cls, column):
try:
value = cls.TEXT[column]
except IndexError:
# Defer translation until runtime
cls.init()
value = cls.TEXT[column]
return value
@classmethod
def attr(cls, column):
"""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):
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):
paths = qtutils.paths_from_indexes(
self, indexes, item_type=GitRepoNameItem.TYPE
)
return qtutils.mimedata_from_paths(self.context, paths)
def mimeTypes(self):
return qtutils.path_mimetypes()
def clear(self):
self.entries.clear()
super().clear()
def hasChildren(self, index):
if index.isValid():
item = self.itemFromIndex(index)
result = item.hasChildren()
else:
result = True
return result
def get(self, path, default=None):
if not path:
item = self.invisibleRootItem()
else:
item = self.entries.get(path, default)
return item
def create_row(self, path, create=True, is_dir=False):
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):
self.populate_dir(item, item.path + '/')
def add_directory(self, parent, path):
"""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, path):
"""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, path):
"""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, dirname):
"""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):
"""Return True if path has a status."""
return path in self._interesting_paths
def get_paths(self, files=None):
"""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):
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):
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):
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):
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, is_dir):
"""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, default_author):
qtutils.Task.__init__(self)
self.context = context
self.path = path
self._default_author = default_author
self._data = {}
def data(self, key):
"""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):
"""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):
"""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):
"""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):
QtGui.QStandardItem.__init__(self)
self.path = path
self.cached = False
self.setDragEnabled(False)
self.setEditable(False)
def set_status(self, data):
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, is_dir):
GitRepoItem.__init__(self, path)
self.is_dir = 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):
return self.is_dir
| 11,969 | Python | .py | 324 | 27.66358 | 78 | 0.588139 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
116 | stash.py | git-cola_git-cola/cola/models/stash.py | import re
from .. import cmds
from .. import core
from .. import gitcmds
from .. import utils
from ..i18n import N_
from ..git import STDOUT
from ..interaction import Interaction
class StashModel:
def __init__(self, context):
self.context = context
self.git = context.git
self.model = model = context.model
if not model.initialized:
model.update_status()
def stash_list(self, *args):
return self.git.stash('list', *args)[STDOUT].splitlines()
def is_staged(self):
return bool(self.model.staged)
def is_changed(self):
model = self.model
return bool(model.modified or model.staged)
def stash_info(self, revids=False, names=False):
"""Parses "git stash list" and returns a list of stashes."""
stashes = self.stash_list(r'--format=%gd/%aD/%gs')
split_stashes = [s.split('/', 2) for s in stashes if s]
stashes = [f'{s[0]}: {s[2]}' for s in split_stashes]
revids = [s[0] for s in split_stashes]
author_dates = [s[1] for s in split_stashes]
names = [s[2] for s in split_stashes]
return stashes, revids, author_dates, names
def stash_diff(self, rev):
git = self.git
diffstat = git.stash('show', rev)[STDOUT]
diff = git.stash('show', '-p', '--no-ext-diff', rev)[STDOUT]
return diffstat + '\n\n' + diff
class ApplyStash(cmds.ContextCommand):
def __init__(self, context, stash_index, index, pop):
super().__init__(context)
self.stash_ref = 'refs/' + stash_index
self.index = index
self.pop = pop
def do(self):
ref = self.stash_ref
pop = self.pop
if pop:
action = 'pop'
else:
action = 'apply'
if self.index:
args = [action, '--index', ref]
else:
args = [action, ref]
status, out, err = self.git.stash(*args)
if status == 0:
Interaction.log_status(status, out, err)
else:
title = N_('Error')
cmdargs = core.list2cmdline(args)
Interaction.command_error(title, 'git stash ' + cmdargs, status, out, err)
self.model.update_status()
class DropStash(cmds.ContextCommand):
def __init__(self, context, stash_index):
super().__init__(context)
self.stash_ref = 'refs/' + stash_index
def do(self):
git = self.git
status, out, err = git.stash('drop', self.stash_ref)
if status == 0:
Interaction.log_status(status, out, err)
match = re.search(r'\((.*)\)', out)
if match:
return match.group(1)
return ''
title = N_('Error')
Interaction.command_error(
title, 'git stash drop ' + self.stash_ref, status, out, err
)
return ''
class SaveStash(cmds.ContextCommand):
def __init__(self, context, stash_name, keep_index):
super().__init__(context)
self.stash_name = stash_name
self.keep_index = keep_index
def do(self):
if self.keep_index:
args = ['push', '--keep-index', '-m', self.stash_name]
else:
args = ['push', '-m', self.stash_name]
status, out, err = self.git.stash(*args)
if status == 0:
Interaction.log_status(status, out, err)
else:
title = N_('Error')
cmdargs = core.list2cmdline(args)
Interaction.command_error(title, 'git stash ' + cmdargs, status, out, err)
self.model.update_status()
class RenameStash(cmds.ContextCommand):
"""Rename the stash"""
def __init__(self, context, stash_index, stash_name):
super().__init__(context)
self.context = context
self.stash_index = stash_index
self.stash_name = stash_name
def do(self):
# Drop the stash first and get the returned ref
ref = DropStash(self.context, self.stash_index).do()
# Store the stash with a new name
if ref:
args = ['store', '-m', self.stash_name, ref]
status, out, err = self.git.stash(*args)
if status == 0:
Interaction.log_status(status, out, err)
else:
title = N_('Error')
cmdargs = core.list2cmdline(args)
Interaction.command_error(
title, 'git stash ' + cmdargs, status, out, err
)
else:
title = N_('Error Renaming Stash')
msg = N_('"git stash drop" did not return a ref to rename.')
Interaction.critical(title, message=msg)
self.model.update_status()
class StashIndex(cmds.ContextCommand):
"""Stash the index away"""
def __init__(self, context, stash_name):
super().__init__(context)
self.stash_name = stash_name
def do(self):
# Manually create a stash representing the index state
context = self.context
git = self.git
name = self.stash_name
branch = gitcmds.current_branch(context)
head = gitcmds.rev_parse(context, 'HEAD')
message = f'On {branch}: {name}'
# Get the message used for the "index" commit
status, out, err = git.rev_list('HEAD', '--', oneline=True, n=1)
if status != 0:
stash_error('rev-list', status, out, err)
return
head_msg = out.strip()
# Create a commit representing the index
status, out, err = git.write_tree()
if status != 0:
stash_error('write-tree', status, out, err)
return
index_tree = out.strip()
status, out, err = git.commit_tree(
'-m', f'index on {branch}: {head_msg}', '-p', head, index_tree
)
if status != 0:
stash_error('commit-tree', status, out, err)
return
index_commit = out.strip()
# Create a commit representing the worktree
status, out, err = git.commit_tree(
'-p', head, '-p', index_commit, '-m', message, index_tree
)
if status != 0:
stash_error('commit-tree', status, out, err)
return
worktree_commit = out.strip()
# Record the stash entry
status, out, err = git.update_ref(
'-m', message, 'refs/stash', worktree_commit, create_reflog=True
)
if status != 0:
stash_error('update-ref', status, out, err)
return
# Sync the worktree with the post-stash state. We've created the
# stash ref, so now we have to remove the staged changes from the
# worktree. We do this by applying a reverse diff of the staged
# changes. The diff from stash->HEAD is a reverse diff of the stash.
patch = utils.tmp_filename('stash')
with core.xopen(patch, mode='wb') as patch_fd:
status, out, err = git.diff_tree(
'refs/stash', 'HEAD', '--', binary=True, _stdout=patch_fd
)
if status != 0:
stash_error('diff-tree', status, out, err)
return
# Apply the patch
status, out, err = git.apply(patch)
core.unlink(patch)
ok = status == 0
if ok:
# Finally, clear the index we just stashed
git.reset()
else:
stash_error('apply', status, out, err)
self.model.update_status()
def stash_error(cmd, status, out, err):
title = N_('Error creating stash')
Interaction.command_error(title, cmd, status, out, err)
| 7,640 | Python | .py | 196 | 29.438776 | 86 | 0.564677 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
117 | dag.py | git-cola_git-cola/cola/models/dag.py | import json
from .. import core
from .. import utils
from ..models import prefs
# put summary at the end b/c it can contain
# any number of funky characters, including the separator
logfmt = r'format:%H%x01%P%x01%d%x01%an%x01%ad%x01%ae%x01%s'
logsep = chr(0x01)
class CommitFactory:
root_generation = 0
commits = {}
@classmethod
def reset(cls):
cls.commits.clear()
cls.root_generation = 0
@classmethod
def new(cls, oid=None, log_entry=None):
if not oid and log_entry:
oid = log_entry[:40]
try:
commit = cls.commits[oid]
if log_entry and not commit.parsed:
commit.parse(log_entry)
cls.root_generation = max(commit.generation, cls.root_generation)
except KeyError:
commit = Commit(oid=oid, log_entry=log_entry)
if not log_entry:
cls.root_generation += 1
commit.generation = max(commit.generation, cls.root_generation)
cls.commits[oid] = commit
return commit
class DAG:
def __init__(self, ref, count):
self.ref = ref
self.count = count
self.overrides = {}
def set_ref(self, ref):
changed = ref != self.ref
if changed:
self.ref = ref
return changed
def set_count(self, count):
changed = count != self.count
if changed:
self.count = count
return changed
def set_arguments(self, args):
if args is None:
return
if self.set_count(args.count):
self.overrides['count'] = args.count
if hasattr(args, 'args') and args.args:
ref = core.list2cmdline(args.args)
if self.set_ref(ref):
self.overrides['ref'] = ref
def overridden(self, opt):
return opt in self.overrides
def paths(self):
all_refs = utils.shell_split(self.ref)
if '--' in all_refs:
all_refs = all_refs[all_refs.index('--') :]
return [p for p in all_refs if p and core.exists(p)]
class Commit:
root_generation = 0
__slots__ = (
'oid',
'summary',
'parents',
'children',
'branches',
'tags',
'author',
'authdate',
'email',
'generation',
'column',
'row',
'parsed',
)
def __init__(self, oid=None, log_entry=None):
self.oid = oid
self.summary = None
self.parents = []
self.children = []
self.tags = []
self.branches = []
self.email = None
self.author = None
self.authdate = None
self.parsed = False
self.generation = CommitFactory.root_generation
self.column = None
self.row = None
if log_entry:
self.parse(log_entry)
def parse(self, log_entry, sep=logsep):
self.oid = log_entry[:40]
after_oid = log_entry[41:]
details = after_oid.split(sep, 5)
(parents, tags, author, authdate, email, summary) = details
self.summary = summary if summary else ''
self.author = author if author else ''
self.authdate = authdate if authdate else ''
self.email = email if email else ''
if parents:
generation = None
for parent_oid in parents.split(' '):
parent = CommitFactory.new(oid=parent_oid)
parent.children.append(self)
if generation is None:
generation = parent.generation + 1
self.parents.append(parent)
generation = max(parent.generation + 1, generation)
self.generation = generation
if tags:
for tag in tags[2:-1].split(', '):
self.add_label(tag)
self.parsed = True
return self
def add_label(self, tag):
"""Add tag/branch labels from `git log --decorate ....`"""
if tag.startswith('tag: '):
tag = tag[5:] # strip off "tag: " leaving refs/tags/
if tag.startswith('refs/heads/'):
branch = tag[11:]
self.branches.append(branch)
if tag.startswith('refs/'):
# strip off refs/ leaving just tags/XXX remotes/XXX heads/XXX
tag = tag[5:]
if tag.endswith('/HEAD'):
return
# Git 2.4 Release Notes (draft)
# =============================
#
# Backward compatibility warning(s)
# ---------------------------------
#
# This release has a few changes in the user-visible output from
# Porcelain commands. These are not meant to be parsed by scripts, but
# the users still may want to be aware of the changes:
#
# * Output from "git log --decorate" (and "%d" format specifier used in
# the userformat "--format=<string>" parameter "git log" family of
# command takes) used to list "HEAD" just like other tips of branch
# names, separated with a comma in between. E.g.
#
# $ git log --decorate -1 main
# commit bdb0f6788fa5e3cacc4315e9ff318a27b2676ff4 (HEAD, main)
# ...
#
# This release updates the output slightly when HEAD refers to the tip
# of a branch whose name is also shown in the output. The above is
# shown as:
#
# $ git log --decorate -1 main
# commit bdb0f6788fa5e3cacc4315e9ff318a27b2676ff4 (HEAD -> main)
# ...
#
# C.f. http://thread.gmane.org/gmane.linux.kernel/1931234
head_arrow = 'HEAD -> '
if tag.startswith(head_arrow):
self.tags.append('HEAD')
self.add_label(tag[len(head_arrow) :])
else:
self.tags.append(tag)
def __str__(self):
return self.oid
def data(self):
return {
'oid': self.oid,
'summary': self.summary,
'author': self.author,
'authdate': self.authdate,
'parents': [p.oid for p in self.parents],
'tags': self.tags,
}
def __repr__(self):
return json.dumps(self.data(), sort_keys=True, indent=4, default=list)
def is_fork(self):
"""Returns True if the node is a fork"""
return len(self.children) > 1
def is_merge(self):
"""Returns True if the node is a fork"""
return len(self.parents) > 1
class RepoReader:
def __init__(self, context, params):
self.context = context
self.params = params
self.git = context.git
self.returncode = 0
self._proc = None
self._objects = {}
self._cmd = [
'git',
'-c',
'log.abbrevCommit=false',
'-c',
'log.showSignature=false',
'log',
'--topo-order',
'--decorate=full',
'--pretty=' + logfmt,
]
self._cached = False
"""Indicates that all data has been read"""
self._topo_list = []
"""List of commits objects in topological order"""
cached = property(lambda self: self._cached)
"""Return True when no commits remain to be read"""
def __len__(self):
return len(self._topo_list)
def reset(self):
CommitFactory.reset()
if self._proc:
self._proc.kill()
self._cached = False
self._topo_list = []
def get(self):
"""Generator function returns Commit objects found by the params"""
if self._cached:
idx = 0
while True:
try:
yield self._topo_list[idx]
except IndexError:
break
idx += 1
return
self.reset()
ref_args = utils.shell_split(self.params.ref)
cmd = (
self._cmd
+ ['-%d' % self.params.count]
+ ['--date=%s' % prefs.logdate(self.context)]
+ ref_args
)
status, out, _ = core.run_command(cmd)
for log_entry in reversed(out.splitlines()):
if not log_entry:
break
oid = log_entry[:40]
try:
yield self._objects[oid]
except KeyError:
commit = CommitFactory.new(log_entry=log_entry)
self._objects[commit.oid] = commit
self._topo_list.append(commit)
yield commit
self._cached = True
self.returncode = status
def __getitem__(self, oid):
return self._objects[oid]
def items(self):
return list(self._objects.items())
| 8,778 | Python | .py | 254 | 24.637795 | 79 | 0.537627 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
118 | prefs.py | git-cola_git-cola/cola/models/prefs.py | import sys
from qtpy import QtCore
from qtpy.QtCore import Signal
from .. import core
from .. import git
from .. import hidpi
from .. import utils
from ..cmd import Command
ABBREV = 'core.abbrev'
AUTOCOMPLETE_PATHS = 'cola.autocompletepaths'
AUTODETECT_PROXY = 'cola.autodetectproxy'
AUTOTEMPLATE = 'cola.autoloadcommittemplate'
BACKGROUND_EDITOR = 'cola.backgroundeditor'
BLAME_VIEWER = 'cola.blameviewer'
BLOCK_CURSOR = 'cola.blockcursor'
BOLD_HEADERS = 'cola.boldheaders'
CHECK_CONFLICTS = 'cola.checkconflicts'
CHECK_PUBLISHED_COMMITS = 'cola.checkpublishedcommits'
COMMENT_CHAR = 'core.commentchar'
COMMIT_CLEANUP = 'commit.cleanup'
DIFFCONTEXT = 'gui.diffcontext'
DIFFTOOL = 'diff.tool'
DISPLAY_UNTRACKED = 'gui.displayuntracked'
EDITOR = 'gui.editor'
ENABLE_GRAVATAR = 'cola.gravatar'
EXPANDTAB = 'cola.expandtab'
FONTDIFF = 'cola.fontdiff'
HIDPI = 'cola.hidpi'
HISTORY_BROWSER = 'gui.historybrowser'
HTTP_PROXY = 'http.proxy'
ICON_THEME = 'cola.icontheme'
INOTIFY = 'cola.inotify'
NOTIFY_ON_PUSH = 'cola.notifyonpush'
LINEBREAK = 'cola.linebreak'
LOGDATE = 'cola.logdate'
MAXRECENT = 'cola.maxrecent'
MERGE_DIFFSTAT = 'merge.diffstat'
MERGE_KEEPBACKUP = 'merge.keepbackup'
MERGE_SUMMARY = 'merge.summary'
MERGE_VERBOSITY = 'merge.verbosity'
MERGETOOL = 'merge.tool'
MOUSE_ZOOM = 'cola.mousezoom'
PATCHES_DIRECTORY = 'cola.patchesdirectory'
REFRESH_ON_FOCUS = 'cola.refreshonfocus'
RESIZE_BROWSER_COLUMNS = 'cola.resizebrowsercolumns'
SAFE_MODE = 'cola.safemode'
SAVEWINDOWSETTINGS = 'cola.savewindowsettings'
SHOW_PATH = 'cola.showpath'
SORT_BOOKMARKS = 'cola.sortbookmarks'
SPELL_CHECK = 'cola.spellcheck'
STATUS_INDENT = 'cola.statusindent'
STATUS_SHOW_TOTALS = 'cola.statusshowtotals'
THEME = 'cola.theme'
TABWIDTH = 'cola.tabwidth'
TEXTWIDTH = 'cola.textwidth'
USER_EMAIL = 'user.email'
USER_NAME = 'user.name'
class DateFormat:
DEFAULT = 'default'
RELATIVE = 'relative'
LOCAL = 'local'
ISO = 'iso8601'
ISO_STRICT = 'iso8601-strict'
RFC = 'rfc2822'
SHORT = 'short'
RAW = 'raw'
HUMAN = 'human'
UNIX = 'unix'
def date_formats():
"""Return valid values for git config cola.logdate"""
return [
DateFormat.DEFAULT,
DateFormat.RELATIVE,
DateFormat.LOCAL,
DateFormat.ISO,
DateFormat.ISO_STRICT,
DateFormat.RFC,
DateFormat.SHORT,
DateFormat.RAW,
DateFormat.HUMAN,
DateFormat.UNIX,
]
def commit_cleanup_modes():
"""Return valid values for the git config commit.cleanup"""
return [
'default',
'whitespace',
'strip',
'scissors',
'verbatim',
]
class Defaults:
"""Read-only class for holding defaults that get overridden"""
# These should match Git's defaults for git-defined values.
abbrev = 12
autotemplate = False
autodetect_proxy = True
blame_viewer = 'git gui blame'
block_cursor = True
bold_headers = False
check_conflicts = True
check_published_commits = True
comment_char = '#'
commit_cleanup = 'default'
display_untracked = True
diff_context = 5
difftool = 'xxdiff'
editor = 'gvim'
enable_gravatar = True
expandtab = False
history_browser = 'gitk'
http_proxy = ''
icon_theme = 'default'
inotify = True
notifyonpush = False
linebreak = True
maxrecent = 8
mergetool = difftool
merge_diffstat = True
merge_keep_backup = True
merge_summary = True
merge_verbosity = 2
mouse_zoom = True
refresh_on_focus = False
resize_browser_columns = False
save_window_settings = True
safe_mode = False
autocomplete_paths = True
show_path = True
sort_bookmarks = True
spellcheck = False
tabwidth = 8
textwidth = 72
theme = 'default'
hidpi = hidpi.Option.AUTO
patches_directory = 'patches'
status_indent = False
status_show_totals = False
logdate = DateFormat.DEFAULT
def abbrev(context):
"""Return the configured length for shortening commit IDs"""
default = Defaults.abbrev
value = context.cfg.get(ABBREV, default=default)
if value == 'no':
result = git.OID_LENGTH_SHA256
else:
try:
result = max(4, int(value))
except ValueError:
result = default
return result
def autodetect_proxy(context):
"""Return True when proxy settings should be automatically configured"""
return context.cfg.get(AUTODETECT_PROXY, default=Defaults.autodetect_proxy)
def blame_viewer(context):
"""Return the configured "blame" viewer"""
default = Defaults.blame_viewer
return context.cfg.get(BLAME_VIEWER, default=default)
def block_cursor(context):
"""Should we display a block cursor in diff editors?"""
return context.cfg.get(BLOCK_CURSOR, default=Defaults.block_cursor)
def bold_headers(context):
"""Should we bold the Status column headers?"""
return context.cfg.get(BOLD_HEADERS, default=Defaults.bold_headers)
def check_conflicts(context):
"""Should we check for merge conflict markers in unmerged files?"""
return context.cfg.get(CHECK_CONFLICTS, default=Defaults.check_conflicts)
def check_published_commits(context):
"""Should we check for published commits when amending?"""
return context.cfg.get(
CHECK_PUBLISHED_COMMITS, default=Defaults.check_published_commits
)
def display_untracked(context):
"""Should we display untracked files?"""
return context.cfg.get(DISPLAY_UNTRACKED, default=Defaults.display_untracked)
def editor(context):
"""Return the configured editor"""
app = context.cfg.get(EDITOR, default=fallback_editor())
return _remap_editor(app)
def background_editor(context):
"""Return the configured non-blocking background editor"""
app = context.cfg.get(BACKGROUND_EDITOR, default=editor(context))
return _remap_editor(app)
def fallback_editor():
"""Return a fallback editor for cases where one is not configured
GIT_VISUAL and VISUAL are consulted before GIT_EDITOR and EDITOR to allow
configuring a visual editor for Git Cola using $GIT_VISUAL and an alternative
editor for the Git CLI.
"""
editor_variables = (
'GIT_VISUAL',
'VISUAL',
'GIT_EDITOR',
'EDITOR',
)
for env in editor_variables:
env_editor = core.getenv(env)
if env_editor:
return env_editor
return Defaults.editor
def _remap_editor(app):
"""Remap a configured editor into a visual editor name"""
# We do this for vim users because this configuration is convenient for new users.
return {
'vim': 'gvim -f',
'nvim': 'nvim-qt --nofork',
}.get(app, app)
def comment_char(context):
"""Return the configured git commit comment character"""
return context.cfg.get(COMMENT_CHAR, default=Defaults.comment_char)
def commit_cleanup(context):
"""Return the configured git commit cleanup mode"""
return context.cfg.get(COMMIT_CLEANUP, default=Defaults.commit_cleanup)
def enable_gravatar(context):
"""Is gravatar enabled?"""
return context.cfg.get(ENABLE_GRAVATAR, default=Defaults.enable_gravatar)
def default_history_browser():
"""Return the default history browser (e.g. git-dag, gitk)"""
if utils.is_win32():
# On Windows, a sensible default is "python git-cola dag"
# which is different than `gitk` below, but is preferred
# because we don't have to guess paths.
git_cola = sys.argv[0].replace('\\', '/')
python = sys.executable.replace('\\', '/')
cwd = core.getcwd().replace('\\', '/')
argv = [python, git_cola, 'dag', '--repo', cwd]
argv = core.prep_for_subprocess(argv)
default = core.list2cmdline(argv)
else:
# The `gitk` script can be launched as-is on unix
default = Defaults.history_browser
return default
def history_browser(context):
"""Return the configured history browser"""
default = default_history_browser()
return context.cfg.get(HISTORY_BROWSER, default=default)
def http_proxy(context):
"""Return the configured http proxy"""
return context.cfg.get(HTTP_PROXY, default=Defaults.http_proxy)
def notify_on_push(context):
"""Return whether to notify upon push or not"""
default = Defaults.notifyonpush
return context.cfg.get(NOTIFY_ON_PUSH, default=default)
def linebreak(context):
"""Should we word-wrap lines in the commit message editor?"""
return context.cfg.get(LINEBREAK, default=Defaults.linebreak)
def logdate(context):
"""Return the configured log date format"""
return context.cfg.get(LOGDATE, default=Defaults.logdate)
def maxrecent(context):
"""Return the configured maximum number of Recent Repositories"""
value = Defaults.maxrecent
if context:
value = context.cfg.get(MAXRECENT, default=value)
return value
def mouse_zoom(context):
"""Should we zoom text when using Ctrl + MouseWheel scroll"""
return context.cfg.get(MOUSE_ZOOM, default=Defaults.mouse_zoom)
def spellcheck(context):
"""Should we spellcheck commit messages?"""
return context.cfg.get(SPELL_CHECK, default=Defaults.spellcheck)
def expandtab(context):
"""Should we expand tabs in commit messages?"""
return context.cfg.get(EXPANDTAB, default=Defaults.expandtab)
def patches_directory(context):
"""Return the patches output directory"""
return context.cfg.get(PATCHES_DIRECTORY, default=Defaults.patches_directory)
def sort_bookmarks(context):
"""Should we sort bookmarks by name?"""
return context.cfg.get(SORT_BOOKMARKS, default=Defaults.sort_bookmarks)
def tabwidth(context):
"""Return the configured tab width in the commit message editor"""
return context.cfg.get(TABWIDTH, default=Defaults.tabwidth)
def textwidth(context):
"""Return the configured text width for word wrapping commit messages"""
return context.cfg.get(TEXTWIDTH, default=Defaults.textwidth)
def status_indent(context):
"""Should we indent items in the status widget?"""
return context.cfg.get(STATUS_INDENT, default=Defaults.status_indent)
def status_show_totals(context):
"""Should we display count totals in the status widget headers?"""
return context.cfg.get(STATUS_SHOW_TOTALS, default=Defaults.status_show_totals)
class PreferencesModel(QtCore.QObject):
"""Interact with repo-local and user-global git config preferences"""
config_updated = Signal(str, str, object)
def __init__(self, context):
super().__init__()
self.context = context
self.config = context.cfg
def set_config(self, source, config, value):
"""Set a configuration value"""
if source == 'local':
self.config.set_repo(config, value)
else:
self.config.set_user(config, value)
self.config_updated.emit(source, config, value)
def get_config(self, source, config):
"""Get a configured value"""
if source == 'local':
value = self.config.get_repo(config)
else:
value = self.config.get(config)
return value
class SetConfig(Command):
"""Store a gitconfig value"""
UNDOABLE = True
def __init__(self, model, source, config, value):
self.source = source
self.config = config
self.value = value
self.old_value = None
self.model = model
def do(self):
"""Modify the model and store the updated configuration"""
self.old_value = self.model.get_config(self.source, self.config)
self.model.set_config(self.source, self.config, self.value)
def undo(self):
"""Restore the configuration change to its original value"""
if self.old_value is None:
return
self.model.set_config(self.source, self.config, self.old_value)
| 11,887 | Python | .py | 321 | 31.965732 | 86 | 0.702971 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
119 | selection.py | git-cola_git-cola/cola/models/selection.py | """Provides a selection model to handle selection."""
import collections
from qtpy import QtCore
from qtpy.QtCore import Signal
State = collections.namedtuple('State', 'staged unmerged modified untracked')
def create():
"""Create a SelectionModel"""
return SelectionModel()
def pick(selection):
"""Choose the first list from stage, unmerged, modified, untracked"""
if selection.staged:
files = selection.staged
elif selection.unmerged:
files = selection.unmerged
elif selection.modified:
files = selection.modified
elif selection.untracked:
files = selection.untracked
else:
files = []
return files
def union(selection):
"""Return the union of all selected items in a sorted list"""
values = set(
selection.staged + selection.unmerged + selection.modified + selection.untracked
)
return list(sorted(values))
def _filter(values, remove):
"""Filter a list in-place by removing items"""
remove_set = set(remove)
values_copy = list(values)
last = len(values_copy) - 1
for idx, value in enumerate(reversed(values)):
if value not in remove_set:
values.pop(last - idx)
class SelectionModel(QtCore.QObject):
"""Provides information about selected file paths."""
selection_changed = Signal()
# These properties wrap the individual selection items
# to provide higher-level pseudo-selections.
unstaged = property(lambda self: self.unmerged + self.modified + self.untracked)
def __init__(self):
super().__init__()
self.staged = []
self.unmerged = []
self.modified = []
self.untracked = []
self.line_number = None
def reset(self, emit=False):
self.staged = []
self.unmerged = []
self.modified = []
self.untracked = []
self.line_number = None
if emit:
self.selection_changed.emit()
def is_empty(self):
return not (
bool(self.staged or self.unmerged or self.modified or self.untracked)
)
def set_selection(self, s):
"""Set the new selection."""
self.staged = s.staged
self.unmerged = s.unmerged
self.modified = s.modified
self.untracked = s.untracked
self.selection_changed.emit()
def update(self, other):
_filter(self.staged, other.staged)
_filter(self.unmerged, other.unmerged)
_filter(self.modified, other.modified)
_filter(self.untracked, other.untracked)
self.selection_changed.emit()
def selection(self):
return State(self.staged, self.unmerged, self.modified, self.untracked)
def single_selection(self):
"""Scan across staged, modified, etc. and return a single item."""
staged = None
modified = None
unmerged = None
untracked = None
if self.staged:
staged = self.staged[0]
elif self.modified:
modified = self.modified[0]
elif self.unmerged:
unmerged = self.unmerged[0]
elif self.untracked:
untracked = self.untracked[0]
return State(staged, unmerged, modified, untracked)
def filename(self):
"""Return the currently selected filename"""
paths = [path for path in self.single_selection() if path is not None]
if paths:
filename = paths[0]
else:
filename = None
return filename
def group(self):
"""A list of selected files in various states of being"""
return pick(self.selection())
def union(self):
"""Return the union of all selected items in a sorted list"""
return union(self)
| 3,753 | Python | .py | 104 | 28.548077 | 88 | 0.639724 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
120 | main.py | git-cola_git-cola/cola/models/main.py | """The central cola model"""
import os
from qtpy import QtCore
from qtpy.QtCore import Signal
from .. import core
from .. import gitcmds
from .. import gitcfg
from .. import version
from ..git import STDOUT
from ..interaction import Interaction
from ..i18n import N_
from . import prefs
FETCH = 'fetch'
FETCH_HEAD = 'FETCH_HEAD'
PUSH = 'push'
PULL = 'pull'
def create(context):
"""Create the repository status model"""
return MainModel(context)
class MainModel(QtCore.QObject):
"""Repository status model"""
# Refactor: split this class apart into separate DiffModel, CommitMessageModel,
# StatusModel, and an DiffEditorState.
# Signals
about_to_update = Signal()
previous_contents = Signal(list, list, list, list)
commit_message_changed = Signal(object)
diff_text_changed = Signal()
diff_text_updated = Signal(str)
# "diff_type" {text,image} represents the diff viewer mode.
diff_type_changed = Signal(object)
# "file_type" {text,image} represents the selected file type.
file_type_changed = Signal(object)
images_changed = Signal(object)
mode_changed = Signal(str)
submodules_changed = Signal()
refs_updated = Signal()
updated = Signal()
worktree_changed = Signal()
# States
mode_none = 'none' # Default: nothing's happened, do nothing
mode_worktree = 'worktree' # Comparing index to worktree
mode_diffstat = 'diffstat' # Showing a diffstat
mode_display = 'display' # Displaying arbitrary information
mode_untracked = 'untracked' # Dealing with an untracked file
mode_untracked_diff = 'untracked-diff' # Diffing an untracked file
mode_index = 'index' # Comparing index to last commit
mode_amend = 'amend' # Amending a commit
mode_diff = 'diff' # Diffing against an arbitrary commit
# Modes where we can checkout files from the $head
modes_undoable = {mode_amend, mode_diff, mode_index, mode_worktree}
# Modes where we can partially stage files
modes_partially_stageable = {
mode_amend,
mode_diff,
mode_worktree,
mode_untracked_diff,
}
# Modes where we can partially unstage files
modes_unstageable = {mode_amend, mode_diff, mode_index}
unstaged = property(lambda self: self.modified + self.unmerged + self.untracked)
"""An aggregate of the modified, unmerged, and untracked file lists."""
def __init__(self, context, cwd=None):
"""Interface to the main repository status"""
super().__init__()
self.context = context
self.git = context.git
self.cfg = context.cfg
self.selection = context.selection
self.initialized = False
self.annex = False
self.lfs = False
self.head = 'HEAD'
self.diff_text = ''
self.diff_type = Types.TEXT
self.file_type = Types.TEXT
self.mode = self.mode_none
self.filename = None
self.is_cherry_picking = False
self.is_merging = False
self.is_rebasing = False
self.is_applying_patch = False
self.currentbranch = ''
self.directory = ''
self.project = ''
self.remotes = []
self.filter_paths = None
self.images = []
self.commitmsg = '' # current commit message
self._auto_commitmsg = '' # e.g. .git/MERGE_MSG
self._prev_commitmsg = '' # saved here when clobbered by .git/MERGE_MSG
self.modified = [] # modified, staged, untracked, unmerged paths
self.staged = []
self.untracked = []
self.unmerged = []
self.upstream_changed = [] # paths that've changed upstream
self.staged_deleted = set()
self.unstaged_deleted = set()
self.submodules = set()
self.submodules_list = None # lazy loaded
self.error = None # The last error message.
self.ref_sort = 0 # (0: version, 1:reverse-chrono)
self.local_branches = []
self.remote_branches = []
self.tags = []
if cwd:
self.set_worktree(cwd)
def is_diff_mode(self):
"""Are we in diff mode?"""
return self.mode == self.mode_diff
def is_unstageable(self):
"""Are we in a mode that supports "unstage" actions?"""
return self.mode in self.modes_unstageable
def is_amend_mode(self):
"""Are we amending a commit?"""
return self.mode == self.mode_amend
def is_undoable(self):
"""Can we checkout from the current branch or head ref?"""
return self.mode in self.modes_undoable
def is_partially_stageable(self):
"""Whether partial staging should be allowed."""
return self.mode in self.modes_partially_stageable
def is_stageable(self):
"""Whether staging should be allowed."""
return self.is_partially_stageable() or self.mode == self.mode_untracked
def all_branches(self):
return self.local_branches + self.remote_branches
def set_worktree(self, worktree):
last_worktree = self.git.paths.worktree
self.git.set_worktree(worktree)
is_valid = self.git.is_valid()
if is_valid:
reset = last_worktree is None or last_worktree != worktree
cwd = self.git.getcwd()
self.project = os.path.basename(cwd)
self.set_directory(cwd)
core.chdir(cwd)
self.update_config(reset=reset)
# Detect the "git init" scenario by checking for branches.
# If no branches exist then we cannot use "git rev-parse" yet.
err = None
refs = self.git.git_path('refs', 'heads')
if core.exists(refs) and core.listdir(refs):
# "git rev-parse" exits with a non-zero exit status when the
# safe.directory protection is active.
status, _, err = self.git.rev_parse('HEAD')
is_valid = status == 0
if is_valid:
self.error = None
self.worktree_changed.emit()
else:
self.error = err
return is_valid
def is_git_lfs_enabled(self):
"""Return True if `git lfs install` has been run
We check for the existence of the "lfs" object-storea, and one of the
"git lfs install"-provided hooks. This allows us to detect when
"git lfs uninstall" has been run.
"""
lfs_filter = self.cfg.get('filter.lfs.clean', default=False)
lfs_dir = lfs_filter and self.git.git_path('lfs')
lfs_hook = lfs_filter and self.cfg.hooks_path('post-merge')
return (
lfs_filter
and lfs_dir
and core.exists(lfs_dir)
and lfs_hook
and core.exists(lfs_hook)
)
def set_commitmsg(self, msg, notify=True):
self.commitmsg = msg
if notify:
self.commit_message_changed.emit(msg)
def save_commitmsg(self, msg=None):
if msg is None:
msg = self.commitmsg
path = self.git.git_path('GIT_COLA_MSG')
try:
if not msg.endswith('\n'):
msg += '\n'
core.write(path, msg)
except OSError:
pass
return path
def set_diff_text(self, txt):
"""Update the text displayed in the diff editor"""
changed = txt != self.diff_text
self.diff_text = txt
self.diff_text_updated.emit(txt)
if changed:
self.diff_text_changed.emit()
def set_diff_type(self, diff_type): # text, image
"""Set the diff type to either text or image"""
changed = diff_type != self.diff_type
self.diff_type = diff_type
if changed:
self.diff_type_changed.emit(diff_type)
def set_file_type(self, file_type): # text, image
"""Set the file type to either text or image"""
changed = file_type != self.file_type
self.file_type = file_type
if changed:
self.file_type_changed.emit(file_type)
def set_images(self, images):
"""Update the images shown in the preview pane"""
self.images = images
self.images_changed.emit(images)
def set_directory(self, path):
self.directory = path
def set_mode(self, mode, head=None):
"""Set the current editing mode (worktree, index, amending, ...)"""
# Do not allow going into index or worktree mode when amending.
if self.is_amend_mode() and mode != self.mode_none:
return
# We cannot amend in the middle of git cherry-pick, git am or git merge.
if (
self.is_cherry_picking or self.is_merging or self.is_applying_patch
) and mode == self.mode_amend:
mode = self.mode
# Stay in diff mode until explicitly reset.
if self.mode == self.mode_diff and mode != self.mode_none:
mode = self.mode_diff
head = head or self.head
else:
# If we are amending then we'll use "HEAD^", otherwise use the specified
# head or "HEAD" if head has not been specified.
if mode == self.mode_amend:
head = 'HEAD^'
elif not head:
head = 'HEAD'
self.head = head
self.mode = mode
self.mode_changed.emit(mode)
def update_path_filter(self, filter_paths):
self.filter_paths = filter_paths
self.update_file_status()
def emit_about_to_update(self):
self.previous_contents.emit(
self.staged, self.unmerged, self.modified, self.untracked
)
self.about_to_update.emit()
def emit_updated(self):
self.updated.emit()
def update_file_status(self, update_index=False):
"""Update modified/staged files status"""
self.emit_about_to_update()
self.update_files(update_index=update_index, emit=True)
def update_file_merge_status(self):
"""Update modified/staged files and Merge/Rebase/Cherry-pick status"""
self.emit_about_to_update()
self._update_merge_rebase_status()
self.update_file_status()
def update_status(self, update_index=False, reset=False):
# Give observers a chance to respond
self.emit_about_to_update()
self.initialized = True
self._update_merge_rebase_status()
self._update_files(update_index=update_index)
self._update_remotes()
self._update_branches_and_tags()
self._update_commitmsg()
self.update_config()
if reset:
self.update_submodules_list()
self.emit_updated()
def update_config(self, emit=False, reset=False):
if reset:
self.cfg.reset()
self.annex = self.cfg.is_annex()
self.lfs = self.is_git_lfs_enabled()
if emit:
self.emit_updated()
def update_files(self, update_index=False, emit=False):
self._update_files(update_index=update_index)
if emit:
self.emit_updated()
def _update_files(self, update_index=False):
context = self.context
display_untracked = prefs.display_untracked(context)
state = gitcmds.worktree_state(
context,
head=self.head,
update_index=update_index,
display_untracked=display_untracked,
paths=self.filter_paths,
)
self.staged = state.get('staged', [])
self.modified = state.get('modified', [])
self.unmerged = state.get('unmerged', [])
self.untracked = state.get('untracked', [])
self.upstream_changed = state.get('upstream_changed', [])
self.staged_deleted = state.get('staged_deleted', set())
self.unstaged_deleted = state.get('unstaged_deleted', set())
self.submodules = state.get('submodules', set())
selection = self.selection
if self.is_empty():
selection.reset()
else:
selection.update(self)
if selection.is_empty():
self.set_diff_text('')
def is_empty(self):
return not (
bool(self.staged or self.modified or self.unmerged or self.untracked)
)
def is_empty_repository(self):
return not self.local_branches
def _update_remotes(self):
self.remotes = gitcfg.get_remotes(self.cfg)
def _update_branches_and_tags(self):
context = self.context
sort_types = (
'version:refname',
'-committerdate',
)
sort_key = sort_types[self.ref_sort]
local_branches, remote_branches, tags = gitcmds.all_refs(
context, split=True, sort_key=sort_key
)
self.local_branches = local_branches
self.remote_branches = remote_branches
self.tags = tags
# Set these early since they are used to calculate 'upstream_changed'.
self.currentbranch = gitcmds.current_branch(self.context)
self.refs_updated.emit()
def _update_merge_rebase_status(self):
cherry_pick_head = self.git.git_path('CHERRY_PICK_HEAD')
merge_head = self.git.git_path('MERGE_HEAD')
rebase_merge = self.git.git_path('rebase-merge')
rebase_apply = self.git.git_path('rebase-apply', 'applying')
self.is_cherry_picking = cherry_pick_head and core.exists(cherry_pick_head)
self.is_merging = merge_head and core.exists(merge_head)
self.is_rebasing = rebase_merge and core.exists(rebase_merge)
self.is_applying_patch = rebase_apply and core.exists(rebase_apply)
if self.mode == self.mode_amend and (
self.is_merging or self.is_cherry_picking or self.is_applying_patch
):
self.set_mode(self.mode_none)
def _update_commitmsg(self):
"""Check for merge message files and update the commit message
The message is cleared when the merge completes.
"""
if self.is_amend_mode():
return
# Check if there's a message file in .git/
context = self.context
merge_msg_path = gitcmds.merge_message_path(context)
if merge_msg_path:
msg = gitcmds.read_merge_commit_message(context, merge_msg_path)
if msg != self._auto_commitmsg:
self._auto_commitmsg = msg
self._prev_commitmsg = self.commitmsg
self.set_commitmsg(msg)
elif self._auto_commitmsg and self._auto_commitmsg == self.commitmsg:
self._auto_commitmsg = ''
self.set_commitmsg(self._prev_commitmsg)
def update_submodules_list(self):
self.submodules_list = gitcmds.list_submodule(self.context)
self.submodules_changed.emit()
def update_remotes(self):
self._update_remotes()
self.update_refs()
def update_refs(self):
"""Update tag and branch names"""
self.emit_about_to_update()
self._update_branches_and_tags()
self.emit_updated()
def delete_branch(self, branch):
status, out, err = self.git.branch(branch, D=True)
self.update_refs()
return status, out, err
def rename_branch(self, branch, new_branch):
status, out, err = self.git.branch(branch, new_branch, M=True)
self.update_refs()
return status, out, err
def remote_url(self, name, action):
push = action == 'PUSH'
return gitcmds.remote_url(self.context, name, push=push)
def fetch(self, remote, **opts):
result = run_remote_action(self.context, self.git.fetch, remote, FETCH, **opts)
self.update_refs()
return result
def push(self, remote, remote_branch='', local_branch='', **opts):
# Swap the branches in push mode (reverse of fetch)
opts.update({
'local_branch': remote_branch,
'remote_branch': local_branch,
})
result = run_remote_action(self.context, self.git.push, remote, PUSH, **opts)
self.update_refs()
return result
def pull(self, remote, **opts):
result = run_remote_action(self.context, self.git.pull, remote, PULL, **opts)
# Pull can result in merge conflicts
self.update_refs()
self.update_files(update_index=False, emit=True)
return result
def create_branch(self, name, base, track=False, force=False):
"""Create a branch named 'name' from revision 'base'
Pass track=True to create a local tracking branch.
"""
return self.git.branch(name, base, track=track, force=force)
def is_commit_published(self):
"""Return True if the latest commit exists in any remote branch"""
return bool(self.git.branch(r=True, contains='HEAD')[STDOUT])
def untrack_paths(self, paths):
context = self.context
status, out, err = gitcmds.untrack_paths(context, paths)
self.update_file_status()
return status, out, err
def getcwd(self):
"""If we've chosen a directory then use it, otherwise use current"""
if self.directory:
return self.directory
return core.getcwd()
def cycle_ref_sort(self):
"""Choose the next ref sort type (version, reverse-chronological)"""
self.set_ref_sort(self.ref_sort + 1)
def set_ref_sort(self, raw_value):
value = raw_value % 2 # Currently two sort types
if value == self.ref_sort:
return
self.ref_sort = value
self.update_refs()
class Types:
"""File types (used for image diff modes)"""
IMAGE = 'image'
TEXT = 'text'
def remote_args(
context,
remote,
action,
local_branch='',
remote_branch='',
ff_only=False,
force=False,
no_ff=False,
tags=False,
rebase=False,
set_upstream=False,
prune=False,
):
"""Return arguments for git fetch/push/pull"""
args = [remote]
what = refspec_arg(local_branch, remote_branch, remote, action)
if what:
args.append(what)
kwargs = {
'verbose': True,
}
if action == PULL:
if rebase:
kwargs['rebase'] = True
elif ff_only:
kwargs['ff_only'] = True
elif no_ff:
kwargs['no_ff'] = True
elif force:
if action == PUSH and version.check_git(context, 'force-with-lease'):
kwargs['force_with_lease'] = True
else:
kwargs['force'] = True
if action == PUSH and set_upstream:
kwargs['set_upstream'] = True
if tags:
kwargs['tags'] = True
if prune:
kwargs['prune'] = True
return (args, kwargs)
def refspec(src, dst, action):
if action == PUSH and src == dst:
spec = src
else:
spec = f'{src}:{dst}'
return spec
def refspec_arg(local_branch, remote_branch, remote, action):
"""Return the refspec for a fetch or pull command"""
ref = None
if action == PUSH and local_branch and remote_branch: # Push with local and remote.
ref = refspec(local_branch, remote_branch, action)
elif action == FETCH:
if local_branch and remote_branch: # Fetch with local and remote.
if local_branch == FETCH_HEAD:
ref = remote_branch
else:
ref = refspec(remote_branch, local_branch, action)
elif remote_branch:
# If we are fetching and only a remote branch was specified then setup
# a refspec that will fetch into the remote tracking branch only.
ref = refspec(
remote_branch,
f'refs/remotes/{remote}/{remote_branch}',
action,
)
if not ref and local_branch != FETCH_HEAD:
ref = local_branch or remote_branch or None
return ref
def run_remote_action(context, fn, remote, action, **kwargs):
"""Run fetch, push or pull"""
kwargs.pop('_add_env', None)
args, kwargs = remote_args(context, remote, action, **kwargs)
autodetect_proxy(context, kwargs)
no_color(kwargs)
return fn(*args, **kwargs)
def no_color(kwargs):
"""Augment kwargs with an _add_env environment dict that disables colors"""
try:
env = kwargs['_add_env']
except KeyError:
env = kwargs['_add_env'] = {}
else:
if env is None:
env = kwargs['_add_env'] = {}
env['NO_COLOR'] = '1'
env['TERM'] = 'dumb'
def autodetect_proxy(context, kwargs):
"""Detect proxy settings when running on Gnome and KDE"""
# kwargs can refer to persistant global state so we purge it.
# Callers should not expect their _add_env to persist.
kwargs.pop('_add_env', None)
enabled = prefs.autodetect_proxy(context)
if not enabled:
return
# If "git config http.proxy" is configured then there's nothing to do.
http_proxy = prefs.http_proxy(context)
if http_proxy:
Interaction.log(
N_('http proxy configured by "git config http.proxy %(url)s"')
% dict(url=http_proxy)
)
return
xdg_current_desktop = core.getenv('XDG_CURRENT_DESKTOP', default='')
if not xdg_current_desktop:
return
add_env = {}
http_proxy = None
https_proxy = None
if xdg_current_desktop == 'KDE' or xdg_current_desktop.endswith(':KDE'):
kreadconfig = core.find_executable('kreadconfig5')
if kreadconfig:
http_proxy = autodetect_proxy_kde(kreadconfig, 'http')
https_proxy = autodetect_proxy_kde(kreadconfig, 'https')
elif xdg_current_desktop:
# If we're not on KDE then we'll fallback to GNOME / gsettings.
gsettings = core.find_executable('gsettings')
if gsettings and autodetect_proxy_gnome_is_enabled(gsettings):
http_proxy = autodetect_proxy_gnome(gsettings, 'http')
https_proxy = autodetect_proxy_gnome(gsettings, 'https')
if os.environ.get('http_proxy'):
Interaction.log(
N_('http proxy configured by the "http_proxy" environment variable')
)
elif http_proxy:
Interaction.log(
N_('%(scheme)s proxy configured from %(desktop)s settings: %(url)s')
% dict(scheme='http', desktop=xdg_current_desktop, url=http_proxy)
)
add_env['http_proxy'] = http_proxy
if os.environ.get('https_proxy', None):
Interaction.log(
N_('https proxy configured by the "https_proxy" environment variable')
)
elif https_proxy:
Interaction.log(
N_('%(scheme)s proxy configured from %(desktop)s settings: %(url)s')
% dict(scheme='https', desktop=xdg_current_desktop, url=https_proxy)
)
add_env['https_proxy'] = https_proxy
# This function has the side-effect of updating the kwargs dict.
# The "_add_env" parameter gets forwarded to the __getattr__ git function's
# _add_env option which forwards to core.run_command()'s add_env option.
if add_env:
kwargs['_add_env'] = add_env
def autodetect_proxy_gnome_is_enabled(gsettings):
"""Is the proxy manually configured on Gnome?"""
status, out, _ = core.run_command(
[gsettings, 'get', 'org.gnome.system.proxy', 'mode']
)
return status == 0 and out.strip().strip("'") == 'manual'
def autodetect_proxy_gnome(gsettings, scheme):
"""Return the configured HTTP proxy for Gnome"""
status, out, _ = core.run_command(
[gsettings, 'get', f'org.gnome.system.proxy.{scheme}', 'host']
)
if status != 0:
return None
host = out.strip().strip("'")
port = ''
status, out, _ = core.run_command(
[gsettings, 'get', f'org.gnome.system.proxy.{scheme}', 'port']
)
if status == 0:
port = ':' + out.strip()
proxy = host + port
return proxy
def autodetect_proxy_kde(kreadconfig, scheme):
"""Return the configured HTTP proxy for KDE"""
cmd = [
kreadconfig,
'--file',
'kioslaverc',
'--group',
'Proxy Settings',
'--key',
f'{scheme}Proxy',
]
status, out, err = core.run_command(cmd)
if status == 0:
proxy = out.strip()
return proxy
return None
| 24,249 | Python | .py | 611 | 31.261866 | 88 | 0.615963 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
121 | enums_compat.py | git-cola_git-cola/qtpy/enums_compat.py | # Copyright © 2009- The Spyder Development Team
# Copyright © 2012- University of North Carolina at Chapel Hill
# Luke Campagnola ('luke.campagnola@%s.com' % 'gmail')
# Ogi Moore ('ognyan.moore@%s.com' % 'gmail')
# KIU Shueng Chuan ('nixchuan@%s.com' % 'gmail')
# Licensed under the terms of the MIT License
"""
Compatibility functions for scoped and unscoped enum access.
"""
from . import PYQT6
if PYQT6:
import enum
from . import sip
def promote_enums(module):
"""
Search enums in the given module and allow unscoped access.
Taken from:
https://github.com/pyqtgraph/pyqtgraph/blob/pyqtgraph-0.12.1/pyqtgraph/Qt.py#L331-L377
and adapted to also copy enum values aliased under different names.
"""
class_names = [name for name in dir(module) if name.startswith("Q")]
for class_name in class_names:
klass = getattr(module, class_name)
if not isinstance(klass, sip.wrappertype):
continue
attrib_names = [name for name in dir(klass) if name[0].isupper()]
for attrib_name in attrib_names:
attrib = getattr(klass, attrib_name)
if not isinstance(attrib, enum.EnumMeta):
continue
for name, value in attrib.__members__.items():
setattr(klass, name, value)
| 1,454 | Python | .py | 32 | 37.03125 | 94 | 0.606511 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
122 | QtCore.py | git-cola_git-cola/qtpy/QtCore.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtCore classes and functions."""
import contextlib
from typing import TYPE_CHECKING
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
from . import QT_VERSION as _qt_version
from . import parse
from ._utils import possibly_static_exec, possibly_static_exec_
if PYQT5:
from PyQt5.QtCore import *
from PyQt5.QtCore import pyqtBoundSignal as SignalInstance
from PyQt5.QtCore import pyqtProperty as Property
from PyQt5.QtCore import pyqtSignal as Signal
from PyQt5.QtCore import pyqtSlot as Slot
try:
from PyQt5.QtCore import Q_ENUM as QEnum
del Q_ENUM
except ImportError: # fallback for Qt5.9
from PyQt5.QtCore import Q_ENUMS as QEnum
del Q_ENUMS
from PyQt5.QtCore import QT_VERSION_STR as __version__
# Those are imported from `import *`
del pyqtSignal, pyqtBoundSignal, pyqtSlot, pyqtProperty, QT_VERSION_STR
elif PYQT6:
from PyQt6 import QtCore
from PyQt6.QtCore import *
from PyQt6.QtCore import QT_VERSION_STR as __version__
from PyQt6.QtCore import pyqtBoundSignal as SignalInstance
from PyQt6.QtCore import pyqtEnum as QEnum
from PyQt6.QtCore import pyqtProperty as Property
from PyQt6.QtCore import pyqtSignal as Signal
from PyQt6.QtCore import pyqtSlot as Slot
# For issue #311
# Seems like there is an error with sip. Without first
# trying to import `PyQt6.QtGui.Qt`, some functions like
# `PyQt6.QtCore.Qt.mightBeRichText` are missing.
if not TYPE_CHECKING:
with contextlib.suppress(ImportError):
from PyQt6.QtGui import Qt
# Map missing methods
QCoreApplication.exec_ = lambda *args, **kwargs: possibly_static_exec(
QCoreApplication,
*args,
**kwargs,
)
QEventLoop.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QThread.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
# Those are imported from `import *`
del (
pyqtSignal,
pyqtBoundSignal,
pyqtSlot,
pyqtProperty,
pyqtEnum,
QT_VERSION_STR,
)
# Allow unscoped access for enums inside the QtCore module
from .enums_compat import promote_enums
promote_enums(QtCore)
del QtCore
# Alias deprecated ItemDataRole enum values removed in Qt6
Qt.BackgroundColorRole = (
Qt.ItemDataRole.BackgroundColorRole
) = Qt.BackgroundRole
Qt.TextColorRole = Qt.ItemDataRole.TextColorRole = Qt.ForegroundRole
# Alias for MiddleButton removed in PyQt6 but available in PyQt5, PySide2 and PySide6
Qt.MidButton = Qt.MiddleButton
# Add removed definition for `Qt.ItemFlags` as an alias of `Qt.ItemFlag`
# passing as default value 0 in the same way PySide6 6.5+ does.
# Note that for PyQt5 and PySide2 those definitions are two different classes
# (one is the flag definition and the other the enum definition)
Qt.ItemFlags = lambda value=0: Qt.ItemFlag(value)
elif PYSIDE2:
import PySide2.QtCore
from PySide2.QtCore import *
__version__ = PySide2.QtCore.__version__
# Missing QtGui utility functions on Qt
if getattr(Qt, "mightBeRichText", None) is None:
try:
from PySide2.QtGui import Qt as guiQt
Qt.mightBeRichText = guiQt.mightBeRichText
del guiQt
except ImportError:
# Fails with PySide2 5.12.0
pass
QCoreApplication.exec = lambda *args, **kwargs: possibly_static_exec_(
QCoreApplication,
*args,
**kwargs,
)
QEventLoop.exec = lambda self, *args, **kwargs: self.exec_(*args, **kwargs)
QThread.exec = lambda self, *args, **kwargs: self.exec_(*args, **kwargs)
QTextStreamManipulator.exec = lambda self, *args, **kwargs: self.exec_(
*args,
**kwargs,
)
elif PYSIDE6:
import PySide6.QtCore
from PySide6.QtCore import *
__version__ = PySide6.QtCore.__version__
# Missing QtGui utility functions on Qt
if getattr(Qt, "mightBeRichText", None) is None:
from PySide6.QtGui import Qt as guiQt
Qt.mightBeRichText = guiQt.mightBeRichText
del guiQt
# Alias deprecated ItemDataRole enum values removed in Qt6
Qt.BackgroundColorRole = (
Qt.ItemDataRole.BackgroundColorRole
) = Qt.BackgroundRole
Qt.TextColorRole = Qt.ItemDataRole.TextColorRole = Qt.ForegroundRole
Qt.MidButton = Qt.MiddleButton
# Map DeprecationWarning methods
QCoreApplication.exec_ = lambda *args, **kwargs: possibly_static_exec(
QCoreApplication,
*args,
**kwargs,
)
QEventLoop.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QThread.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QTextStreamManipulator.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
# Passing as default value 0 in the same way PySide6 6.3.2 does for the `Qt.ItemFlags` definition.
if parse(_qt_version) > parse("6.3"):
Qt.ItemFlags = lambda value=0: Qt.ItemFlag(value)
# For issue #153 and updated for issue #305
if PYQT5 or PYQT6:
QDate.toPython = lambda self, *args, **kwargs: self.toPyDate(
*args,
**kwargs,
)
QDateTime.toPython = lambda self, *args, **kwargs: self.toPyDateTime(
*args,
**kwargs,
)
QTime.toPython = lambda self, *args, **kwargs: self.toPyTime(
*args,
**kwargs,
)
if PYSIDE2 or PYSIDE6:
QDate.toPyDate = lambda self, *args, **kwargs: self.toPython(
*args,
**kwargs,
)
QDateTime.toPyDateTime = lambda self, *args, **kwargs: self.toPython(
*args,
**kwargs,
)
QTime.toPyTime = lambda self, *args, **kwargs: self.toPython(
*args,
**kwargs,
)
# Mirror https://github.com/spyder-ide/qtpy/pull/393
if PYQT5 or PYSIDE2:
QLibraryInfo.path = QLibraryInfo.location
QLibraryInfo.LibraryPath = QLibraryInfo.LibraryLocation
if PYQT6 or PYSIDE6:
QLibraryInfo.location = QLibraryInfo.path
QLibraryInfo.LibraryLocation = QLibraryInfo.LibraryPath
| 6,457 | Python | .py | 166 | 32.933735 | 102 | 0.672631 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
123 | Qt3DInput.py | git-cola_git-cola/qtpy/Qt3DInput.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DInput classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qt3DInput import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DInput",
missing_package="PyQt3D",
) from error
elif PYQT6:
try:
from PyQt6.Qt3DInput import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DInput",
missing_package="PyQt6-3D",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.Qt3DInput as __temp
for __name in inspect.getmembers(__temp.Qt3DInput):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide6.Qt3DInput as __temp
for __name in inspect.getmembers(__temp.Qt3DInput):
globals()[__name[0]] = __name[1]
| 1,371 | Python | .py | 42 | 27.190476 | 79 | 0.593797 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
124 | QtConcurrent.py | git-cola_git-cola/qtpy/QtConcurrent.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtConcurrent classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6:
raise QtBindingMissingModuleError(name="QtConcurrent")
elif PYSIDE2:
from PySide2.QtConcurrent import *
elif PYSIDE6:
from PySide6.QtConcurrent import *
| 626 | Python | .py | 20 | 28.55 | 79 | 0.562189 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
125 | QtDataVisualization.py | git-cola_git-cola/qtpy/QtDataVisualization.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtDataVisualization classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.QtDataVisualization import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtDataVisualization",
missing_package="PyQtDataVisualization",
) from error
elif PYQT6:
try:
from PyQt6.QtDataVisualization import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtDataVisualization",
missing_package="PyQt6-DataVisualization",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.QtDataVisualization as __temp
for __name in inspect.getmembers(__temp.QtDataVisualization):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
from PySide6.QtDataVisualization import *
| 1,294 | Python | .py | 38 | 28.710526 | 79 | 0.619504 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
126 | QtRemoteObjects.py | git-cola_git-cola/qtpy/QtRemoteObjects.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtRemoteObjects classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtRemoteObjects import *
elif PYQT6:
from PyQt6.QtRemoteObjects import *
elif PYSIDE6:
from PySide6.QtRemoteObjects import *
elif PYSIDE2:
from PySide2.QtRemoteObjects import *
| 605 | Python | .py | 16 | 35.625 | 79 | 0.571672 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
127 | QtDBus.py | git-cola_git-cola/qtpy/QtDBus.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtDBus classes and functions."""
import sys
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
QtModuleNotInOSError,
)
if PYQT5:
from PyQt5.QtDBus import *
elif PYQT6:
from PyQt6.QtDBus import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtDBus")
elif PYSIDE6:
if sys.platform != "win32":
from PySide6.QtDBus import *
else:
raise QtModuleNotInOSError(name="QtDBus")
| 768 | Python | .py | 27 | 25.074074 | 79 | 0.572592 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
128 | QtWebChannel.py | git-cola_git-cola/qtpy/QtWebChannel.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtWebChannel classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtWebChannel import *
elif PYQT6:
from PyQt6.QtWebChannel import *
elif PYSIDE2:
from PySide2.QtWebChannel import *
elif PYSIDE6:
from PySide6.QtWebChannel import *
| 590 | Python | .py | 16 | 34.6875 | 79 | 0.56042 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
129 | QtGui.py | git-cola_git-cola/qtpy/QtGui.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtGui classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, QtModuleNotInstalledError
from ._utils import getattr_missing_optional_dep, possibly_static_exec
_missing_optional_names = {}
_QTOPENGL_NAMES = {
"QOpenGLBuffer",
"QOpenGLContext",
"QOpenGLContextGroup",
"QOpenGLDebugLogger",
"QOpenGLDebugMessage",
"QOpenGLFramebufferObject",
"QOpenGLFramebufferObjectFormat",
"QOpenGLPixelTransferOptions",
"QOpenGLShader",
"QOpenGLShaderProgram",
"QOpenGLTexture",
"QOpenGLTextureBlitter",
"QOpenGLVersionProfile",
"QOpenGLVertexArrayObject",
"QOpenGLWindow",
}
def __getattr__(name):
"""Custom getattr to chain and wrap errors due to missing optional deps."""
raise getattr_missing_optional_dep(
name,
module_name=__name__,
optional_names=_missing_optional_names,
)
if PYQT5:
from PyQt5.QtGui import *
# Backport items moved to QtGui in Qt6
from PyQt5.QtWidgets import (
QAction,
QActionGroup,
QFileSystemModel,
QShortcut,
QUndoCommand,
)
elif PYQT6:
from PyQt6 import QtGui
from PyQt6.QtGui import *
# Attempt to import QOpenGL* classes, but if that fails,
# don't raise an exception until the name is explicitly accessed.
# See https://github.com/spyder-ide/qtpy/pull/387/
try:
from PyQt6.QtOpenGL import *
except ImportError as error:
for name in _QTOPENGL_NAMES:
_missing_optional_names[name] = {
"name": "PyQt6.QtOpenGL",
"missing_package": "pyopengl",
"import_error": error,
}
QFontMetrics.width = lambda self, *args, **kwargs: self.horizontalAdvance(
*args,
**kwargs,
)
QFontMetricsF.width = lambda self, *args, **kwargs: self.horizontalAdvance(
*args,
**kwargs,
)
# Map missing/renamed methods
QDrag.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QGuiApplication.exec_ = lambda *args, **kwargs: possibly_static_exec(
QGuiApplication,
*args,
**kwargs,
)
QTextDocument.print_ = lambda self, *args, **kwargs: self.print(
*args,
**kwargs,
)
# Allow unscoped access for enums inside the QtGui module
from .enums_compat import promote_enums
promote_enums(QtGui)
del QtGui
elif PYSIDE2:
from PySide2.QtGui import *
# Backport items moved to QtGui in Qt6
from PySide2.QtWidgets import (
QAction,
QActionGroup,
QFileSystemModel,
QShortcut,
QUndoCommand,
)
if hasattr(QFontMetrics, "horizontalAdvance"):
# Needed to prevent raising a DeprecationWarning when using QFontMetrics.width
QFontMetrics.width = (
lambda self, *args, **kwargs: self.horizontalAdvance(
*args,
**kwargs,
)
)
elif PYSIDE6:
from PySide6.QtGui import *
# Attempt to import QOpenGL* classes, but if that fails,
# don't raise an exception until the name is explicitly accessed.
# See https://github.com/spyder-ide/qtpy/pull/387/
try:
from PySide6.QtOpenGL import *
except ImportError as error:
for name in _QTOPENGL_NAMES:
_missing_optional_names[name] = {
"name": "PySide6.QtOpenGL",
"missing_package": "pyopengl",
"import_error": error,
}
# Backport `QFileSystemModel` moved to QtGui in Qt6
from PySide6.QtWidgets import QFileSystemModel
QFontMetrics.width = lambda self, *args, **kwargs: self.horizontalAdvance(
*args,
**kwargs,
)
QFontMetricsF.width = lambda self, *args, **kwargs: self.horizontalAdvance(
*args,
**kwargs,
)
# Map DeprecationWarning methods
QDrag.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QGuiApplication.exec_ = lambda *args, **kwargs: possibly_static_exec(
QGuiApplication,
*args,
**kwargs,
)
if PYSIDE2 or PYSIDE6:
# PySide{2,6} do not accept the `mode` keyword argument in
# QTextCursor.movePosition() even though it is a valid optional argument
# as per C++ API. Fix this by monkeypatching.
#
# Notes:
#
# * The `mode` argument is called `arg__2` in PySide{2,6} as per
# QTextCursor.movePosition.__doc__ and __signature__. Using `arg__2` as
# keyword argument works as intended, so does using a positional
# argument. Tested with PySide2 5.15.0, 5.15.2.1 and 5.15.3 and PySide6
# 6.3.0; older version, down to PySide 1, are probably affected as well [1].
#
# * PySide2 5.15.0 and 5.15.2.1 silently ignore invalid keyword arguments,
# i.e. passing the `mode` keyword argument has no effect and doesn`t
# raise an exception. Older versions, down to PySide 1, are probably
# affected as well [1]. At least PySide2 5.15.3 and PySide6 6.3.0 raise an
# exception when `mode` or any other invalid keyword argument is passed.
#
# [1] https://bugreports.qt.io/browse/PYSIDE-185
movePosition = QTextCursor.movePosition
def movePositionPatched(
self,
operation: QTextCursor.MoveOperation,
mode: QTextCursor.MoveMode = QTextCursor.MoveAnchor,
n: int = 1,
) -> bool:
return movePosition(self, operation, mode, n)
QTextCursor.movePosition = movePositionPatched
if PYQT5 or PYSIDE2:
# Part of the fix for https://github.com/spyder-ide/qtpy/issues/394
from qtpy.QtCore import QPointF as __QPointF
QNativeGestureEvent.x = lambda self: self.localPos().toPoint().x()
QNativeGestureEvent.y = lambda self: self.localPos().toPoint().y()
QNativeGestureEvent.position = lambda self: self.localPos()
QNativeGestureEvent.globalX = lambda self: self.globalPos().x()
QNativeGestureEvent.globalY = lambda self: self.globalPos().y()
QNativeGestureEvent.globalPosition = lambda self: __QPointF(
float(self.globalPos().x()),
float(self.globalPos().y()),
)
QEnterEvent.position = lambda self: self.localPos()
QEnterEvent.globalPosition = lambda self: __QPointF(
float(self.globalX()),
float(self.globalY()),
)
QTabletEvent.position = lambda self: self.posF()
QTabletEvent.globalPosition = lambda self: self.globalPosF()
QHoverEvent.x = lambda self: self.pos().x()
QHoverEvent.y = lambda self: self.pos().y()
QHoverEvent.position = lambda self: self.posF()
# No `QHoverEvent.globalPosition`, `QHoverEvent.globalX`,
# nor `QHoverEvent.globalY` in the Qt5 docs.
QMouseEvent.position = lambda self: self.localPos()
QMouseEvent.globalPosition = lambda self: __QPointF(
float(self.globalX()),
float(self.globalY()),
)
# Follow similar approach for `QDropEvent` and child classes
QDropEvent.position = lambda self: self.posF()
if PYQT6 or PYSIDE6:
# Part of the fix for https://github.com/spyder-ide/qtpy/issues/394
for _class in (
QNativeGestureEvent,
QEnterEvent,
QTabletEvent,
QHoverEvent,
QMouseEvent,
):
for _obsolete_function in (
"pos",
"x",
"y",
"globalPos",
"globalX",
"globalY",
):
if hasattr(_class, _obsolete_function):
delattr(_class, _obsolete_function)
QSinglePointEvent.pos = lambda self: self.position().toPoint()
QSinglePointEvent.posF = lambda self: self.position()
QSinglePointEvent.localPos = lambda self: self.position()
QSinglePointEvent.x = lambda self: self.position().toPoint().x()
QSinglePointEvent.y = lambda self: self.position().toPoint().y()
QSinglePointEvent.globalPos = lambda self: self.globalPosition().toPoint()
QSinglePointEvent.globalX = (
lambda self: self.globalPosition().toPoint().x()
)
QSinglePointEvent.globalY = (
lambda self: self.globalPosition().toPoint().y()
)
# Follow similar approach for `QDropEvent` and child classes
QDropEvent.pos = lambda self: self.position().toPoint()
QDropEvent.posF = lambda self: self.position()
| 8,624 | Python | .py | 226 | 31.469027 | 86 | 0.648064 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
130 | QtPurchasing.py | git-cola_git-cola/qtpy/QtPurchasing.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPurchasing classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.QtPurchasing import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtPurchasing",
missing_package="PyQtPurchasing",
) from error
elif PYQT6 or PYSIDE2 or PYSIDE6:
raise QtBindingMissingModuleError(name="QtPurchasing")
| 808 | Python | .py | 25 | 27.84 | 79 | 0.575641 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
131 | QtQml.py | git-cola_git-cola/qtpy/QtQml.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtQml classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtQml import *
elif PYQT6:
from PyQt6.QtQml import *
elif PYSIDE6:
from PySide6.QtQml import *
elif PYSIDE2:
from PySide2.QtQml import *
| 555 | Python | .py | 16 | 32.5 | 79 | 0.531716 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
132 | QtXml.py | git-cola_git-cola/qtpy/QtXml.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtXml classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtXml import *
elif PYQT6:
from PyQt6.QtXml import *
elif PYSIDE2:
from PySide2.QtXml import *
elif PYSIDE6:
from PySide6.QtXml import *
| 555 | Python | .py | 16 | 32.5 | 79 | 0.531716 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
133 | QtStateMachine.py | git-cola_git-cola/qtpy/QtStateMachine.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtStateMachine classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6 or PYSIDE2:
raise QtBindingMissingModuleError(name="QtStateMachine")
elif PYSIDE6:
from PySide6.QtStateMachine import *
| 590 | Python | .py | 18 | 30.055556 | 79 | 0.551845 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
134 | Qt3DExtras.py | git-cola_git-cola/qtpy/Qt3DExtras.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DExtras classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qt3DExtras import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DExtras",
missing_package="PyQt3D",
) from error
elif PYQT6:
try:
from PyQt6.Qt3DExtras import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DExtras",
missing_package="PyQt6-3D",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.Qt3DExtras as __temp
for __name in inspect.getmembers(__temp.Qt3DExtras):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide6.Qt3DExtras as __temp
for __name in inspect.getmembers(__temp.Qt3DExtras):
globals()[__name[0]] = __name[1]
| 1,380 | Python | .py | 42 | 27.404762 | 79 | 0.596544 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
135 | QtAxContainer.py | git-cola_git-cola/qtpy/QtAxContainer.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtAxContainer classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6:
raise QtBindingMissingModuleError(name="QtAxContainer")
elif PYSIDE2:
from PySide2.QtAxContainer import *
elif PYSIDE6:
from PySide6.QtAxContainer import *
| 630 | Python | .py | 20 | 28.75 | 79 | 0.565074 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
136 | QtQuickWidgets.py | git-cola_git-cola/qtpy/QtQuickWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtQuickWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtQuickWidgets import *
elif PYQT6:
from PyQt6.QtQuickWidgets import *
elif PYSIDE6:
from PySide6.QtQuickWidgets import *
elif PYSIDE2:
from PySide2.QtQuickWidgets import *
| 600 | Python | .py | 16 | 35.3125 | 79 | 0.567986 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
137 | QtWebEngineCore.py | git-cola_git-cola/qtpy/QtWebEngineCore.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtWebEngineCore classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.QtWebEngineCore import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtWebEngineCore",
missing_package="PyQtWebEngine",
) from error
elif PYQT6:
try:
from PyQt6.QtWebEngineCore import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtWebEngineCore",
missing_package="PyQt6-WebEngine",
) from error
elif PYSIDE2:
from PySide2.QtWebEngineCore import *
elif PYSIDE6:
from PySide6.QtWebEngineCore import *
| 1,053 | Python | .py | 34 | 25.764706 | 79 | 0.591535 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
138 | QtX11Extras.py | git-cola_git-cola/qtpy/QtX11Extras.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Linux-specific utilities"""
import sys
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInOSError,
QtModuleNotInQtVersionError,
)
if sys.platform == "linux":
if PYQT5:
from PyQt5.QtX11Extras import *
elif PYQT6:
raise QtModuleNotInQtVersionError(name="QtX11Extras")
elif PYSIDE2:
from PySide2.QtX11Extras import *
elif PYSIDE6:
raise QtModuleNotInQtVersionError(name="QtX11Extras")
else:
raise QtModuleNotInOSError(name="QtX11Extras")
| 826 | Python | .py | 27 | 26.62963 | 79 | 0.584906 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
139 | shiboken.py | git-cola_git-cola/qtpy/shiboken.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides access to shiboken."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6:
raise QtBindingMissingModuleError(name="shiboken")
elif PYSIDE2:
from shiboken2 import *
elif PYSIDE6:
from shiboken6 import *
| 584 | Python | .py | 20 | 26.45 | 79 | 0.534759 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
140 | Qt3DRender.py | git-cola_git-cola/qtpy/Qt3DRender.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DRender classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qt3DRender import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DRender",
missing_package="PyQt3D",
) from error
elif PYQT6:
try:
from PyQt6.Qt3DRender import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DRender",
missing_package="PyQt6-3D",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.Qt3DRender as __temp
for __name in inspect.getmembers(__temp.Qt3DRender):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide6.Qt3DRender as __temp
for __name in inspect.getmembers(__temp.Qt3DRender):
globals()[__name[0]] = __name[1]
| 1,380 | Python | .py | 42 | 27.404762 | 79 | 0.596544 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
141 | sip.py | git-cola_git-cola/qtpy/sip.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides access to sip."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.sip import *
elif PYQT6:
from PyQt6.sip import *
elif PYSIDE2 or PYSIDE6:
raise QtBindingMissingModuleError(name="sip")
| 574 | Python | .py | 20 | 25.95 | 79 | 0.522686 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
142 | QtWebEngineQuick.py | git-cola_git-cola/qtpy/QtWebEngineQuick.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtWebEngineQuick classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
QtModuleNotInstalledError,
)
if PYQT5:
raise QtBindingMissingModuleError(name="QtWebEngineQuick")
elif PYQT6:
try:
from PyQt6.QtWebEngineQuick import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtWebEngineQuick",
missing_package="PyQt6-WebEngine",
) from error
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtWebEngineQuick")
elif PYSIDE6:
from PySide6.QtWebEngineQuick import *
| 937 | Python | .py | 29 | 28.034483 | 79 | 0.612155 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
143 | QtCharts.py | git-cola_git-cola/qtpy/QtCharts.py | # -----------------------------------------------------------------------------
# Copyright © 2019- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtChart classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5 import QtChart as QtCharts
from PyQt5.QtChart import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtCharts",
missing_package="PyQtChart",
) from error
elif PYQT6:
try:
from PyQt6 import QtCharts
from PyQt6.QtCharts import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtCharts",
missing_package="PyQt6-Charts",
) from error
elif PYSIDE2:
import inspect
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import PySide2.QtCharts as __temp
from PySide2.QtCharts import *
for __name in inspect.getmembers(__temp.QtCharts):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
from PySide6 import QtCharts
from PySide6.QtCharts import *
| 1,330 | Python | .py | 42 | 26.166667 | 79 | 0.597818 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
144 | cli.py | git-cola_git-cola/qtpy/cli.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The QtPy Contributors
#
# Released under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provide a CLI to allow configuring developer settings, including mypy."""
# Standard library imports
import argparse
import json
import textwrap
def print_version():
"""Print the current version of the package."""
import qtpy
print("QtPy version", qtpy.__version__)
def get_api_status():
"""Get the status of each Qt API usage."""
import qtpy
return {name: name == qtpy.API for name in qtpy.API_NAMES}
def generate_mypy_args():
"""Generate a string with always-true/false args to pass to mypy."""
options = {False: "--always-false", True: "--always-true"}
apis_active = get_api_status()
return " ".join(
f"{options[is_active]}={name.upper()}"
for name, is_active in apis_active.items()
)
def generate_pyright_config_json():
"""Generate Pyright config to be used in `pyrightconfig.json`."""
apis_active = get_api_status()
return json.dumps(
{
"defineConstant": {
name.upper(): is_active
for name, is_active in apis_active.items()
},
},
)
def generate_pyright_config_toml():
"""Generate a Pyright config to be used in `pyproject.toml`."""
apis_active = get_api_status()
return "[tool.pyright.defineConstant]\n" + "\n".join(
f"{name.upper()} = {str(is_active).lower()}"
for name, is_active in apis_active.items()
)
def print_mypy_args():
"""Print the generated mypy args to stdout."""
print(generate_mypy_args())
def print_pyright_config_json():
"""Print the generated Pyright JSON config to stdout."""
print(generate_pyright_config_json())
def print_pyright_config_toml():
"""Print the generated Pyright TOML config to stdout."""
print(generate_pyright_config_toml())
def print_pyright_configs():
"""Print the generated Pyright configs to stdout."""
print("pyrightconfig.json:")
print_pyright_config_json()
print()
print("pyproject.toml:")
print_pyright_config_toml()
def generate_arg_parser():
"""Generate the argument parser for the dev CLI for QtPy."""
parser = argparse.ArgumentParser(
description="Features to support development with QtPy.",
)
parser.set_defaults(func=parser.print_help)
parser.add_argument(
"--version",
action="store_const",
dest="func",
const=print_version,
help="If passed, will print the version and exit",
)
cli_subparsers = parser.add_subparsers(
title="Subcommands",
help="Subcommand to run",
metavar="Subcommand",
)
# Parser for the MyPy args subcommand
mypy_args_parser = cli_subparsers.add_parser(
name="mypy-args",
help="Generate command line arguments for using mypy with QtPy.",
formatter_class=argparse.RawTextHelpFormatter,
description=textwrap.dedent(
"""
Generate command line arguments for using mypy with QtPy.
This will generate strings similar to the following
which help guide mypy through which library QtPy would have used
so that mypy can get the proper underlying type hints.
--always-false=PYQT5 --always-false=PYQT6 --always-true=PYSIDE2 --always-false=PYSIDE6
It can be used as follows on Bash or a similar shell:
mypy --package mypackage $(qtpy mypy-args)
""",
),
)
mypy_args_parser.set_defaults(func=print_mypy_args)
# Parser for the Pyright config subcommand
pyright_config_parser = cli_subparsers.add_parser(
name="pyright-config",
help="Generate Pyright config for using Pyright with QtPy.",
formatter_class=argparse.RawTextHelpFormatter,
description=textwrap.dedent(
"""
Generate Pyright config for using Pyright with QtPy.
This will generate config sections to be included in a Pyright
config file (either `pyrightconfig.json` or `pyproject.toml`)
which help guide Pyright through which library QtPy would have used
so that Pyright can get the proper underlying type hints.
""",
),
)
pyright_config_parser.set_defaults(func=print_pyright_configs)
return parser
def main(args=None):
"""Run the development CLI for QtPy."""
parser = generate_arg_parser()
parsed_args = parser.parse_args(args=args)
reserved_params = {"func"}
cleaned_args = {
key: value
for key, value in vars(parsed_args).items()
if key not in reserved_params
}
parsed_args.func(**cleaned_args)
| 4,945 | Python | .py | 125 | 32.632 | 102 | 0.63507 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
145 | QtTextToSpeech.py | git-cola_git-cola/qtpy/QtTextToSpeech.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtTextToSpeech classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtTextToSpeech import *
elif PYQT6:
raise QtBindingMissingModuleError(name="QtTextToSpeech")
elif PYSIDE2:
from PySide2.QtTextToSpeech import *
elif PYSIDE6:
raise QtBindingMissingModuleError(name="QtTextToSpeech")
| 696 | Python | .py | 22 | 28.863636 | 79 | 0.591654 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
146 | QtPositioning.py | git-cola_git-cola/qtpy/QtPositioning.py | # -----------------------------------------------------------------------------
# Copyright 2020 Antonio Valentino
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPositioning classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtPositioning import *
elif PYQT6:
from PyQt6.QtPositioning import *
elif PYSIDE2:
from PySide2.QtPositioning import *
elif PYSIDE6:
from PySide6.QtPositioning import *
| 581 | Python | .py | 16 | 34.125 | 79 | 0.562278 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
147 | QtDesigner.py | git-cola_git-cola/qtpy/QtDesigner.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtDesigner classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtDesigner import *
elif PYQT6:
from PyQt6.QtDesigner import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtDesigner")
elif PYSIDE6:
from PySide6.QtDesigner import *
| 646 | Python | .py | 22 | 26.590909 | 79 | 0.563607 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
148 | QtPdf.py | git-cola_git-cola/qtpy/QtPdf.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPdf classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
raise QtBindingMissingModuleError(name="QtPdf")
elif PYQT6:
# Available with version >=6.4.0
from PyQt6.QtPdf import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtPdf")
elif PYSIDE6:
# Available with version >=6.4.0
from PySide6.QtPdf import *
| 725 | Python | .py | 24 | 27.25 | 79 | 0.570201 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
149 | Qt3DAnimation.py | git-cola_git-cola/qtpy/Qt3DAnimation.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DAnimation classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qt3DAnimation import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DAnimation",
missing_package="PyQt3D",
) from error
elif PYQT6:
try:
from PyQt6.Qt3DAnimation import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DAnimation",
missing_package="PyQt6-3D",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.Qt3DAnimation as __temp
for __name in inspect.getmembers(__temp.Qt3DAnimation):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide6.Qt3DAnimation as __temp
for __name in inspect.getmembers(__temp.Qt3DAnimation):
globals()[__name[0]] = __name[1]
| 1,407 | Python | .py | 42 | 28.047619 | 79 | 0.604566 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
150 | QtWidgets.py | git-cola_git-cola/qtpy/QtWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides widget classes and functions."""
from functools import partialmethod
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
from . import QT_VERSION as _qt_version
from . import parse
from ._utils import (
add_action,
getattr_missing_optional_dep,
possibly_static_exec,
static_method_kwargs_wrapper,
)
_missing_optional_names = {}
def __getattr__(name):
"""Custom getattr to chain and wrap errors due to missing optional deps."""
raise getattr_missing_optional_dep(
name,
module_name=__name__,
optional_names=_missing_optional_names,
)
if PYQT5:
from PyQt5.QtWidgets import *
elif PYQT6:
from PyQt6 import QtWidgets
from PyQt6.QtGui import (
QAction,
QActionGroup,
QFileSystemModel,
QShortcut,
QUndoCommand,
)
from PyQt6.QtWidgets import *
# Attempt to import QOpenGLWidget, but if that fails,
# don't raise an exception until the name is explicitly accessed.
# See https://github.com/spyder-ide/qtpy/pull/387/
try:
from PyQt6.QtOpenGLWidgets import QOpenGLWidget
except ImportError as error:
_missing_optional_names["QOpenGLWidget"] = {
"name": "PyQt6.QtOpenGLWidgets",
"missing_package": "pyopengl",
"import_error": error,
}
# Map missing/renamed methods
QTextEdit.setTabStopWidth = (
lambda self, *args, **kwargs: self.setTabStopDistance(*args, **kwargs)
)
QTextEdit.tabStopWidth = (
lambda self, *args, **kwargs: self.tabStopDistance(*args, **kwargs)
)
QTextEdit.print_ = lambda self, *args, **kwargs: self.print(
*args,
**kwargs,
)
QPlainTextEdit.setTabStopWidth = (
lambda self, *args, **kwargs: self.setTabStopDistance(*args, **kwargs)
)
QPlainTextEdit.tabStopWidth = (
lambda self, *args, **kwargs: self.tabStopDistance(*args, **kwargs)
)
QPlainTextEdit.print_ = lambda self, *args, **kwargs: self.print(
*args,
**kwargs,
)
QApplication.exec_ = lambda *args, **kwargs: possibly_static_exec(
QApplication,
*args,
**kwargs,
)
QDialog.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QMenu.exec_ = lambda *args, **kwargs: possibly_static_exec(
QMenu,
*args,
**kwargs,
)
QLineEdit.getTextMargins = lambda self: (
self.textMargins().left(),
self.textMargins().top(),
self.textMargins().right(),
self.textMargins().bottom(),
)
# Add removed definition for `QFileDialog.Options` as an alias of `QFileDialog.Option`
# passing as default value 0 in the same way PySide6 6.5+ does.
# Note that for PyQt5 and PySide2 those definitions are two different classes
# (one is the flag definition and the other the enum definition)
QFileDialog.Options = lambda value=0: QFileDialog.Option(value)
# Allow unscoped access for enums inside the QtWidgets module
from .enums_compat import promote_enums
promote_enums(QtWidgets)
del QtWidgets
elif PYSIDE2:
from PySide2.QtWidgets import *
elif PYSIDE6:
from PySide6.QtGui import QAction, QActionGroup, QShortcut, QUndoCommand
from PySide6.QtWidgets import *
# Attempt to import QOpenGLWidget, but if that fails,
# don't raise an exception until the name is explicitly accessed.
# See https://github.com/spyder-ide/qtpy/pull/387/
try:
from PySide6.QtOpenGLWidgets import QOpenGLWidget
except ImportError as error:
_missing_optional_names["QOpenGLWidget"] = {
"name": "PySide6.QtOpenGLWidgets",
"missing_package": "pyopengl",
"import_error": error,
}
# Map missing/renamed methods
QTextEdit.setTabStopWidth = (
lambda self, *args, **kwargs: self.setTabStopDistance(*args, **kwargs)
)
QTextEdit.tabStopWidth = (
lambda self, *args, **kwargs: self.tabStopDistance(*args, **kwargs)
)
QPlainTextEdit.setTabStopWidth = (
lambda self, *args, **kwargs: self.setTabStopDistance(*args, **kwargs)
)
QPlainTextEdit.tabStopWidth = (
lambda self, *args, **kwargs: self.tabStopDistance(*args, **kwargs)
)
QLineEdit.getTextMargins = lambda self: (
self.textMargins().left(),
self.textMargins().top(),
self.textMargins().right(),
self.textMargins().bottom(),
)
# Map DeprecationWarning methods
QApplication.exec_ = lambda *args, **kwargs: possibly_static_exec(
QApplication,
*args,
**kwargs,
)
QDialog.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QMenu.exec_ = lambda *args, **kwargs: possibly_static_exec(
QMenu,
*args,
**kwargs,
)
# Passing as default value 0 in the same way PySide6 < 6.3.2 does for the `QFileDialog.Options` definition.
if parse(_qt_version) > parse("6.3"):
QFileDialog.Options = lambda value=0: QFileDialog.Option(value)
if PYSIDE2 or PYSIDE6:
# Make PySide2/6 `QFileDialog` static methods accept the `directory` kwarg as `dir`
QFileDialog.getExistingDirectory = static_method_kwargs_wrapper(
QFileDialog.getExistingDirectory,
"directory",
"dir",
)
QFileDialog.getOpenFileName = static_method_kwargs_wrapper(
QFileDialog.getOpenFileName,
"directory",
"dir",
)
QFileDialog.getOpenFileNames = static_method_kwargs_wrapper(
QFileDialog.getOpenFileNames,
"directory",
"dir",
)
QFileDialog.getSaveFileName = static_method_kwargs_wrapper(
QFileDialog.getSaveFileName,
"directory",
"dir",
)
else:
# Make PyQt5/6 `QFileDialog` static methods accept the `dir` kwarg as `directory`
QFileDialog.getExistingDirectory = static_method_kwargs_wrapper(
QFileDialog.getExistingDirectory,
"dir",
"directory",
)
QFileDialog.getOpenFileName = static_method_kwargs_wrapper(
QFileDialog.getOpenFileName,
"dir",
"directory",
)
QFileDialog.getOpenFileNames = static_method_kwargs_wrapper(
QFileDialog.getOpenFileNames,
"dir",
"directory",
)
QFileDialog.getSaveFileName = static_method_kwargs_wrapper(
QFileDialog.getSaveFileName,
"dir",
"directory",
)
# Make `addAction` compatible with Qt6 >= 6.3
if PYQT5 or PYSIDE2 or parse(_qt_version) < parse("6.3"):
QMenu.addAction = partialmethod(add_action, old_add_action=QMenu.addAction)
QToolBar.addAction = partialmethod(
add_action,
old_add_action=QToolBar.addAction,
)
| 7,051 | Python | .py | 197 | 29.446701 | 111 | 0.650227 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
151 | QtUiTools.py | git-cola_git-cola/qtpy/QtUiTools.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtUiTools classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6:
raise QtBindingMissingModuleError(name="QtUiTools")
elif PYSIDE2:
from PySide2.QtUiTools import *
elif PYSIDE6:
from PySide6.QtUiTools import *
| 614 | Python | .py | 20 | 27.95 | 79 | 0.553299 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
152 | QtNetwork.py | git-cola_git-cola/qtpy/QtNetwork.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtNetwork classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtNetwork import *
elif PYQT6:
from PyQt6.QtNetwork import *
elif PYSIDE2:
from PySide2.QtNetwork import *
elif PYSIDE6:
from PySide6.QtNetwork import *
| 616 | Python | .py | 17 | 34 | 79 | 0.563973 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
153 | QtMultimediaWidgets.py | git-cola_git-cola/qtpy/QtMultimediaWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtMultimediaWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtMultimediaWidgets import *
elif PYQT6:
from PyQt6.QtMultimediaWidgets import *
elif PYSIDE2:
from PySide2.QtMultimediaWidgets import *
elif PYSIDE6:
from PySide6.QtMultimediaWidgets import *
| 625 | Python | .py | 16 | 36.875 | 79 | 0.585809 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
154 | QtMacExtras.py | git-cola_git-cola/qtpy/QtMacExtras.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides classes and functions specific to macOS and iOS operating systems"""
import sys
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInOSError,
QtModuleNotInQtVersionError,
)
if sys.platform == "darwin":
if PYQT5:
from PyQt5.QtMacExtras import *
elif PYQT6:
raise QtModuleNotInQtVersionError(name="QtMacExtras")
elif PYSIDE2:
from PySide2.QtMacExtras import *
elif PYSIDE6:
raise QtModuleNotInQtVersionError(name="QtMacExtras")
else:
raise QtModuleNotInOSError(name="QtMacExtras")
| 868 | Python | .py | 27 | 28.185185 | 80 | 0.597372 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
155 | __init__.py | git-cola_git-cola/qtpy/__init__.py | #
# Copyright © 2009- The Spyder Development Team
# Copyright © 2014-2015 Colin Duquesnoy
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
**QtPy** is a shim over the various Python Qt bindings. It is used to write
Qt binding independent libraries or applications.
If one of the APIs has already been imported, then it will be used.
Otherwise, the shim will automatically select the first available API (PyQt5, PySide2,
PyQt6 and PySide6); in that case, you can force the use of one
specific bindings (e.g. if your application is using one specific bindings and
you need to use library that use QtPy) by setting up the ``QT_API`` environment
variable.
PyQt5
=====
For PyQt5, you don't have to set anything as it will be used automatically::
>>> from qtpy import QtGui, QtWidgets, QtCore
>>> print(QtWidgets.QWidget)
PySide2
======
Set the QT_API environment variable to 'pyside2' before importing other
packages::
>>> import os
>>> os.environ['QT_API'] = 'pyside2'
>>> from qtpy import QtGui, QtWidgets, QtCore
>>> print(QtWidgets.QWidget)
PyQt6
=====
>>> import os
>>> os.environ['QT_API'] = 'pyqt6'
>>> from qtpy import QtGui, QtWidgets, QtCore
>>> print(QtWidgets.QWidget)
PySide6
=======
>>> import os
>>> os.environ['QT_API'] = 'pyside6'
>>> from qtpy import QtGui, QtWidgets, QtCore
>>> print(QtWidgets.QWidget)
"""
import contextlib
import os
import platform
import sys
import warnings
# Version of QtPy
__version__ = "2.4.1"
class PythonQtError(RuntimeError):
"""Generic error superclass for QtPy."""
class PythonQtWarning(RuntimeWarning):
"""Warning class for QtPy."""
class PythonQtValueError(ValueError):
"""Error raised if an invalid QT_API is specified."""
class QtBindingsNotFoundError(PythonQtError, ImportError):
"""Error raised if no bindings could be selected."""
_msg = "No Qt bindings could be found"
def __init__(self):
super().__init__(self._msg)
class QtModuleNotFoundError(ModuleNotFoundError, PythonQtError):
"""Raised when a Python Qt binding submodule is not installed/supported."""
_msg = "The {name} module was not found."
_msg_binding = "{binding}"
_msg_extra = ""
def __init__(self, *, name, msg=None, **msg_kwargs):
global API_NAME
binding = self._msg_binding.format(binding=API_NAME)
msg = msg or f"{self._msg} {self._msg_extra}".strip()
msg = msg.format(name=name, binding=binding, **msg_kwargs)
super().__init__(msg, name=name)
class QtModuleNotInOSError(QtModuleNotFoundError):
"""Raised when a module is not supported on the current operating system."""
_msg = "{name} does not exist on this operating system."
class QtModuleNotInQtVersionError(QtModuleNotFoundError):
"""Raised when a module is not implemented in the current Qt version."""
_msg = "{name} does not exist in {version}."
def __init__(self, *, name, msg=None, **msg_kwargs):
global QT5, QT6
version = "Qt5" if QT5 else "Qt6"
super().__init__(name=name, version=version)
class QtBindingMissingModuleError(QtModuleNotFoundError):
"""Raised when a module is not supported by a given binding."""
_msg_extra = "It is not currently implemented in {binding}."
class QtModuleNotInstalledError(QtModuleNotFoundError):
"""Raise when a module is supported by the binding, but not installed."""
_msg_extra = "It must be installed separately"
def __init__(self, *, missing_package=None, **superclass_kwargs):
self.missing_package = missing_package
if missing_package is not None:
self._msg_extra += " as {missing_package}."
super().__init__(missing_package=missing_package, **superclass_kwargs)
# Qt API environment variable name
QT_API = "QT_API"
# Names of the expected PyQt5 api
PYQT5_API = ["pyqt5"]
PYQT6_API = ["pyqt6"]
# Names of the expected PySide2 api
PYSIDE2_API = ["pyside2"]
# Names of the expected PySide6 api
PYSIDE6_API = ["pyside6"]
# Minimum supported versions of Qt and the bindings
QT5_VERSION_MIN = PYQT5_VERSION_MIN = "5.9.0"
PYSIDE2_VERSION_MIN = "5.12.0"
QT6_VERSION_MIN = PYQT6_VERSION_MIN = PYSIDE6_VERSION_MIN = "6.2.0"
QT_VERSION_MIN = QT5_VERSION_MIN
PYQT_VERSION_MIN = PYQT5_VERSION_MIN
PYSIDE_VERSION_MIN = PYSIDE2_VERSION_MIN
# Detecting if a binding was specified by the user
binding_specified = QT_API in os.environ
API_NAMES = {
"pyqt5": "PyQt5",
"pyside2": "PySide2",
"pyqt6": "PyQt6",
"pyside6": "PySide6",
}
API = os.environ.get(QT_API, "pyqt5").lower()
initial_api = API
if API not in API_NAMES:
raise PythonQtValueError(
f"Specified QT_API={QT_API.lower()!r} is not in valid options: "
f"{API_NAMES}",
)
is_old_pyqt = is_pyqt46 = False
QT5 = PYQT5 = True
QT4 = QT6 = PYQT4 = PYQT6 = PYSIDE = PYSIDE2 = PYSIDE6 = False
PYQT_VERSION = None
PYSIDE_VERSION = None
QT_VERSION = None
def _parse_int(value):
"""Convert a value into an integer"""
try:
return int(value)
except ValueError:
return 0
def parse(version):
"""Parse a version string into a tuple of ints"""
return tuple(_parse_int(x) for x in version.split('.'))
# Unless `FORCE_QT_API` is set, use previously imported Qt Python bindings
if not os.environ.get("FORCE_QT_API"):
if "PyQt5" in sys.modules:
API = initial_api if initial_api in PYQT5_API else "pyqt5"
elif "PySide2" in sys.modules:
API = initial_api if initial_api in PYSIDE2_API else "pyside2"
elif "PyQt6" in sys.modules:
API = initial_api if initial_api in PYQT6_API else "pyqt6"
elif "PySide6" in sys.modules:
API = initial_api if initial_api in PYSIDE6_API else "pyside6"
if API in PYQT5_API:
try:
from PyQt5.QtCore import (
PYQT_VERSION_STR as PYQT_VERSION,
)
from PyQt5.QtCore import (
QT_VERSION_STR as QT_VERSION,
)
QT5 = PYQT5 = True
if sys.platform == "darwin":
macos_version = parse(platform.mac_ver()[0])
qt_ver = parse(QT_VERSION)
if macos_version < parse("10.10") and qt_ver >= parse("5.9"):
raise PythonQtError(
"Qt 5.9 or higher only works in "
"macOS 10.10 or higher. Your "
"program will fail in this "
"system.",
)
elif macos_version < parse("10.11") and qt_ver >= parse("5.11"):
raise PythonQtError(
"Qt 5.11 or higher only works in "
"macOS 10.11 or higher. Your "
"program will fail in this "
"system.",
)
del macos_version
del qt_ver
except ImportError:
API = "pyside2"
else:
os.environ[QT_API] = API
if API in PYSIDE2_API:
try:
from PySide2 import __version__ as PYSIDE_VERSION # analysis:ignore
from PySide2.QtCore import __version__ as QT_VERSION # analysis:ignore
PYQT5 = False
QT5 = PYSIDE2 = True
if sys.platform == "darwin":
macos_version = parse(platform.mac_ver()[0])
qt_ver = parse(QT_VERSION)
if macos_version < parse("10.11") and qt_ver >= parse("5.11"):
raise PythonQtError(
"Qt 5.11 or higher only works in "
"macOS 10.11 or higher. Your "
"program will fail in this "
"system.",
)
del macos_version
del qt_ver
except ImportError:
API = "pyqt6"
else:
os.environ[QT_API] = API
if API in PYQT6_API:
try:
from PyQt6.QtCore import (
PYQT_VERSION_STR as PYQT_VERSION,
)
from PyQt6.QtCore import (
QT_VERSION_STR as QT_VERSION,
)
QT5 = PYQT5 = False
QT6 = PYQT6 = True
except ImportError:
API = "pyside6"
else:
os.environ[QT_API] = API
if API in PYSIDE6_API:
try:
from PySide6 import __version__ as PYSIDE_VERSION # analysis:ignore
from PySide6.QtCore import __version__ as QT_VERSION # analysis:ignore
QT5 = PYQT5 = False
QT6 = PYSIDE6 = True
except ImportError:
raise QtBindingsNotFoundError from None
else:
os.environ[QT_API] = API
# If a correct API name is passed to QT_API and it could not be found,
# switches to another and informs through the warning
if initial_api != API and binding_specified:
warnings.warn(
f"Selected binding {initial_api!r} could not be found; "
f"falling back to {API!r}",
PythonQtWarning,
stacklevel=2,
)
# Set display name of the Qt API
API_NAME = API_NAMES[API]
with contextlib.suppress(ImportError, PythonQtError):
# QtDataVisualization backward compatibility (QtDataVisualization vs. QtDatavisualization)
# Only available for Qt5 bindings > 5.9 on Windows
from . import QtDataVisualization as QtDatavisualization # analysis:ignore
def _warn_old_minor_version(name, old_version, min_version):
"""Warn if using a Qt or binding version no longer supported by QtPy."""
warning_message = (
f"{name} version {old_version} is not supported by QtPy. "
"To ensure your application works correctly with QtPy, "
f"please upgrade to {name} {min_version} or later."
)
warnings.warn(warning_message, PythonQtWarning, stacklevel=2)
# Warn if using an End of Life or unsupported Qt API/binding minor version
if QT_VERSION:
if QT5 and (parse(QT_VERSION) < parse(QT5_VERSION_MIN)):
_warn_old_minor_version("Qt5", QT_VERSION, QT5_VERSION_MIN)
elif QT6 and (parse(QT_VERSION) < parse(QT6_VERSION_MIN)):
_warn_old_minor_version("Qt6", QT_VERSION, QT6_VERSION_MIN)
if PYQT_VERSION:
if PYQT5 and (parse(PYQT_VERSION) < parse(PYQT5_VERSION_MIN)):
_warn_old_minor_version("PyQt5", PYQT_VERSION, PYQT5_VERSION_MIN)
elif PYQT6 and (parse(PYQT_VERSION) < parse(PYQT6_VERSION_MIN)):
_warn_old_minor_version("PyQt6", PYQT_VERSION, PYQT6_VERSION_MIN)
elif PYSIDE_VERSION:
if PYSIDE2 and (parse(PYSIDE_VERSION) < parse(PYSIDE2_VERSION_MIN)):
_warn_old_minor_version("PySide2", PYSIDE_VERSION, PYSIDE2_VERSION_MIN)
elif PYSIDE6 and (parse(PYSIDE_VERSION) < parse(PYSIDE6_VERSION_MIN)):
_warn_old_minor_version("PySide6", PYSIDE_VERSION, PYSIDE6_VERSION_MIN)
| 10,598 | Python | .py | 264 | 33.765152 | 94 | 0.656451 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
156 | QtWebSockets.py | git-cola_git-cola/qtpy/QtWebSockets.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtWebSockets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtWebSockets import *
elif PYQT6:
from PyQt6.QtWebSockets import *
elif PYSIDE2:
from PySide2.QtWebSockets import *
elif PYSIDE6:
from PySide6.QtWebSockets import *
| 590 | Python | .py | 16 | 34.6875 | 79 | 0.56042 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
157 | QtPdfWidgets.py | git-cola_git-cola/qtpy/QtPdfWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPdfWidgets classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
raise QtBindingMissingModuleError(name="QtPdfWidgets")
elif PYQT6:
# Available with version >=6.4.0
from PyQt6.QtPdfWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtPdfWidgets")
elif PYSIDE6:
# Available with version >=6.4.0
from PySide6.QtPdfWidgets import *
| 760 | Python | .py | 24 | 28.708333 | 79 | 0.590723 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
158 | QtMultimedia.py | git-cola_git-cola/qtpy/QtMultimedia.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides low-level multimedia functionality."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtMultimedia import *
elif PYQT6:
from PyQt6.QtMultimedia import *
elif PYSIDE2:
from PySide2.QtMultimedia import *
elif PYSIDE6:
from PySide6.QtMultimedia import *
| 590 | Python | .py | 16 | 34.6875 | 79 | 0.56042 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
159 | QtSvg.py | git-cola_git-cola/qtpy/QtSvg.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtSvg classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtSvg import *
elif PYQT6:
from PyQt6.QtSvg import *
elif PYSIDE2:
from PySide2.QtSvg import *
elif PYSIDE6:
from PySide6.QtSvg import *
| 555 | Python | .py | 16 | 32.5 | 79 | 0.531716 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
160 | QtWebEngine.py | git-cola_git-cola/qtpy/QtWebEngine.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtWebEngine classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInQtVersionError,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.QtWebEngine import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtWebEngine",
missing_package="PyQtWebEngine",
) from error
elif PYQT6:
raise QtModuleNotInQtVersionError(name="QtWebEngine")
elif PYSIDE2:
from PySide2.QtWebEngine import *
elif PYSIDE6:
raise QtModuleNotInQtVersionError(name="QtWebEngine")
| 946 | Python | .py | 30 | 27.3 | 79 | 0.607025 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
161 | QtTest.py | git-cola_git-cola/qtpy/QtTest.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtTest and functions"""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtTest import *
elif PYQT6:
from PyQt6 import QtTest
from PyQt6.QtTest import *
# Allow unscoped access for enums inside the QtTest module
from .enums_compat import promote_enums
promote_enums(QtTest)
del QtTest
elif PYSIDE2:
from PySide2.QtTest import *
elif PYSIDE6:
from PySide6.QtTest import *
| 771 | Python | .py | 22 | 32.090909 | 79 | 0.595687 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
162 | QtQuickControls2.py | git-cola_git-cola/qtpy/QtQuickControls2.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtQuickControls2 classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6:
raise QtBindingMissingModuleError(name="QtQuickControls2")
elif PYSIDE2:
from PySide2.QtQuickControls2 import *
elif PYSIDE6:
from PySide6.QtQuickControls2 import *
| 642 | Python | .py | 20 | 29.35 | 79 | 0.573506 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
163 | QtSvgWidgets.py | git-cola_git-cola/qtpy/QtSvgWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtSvgWidgets classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
raise QtBindingMissingModuleError(name="QtSvgWidgets")
elif PYQT6:
from PyQt6.QtSvgWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtSvgWidgets")
elif PYSIDE6:
from PySide6.QtSvgWidgets import *
| 686 | Python | .py | 22 | 28.409091 | 79 | 0.585477 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
164 | QtNetworkAuth.py | git-cola_git-cola/qtpy/QtNetworkAuth.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtNetworkAuth classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.QtNetworkAuth import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtNetworkAuth",
missing_package="PyQtNetworkAuth",
) from error
elif PYQT6:
try:
from PyQt6.QtNetworkAuth import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtNetworkAuth",
missing_package="PyQt6-NetworkAuth",
) from error
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtNetworkAuth")
elif PYSIDE6:
from PySide6.QtNetworkAuth import *
| 1,096 | Python | .py | 35 | 26.114286 | 79 | 0.602079 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
165 | QtSerialPort.py | git-cola_git-cola/qtpy/QtSerialPort.py | # -----------------------------------------------------------------------------
# Copyright © 2020 Marcin Stano
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtSerialPort classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtSerialPort import *
elif PYQT6:
from PyQt6.QtSerialPort import *
elif PYSIDE6:
from PySide6.QtSerialPort import *
elif PYSIDE2:
from PySide2.QtSerialPort import *
| 623 | Python | .py | 17 | 34.411765 | 79 | 0.570715 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
166 | QtHelp.py | git-cola_git-cola/qtpy/QtHelp.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""QtHelp Wrapper."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtHelp import *
elif PYQT6:
from PyQt6.QtHelp import *
elif PYSIDE2:
from PySide2.QtHelp import *
elif PYSIDE6:
from PySide6.QtHelp import *
| 537 | Python | .py | 16 | 31.375 | 79 | 0.521236 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
167 | compat.py | git-cola_git-cola/qtpy/compat.py | #
# Copyright © 2009- The Spyder Development Team
# Licensed under the terms of the MIT License
"""
Compatibility functions
"""
import sys
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
)
from .QtWidgets import QFileDialog
TEXT_TYPES = (str,)
def is_text_string(obj):
"""Return True if `obj` is a text string, False if it is anything else,
like binary data."""
return isinstance(obj, str)
def to_text_string(obj, encoding=None):
"""Convert `obj` to (unicode) text string"""
if encoding is None:
return str(obj)
if isinstance(obj, str):
# In case this function is not used properly, this could happen
return obj
return str(obj, encoding)
# =============================================================================
# QVariant conversion utilities
# =============================================================================
PYQT_API_1 = False
def to_qvariant(obj=None): # analysis:ignore
"""Convert Python object to QVariant
This is a transitional function from PyQt API#1 (QVariant exist)
to PyQt API#2 and Pyside (QVariant does not exist)"""
return obj
def from_qvariant(qobj=None, pytype=None): # analysis:ignore
"""Convert QVariant object to Python object
This is a transitional function from PyQt API #1 (QVariant exist)
to PyQt API #2 and Pyside (QVariant does not exist)"""
return qobj
# =============================================================================
# Wrappers around QFileDialog static methods
# =============================================================================
def getexistingdirectory(
parent=None,
caption="",
basedir="",
options=QFileDialog.ShowDirsOnly,
):
"""Wrapper around QtGui.QFileDialog.getExistingDirectory static method
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0"""
# Calling QFileDialog static method
if sys.platform == "win32":
# On Windows platforms: redirect standard outputs
_temp1, _temp2 = sys.stdout, sys.stderr
sys.stdout, sys.stderr = None, None
try:
result = QFileDialog.getExistingDirectory(
parent,
caption,
basedir,
options,
)
finally:
if sys.platform == "win32":
# On Windows platforms: restore standard outputs
sys.stdout, sys.stderr = _temp1, _temp2
if not is_text_string(result):
# PyQt API #1
result = to_text_string(result)
return result
def _qfiledialog_wrapper(
attr,
parent=None,
caption="",
basedir="",
filters="",
selectedfilter="",
options=None,
):
if options is None:
options = QFileDialog.Option(0)
func = getattr(QFileDialog, attr)
# Calling QFileDialog static method
if sys.platform == "win32":
# On Windows platforms: redirect standard outputs
_temp1, _temp2 = sys.stdout, sys.stderr
sys.stdout, sys.stderr = None, None
result = func(parent, caption, basedir, filters, selectedfilter, options)
if sys.platform == "win32":
# On Windows platforms: restore standard outputs
sys.stdout, sys.stderr = _temp1, _temp2
output, selectedfilter = result
# Always returns the tuple (output, selectedfilter)
return output, selectedfilter
def getopenfilename(
parent=None,
caption="",
basedir="",
filters="",
selectedfilter="",
options=None,
):
"""Wrapper around QtGui.QFileDialog.getOpenFileName static method
Returns a tuple (filename, selectedfilter) -- when dialog box is canceled,
returns a tuple of empty strings
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0"""
return _qfiledialog_wrapper(
"getOpenFileName",
parent=parent,
caption=caption,
basedir=basedir,
filters=filters,
selectedfilter=selectedfilter,
options=options,
)
def getopenfilenames(
parent=None,
caption="",
basedir="",
filters="",
selectedfilter="",
options=None,
):
"""Wrapper around QtGui.QFileDialog.getOpenFileNames static method
Returns a tuple (filenames, selectedfilter) -- when dialog box is canceled,
returns a tuple (empty list, empty string)
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0"""
return _qfiledialog_wrapper(
"getOpenFileNames",
parent=parent,
caption=caption,
basedir=basedir,
filters=filters,
selectedfilter=selectedfilter,
options=options,
)
def getsavefilename(
parent=None,
caption="",
basedir="",
filters="",
selectedfilter="",
options=None,
):
"""Wrapper around QtGui.QFileDialog.getSaveFileName static method
Returns a tuple (filename, selectedfilter) -- when dialog box is canceled,
returns a tuple of empty strings
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0"""
return _qfiledialog_wrapper(
"getSaveFileName",
parent=parent,
caption=caption,
basedir=basedir,
filters=filters,
selectedfilter=selectedfilter,
options=options,
)
# =============================================================================
def isalive(obj):
"""Wrapper around sip.isdeleted and shiboken.isValid which tests whether
an object is currently alive."""
if PYQT5 or PYQT6:
from . import sip
return not sip.isdeleted(obj)
if PYSIDE2 or PYSIDE6:
from . import shiboken
return shiboken.isValid(obj)
return None
| 5,624 | Python | .py | 170 | 27.423529 | 79 | 0.621726 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
168 | QtOpenGLWidgets.py | git-cola_git-cola/qtpy/QtOpenGLWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtOpenGLWidgets classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
raise QtBindingMissingModuleError(name="QtOpenGLWidgets")
elif PYQT6:
from PyQt6.QtOpenGLWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtOpenGLWidgets")
elif PYSIDE6:
from PySide6.QtOpenGLWidgets import *
| 701 | Python | .py | 22 | 29.090909 | 79 | 0.594675 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
169 | QtScxml.py | git-cola_git-cola/qtpy/QtScxml.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtScxml classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5 or PYQT6:
raise QtBindingMissingModuleError(name="QtScxml")
elif PYSIDE2:
from PySide2.QtScxml import *
elif PYSIDE6:
from PySide6.QtScxml import *
| 606 | Python | .py | 20 | 27.55 | 79 | 0.54717 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
170 | QtQuick3D.py | git-cola_git-cola/qtpy/QtQuick3D.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtQuick3D classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtQuick3D import *
elif PYQT6:
from PyQt6.QtQuick3D import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtQuick3D")
elif PYSIDE6:
from PySide6.QtQuick3D import *
| 649 | Python | .py | 22 | 26.727273 | 79 | 0.5625 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
171 | QtSql.py | git-cola_git-cola/qtpy/QtSql.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtSql classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtSql import *
elif PYQT6:
from PyQt6.QtSql import *
QSqlDatabase.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
QSqlQuery.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QSqlResult.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
elif PYSIDE6:
from PySide6.QtSql import *
# Map DeprecationWarning methods
QSqlDatabase.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
QSqlQuery.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
QSqlResult.exec_ = lambda self, *args, **kwargs: self.exec(*args, **kwargs)
elif PYSIDE2:
from PySide2.QtSql import *
| 1,122 | Python | .py | 29 | 34.62069 | 79 | 0.576287 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
172 | QtNfc.py | git-cola_git-cola/qtpy/QtNfc.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtNfc classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtNfc import *
elif PYQT6:
from PyQt6.QtNfc import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtNfc")
elif PYSIDE6:
from PySide6.QtNfc import *
| 629 | Python | .py | 22 | 25.818182 | 79 | 0.548013 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
173 | Qt3DCore.py | git-cola_git-cola/qtpy/Qt3DCore.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DCore classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qt3DCore import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DCore",
missing_package="PyQt3D",
) from error
elif PYQT6:
try:
from PyQt6.Qt3DCore import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DCore",
missing_package="PyQt6-3D",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.Qt3DCore as __temp
for __name in inspect.getmembers(__temp.Qt3DCore):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide6.Qt3DCore as __temp
for __name in inspect.getmembers(__temp.Qt3DCore):
globals()[__name[0]] = __name[1]
| 1,362 | Python | .py | 42 | 26.97619 | 79 | 0.591013 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
174 | uic.py | git-cola_git-cola/qtpy/uic.py | from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT6:
from PyQt6.uic import *
elif PYQT5:
from PyQt5.uic import *
else:
__all__ = ["loadUi", "loadUiType"]
# In PySide, loadUi does not exist, so we define it using QUiLoader, and
# then make sure we expose that function. This is adapted from qt-helpers
# which was released under a 3-clause BSD license:
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the
# distribution.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <[email protected]>
# Modifications by Charl Botha <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
if PYSIDE6:
from PySide6.QtCore import QMetaObject
from PySide6.QtUiTools import QUiLoader, loadUiType
elif PYSIDE2:
from PySide2.QtCore import QMetaObject
from PySide2.QtUiTools import QUiLoader
try:
from xml.etree.ElementTree import Element
from pyside2uic import compileUi
# Patch UIParser as xml.etree.Elementree.Element.getiterator
# was deprecated since Python 3.2 and removed in Python 3.9
# https://docs.python.org/3.9/whatsnew/3.9.html#removed
from pyside2uic.uiparser import UIParser
class ElemPatched(Element):
def getiterator(self, *args, **kwargs):
return self.iter(*args, **kwargs)
def readResources(self, elem):
return self._readResources(ElemPatched(elem))
UIParser._readResources = UIParser.readResources
UIParser.readResources = readResources
except ImportError:
pass
class UiLoader(QUiLoader):
"""
Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user
interface in a base instance.
Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of :func:`PyQt4.uic.loadUi`.
"""
def __init__(self, baseinstance, customWidgets=None):
"""
Create a loader for the given ``baseinstance``.
The user interface is created in ``baseinstance``, which must be an
instance of the top-level class in the user interface to load, or a
subclass thereof.
``customWidgets`` is a dictionary mapping from class name to class
object for custom widgets. Usually, this should be done by calling
registerCustomWidget on the QUiLoader, but with PySide 1.1.2 on
Ubuntu 12.04 x86_64 this causes a segfault.
``parent`` is the parent object of this loader.
"""
QUiLoader.__init__(self, baseinstance)
self.baseinstance = baseinstance
if customWidgets is None:
self.customWidgets = {}
else:
self.customWidgets = customWidgets
def createWidget(self, class_name, parent=None, name=""):
"""
Function that is called for each widget defined in ui file,
overridden here to populate baseinstance instead.
"""
if parent is None and self.baseinstance:
# supposed to create the top-level widget, return the base
# instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() or class_name == "Line":
# create a new widget for child widgets
widget = QUiLoader.createWidget(
self,
class_name,
parent,
name,
)
else:
# If not in the list of availableWidgets, must be a custom
# widget. This will raise KeyError if the user has not
# supplied the relevant class_name in the dictionary or if
# customWidgets is empty.
try:
widget = self.customWidgets[class_name](parent)
except KeyError as error:
raise NoCustomWidget(
f"No custom widget {class_name} "
"found in customWidgets",
) from error
if self.baseinstance:
# set an attribute for the new child widget on the base
# instance, just like PyQt4.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
def _get_custom_widgets(ui_file):
"""
This function is used to parse a ui file and look for the <customwidgets>
section, then automatically load all the custom widget classes.
"""
import importlib
from xml.etree.ElementTree import ElementTree
# Parse the UI file
etree = ElementTree()
ui = etree.parse(ui_file)
# Get the customwidgets section
custom_widgets = ui.find("customwidgets")
if custom_widgets is None:
return {}
custom_widget_classes = {}
for custom_widget in list(custom_widgets):
cw_class = custom_widget.find("class").text
cw_header = custom_widget.find("header").text
module = importlib.import_module(cw_header)
custom_widget_classes[cw_class] = getattr(module, cw_class)
return custom_widget_classes
def loadUi(uifile, baseinstance=None, workingDirectory=None):
"""
Dynamically load a user interface from the given ``uifile``.
``uifile`` is a string containing a file name of the UI file to load.
If ``baseinstance`` is ``None``, the a new instance of the top-level
widget will be created. Otherwise, the user interface is created within
the given ``baseinstance``. In this case ``baseinstance`` must be an
instance of the top-level widget class in the UI file to load, or a
subclass thereof. In other words, if you've created a ``QMainWindow``
interface in the designer, ``baseinstance`` must be a ``QMainWindow``
or a subclass thereof, too. You cannot load a ``QMainWindow`` UI file
with a plain :class:`~PySide.QtGui.QWidget` as ``baseinstance``.
:method:`~PySide.QtCore.QMetaObject.connectSlotsByName()` is called on
the created user interface, so you can implemented your slots according
to its conventions in your widget class.
Return ``baseinstance``, if ``baseinstance`` is not ``None``. Otherwise
return the newly created instance of the user interface.
"""
# We parse the UI file and import any required custom widgets
customWidgets = _get_custom_widgets(uifile)
loader = UiLoader(baseinstance, customWidgets)
if workingDirectory is not None:
loader.setWorkingDirectory(workingDirectory)
widget = loader.load(uifile)
QMetaObject.connectSlotsByName(widget)
return widget
if PYSIDE2:
def loadUiType(uifile, from_imports=False):
"""Load a .ui file and return the generated form class and
the Qt base class.
The "loadUiType" command convert the ui file to py code
in-memory first and then execute it in a special frame to
retrieve the form_class.
Credit: https://stackoverflow.com/a/14195313/15954282
"""
import sys
from io import StringIO
from xml.etree.ElementTree import ElementTree
from . import QtWidgets
# Parse the UI file
etree = ElementTree()
ui = etree.parse(uifile)
widget_class = ui.find("widget").get("class")
form_class = ui.find("class").text
with open(uifile, encoding="utf-8") as fd:
code_stream = StringIO()
frame = {}
compileUi(fd, code_stream, indent=0, from_imports=from_imports)
pyc = compile(code_stream.getvalue(), "<string>", "exec")
exec(pyc, frame)
# Fetch the base_class and form class based on their type in the
# xml from designer
form_class = frame["Ui_%s" % form_class]
base_class = getattr(QtWidgets, widget_class)
return form_class, base_class
| 11,647 | Python | .py | 229 | 40.366812 | 81 | 0.64507 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
175 | Qt3DLogic.py | git-cola_git-cola/qtpy/Qt3DLogic.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DLogic classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qt3DLogic import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DLogic",
missing_package="PyQt3D",
) from error
elif PYQT6:
try:
from PyQt6.Qt3DLogic import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qt3DLogic",
missing_package="PyQt6-3D",
) from error
elif PYSIDE2:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide2.Qt3DLogic as __temp
for __name in inspect.getmembers(__temp.Qt3DLogic):
globals()[__name[0]] = __name[1]
elif PYSIDE6:
# https://bugreports.qt.io/projects/PYSIDE/issues/PYSIDE-1026
import inspect
import PySide6.Qt3DLogic as __temp
for __name in inspect.getmembers(__temp.Qt3DLogic):
globals()[__name[0]] = __name[1]
| 1,371 | Python | .py | 42 | 27.190476 | 79 | 0.593797 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
176 | QtPrintSupport.py | git-cola_git-cola/qtpy/QtPrintSupport.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPrintSupport classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtPrintSupport import *
elif PYQT6:
from PyQt6.QtPrintSupport import *
QPageSetupDialog.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
QPrintDialog.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
QPrintPreviewWidget.print_ = lambda self, *args, **kwargs: self.print(
*args,
**kwargs,
)
elif PYSIDE6:
from PySide6.QtPrintSupport import *
# Map DeprecationWarning methods
QPageSetupDialog.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
QPrintDialog.exec_ = lambda self, *args, **kwargs: self.exec(
*args,
**kwargs,
)
elif PYSIDE2:
from PySide2.QtPrintSupport import *
| 1,181 | Python | .py | 37 | 27 | 79 | 0.566286 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
177 | QtXmlPatterns.py | git-cola_git-cola/qtpy/QtXmlPatterns.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtXmlPatterns classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtXmlPatterns import *
elif PYQT6:
raise QtBindingMissingModuleError(name="QtXmlPatterns")
elif PYSIDE2:
from PySide2.QtXmlPatterns import *
elif PYSIDE6:
raise QtBindingMissingModuleError(name="QtXmlPatterns")
| 691 | Python | .py | 22 | 28.636364 | 79 | 0.588589 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
178 | QtQuick.py | git-cola_git-cola/qtpy/QtQuick.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtQuick classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtQuick import *
elif PYQT6:
from PyQt6.QtQuick import *
elif PYSIDE6:
from PySide6.QtQuick import *
elif PYSIDE2:
from PySide2.QtQuick import *
| 565 | Python | .py | 16 | 33.125 | 79 | 0.540293 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
179 | _utils.py | git-cola_git-cola/qtpy/_utils.py | # -----------------------------------------------------------------------------
# Copyright © 2023- The Spyder Development Team
#
# Released under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides utility functions for use by QtPy itself."""
from functools import wraps
from typing import TYPE_CHECKING
import qtpy
if TYPE_CHECKING:
from qtpy.QtWidgets import QAction
def _wrap_missing_optional_dep_error(
attr_error,
*,
import_error,
wrapper=qtpy.QtModuleNotInstalledError,
**wrapper_kwargs,
):
"""Create a __cause__-chained wrapper error for a missing optional dep."""
qtpy_error = wrapper(**wrapper_kwargs)
import_error.__cause__ = attr_error
qtpy_error.__cause__ = import_error
return qtpy_error
def getattr_missing_optional_dep(name, module_name, optional_names):
"""Wrap AttributeError in a special error if it matches."""
attr_error = AttributeError(
f"module {module_name!r} has no attribute {name!r}",
)
if name in optional_names:
return _wrap_missing_optional_dep_error(
attr_error,
**optional_names[name],
)
return attr_error
def possibly_static_exec(cls, *args, **kwargs):
"""Call `self.exec` when `self` is given or a static method otherwise."""
if not args and not kwargs:
# A special case (`cls.exec_()`) to avoid the function resolving error
return cls.exec()
if isinstance(args[0], cls):
if len(args) == 1 and not kwargs:
# A special case (`self.exec_()`) to avoid the function resolving error
return args[0].exec()
return args[0].exec(*args[1:], **kwargs)
return cls.exec(*args, **kwargs)
def possibly_static_exec_(cls, *args, **kwargs):
"""Call `self.exec` when `self` is given or a static method otherwise."""
if not args and not kwargs:
# A special case (`cls.exec()`) to avoid the function resolving error
return cls.exec_()
if isinstance(args[0], cls):
if len(args) == 1 and not kwargs:
# A special case (`self.exec()`) to avoid the function resolving error
return args[0].exec_()
return args[0].exec_(*args[1:], **kwargs)
return cls.exec_(*args, **kwargs)
def add_action(self, *args, old_add_action):
"""Re-order arguments of `addAction` to backport compatibility with Qt>=6.3."""
from qtpy.QtCore import QObject
from qtpy.QtGui import QIcon, QKeySequence
action: QAction
icon: QIcon
text: str
shortcut: QKeySequence | QKeySequence.StandardKey | str | int
receiver: QObject
member: bytes
if all(
isinstance(arg, t)
for arg, t in zip(
args,
[
str,
(QKeySequence, QKeySequence.StandardKey, str, int),
QObject,
bytes,
],
)
):
if len(args) == 2:
text, shortcut = args
action = old_add_action(self, text)
action.setShortcut(shortcut)
elif len(args) == 3:
text, shortcut, receiver = args
action = old_add_action(self, text, receiver)
action.setShortcut(shortcut)
elif len(args) == 4:
text, shortcut, receiver, member = args
action = old_add_action(self, text, receiver, member, shortcut)
else:
return old_add_action(self, *args)
return action
if all(
isinstance(arg, t)
for arg, t in zip(
args,
[
QIcon,
str,
(QKeySequence, QKeySequence.StandardKey, str, int),
QObject,
bytes,
],
)
):
if len(args) == 3:
icon, text, shortcut = args
action = old_add_action(self, icon, text)
action.setShortcut(QKeySequence(shortcut))
elif len(args) == 4:
icon, text, shortcut, receiver = args
action = old_add_action(self, icon, text, receiver)
action.setShortcut(QKeySequence(shortcut))
elif len(args) == 5:
icon, text, shortcut, receiver, member = args
action = old_add_action(
self,
icon,
text,
receiver,
member,
QKeySequence(shortcut),
)
else:
return old_add_action(self, *args)
return action
return old_add_action(self, *args)
def static_method_kwargs_wrapper(func, from_kwarg_name, to_kwarg_name):
"""
Helper function to manage `from_kwarg_name` to `to_kwarg_name` kwargs name changes in static methods.
Makes static methods accept the `from_kwarg_name` kwarg as `to_kwarg_name`.
"""
@staticmethod
@wraps(func)
def _from_kwarg_name_to_kwarg_name_(*args, **kwargs):
if from_kwarg_name in kwargs:
kwargs[to_kwarg_name] = kwargs.pop(from_kwarg_name)
return func(*args, **kwargs)
return _from_kwarg_name_to_kwarg_name_
| 5,187 | Python | .py | 140 | 28.471429 | 105 | 0.577596 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
180 | QtWebEngineWidgets.py | git-cola_git-cola/qtpy/QtWebEngineWidgets.py | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtWebEngineWidgets classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInstalledError,
)
# To test if we are using WebEngine or WebKit
# NOTE: This constant is imported by other projects (e.g. Spyder), so please
# don't remove it.
WEBENGINE = True
if PYQT5:
try:
# Based on the work at https://github.com/spyder-ide/qtpy/pull/203
from PyQt5.QtWebEngineWidgets import (
QWebEnginePage,
QWebEngineProfile,
QWebEngineScript,
QWebEngineSettings,
QWebEngineView,
)
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtWebEngineWidgets",
missing_package="PyQtWebEngine",
) from error
elif PYQT6:
try:
from PyQt6.QtWebEngineCore import (
QWebEnginePage,
QWebEngineProfile,
QWebEngineScript,
QWebEngineSettings,
)
from PyQt6.QtWebEngineWidgets import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="QtWebEngineWidgets",
missing_package="PyQt6-WebEngine",
) from error
elif PYSIDE2:
# Based on the work at https://github.com/spyder-ide/qtpy/pull/203
from PySide2.QtWebEngineWidgets import (
QWebEnginePage,
QWebEngineProfile,
QWebEngineScript,
QWebEngineSettings,
QWebEngineView,
)
elif PYSIDE6:
from PySide6.QtWebEngineCore import (
QWebEnginePage,
QWebEngineProfile,
QWebEngineScript,
QWebEngineSettings,
)
from PySide6.QtWebEngineWidgets import *
| 2,044 | Python | .py | 65 | 24.676923 | 79 | 0.618154 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
181 | Qsci.py | git-cola_git-cola/qtpy/Qsci.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qsci classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
QtModuleNotInstalledError,
)
if PYQT5:
try:
from PyQt5.Qsci import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qsci",
missing_package="QScintilla",
) from error
elif PYQT6:
try:
from PyQt6.Qsci import *
except ModuleNotFoundError as error:
raise QtModuleNotInstalledError(
name="Qsci",
missing_package="PyQt6-QScintilla",
) from error
elif PYSIDE2 or PYSIDE6:
raise QtBindingMissingModuleError(name="Qsci")
| 993 | Python | .py | 33 | 24.757576 | 79 | 0.569488 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
182 | QtOpenGL.py | git-cola_git-cola/qtpy/QtOpenGL.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtOpenGL classes and functions."""
import contextlib
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtGui import (
QOpenGLBuffer,
QOpenGLContext,
QOpenGLContextGroup,
QOpenGLDebugLogger,
QOpenGLDebugMessage,
QOpenGLFramebufferObject,
QOpenGLFramebufferObjectFormat,
QOpenGLPixelTransferOptions,
QOpenGLShader,
QOpenGLShaderProgram,
QOpenGLTexture,
QOpenGLTextureBlitter,
QOpenGLVersionProfile,
QOpenGLVertexArrayObject,
QOpenGLWindow,
)
from PyQt5.QtOpenGL import *
# These are not present on some architectures such as armhf
with contextlib.suppress(ImportError):
from PyQt5.QtGui import QOpenGLTimeMonitor, QOpenGLTimerQuery
elif PYQT6:
from PyQt6.QtGui import QOpenGLContext, QOpenGLContextGroup
from PyQt6.QtOpenGL import *
elif PYSIDE6:
from PySide6.QtGui import QOpenGLContext, QOpenGLContextGroup
from PySide6.QtOpenGL import *
elif PYSIDE2:
from PySide2.QtGui import (
QOpenGLBuffer,
QOpenGLContext,
QOpenGLContextGroup,
QOpenGLDebugLogger,
QOpenGLDebugMessage,
QOpenGLFramebufferObject,
QOpenGLFramebufferObjectFormat,
QOpenGLPixelTransferOptions,
QOpenGLShader,
QOpenGLShaderProgram,
QOpenGLTexture,
QOpenGLTextureBlitter,
QOpenGLVersionProfile,
QOpenGLVertexArrayObject,
QOpenGLWindow,
)
from PySide2.QtOpenGL import *
# These are not present on some architectures such as armhf
with contextlib.suppress(ImportError):
from PySide2.QtGui import QOpenGLTimeMonitor, QOpenGLTimerQuery
| 2,032 | Python | .py | 59 | 28.033898 | 79 | 0.671414 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
183 | QtLocation.py | git-cola_git-cola/qtpy/QtLocation.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtLocation classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtLocation import *
elif PYQT6:
raise QtBindingMissingModuleError(name="QtLocation")
elif PYSIDE2:
from PySide2.QtLocation import *
elif PYSIDE6:
raise QtBindingMissingModuleError(name="QtLocation")
| 676 | Python | .py | 22 | 27.954545 | 79 | 0.579109 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
184 | QtBluetooth.py | git-cola_git-cola/qtpy/QtBluetooth.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtBluetooth classes and functions."""
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingMissingModuleError,
)
if PYQT5:
from PyQt5.QtBluetooth import *
elif PYQT6:
from PyQt6.QtBluetooth import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name="QtBluetooth")
elif PYSIDE6:
from PySide6.QtBluetooth import *
| 659 | Python | .py | 22 | 27.181818 | 79 | 0.569401 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
185 | QtWinExtras.py | git-cola_git-cola/qtpy/QtWinExtras.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Windows-specific utilities"""
import sys
from . import (
PYQT5,
PYQT6,
PYSIDE2,
PYSIDE6,
QtModuleNotInOSError,
QtModuleNotInQtVersionError,
)
if sys.platform == "win32":
if PYQT5:
from PyQt5.QtWinExtras import *
elif PYQT6:
raise QtModuleNotInQtVersionError(name="QtWinExtras")
elif PYSIDE2:
from PySide2.QtWinExtras import *
elif PYSIDE6:
raise QtModuleNotInQtVersionError(name="QtWinExtras")
else:
raise QtModuleNotInOSError(name="QtWinExtras")
| 828 | Python | .py | 27 | 26.703704 | 79 | 0.585947 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
186 | QtSensors.py | git-cola_git-cola/qtpy/QtSensors.py | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtSensors classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6
if PYQT5:
from PyQt5.QtSensors import *
elif PYQT6:
from PyQt6.QtSensors import *
elif PYSIDE6:
from PySide6.QtSensors import *
elif PYSIDE2:
from PySide2.QtSensors import *
| 575 | Python | .py | 16 | 33.75 | 79 | 0.548561 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
187 | setup.py | internetarchive_openlibrary/setup.py | # setup.py is only used by solrbuilder to cythonize some files See
# scripts/solr_builder/build-cython.sh We might be able to remove
# it entirely if we call cython directly from that script.
from setuptools import find_packages, setup
from Cython.Build import cythonize
setup(
# Used to make solrbuilder faster
packages=find_packages(include=['openlibrary', 'openlibrary.*']),
ext_modules=cythonize(
"openlibrary/solr/update.py", compiler_directives={'language_level': "3"}
),
)
| 505 | Python | .py | 12 | 39 | 81 | 0.75813 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
188 | conftest.py | internetarchive_openlibrary/openlibrary/conftest.py | """pytest configuration for openlibrary
"""
import pytest
import web
from infogami.infobase.tests.pytest_wildcard import Wildcard
from infogami.utils import template
from infogami.utils.view import render_template as infobase_render_template
from openlibrary.i18n import gettext
from openlibrary.core import helpers
from openlibrary.mocks.mock_infobase import mock_site
from openlibrary.mocks.mock_ia import mock_ia
from openlibrary.mocks.mock_memcache import mock_memcache
@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
def mock_request(*args, **kwargs):
raise Warning('Network requests are blocked in the testing environment')
monkeypatch.setattr("requests.sessions.Session.request", mock_request)
@pytest.fixture(autouse=True)
def no_sleep(monkeypatch):
def mock_sleep(*args, **kwargs):
raise Warning(
'''
Sleeping is blocked in the testing environment.
Use monkeytime instead; it stubs time.time() and time.sleep().
Eg:
def test_foo(monkeytime):
assert time.time() == 1
time.sleep(1)
assert time.time() == 2
If you need more methods stubbed, edit monkeytime in openlibrary/conftest.py
'''
)
monkeypatch.setattr("time.sleep", mock_sleep)
@pytest.fixture
def monkeytime(monkeypatch):
cur_time = 1
def time():
return cur_time
def sleep(secs):
nonlocal cur_time
cur_time += secs
monkeypatch.setattr("time.time", time)
monkeypatch.setattr("time.sleep", sleep)
@pytest.fixture
def wildcard():
return Wildcard()
@pytest.fixture
def render_template(request):
"""Utility to test templates."""
template.load_templates("openlibrary")
# TODO: call setup on upstream and openlibrary plugins to
# load all globals.
web.template.Template.globals["_"] = gettext
web.template.Template.globals.update(helpers.helpers)
web.ctx.env = web.storage()
web.ctx.headers = []
web.ctx.lang = "en"
# ol_infobase.init_plugin call is failing when trying to import plugins.openlibrary.code.
# monkeypatch to avoid that.
from openlibrary.plugins import ol_infobase
init_plugin = ol_infobase.init_plugin
ol_infobase.init_plugin = lambda: None
def undo():
ol_infobase.init_plugin = init_plugin
request.addfinalizer(undo)
from openlibrary.plugins.openlibrary import code
web.config.db_parameters = {}
code.setup_template_globals()
def finalizer():
template.disktemplates.clear()
web.ctx.clear()
request.addfinalizer(finalizer)
def render(name, *a, **kw):
as_string = kw.pop("as_string", True)
d = infobase_render_template(name, *a, **kw)
return str(d) if as_string else d
return render
| 2,875 | Python | .py | 77 | 31.038961 | 93 | 0.695228 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
189 | config.py | internetarchive_openlibrary/openlibrary/config.py | """Utility for loading config file.
"""
import os
import sys
import yaml
import infogami
from infogami import config
from infogami.infobase import server
runtime_config = {}
def load(config_file):
"""legacy function to load openlibary config.
The loaded config will be available via runtime_config var in this module.
This doesn't affect the global config.
WARNING: This function is deprecated, please use load_config instead.
"""
if 'pytest' in sys.modules:
# During pytest ensure we're not using like olsystem or something
assert config_file == 'conf/openlibrary.yml'
# for historic reasons
global runtime_config
with open(config_file) as in_file:
runtime_config = yaml.safe_load(in_file)
def load_config(config_file):
"""Loads the config file.
The loaded config will be available via infogami.config.
"""
if 'pytest' in sys.modules:
# During pytest ensure we're not using like olsystem or something
assert config_file == 'conf/openlibrary.yml'
infogami.load_config(config_file)
setup_infobase_config(config_file)
# This sets web.config.db_parameters
server.update_config(config.infobase)
def setup_infobase_config(config_file):
"""Reads the infobase config file and assign it to config.infobase.
The config_file is used as base to resolve relative path, if specified in the config.
"""
if config.get("infobase_config_file"):
dir = os.path.dirname(config_file)
path = os.path.join(dir, config.infobase_config_file)
with open(path) as in_file:
config.infobase = yaml.safe_load(in_file)
else:
config.infobase = {}
| 1,698 | Python | .py | 44 | 33.409091 | 89 | 0.713764 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
190 | code.py | internetarchive_openlibrary/openlibrary/code.py | """Main entry point for openlibrary app.
Loaded from Infogami plugin mechanism.
"""
import sys
import os
import logging
import logging.config
from infogami.utils import template, macro, i18n, delegate
import infogami
old_plugins = [
"openlibrary",
"worksearch",
"inside",
"books",
"admin",
"upstream",
"importapi",
"recaptcha",
]
def setup():
setup_logging()
logger = logging.getLogger("openlibrary")
logger.info("Application init")
for p in old_plugins:
logger.info("loading plugin %s", p)
modname = "openlibrary.plugins.%s.code" % p
path = "openlibrary/plugins/" + p
template.load_templates(path, lazy=True)
macro.load_macros(path, lazy=True)
i18n.load_strings(path)
__import__(modname, globals(), locals(), ['plugins'])
delegate.plugins += [
delegate._make_plugin_module('openlibrary.plugins.' + name)
for name in old_plugins
]
load_views()
# load actions
from . import actions
logger.info("loading complete.")
def setup_logging():
"""Reads the logging configuration from config file and configures logger."""
try:
logconfig = infogami.config.get("logging_config_file")
if logconfig and os.path.exists(logconfig):
logging.config.fileConfig(logconfig, disable_existing_loggers=False)
except Exception as e:
print("Unable to set logging configuration:", str(e), file=sys.stderr)
raise
def load_views():
"""Registers all views by loading all view modules."""
from .views import showmarc
setup()
| 1,621 | Python | .py | 52 | 25.826923 | 81 | 0.675048 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
191 | api.py | internetarchive_openlibrary/openlibrary/api.py | r"""Open Library API Client.
Sample Usage::
ol = OpenLibrary("http://0.0.0.0:8080")
ol.login('joe', 'secret')
page = ol.get("/sandbox")
print page["body"]
page["body"] += "\n\nTest from API"
ol.save("/sandbox", page, "test from api")
"""
__version__ = "0.1"
__author__ = "Anand Chitipothu <[email protected]>"
import os
import re
import datetime
import json
import web
import logging
import requests
from configparser import ConfigParser
logger = logging.getLogger("openlibrary.api")
class OLError(Exception):
def __init__(self, e):
self.code = e.response.status_code
self.headers = e.response.headers
self.text = e.response.text
Exception.__init__(self, f"{e}. Response: {self.text}")
class OpenLibrary:
def __init__(self, base_url="https://openlibrary.org"):
self.base_url = base_url.rstrip('/') if base_url else "https://openlibrary.org"
self.cookie = None
def _request(self, path, method='GET', data=None, headers=None, params=None):
logger.info("%s %s", method, path)
url = self.base_url + path
headers = headers or {}
params = params or {}
if self.cookie:
headers['Cookie'] = self.cookie
try:
response = requests.request(
method, url, data=data, headers=headers, params=params
)
response.raise_for_status()
return response
except requests.HTTPError as e:
raise OLError(e)
def autologin(self, section=None):
"""Login to Open Library with credentials taken from ~/.olrc file.
The ~/.olrc file must be in ini format (format readable by
configparser module) and there should be a section with the
server name. A sample configuration file may look like this::
[openlibrary.org]
username = joe
password = secret
[0.0.0.0:8080]
username = joe
password = joe123
Optionally section name can be passed as argument to force using a different section name.
If environment variable OPENLIBRARY_RCFILE is specified, it'll read that file instead of ~/.olrc.
"""
config = ConfigParser()
configfile = os.getenv('OPENLIBRARY_RCFILE', os.path.expanduser('~/.olrc'))
logger.info("reading %s", configfile)
config.read(configfile)
section = section or self.base_url.split('://')[-1]
if not config.has_section(section):
raise Exception("No section found with name %s in ~/.olrc" % repr(section))
username = config.get(section, 'username')
password = config.get(section, 'password')
return self.login(username, password)
def login(self, username, password):
"""Login to Open Library with given credentials."""
headers = {'Content-Type': 'application/json'}
try:
data = json.dumps({"username": username, "password": password})
response = self._request(
'/account/login', method='POST', data=data, headers=headers
)
except OLError as e:
response = e
if 'Set-Cookie' in response.headers:
cookies = response.headers['Set-Cookie'].split(',')
self.cookie = ';'.join([c.split(';')[0] for c in cookies])
def get(self, key, v=None):
response = self._request(key + '.json', params={'v': v} if v else {})
return unmarshal(response.json())
def get_many(self, keys):
"""Get multiple documents in a single request as a dictionary."""
if len(keys) > 100:
# Process in batches to avoid crossing the URL length limit.
d = {}
for chunk in web.group(keys, 100):
d.update(self._get_many(chunk))
return d
else:
return self._get_many(keys)
def _get_many(self, keys):
response = self._request("/api/get_many", params={"keys": json.dumps(keys)})
return response.json()['result']
def save(self, key, data, comment=None):
headers = {'Content-Type': 'application/json'}
data = marshal(data)
if comment:
headers['Opt'] = '"%s/dev/docs/api"; ns=42' % self.base_url
headers['42-comment'] = comment
data = json.dumps(data)
return self._request(key, method="PUT", data=data, headers=headers).content
def _call_write(self, name, query, comment, action):
headers = {'Content-Type': 'application/json'}
query = marshal(query)
# use HTTP Extension Framework to add custom headers. see RFC 2774 for more details.
if comment or action:
headers['Opt'] = '"%s/dev/docs/api"; ns=42' % self.base_url
if comment:
headers['42-comment'] = comment
if action:
headers['42-action'] = action
response = self._request(
'/api/' + name, method="POST", data=json.dumps(query), headers=headers
)
return response.json()
def save_many(self, query, comment=None, action=None):
return self._call_write('save_many', query, comment, action)
def write(self, query, comment="", action=""):
"""Internal write API."""
return self._call_write('write', query, comment, action)
def new(self, query, comment=None, action=None):
return self._call_write('new', query, comment, action)
def query(self, q=None, **kw):
"""Query Open Library.
Open Library always limits the result to 1000 items due to
performance issues. Pass limit=False to fetch all matching
results by making multiple requests to the server. Please note
that an iterator is returned instead of list when limit=False is
passed.::
>>> ol.query({'type': '/type/type', 'limit': 2}) #doctest: +SKIP
[{'key': '/type/property'}, {'key': '/type/type'}]
>>> ol.query(type='/type/type', limit=2) #doctest: +SKIP
[{'key': '/type/property'}, {'key': '/type/type'}]
"""
q = dict(q or {})
q.update(kw)
q = marshal(q)
def unlimited_query(q):
q['limit'] = 1000
q.setdefault('offset', 0)
q.setdefault('sort', 'key')
while True:
result = self.query(q)
yield from result
if len(result) < 1000:
break
q['offset'] += len(result)
if 'limit' in q and q['limit'] is False:
return unlimited_query(q)
else:
response = self._request("/query.json", params={"query": json.dumps(q)})
return unmarshal(response.json())
def search(self, query, limit=10, offset=0, fields: list[str] | None = None):
return self._request(
'/search.json',
params={
'q': query,
'limit': limit,
'offset': offset,
**({'fields': ','.join(fields)} if fields else {}),
},
).json()
def import_ocaid(self, ocaid, require_marc=True):
data = {
'identifier': ocaid,
'require_marc': 'true' if require_marc else 'false',
}
return self._request('/api/import/ia', method='POST', data=data).text
def import_data(self, data):
return self._request('/api/import', method='POST', data=data).text
def marshal(data):
"""Serializes the specified data in the format required by OL.::
>>> marshal(datetime.datetime(2009, 1, 2, 3, 4, 5, 6789))
{'type': '/type/datetime', 'value': '2009-01-02T03:04:05.006789'}
"""
if isinstance(data, list):
return [marshal(d) for d in data]
elif isinstance(data, dict):
return {k: marshal(v) for k, v in data.items()}
elif isinstance(data, datetime.datetime):
return {"type": "/type/datetime", "value": data.isoformat()}
elif isinstance(data, Text):
return {"type": "/type/text", "value": str(data)}
elif isinstance(data, Reference):
return {"key": str(data)}
else:
return data
def unmarshal(d):
"""Converts OL serialized objects to python.::
>>> unmarshal({"type": "/type/text",
... "value": "hello, world"}) # doctest: +ALLOW_UNICODE
<text: u'hello, world'>
>>> unmarshal({"type": "/type/datetime", "value": "2009-01-02T03:04:05.006789"})
datetime.datetime(2009, 1, 2, 3, 4, 5, 6789)
"""
if isinstance(d, list):
return [unmarshal(v) for v in d]
elif isinstance(d, dict):
if 'key' in d and len(d) == 1:
return Reference(d['key'])
elif 'value' in d and 'type' in d:
if d['type'] == '/type/text':
return Text(d['value'])
elif d['type'] == '/type/datetime':
return parse_datetime(d['value'])
else:
return d['value']
else:
return {k: unmarshal(v) for k, v in d.items()}
else:
return d
def parse_datetime(value):
"""Parses ISO datetime formatted string.::
>>> parse_datetime("2009-01-02T03:04:05.006789")
datetime.datetime(2009, 1, 2, 3, 4, 5, 6789)
"""
if isinstance(value, datetime.datetime):
return value
else:
tokens = re.split(r'-|T|:|\.| ', value)
return datetime.datetime(*map(int, tokens))
class Text(str):
__slots__ = ()
def __repr__(self):
return "<text: %s>" % str.__repr__(self)
class Reference(str):
__slots__ = ()
def __repr__(self):
return "<ref: %s>" % str.__repr__(self)
| 9,714 | Python | .py | 234 | 32.474359 | 105 | 0.578724 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
192 | app.py | internetarchive_openlibrary/openlibrary/app.py | """Utilities to build the app.
"""
from infogami.utils import app as _app
from infogami.utils.view import render, public
from infogami.utils.macro import macro
from web.template import TemplateResult
class view(_app.page):
"""A view is a class that defines how a page or a set of pages
identified by a regular expression are rendered.
Here is a sample view::
from openlibrary import app
class hello(app.view):
path = "/hello/(.*)"
def GET(self, name):
return app.render_template("hello", name)
"""
# In infogami, the class with this functionality is called page.
# We are redefining with a slightly different terminology to make
# things more readable.
pass
# view is just a base class.
# Defining a class extending from _app.page auto-registers it inside infogami.
# Undoing that.
del _app.pages['/view']
class subview(_app.view):
"""Subviews are views that work an object in the database.
Each subview URL will have two parts, the prefix identifying the key
of the document in the database to work on and the suffix iden identifying
the action.
For example, the in the subview with URL "/works/OL123W/foo/identifiers",
"identifiers" is the action and "/works/OL123W" is the key of the document.
The middle part "foo" is added by a middleware to make the URLs readable
and not that is transparent to this.
Here is a sample subview:
class work_identifiers(delegate.view):
suffix = "identifiers"
types = ["/type/edition"]
"""
# In infogami, the class with this functionality is called a view.
# We are redefining with a slightly different terminology to make
# things more readable.
# Tell infogami not to consider this as a view class
suffix = None
types = None
@macro
@public
def render_template(name: str, *a, **kw) -> TemplateResult:
if "." in name:
name = name.rsplit(".", 1)[0]
return render[name](*a, **kw)
| 2,033 | Python | .py | 50 | 35.26 | 79 | 0.695364 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
193 | book_providers.py | internetarchive_openlibrary/openlibrary/book_providers.py | from dataclasses import dataclass
import logging
from collections.abc import Callable, Iterator
from typing import TypedDict, Literal, cast, TypeVar, Generic
from urllib import parse
import web
from web import uniq
from web.template import TemplateResult
from openlibrary.app import render_template
from openlibrary.plugins.upstream.models import Edition
from openlibrary.plugins.upstream.utils import get_coverstore_public_url
from openlibrary.utils import OrderedEnum, multisort_best
logger = logging.getLogger("openlibrary.book_providers")
AcquisitionAccessLiteral = Literal[
'sample', 'buy', 'open-access', 'borrow', 'subscribe'
]
class EbookAccess(OrderedEnum):
# Keep in sync with solr/conf/enumsConfig.xml !
NO_EBOOK = 0
UNCLASSIFIED = 1
PRINTDISABLED = 2
BORROWABLE = 3
PUBLIC = 4
def to_solr_str(self):
return self.name.lower()
@staticmethod
def from_acquisition_access(literal: AcquisitionAccessLiteral) -> 'EbookAccess':
if literal == 'sample':
# We need to update solr to handle these! Requires full reindex
return EbookAccess.PRINTDISABLED
elif literal == 'buy':
return EbookAccess.NO_EBOOK
elif literal == 'open-access':
return EbookAccess.PUBLIC
elif literal == 'borrow':
return EbookAccess.BORROWABLE
elif literal == 'subscribe':
return EbookAccess.NO_EBOOK
else:
raise ValueError(f'Unknown access literal: {literal}')
@dataclass
class Acquisition:
"""
Acquisition represents a book resource found on another website, such as
Standard Ebooks.
Wording inspired by OPDS; see https://specs.opds.io/opds-1.2#23-acquisition-feeds
"""
access: AcquisitionAccessLiteral
format: Literal['web', 'pdf', 'epub', 'audio']
price: str | None
url: str
provider_name: str | None = None
@property
def ebook_access(self) -> EbookAccess:
return EbookAccess.from_acquisition_access(self.access)
@staticmethod
def from_json(json: dict) -> 'Acquisition':
if 'href' in json:
# OPDS-style provider
return Acquisition.from_opds_json(json)
elif 'url' in json:
# We have an inconsistency in our API
html_access: dict[str, AcquisitionAccessLiteral] = {
'read': 'open-access',
'listen': 'open-access',
'buy': 'buy',
'borrow': 'borrow',
'preview': 'sample',
}
access = json.get('access', 'open-access')
if access in html_access:
access = html_access[access]
# Pressbooks/OL-style
return Acquisition(
access=access,
format=json.get('format', 'web'),
price=json.get('price'),
url=json['url'],
provider_name=json.get('provider_name'),
)
else:
raise ValueError(f'Unknown ebook acquisition format: {json}')
@staticmethod
def from_opds_json(json: dict) -> 'Acquisition':
if json.get('properties', {}).get('indirectAcquisition', None):
mimetype = json['properties']['indirectAcquisition'][0]['type']
else:
mimetype = json['type']
fmt: Literal['web', 'pdf', 'epub', 'audio'] = 'web'
if mimetype.startswith('audio/'):
fmt = 'audio'
elif mimetype == 'application/pdf':
fmt = 'pdf'
elif mimetype == 'application/epub+zip':
fmt = 'epub'
elif mimetype == 'text/html':
fmt = 'web'
else:
logger.warning(f'Unknown mimetype: {mimetype}')
fmt = 'web'
if json.get('properties', {}).get('price', None):
price = f"{json['properties']['price']['value']} {json['properties']['price']['currency']}"
else:
price = None
return Acquisition(
access=json['rel'].split('/')[-1],
format=fmt,
price=price,
url=json['href'],
provider_name=json.get('name'),
)
class IALiteMetadata(TypedDict):
boxid: set[str]
collection: set[str]
access_restricted_item: Literal['true', 'false'] | None
TProviderMetadata = TypeVar('TProviderMetadata')
class AbstractBookProvider(Generic[TProviderMetadata]):
short_name: str
"""
The key in the identifiers field on editions;
see https://openlibrary.org/config/edition
"""
identifier_key: str | None
def get_olids(self, identifier: str) -> list[str]:
return web.ctx.site.things(
{"type": "/type/edition", self.db_selector: identifier}
)
@property
def editions_query(self):
return {f"{self.db_selector}~": "*"}
@property
def db_selector(self) -> str:
return f"identifiers.{self.identifier_key}"
@property
def solr_key(self):
return f"id_{self.identifier_key}"
def get_identifiers(self, ed_or_solr: Edition | dict) -> list[str]:
return (
# If it's an edition
ed_or_solr.get('identifiers', {}).get(self.identifier_key, [])
or
# if it's a solr work record
ed_or_solr.get(f'id_{self.identifier_key}', [])
)
def choose_best_identifier(self, identifiers: list[str]) -> str:
return identifiers[0]
def get_best_identifier(self, ed_or_solr: Edition | dict) -> str:
identifiers = self.get_identifiers(ed_or_solr)
assert identifiers
return self.choose_best_identifier(identifiers)
def get_best_identifier_slug(self, ed_or_solr: Edition | dict) -> str:
"""Used in eg /work/OL1W?edition=ia:foobar URLs, for example"""
return f'{self.short_name}:{self.get_best_identifier(ed_or_solr)}'
def get_template_path(self, typ: Literal['read_button', 'download_options']) -> str:
return f"book_providers/{self.short_name}_{typ}.html"
def render_read_button(
self, ed_or_solr: Edition | dict, analytics_attr: Callable[[str], str]
) -> TemplateResult:
return render_template(
self.get_template_path('read_button'),
self.get_best_identifier(ed_or_solr),
analytics_attr,
)
def render_download_options(
self, edition: Edition, extra_args: list | None = None
) -> TemplateResult:
return render_template(
self.get_template_path('download_options'),
self.get_best_identifier(edition),
*(extra_args or []),
)
def is_own_ocaid(self, ocaid: str) -> bool:
"""Whether the ocaid is an archive of content from this provider"""
return False
def get_access(
self,
edition: dict,
metadata: TProviderMetadata | None = None,
) -> EbookAccess:
"""
Return the access level of the edition.
"""
# Most providers are for public-only ebooks right now
return EbookAccess.PUBLIC
def get_acquisitions(
self,
edition: Edition | web.Storage,
) -> list[Acquisition]:
if edition.providers:
return [Acquisition.from_json(dict(p)) for p in edition.providers]
else:
return []
class InternetArchiveProvider(AbstractBookProvider[IALiteMetadata]):
short_name = 'ia'
identifier_key = 'ocaid'
@property
def db_selector(self) -> str:
return self.identifier_key
@property
def solr_key(self) -> str:
return "ia"
def get_identifiers(self, ed_or_solr: Edition | dict) -> list[str]:
# Solr work record augmented with availability
# Sometimes it's set explicitly to None, for some reason
availability = ed_or_solr.get('availability', {}) or {}
if availability.get('identifier'):
return [ed_or_solr['availability']['identifier']]
# Edition
if ed_or_solr.get('ocaid'):
return [ed_or_solr['ocaid']]
# Solr work record
return ed_or_solr.get('ia', [])
def is_own_ocaid(self, ocaid: str) -> bool:
return True
def render_download_options(
self, edition: Edition, extra_args: list | None = None
) -> TemplateResult | str:
if edition.is_access_restricted():
return ''
formats = {
'pdf': edition.get_ia_download_link('.pdf'),
'epub': edition.get_ia_download_link('.epub'),
'mobi': edition.get_ia_download_link('.mobi'),
'txt': edition.get_ia_download_link('_djvu.txt'),
}
if any(formats.values()):
return render_template(
self.get_template_path('download_options'),
formats,
edition.url('/daisy'),
)
else:
return ''
def get_access(
self, edition: dict, metadata: IALiteMetadata | None = None
) -> EbookAccess:
if not metadata:
if edition.get('ocaid'):
return EbookAccess.UNCLASSIFIED
else:
return EbookAccess.NO_EBOOK
collections = metadata.get('collection', set())
access_restricted_item = metadata.get('access_restricted_item') == "true"
if 'inlibrary' in collections:
return EbookAccess.BORROWABLE
elif 'printdisabled' in collections:
return EbookAccess.PRINTDISABLED
elif access_restricted_item or not collections:
return EbookAccess.UNCLASSIFIED
else:
return EbookAccess.PUBLIC
def get_acquisitions(
self,
edition: Edition,
) -> list[Acquisition]:
return [
Acquisition(
access='open-access',
format='web',
price=None,
url=f'https://archive.org/details/{self.get_best_identifier(edition)}',
provider_name=self.short_name,
)
]
class LibriVoxProvider(AbstractBookProvider):
short_name = 'librivox'
identifier_key = 'librivox'
def render_download_options(self, edition: Edition, extra_args: list | None = None):
# The template also needs the ocaid, since some of the files are hosted on IA
return super().render_download_options(edition, [edition.get('ocaid')])
def is_own_ocaid(self, ocaid: str) -> bool:
return 'librivox' in ocaid
def get_acquisitions(
self,
edition: Edition,
) -> list[Acquisition]:
return [
Acquisition(
access='open-access',
format='audio',
price=None,
url=f'https://librivox.org/{self.get_best_identifier(edition)}',
provider_name=self.short_name,
)
]
class ProjectGutenbergProvider(AbstractBookProvider):
short_name = 'gutenberg'
identifier_key = 'project_gutenberg'
def is_own_ocaid(self, ocaid: str) -> bool:
return ocaid.endswith('gut')
def get_acquisitions(
self,
edition: Edition,
) -> list[Acquisition]:
return [
Acquisition(
access='open-access',
format='web',
price=None,
url=f'https://www.gutenberg.org/ebooks/{self.get_best_identifier(edition)}',
provider_name=self.short_name,
)
]
class StandardEbooksProvider(AbstractBookProvider):
short_name = 'standard_ebooks'
identifier_key = 'standard_ebooks'
def is_own_ocaid(self, ocaid: str) -> bool:
# Standard ebooks isn't archived on IA
return False
def get_acquisitions(
self,
edition: Edition,
) -> list[Acquisition]:
standard_ebooks_id = self.get_best_identifier(edition)
base_url = 'https://standardebooks.org/ebooks/' + standard_ebooks_id
flat_id = standard_ebooks_id.replace('/', '_')
return [
Acquisition(
access='open-access',
format='web',
price=None,
url=f'{base_url}/text/single-page',
provider_name=self.short_name,
),
Acquisition(
access='open-access',
format='epub',
price=None,
url=f'{base_url}/downloads/{flat_id}.epub',
provider_name=self.short_name,
),
]
class OpenStaxProvider(AbstractBookProvider):
short_name = 'openstax'
identifier_key = 'openstax'
def is_own_ocaid(self, ocaid: str) -> bool:
return False
def get_acquisitions(
self,
edition: Edition,
) -> list[Acquisition]:
return [
Acquisition(
access='open-access',
format='web',
price=None,
url=f'https://openstax.org/details/books/{self.get_best_identifier(edition)}',
provider_name=self.short_name,
)
]
class CitaPressProvider(AbstractBookProvider):
short_name = 'cita_press'
identifier_key = 'cita_press'
def is_own_ocaid(self, ocaid: str) -> bool:
return False
class DirectProvider(AbstractBookProvider):
short_name = 'direct'
identifier_key = None
@property
def db_selector(self) -> str:
return "providers.url"
@property
def solr_key(self) -> None:
# TODO: Not implemented yet
return None
def get_identifiers(self, ed_or_solr: Edition | dict) -> list[str]:
"""
Note: This will only work for solr records if the provider field was fetched
in the solr request. (Note: this field is populated from db)
"""
if providers := ed_or_solr.get('providers', []):
identifiers = [
provider.url
for provider in map(Acquisition.from_json, ed_or_solr['providers'])
if provider.ebook_access >= EbookAccess.PRINTDISABLED
]
to_remove = set()
for tbp in PROVIDER_ORDER:
# Avoid infinite recursion.
if isinstance(tbp, DirectProvider):
continue
if not tbp.get_identifiers(ed_or_solr):
continue
for acq in tbp.get_acquisitions(ed_or_solr):
to_remove.add(acq.url)
return [
identifier for identifier in identifiers if identifier not in to_remove
]
else:
# TODO: Not implemented for search/solr yet
return []
def render_read_button(
self, ed_or_solr: Edition | dict, analytics_attr: Callable[[str], str]
) -> TemplateResult | str:
acq_sorted = sorted(
(
p
for p in map(Acquisition.from_json, ed_or_solr.get('providers', []))
if p.ebook_access >= EbookAccess.PRINTDISABLED
),
key=lambda p: p.ebook_access,
reverse=True,
)
if not acq_sorted:
return ''
acquisition = acq_sorted[0]
# pre-process acquisition.url so ParseResult.netloc is always the domain. Only netloc is used.
url = (
"https://" + acquisition.url
if not acquisition.url.startswith("http")
else acquisition.url
)
parsed_url = parse.urlparse(url)
domain = parsed_url.netloc
return render_template(
self.get_template_path('read_button'), acquisition, domain
)
def render_download_options(self, edition: Edition, extra_args: list | None = None):
# Return an empty string until #9581 is addressed.
return ""
def get_access(
self,
edition: dict,
metadata: TProviderMetadata | None = None,
) -> EbookAccess:
"""
Return the access level of the edition.
"""
# For now assume 0 is best
return EbookAccess.from_acquisition_access(
Acquisition.from_json(edition['providers'][0]).access
)
class WikisourceProvider(AbstractBookProvider):
short_name = 'wikisource'
identifier_key = 'wikisource'
PROVIDER_ORDER: list[AbstractBookProvider] = [
# These providers act essentially as their own publishers, so link to the first when
# we're on an edition page
DirectProvider(),
LibriVoxProvider(),
ProjectGutenbergProvider(),
StandardEbooksProvider(),
OpenStaxProvider(),
CitaPressProvider(),
WikisourceProvider(),
# Then link to IA
InternetArchiveProvider(),
]
def get_cover_url(ed_or_solr: Edition | dict) -> str | None:
"""
Get the cover url most appropriate for this edition or solr work search result
"""
size = 'M'
# Editions
if isinstance(ed_or_solr, Edition):
cover = ed_or_solr.get_cover()
return cover.url(size) if cover else None
# Solr edition
elif ed_or_solr['key'].startswith('/books/'):
if ed_or_solr.get('cover_i'):
return (
get_coverstore_public_url()
+ f'/b/id/{ed_or_solr["cover_i"]}-{size}.jpg'
)
else:
return None
# Solr document augmented with availability
availability = ed_or_solr.get('availability', {}) or {}
if availability.get('openlibrary_edition'):
olid = availability.get('openlibrary_edition')
return f"{get_coverstore_public_url()}/b/olid/{olid}-{size}.jpg"
if availability.get('identifier'):
ocaid = ed_or_solr['availability']['identifier']
return f"//archive.org/services/img/{ocaid}"
# Plain solr - we don't know which edition is which here, so this is most
# preferable
if ed_or_solr.get('cover_i'):
cover_i = ed_or_solr["cover_i"]
return f'{get_coverstore_public_url()}/b/id/{cover_i}-{size}.jpg'
if ed_or_solr.get('cover_edition_key'):
olid = ed_or_solr['cover_edition_key']
return f"{get_coverstore_public_url()}/b/olid/{olid}-{size}.jpg"
if ed_or_solr.get('ocaid'):
return f"//archive.org/services/img/{ed_or_solr.get('ocaid')}"
# No luck
return None
def is_non_ia_ocaid(ocaid: str) -> bool:
"""
Check if the ocaid "looks like" it's from another provider
"""
providers = (provider for provider in PROVIDER_ORDER if provider.short_name != 'ia')
return any(provider.is_own_ocaid(ocaid) for provider in providers)
def get_book_provider_by_name(short_name: str) -> AbstractBookProvider | None:
return next((p for p in PROVIDER_ORDER if p.short_name == short_name), None)
ia_provider = cast(InternetArchiveProvider, get_book_provider_by_name('ia'))
prefer_ia_provider_order = uniq([ia_provider, *PROVIDER_ORDER])
def get_provider_order(prefer_ia: bool = False) -> list[AbstractBookProvider]:
default_order = prefer_ia_provider_order if prefer_ia else PROVIDER_ORDER
provider_order = default_order
provider_overrides = None
# Need this to work in test environments
if 'env' in web.ctx:
provider_overrides = web.input(providerPref=None, _method='GET').providerPref
if provider_overrides:
new_order: list[AbstractBookProvider] = []
for name in provider_overrides.split(','):
if name == '*':
new_order += default_order
else:
provider = get_book_provider_by_name(name)
if not provider:
# TODO: Show the user a warning somehow
continue
new_order.append(provider)
new_order = uniq(new_order + default_order)
if new_order:
provider_order = new_order
return provider_order
def get_book_providers(ed_or_solr: Edition | dict) -> Iterator[AbstractBookProvider]:
# On search results which don't have an edition selected, we want to display
# IA copies first.
# Issue is that an edition can be provided by multiple providers; we can easily
# choose the correct copy when on an edition, but on a solr work record, with all
# copies of all editions aggregated, it's more difficult.
# So we do some ugly ocaid sniffing to try to guess :/ Idea being that we ignore
# OCAIDs that look like they're from other providers.
has_edition = isinstance(ed_or_solr, Edition) or ed_or_solr['key'].startswith(
'/books/'
)
prefer_ia = not has_edition
if prefer_ia:
ia_ocaids = [
ocaid
# Subjects/publisher pages have ia set to a specific value :/
for ocaid in uniq(ia_provider.get_identifiers(ed_or_solr) or [])
if not is_non_ia_ocaid(ocaid)
]
prefer_ia = bool(ia_ocaids)
provider_order = get_provider_order(prefer_ia)
for provider in provider_order:
if provider.get_identifiers(ed_or_solr):
yield provider
def get_book_provider(ed_or_solr: Edition | dict) -> AbstractBookProvider | None:
return next(get_book_providers(ed_or_solr), None)
def get_best_edition(
editions: list[Edition],
) -> tuple[Edition | None, AbstractBookProvider | None]:
provider_order = get_provider_order(True)
# Map provider name to position/ranking
provider_rank_lookup: dict[AbstractBookProvider | None, int] = {
provider: i for i, provider in enumerate(provider_order)
}
# Here, we prefer the ia editions
augmented_editions = [(edition, get_book_provider(edition)) for edition in editions]
best = multisort_best(
augmented_editions,
[
# Prefer the providers closest to the top of the list
('min', lambda rec: provider_rank_lookup.get(rec[1], float('inf'))),
# Prefer the editions with the most fields
('max', lambda rec: len(dict(rec[0]))),
# TODO: Language would go in this queue somewhere
],
)
return best if best else (None, None)
def get_solr_keys() -> list[str]:
return [p.solr_key for p in PROVIDER_ORDER if p.solr_key]
setattr(get_book_provider, 'ia', get_book_provider_by_name('ia')) # noqa: B010
| 22,287 | Python | .py | 568 | 30.105634 | 103 | 0.607057 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
194 | actions.py | internetarchive_openlibrary/openlibrary/actions.py | """Custom OL Actions.
"""
import infogami
import sys
@infogami.action
def runmain(modulename, *args):
print("run_main", modulename, sys.argv)
mod = __import__(modulename, globals(), locals(), modulename.split("."))
mod.main(*args)
| 246 | Python | .py | 9 | 24.666667 | 76 | 0.696581 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
195 | mapreduce.py | internetarchive_openlibrary/openlibrary/data/mapreduce.py | """Simple library to process large datasets using map-reduce.
This works as follows:
* Takes an iterator of key-value pairs as input
* Applies the map function for each key-value pair. The map function does the
required processing to yield zero or more key-value pairs.
* The result of map are stored in the disk in to multiple files based on the
hash of the key. This makes sure the all the entries with same key goes to
the same file.
* Each of the file is sorted on key to group all the values of a key and the
reduce function is applied for each key and its values.
* The reduced key, value pairs are returned as an iterator.
"""
import sys
import itertools
import os
import subprocess
import logging
import gzip
logger = logging.getLogger("mapreduce")
class Task:
"""Abstraction of a map-reduce task.
Each task should extend this class and implement map and reduce functions.
"""
def __init__(self, tmpdir="/tmp/mapreduce", filecount=100, hashfunc=None):
self.tmpdir = tmpdir
self.filecount = 100
self.hashfunc = None
def map(self, key, value):
"""Function to map given key-value pair into zero or more key-value pairs.
The implementation should yield the key-value pairs.
"""
raise NotImplementedError()
def reduce(self, key, values):
"""Function to reduce given values.
The implementation should return a key-value pair, with the reduced value.
"""
raise NotImplementedError()
def read(self):
for line in sys.sydin:
key, value = line.strip().split("\t", 1)
yield key, value
def map_all(self, records, disk):
for key, value in records:
for k, v in self.map(key, value):
disk.write(k, v)
disk.close()
def reduce_all(self, records):
for key, chunk in itertools.groupby(records, lambda record: record[0]):
values = [value for key, value in chunk]
yield self.reduce(key, values)
def process(self, records):
"""Takes key-value pairs, applies map-reduce and returns the resultant key-value pairs."""
# Map the record and write to disk
disk = Disk(self.tmpdir, mode="w", hashfunc=self.hashfunc)
self.map_all(records, disk)
disk.close()
# Read from the disk in the sorted order and reduce
disk = Disk(self.tmpdir, mode="r", hashfunc=self.hashfunc)
records = disk.read_semisorted()
return self.reduce_all(records)
class Disk:
"""Map Reduce Disk to manage key values.
The data is stored over multiple files based on the key. All records with same key will fall in the same file.
"""
def __init__(self, dir, prefix="shard", filecount=100, hashfunc=None, mode="r"):
self.dir = dir
self.prefix = prefix
self.hashfunc = hashfunc or (lambda key: hash(key))
self.buffersize = 1024 * 1024
if not os.path.exists(dir):
os.makedirs(dir)
self.files = [self.openfile(i, mode) for i in range(filecount)]
def openfile(self, index, mode):
filename = "%s-%03d.txt.gz" % (self.prefix, index)
path = os.path.join(self.dir, filename)
return gzip.open(path, mode)
def write(self, key, value):
index = self.hashfunc(key) % len(self.files)
f = self.files[index]
f.write(key + "\t" + value + "\n")
def close(self):
for f in self.files:
f.close()
def read_semisorted(self):
"""Sorts each file in the disk and returns an iterator over the key-values in each file.
All the values with same key will come together as each file is sorted, but there is no guaranty on the global order of keys.
"""
for f in self.files:
cmd = "gzip -cd %s | sort -S1G" % f.name
logger.info(cmd)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in p.stdout:
key, value = line.split("\t", 1)
yield key, value
status = p.wait()
if status != 0:
raise Exception("sort failed with status %d" % status)
| 4,222 | Python | .py | 97 | 35.773196 | 133 | 0.642997 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
196 | db.py | internetarchive_openlibrary/openlibrary/data/db.py | #!/usr/bin/env python
"""Library to provide fast access to Open Library database.
How to use:
from openlibrary.data import db
db.setup_database(db='openlibrary', user='anand', pw='')
db.setup_memcache(['host1:port1', 'host2:port2'])
# get a set of docs
docs = db.get_docs(['/sandbox'])
# get all books
books = dc.itedocs(type="/type/edition")
# update docs
db.update_docs(docs)
Each doc is a storage object with "id", "key", "revision" and "data".
"""
from openlibrary.utils import olmemcache
import json
import web
import datetime
import sys
import time
__all__ = [
"setup_database",
"setup_memcache",
"longquery",
"iterdocs",
# "get_docs", # "get_docs()" is not defined.
"update_docs",
]
db_parameters = None
db = None
mc = None
def setup_database(**db_params):
"""Setup the database. This must be called before using any other functions in this module."""
global db, db_parameters
db_params.setdefault('dbn', 'postgres')
db = web.database(**db_params)
db.printing = False
db_parameters = db_params
def setup_memcache(servers):
"""Setup the memcached servers.
This must be called along with setup_database, if memcached servers are used in the system.
"""
global mc
mc = olmemcache.Client(servers)
def iterdocs(type=None):
"""Returns an iterator over all docs in the database.
If type is specified, then only docs of that type will be returned.
"""
q = 'SELECT id, key, latest_revision as revision FROM thing'
if type:
type_id = get_thing_id(type)
q += ' WHERE type=$type_id'
q += ' ORDER BY id'
for chunk in longquery(q, locals()):
docs = chunk
_fill_data(docs)
yield from docs
def longquery(query, vars, chunk_size=10000):
"""Execute an expensive query using db cursors.
USAGE:
for chunk in longquery("SELECT * FROM bigtable"):
for row in chunk:
print row
"""
# DB cursor is valid only in the transaction
# Create a new database to avoid this transaction interfere with the application code
db = web.database(**db_parameters)
db.printing = False
tx = db.transaction()
try:
db.query("DECLARE longquery NO SCROLL CURSOR FOR " + query, vars=vars)
while True:
chunk = db.query(
"FETCH FORWARD $chunk_size FROM longquery", vars=locals()
).list()
if chunk:
yield chunk
else:
break
finally:
tx.rollback()
def _fill_data(docs):
"""Add `data` to all docs by querying memcache/database."""
def get(keys):
if not keys:
return []
return db.query(
"SELECT thing.id, thing.key, data.revision, data.data"
" FROM thing, data"
" WHERE thing.id = data.thing_id"
" AND thing.latest_revision = data.revision"
" AND key in $keys",
vars=locals(),
)
keys = [doc.key for doc in docs]
d = mc and mc.get_multi(keys) or {}
debug(f"{len(d)}/{len(keys)} found in memcache")
keys = [doc.key for doc in docs if doc.key not in d]
for row in get(keys):
d[row.key] = row.data
for doc in docs:
doc.data = json.loads(d[doc.key])
return docs
def read_docs(keys, for_update=False):
"""Read the docs the docs from DB."""
if not keys:
return []
debug("BEGIN SELECT")
q = "SELECT thing.id, thing.key, thing.latest_revision as revision FROM thing WHERE key IN $keys"
if for_update:
q += " FOR UPDATE"
docs = db.query(q, vars=locals())
docs = docs.list()
debug("END SELECT")
_fill_data(docs)
return docs
def update_docs(docs, comment, author, ip="127.0.0.1"):
"""Updates the given docs in the database by writing all the docs in a chunk.
This doesn't update the index tables. Avoid this function if you have any change that requires updating the index tables.
"""
now = datetime.datetime.utcnow()
author_id = get_thing_id(author)
t = db.transaction()
try:
docdict = {doc.id: doc for doc in docs}
thing_ids = list(docdict)
# lock the rows in the table
rows = db.query(
"SELECT id, key, latest_revision FROM thing where id IN $thing_ids FOR UPDATE",
vars=locals(),
)
# update revision and last_modified in each document
for row in rows:
doc = docdict[row.id]
doc.revision = row.latest_revision + 1
doc.data['revision'] = doc.revision
doc.data['latest_revision'] = doc.revision
doc.data['last_modified']['value'] = now.isoformat()
tx_id = db.insert(
"transaction",
author_id=author_id,
action="bulk_update",
ip="127.0.0.1",
created=now,
comment=comment,
)
debug("INSERT version")
db.multiple_insert(
"version",
[
{"thing_id": doc.id, "transaction_id": tx_id, "revision": doc.revision}
for doc in docs
],
seqname=False,
)
debug("INSERT data")
data = [
web.storage(
thing_id=doc.id, revision=doc.revision, data=json.dumps(doc.data)
)
for doc in docs
]
db.multiple_insert("data", data, seqname=False)
debug("UPDATE thing")
db.query(
"UPDATE thing set latest_revision=latest_revision+1 WHERE id IN $thing_ids",
vars=locals(),
)
except:
t.rollback()
debug("ROLLBACK")
raise
else:
t.commit()
debug("COMMIT")
mapping = {doc.key: d.data for doc, d in zip(docs, data)}
mc and mc.set_multi(mapping)
debug("MC SET")
def debug(*a):
print(time.asctime(), a, file=sys.stderr)
@web.memoize
def get_thing_id(key):
return db.query("SELECT * FROM thing WHERE key=$key", vars=locals())[0].id
| 6,133 | Python | .py | 183 | 25.95082 | 125 | 0.598307 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
197 | sitemap.py | internetarchive_openlibrary/openlibrary/data/sitemap.py | """Library for generating sitemaps from Open Library dump.
Input for generating sitemaps is a tsv file with "path", "title", "created"
and "last_modified" columns. It is desirable that the file is sorted on
"created" and "path".
http://www.archive.org/download/ol-sitemaps/sitemap-books-0001.xml.gz
http://www.archive.org/download/ol-sitemaps/sitemap-books-0001.xml.gz
http://www.archive.org/download/ol-sitemaps/sitindex-books.xml.gz
http://www.archive.org/download/ol-sitemaps/sitindex-authors.xml.gz
http://www.archive.org/download/ol-sitemaps/sitindex-works.xml.gz
http://www.archive.org/download/ol-sitemaps/sitindex-subjects.xml.gz
"""
import sys
import os
import web
import datetime
from gzip import open as gzopen
from openlibrary.plugins.openlibrary.processors import urlsafe
t = web.template.Template
t_sitemap = t(
"""$def with (docs)
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
$for path, title, created, last_modified in docs:
<url><loc>http://openlibrary.org$path</loc><lastmod>${last_modified}Z</lastmod></url>
</urlset>
"""
)
t_siteindex = t(
"""$def with (base_url, rows)
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
$for filename, timestamp in rows:
<sitemap><loc>$base_url/$filename</loc><lastmod>$timestamp</lastmod></sitemap>
</sitemapindex>
"""
)
t_html_layout = t(
"""$def with (page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,follow" />
<link href="/css/all.css" rel="stylesheet" type="text/css" />
<title>$page.title</title>
</head>
<body id="edit">
<div id="background">
<div id="placement">
<div id="position">$:page</div>
</div>
</div>
</body></html>"""
)
t_html_sitemap = t(
"""$def with (back, docs)
$var title: Index
<p><a href="$back">← Back to Index</a></p>
<ul>
$for path, title in docs:
<li><a href="$path">$title</a></li>
</ul>
"""
)
def gzwrite(path, data):
f = gzopen(path, 'w')
f.write(data)
f.close()
def write_sitemaps(data, outdir, prefix):
timestamp = datetime.datetime.utcnow().isoformat() + 'Z'
# maximum permitted entries in one sitemap is 50K.
for i, rows in enumerate(web.group(data, 50000)):
filename = "sitemap_%s_%04d.xml.gz" % (prefix, i)
print("generating", filename, file=sys.stderr)
sitemap = web.safestr(t_sitemap(rows))
path = os.path.join(outdir, filename)
gzwrite(path, sitemap)
yield filename, timestamp
def write_siteindex(data, outdir, prefix):
rows = write_sitemaps(data, outdir, prefix)
base_url = "http://openlibrary.org/static/sitemaps/"
filename = "siteindex_%s.xml.gz" % prefix
print("generating", filename, file=sys.stderr)
path = os.path.join(outdir, filename)
siteindex = web.safestr(t_siteindex(base_url, rows))
gzwrite(path, siteindex)
def parse_index_file(index_file):
data = (line.strip().split("\t") for line in open(index_file))
data = ([t[0], " ".join(t[1:-2]), t[-2], t[-1]] for t in data)
return data
def generate_sitemaps(index_file, outdir, prefix):
data = parse_index_file(index_file)
write_siteindex(data, outdir, prefix)
def mkdir_p(dir):
if not os.path.exists(dir):
os.makedirs(dir)
def write(path, data):
print("writing", path)
mkdir_p(os.path.dirname(path))
f = open(path, "w")
f.write(data)
f.close()
def dirindex(dir, back=".."):
data = [(f, f) for f in sorted(os.listdir(dir))]
index = t_html_layout(t_html_sitemap(back, data))
path = dir + "/index.html"
write(path, web.safestr(index))
def generate_html_index(index_file, outdir):
data = parse_index_file(index_file)
data = ((d[0], d[1]) for d in data)
for i, chunk in enumerate(web.group(data, 1000)):
back = ".."
index = t_html_layout(t_html_sitemap(back, chunk))
path = outdir + "/%02d/%05d.html" % (i / 1000, i)
write(path, web.safestr(index))
for f in os.listdir(outdir):
path = os.path.join(outdir, f)
if os.path.isdir(path):
dirindex(path)
dirindex(outdir, back=".")
| 4,412 | Python | .py | 121 | 32.68595 | 89 | 0.676547 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
198 | __init__.py | internetarchive_openlibrary/openlibrary/data/__init__.py | """Library for managing Open Library data"""
import json
from openlibrary.data.dump import pgdecode
def parse_data_table(filename):
"""Parses the dump of data table and returns an iterator with
<key, type, revision, json> for all entries.
"""
for line in open(filename):
thing_id, revision, json_data = pgdecode(line).strip().split("\t")
d = json.loads(json_data)
yield d['key'], d['type']['key'], str(d['revision']), json_data
| 472 | Python | .py | 11 | 37.909091 | 74 | 0.671772 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |
199 | dump.py | internetarchive_openlibrary/openlibrary/data/dump.py | """Library for generating and processing Open Library data dumps.
Glossary:
* dump - Dump of latest revisions of all documents.
* cdump - Complete dump. Dump of all revisions of all documents.
* idump - Incremental dump. Dump of all revisions created in the given day.
"""
import gzip
import itertools
import json
import logging
import os
import re
import sys
from datetime import datetime
import web
from openlibrary.data import db
from openlibrary.data.sitemap import generate_html_index, generate_sitemaps
from openlibrary.plugins.openlibrary.processors import urlsafe
logger = logging.getLogger(__file__)
logger.setLevel(logging.DEBUG)
def log(*args) -> None:
args_str = " ".join(str(a) for a in args)
msg = f"{datetime.now():%Y-%m-%d %H:%M:%S} [openlibrary.dump] {args_str}"
logger.info(msg)
print(msg, file=sys.stderr)
def print_dump(json_records, filter=None):
"""Print the given json_records in the dump format."""
start_time = datetime.now()
for i, raw_json_data in enumerate(json_records):
if i % 1_000_000 == 0:
log(f"print_dump {i:,}")
d = json.loads(raw_json_data)
d.pop("id", None)
d = _process_data(d)
key = web.safestr(d["key"])
# skip user pages
if key.startswith("/people/") and not re.match(
r"^/people/[^/]+/lists/OL\d+L$", key
):
continue
# skip admin pages
if key.startswith("/admin/"):
continue
# skip obsolete pages. Obsolete pages include volumes, scan_records and users
# marked as spam.
if key.startswith(("/b/", "/scan", "/old/")) or not key.startswith("/"):
continue
if filter and not filter(d):
continue
type_key = d["type"]["key"]
timestamp = d["last_modified"]["value"]
json_data = json.dumps(d)
print("\t".join([type_key, key, str(d["revision"]), timestamp, json_data]))
minutes = (datetime.now() - start_time).seconds // 60
log(f" print_dump() processed {i:,} records in {minutes:,} minutes.")
def read_data_file(filename: str, max_lines: int = 0):
"""
max_lines allows us to test the process with a subset of all records.
Setting max_lines to 0 will processes all records.
"""
start_time = datetime.now()
log(f"read_data_file({filename}, max_lines={max_lines if max_lines else 'all'})")
for i, line in enumerate(xopen(filename, "rt")):
thing_id, revision, json_data = line.strip().split("\t")
yield pgdecode(json_data)
if max_lines and i >= max_lines:
break
minutes = (datetime.now() - start_time).seconds // 60
log(f"read_data_file() processed {i:,} records in {minutes:,} minutes.")
def xopen(path: str, mode: str):
if path.endswith(".gz"):
return gzip.open(path, mode)
else:
return open(path, mode)
def read_tsv(file, strip=True):
"""Read a tab separated file and return an iterator over rows."""
start_time = datetime.now()
log(f"read_tsv({file})")
if isinstance(file, str):
file = xopen(file, "rt")
for i, line in enumerate(file):
if i % 1_000_000 == 0:
log(f"read_tsv {i:,}")
if strip:
line = line.strip()
yield line.split("\t")
minutes = (datetime.now() - start_time).seconds // 60
log(f" read_tsv() processed {i:,} records in {minutes:,} minutes.")
def generate_cdump(data_file, date=None):
"""Generates cdump from a copy of data table. If date is specified, only revisions
created on or before that date will be considered.
"""
# adding Z to the date will make sure all the timestamps are less than that date.
#
# >>> "2010-05-17T10:20:30" < "2010-05-17"
# False
# >>> "2010-05-17T10:20:30" < "2010-05-17Z"
# True
#
# If scripts/oldump.sh has exported $OLDUMP_TESTING then save a lot of time by only
# processing a subset of the lines in data_file.
log(f"generate_cdump({data_file}, {date}) reading")
max_lines = 1_000_000 if os.getenv("OLDUMP_TESTING") else 0 # 0 means unlimited.
filter = date and (lambda doc: doc["last_modified"]["value"] < date + "Z")
print_dump(read_data_file(data_file, max_lines), filter=filter)
def sort_dump(dump_file=None, tmpdir="/tmp/", buffer_size="1G"):
"""Sort the given dump based on key."""
start_time = datetime.now()
tmpdir = os.path.join(tmpdir, "oldumpsort")
if not os.path.exists(tmpdir):
os.makedirs(tmpdir)
M = 1024 * 1024
filenames = [os.path.join(tmpdir, "%02x.txt.gz" % i) for i in range(256)]
files = [gzip.open(f, "wb") for f in filenames]
stdin = xopen(dump_file, "rb") if dump_file else sys.stdin.buffer
# split the file into 256 chunks using hash of key
log("sort_dump", dump_file or "stdin")
for i, line in enumerate(stdin):
if i % 1_000_000 == 0:
log(f"sort_dump {i:,}")
type, key, revision, timestamp, json_data = line.strip().split(b"\t")
findex = hash(key) % 256
files[findex].write(line)
for f in files:
f.flush()
f.close()
files = []
for fname in filenames:
log("sort_dump", fname)
status = os.system(
"gzip -cd %(fname)s | sort -S%(buffer_size)s -k2,3" % locals()
)
if status != 0:
raise Exception("sort failed with status %d" % status)
minutes = (datetime.now() - start_time).seconds // 60
log(f"sort_dump() processed {i:,} records in {minutes:,} minutes.")
def generate_dump(cdump_file=None):
"""Generate dump from cdump.
The given cdump must be sorted by key.
"""
def process(data):
revision = lambda cols: int(cols[2]) # noqa: E731
for key, rows in itertools.groupby(data, key=lambda cols: cols[1]):
row = max(rows, key=revision)
yield row
start_time = datetime.now()
tjoin = "\t".join
data = read_tsv(cdump_file or sys.stdin, strip=False)
# group by key and find the max by revision
sys.stdout.writelines(tjoin(row) for row in process(data))
minutes = (datetime.now() - start_time).seconds // 60
log(f"generate_dump({cdump_file}) ran in {minutes:,} minutes.")
def generate_idump(day, **db_parameters):
"""Generate incremental dump for the given day."""
db.setup_database(**db_parameters)
rows = db.longquery(
"SELECT data.* FROM data, version, transaction "
" WHERE data.thing_id=version.thing_id"
" AND data.revision=version.revision"
" AND version.transaction_id=transaction.id"
" AND transaction.created >= $day"
" AND transaction.created < date $day + interval '1 day'"
" ORDER BY transaction.created",
vars=locals(),
chunk_size=10_000,
)
print_dump(row.data for chunk in rows for row in chunk)
def split_dump(dump_file=None, format="oldump_%s.txt"):
"""Split dump into authors, editions, works, redirects, and other."""
log(f"split_dump({dump_file}, format={format})")
start_time = datetime.now()
types = (
"/type/edition",
"/type/author",
"/type/work",
"/type/redirect",
"/type/delete",
"/type/list",
)
files = {}
files['other'] = xopen(format % 'other', 'wt')
for t in types:
tname = t.split("/")[-1] + "s"
files[t] = xopen(format % tname, "wt")
stdin = xopen(dump_file, "rt") if dump_file else sys.stdin
for i, line in enumerate(stdin):
if i % 1_000_000 == 0:
log(f"split_dump {i:,}")
type, rest = line.split("\t", 1)
if type in files:
files[type].write(line)
else:
files['other'].write(line)
for f in files.values():
f.close()
minutes = (datetime.now() - start_time).seconds // 60
log(f"split_dump() processed {i:,} records in {minutes:,} minutes.")
def make_index(dump_file):
"""Make index with "path", "title", "created" and "last_modified" columns."""
log(f"make_index({dump_file})")
start_time = datetime.now()
for i, line in enumerate(read_tsv(dump_file)):
type, key, revision, timestamp, json_data = line
data = json.loads(json_data)
if type in ("/type/edition", "/type/work"):
title = data.get("title", "untitled")
path = key + "/" + urlsafe(title)
elif type in ("/type/author", "/type/list"):
title = data.get("name", "unnamed")
path = key + "/" + urlsafe(title)
else:
title = data.get("title", key)
path = key
title = title.replace("\t", " ")
if "created" in data:
created = data["created"]["value"]
else:
created = "-"
print("\t".join([web.safestr(path), web.safestr(title), created, timestamp]))
minutes = (datetime.now() - start_time).seconds // 60
log(f"make_index() processed {i:,} records in {minutes:,} minutes.")
def _process_key(key):
mapping = {
"/l/": "/languages/",
"/a/": "/authors/",
"/b/": "/books/",
"/user/": "/people/",
}
for old, new in mapping.items():
if key.startswith(old):
return new + key[len(old) :]
return key
def _process_data(data):
"""Convert keys from /a/, /b/, /l/ and /user/
to /authors/, /books/, /languages/ and /people/ respectively."""
if isinstance(data, list):
return [_process_data(d) for d in data]
elif isinstance(data, dict):
if "key" in data:
data["key"] = _process_key(data["key"])
# convert date to ISO format
if data.get("type") == "/type/datetime":
data["value"] = data["value"].replace(" ", "T")
return {k: _process_data(v) for k, v in data.items()}
else:
return data
def _make_sub(d):
"""Make substituter.
>>> f = _make_sub(dict(a='aa', bb='b'))
>>> f('aabbb')
'aaaabb'
"""
def f(a):
return d[a.group(0)]
rx = re.compile("|".join(re.escape(key) for key in d))
return lambda s: s and rx.sub(f, s)
_pgdecode_dict = {r"\n": "\n", r"\r": "\r", r"\t": "\t", r"\\": "\\"}
_pgdecode = _make_sub(_pgdecode_dict)
def pgdecode(text):
r"""Decode postgres encoded text.
>>> pgdecode('\\n')
'\n'
"""
return _pgdecode(text)
def main(cmd, args):
"""Command Line interface for generating dumps."""
iargs = iter(args)
args = []
kwargs = {}
for a in iargs:
if a.startswith("--"):
name = a[2:].replace("-", "_")
value = next(iargs)
kwargs[name] = value
else:
args.append(a)
func = {
"cdump": generate_cdump,
"dump": generate_dump,
"idump": generate_idump,
"sort": sort_dump,
"split": split_dump,
"index": make_index,
"sitemaps": generate_sitemaps,
"htmlindex": generate_html_index,
}.get(cmd)
if func:
func(*args, **kwargs)
else:
log(f"Unknown command: {cmd}")
logger.error(f"Unknown command: {cmd}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])
| 11,275 | Python | .py | 293 | 31.580205 | 87 | 0.592538 | internetarchive/openlibrary | 5,078 | 1,311 | 956 | AGPL-3.0 | 9/5/2024, 5:07:13 PM (Europe/Amsterdam) |