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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | core_test.py | git-cola_git-cola/test/core_test.py | """Tests the cola.core module's unicode handling"""
from cola import core
from . import helper
def test_core_decode():
"""Test the core.decode function"""
filename = helper.fixture('unicode.txt')
expect = core.decode(core.encode('unicøde'))
actual = core.read(filename).strip()
assert expect == actual
def test_core_encode():
"""Test the core.encode function"""
filename = helper.fixture('unicode.txt')
expect = core.encode('unicøde')
actual = core.encode(core.read(filename).strip())
assert expect == actual
def test_decode_None():
"""Ensure that decode(None) returns None"""
expect = None
actual = core.decode(None)
assert expect == actual
def test_decode_utf8():
filename = helper.fixture('cyrillic-utf-8.txt')
actual = core.read(filename)
assert actual.encoding == 'utf-8'
def test_decode_non_utf8():
filename = helper.fixture('cyrillic-cp1251.txt')
actual = core.read(filename)
assert actual.encoding == 'iso-8859-15'
def test_decode_non_utf8_string():
filename = helper.fixture('cyrillic-cp1251.txt')
with open(filename, 'rb') as f:
content = f.read()
actual = core.decode(content)
assert actual.encoding == 'iso-8859-15'
def test_guess_mimetype():
value = '字龍.txt'
expect = 'text/plain'
actual = core.guess_mimetype(value)
assert expect == actual
# This function is robust to bytes vs. unicode
actual = core.guess_mimetype(core.encode(value))
assert expect == actual
| 1,528 | Python | .py | 42 | 31.714286 | 53 | 0.689891 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
1 | startup_test.py | git-cola_git-cola/test/startup_test.py | """Test Startup Dialog (git cola --prompt) Context Menu and related classes"""
from cola.widgets import startup
from .helper import app_context
# Prevent unused imports lint errors.
assert app_context is not None
def test_get_with_default_repo(app_context):
"""Test BuildItem::get for default repo"""
path = '/home/foo/git-cola'
name = 'git-cola'
mode = startup.ICON_MODE
is_bookmark = True
app_context.cfg.set_repo('cola.defaultrepo', path)
builder = startup.BuildItem(app_context)
actual = builder.get(path, name, mode, is_bookmark)
assert actual.path == path
assert actual.name == name
assert actual.mode == startup.ICON_MODE
assert actual.is_default
assert actual.is_bookmark
assert actual.text() == name
assert actual.isEditable()
def test_get_with_non_default_repo(app_context):
"""Test BuildItem::get for non-default repo"""
default_repo_path = '/home/foo/default_repo'
path = '/home/foo/git-cola'
name = 'git-cola'
mode = startup.ICON_MODE
is_bookmark = True
app_context.cfg.set_repo('cola.defaultrepo', default_repo_path)
builder = startup.BuildItem(app_context)
actual = builder.get(path, name, mode, is_bookmark)
assert actual.path == path
assert actual.name == name
assert not actual.is_default
assert actual.is_bookmark == is_bookmark
assert actual.text() == name
assert actual.isEditable()
def test_get_with_item_from_recent(app_context):
"""Test BuildItem::get for repository from recent list"""
path = '/home/foo/git-cola'
name = 'git-cola'
mode = startup.ICON_MODE
is_bookmark = False
app_context.cfg.set_repo('cola.defaultrepo', path)
builder = startup.BuildItem(app_context)
actual = builder.get(path, name, mode, is_bookmark)
assert actual.path == path
assert actual.name == name
assert actual.is_default
assert not actual.is_bookmark
assert actual.text() == name
assert actual.isEditable()
def test_get_with_list_mode(app_context):
"""Test BuildItem::get for list mode building"""
path = '/home/foo/git-cola'
name = 'git-cola'
mode = startup.LIST_MODE
is_bookmark = True
app_context.cfg.set_repo('cola.defaultrepo', path)
builder = startup.BuildItem(app_context)
actual = builder.get(path, name, mode, is_bookmark)
assert actual.path == path
assert actual.name == name
assert actual.is_default
assert actual.is_bookmark
assert actual.text() == path
assert not actual.isEditable()
| 2,555 | Python | .py | 67 | 33.343284 | 78 | 0.703163 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
2 | spellcheck_test.py | git-cola_git-cola/test/spellcheck_test.py | from cola import compat
from cola import spellcheck
from . import helper
def test_spellcheck_generator():
check = spellcheck.NorvigSpellCheck()
assert_spellcheck(check)
def test_spellcheck_unicode():
path = helper.fixture('unicode.txt')
check = spellcheck.NorvigSpellCheck(words=path)
assert_spellcheck(check)
def assert_spellcheck(check):
for word in check.read():
assert word is not None
assert isinstance(word, compat.ustr)
| 474 | Python | .py | 14 | 29.5 | 51 | 0.752759 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
3 | compat_test.py | git-cola_git-cola/test/compat_test.py | """Tests the compat module"""
import os
from cola import compat
def test_setenv():
"""Test the core.decode function"""
key = 'COLA_UNICODE_TEST'
value = '字龍'
compat.setenv(key, value)
assert key in os.environ
assert os.getenv(key)
compat.unsetenv(key)
assert key not in os.environ
assert not os.getenv(key)
| 351 | Python | .py | 13 | 22.615385 | 39 | 0.690909 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
4 | gitcfg_test.py | git-cola_git-cola/test/gitcfg_test.py | """Test the cola.gitcfg module."""
import pathlib
from . import helper
from .helper import app_context
# Prevent unused imports lint errors.
assert app_context is not None
def assert_color(context, expect, git_value, key='test', default=None):
"""Helper function for testing color values"""
helper.run_git('config', 'cola.color.%s' % key, git_value)
context.cfg.reset()
actual = context.cfg.color(key, default)
assert expect == actual
def test_string(app_context):
"""Test string values in get()."""
helper.run_git('config', 'test.value', 'test')
assert app_context.cfg.get('test.value') == 'test'
def test_int(app_context):
"""Test int values in get()."""
helper.run_git('config', 'test.int', '42')
expect = 42
actual = app_context.cfg.get('test.int')
assert expect == actual
def test_true(app_context):
"""Test bool values in get()."""
helper.run_git('config', 'test.bool', 'true')
assert app_context.cfg.get('test.bool') is True
def test_false(app_context):
helper.run_git('config', 'test.bool', 'false')
assert app_context.cfg.get('test.bool') is False
def test_yes(app_context):
helper.run_git('config', 'test.bool', 'yes')
assert app_context.cfg.get('test.bool') is True
def test_no(app_context):
helper.run_git('config', 'test.bool', 'no')
assert app_context.cfg.get('test.bool') is False
def test_bool_no_value(app_context):
helper.append_file('.git/config', '[test]\n')
helper.append_file('.git/config', '\tbool\n')
assert app_context.cfg.get('test.bool') is True
def test_empty_value(app_context):
helper.append_file('.git/config', '[test]\n')
helper.append_file('.git/config', '\tvalue = \n')
assert app_context.cfg.get('test.value') == ''
def test_default(app_context):
"""Test default values in get()."""
assert app_context.cfg.get('does.not.exist') is None
assert app_context.cfg.get('does.not.exist', default=42) == 42
def test_get_all(app_context):
"""Test getting multiple values in get_all()"""
helper.run_git('config', '--add', 'test.value', 'abc')
helper.run_git('config', '--add', 'test.value', 'def')
expect = ['abc', 'def']
assert expect == app_context.cfg.get_all('test.value')
def test_color_rrggbb(app_context):
assert_color(app_context, (0xAA, 0xBB, 0xCC), 'aabbcc')
assert_color(app_context, (0xAA, 0xBB, 0xCC), '#aabbcc')
def test_color_int(app_context):
assert_color(app_context, (0x10, 0x20, 0x30), '102030')
assert_color(app_context, (0x10, 0x20, 0x30), '#102030')
def test_guitool_opts(app_context):
helper.run_git('config', 'guitool.hello world.cmd', 'hello world')
opts = app_context.cfg.get_guitool_opts('hello world')
expect = 'hello world'
actual = opts['cmd']
assert expect == actual
def test_guitool_names(app_context):
helper.run_git('config', 'guitool.hello meow.cmd', 'hello meow')
names = app_context.cfg.get_guitool_names()
assert 'hello meow' in names
def test_guitool_names_mixed_case(app_context):
helper.run_git('config', 'guitool.Meow Cat.cmd', 'cat hello')
names = app_context.cfg.get_guitool_names()
assert 'Meow Cat' in names
def test_find_mixed_case(app_context):
helper.run_git('config', 'guitool.Meow Cat.cmd', 'cat hello')
opts = app_context.cfg.find('guitool.Meow Cat.*')
assert opts['guitool.Meow Cat.cmd'] == 'cat hello'
def test_guitool_opts_mixed_case(app_context):
helper.run_git('config', 'guitool.Meow Cat.cmd', 'cat hello')
opts = app_context.cfg.get_guitool_opts('Meow Cat')
assert opts['cmd'] == 'cat hello'
def test_hooks(app_context):
helper.run_git('config', 'core.hooksPath', '/test/hooks')
expect = '/test/hooks'
actual = app_context.cfg.hooks()
assert expect == actual
def test_hooks_lowercase(app_context):
helper.run_git('config', 'core.hookspath', '/test/hooks-lowercase')
expect = '/test/hooks-lowercase'
actual = app_context.cfg.hooks()
assert expect == actual
def test_hooks_path(app_context):
helper.run_git('config', 'core.hooksPath', str(pathlib.Path('/test/hooks')))
expect = str(pathlib.Path('/test/hooks/example'))
actual = app_context.cfg.hooks_path('example')
assert expect == actual
def test_hooks_path_lowercase(app_context):
helper.run_git(
'config', 'core.hookspath', str(pathlib.Path('/test/hooks-lowercase'))
)
expect = str(pathlib.Path('/test/hooks-lowercase/example'))
actual = app_context.cfg.hooks_path('example')
assert expect == actual
| 4,587 | Python | .py | 103 | 40.126214 | 80 | 0.680189 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
5 | main_model_test.py | git-cola_git-cola/test/main_model_test.py | import os
import pytest
from cola import core
from cola import git
from cola.models import main
from cola.models.main import FETCH, FETCH_HEAD, PULL, PUSH
from . import helper
from .helper import app_context
from .helper import Mock
# prevent unused imports lint errors.
assert app_context is not None
REMOTE = 'server'
LOCAL_BRANCH = 'local'
REMOTE_BRANCH = 'remote'
@pytest.fixture
def mock_context():
"""Return a Mock context for testing"""
context = Mock()
context.git = git.create()
return context
def test_project(app_context):
"""Test the 'project' attribute."""
project = os.path.basename(core.getcwd())
app_context.model.set_worktree(core.getcwd())
assert app_context.model.project == project
def test_local_branches(app_context):
"""Test the 'local_branches' attribute."""
helper.commit_files()
app_context.model.update_status()
assert app_context.model.local_branches == ['main']
def test_remote_branches(app_context):
"""Test the 'remote_branches' attribute."""
app_context.model.update_status()
assert app_context.model.remote_branches == []
helper.commit_files()
helper.run_git('remote', 'add', 'origin', '.')
helper.run_git('fetch', 'origin')
app_context.model.update_status()
assert app_context.model.remote_branches == ['origin/main']
def test_modified(app_context):
"""Test the 'modified' attribute."""
helper.write_file('A', 'change')
app_context.model.update_status()
assert app_context.model.modified == ['A']
def test_unstaged(app_context):
"""Test the 'unstaged' attribute."""
helper.write_file('A', 'change')
helper.write_file('C', 'C')
app_context.model.update_status()
assert app_context.model.unstaged == ['A', 'C']
def test_untracked(app_context):
"""Test the 'untracked' attribute."""
helper.write_file('C', 'C')
app_context.model.update_status()
assert app_context.model.untracked == ['C']
def test_stageable(app_context):
"""Test the 'stageable' attribute."""
assert not app_context.model.is_stageable()
def test_remotes(app_context):
"""Test the 'remote' attribute."""
helper.run_git('remote', 'add', 'origin', '.')
app_context.model.update_status()
assert app_context.model.remotes == ['origin']
def test_currentbranch(app_context):
"""Test the 'currentbranch' attribute."""
helper.run_git('checkout', '-b', 'test')
app_context.model.update_status()
assert app_context.model.currentbranch == 'test'
def test_tags(app_context):
"""Test the 'tags' attribute."""
helper.commit_files()
helper.run_git('tag', 'test')
app_context.model.update_status()
assert app_context.model.tags == ['test']
def test_remote_args_fetch(mock_context):
"""FETCH swaps arguments vs. PUSH and PULL"""
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
FETCH,
local_branch=LOCAL_BRANCH,
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'remote:local']
assert kwargs['verbose']
assert 'tags' not in kwargs
assert 'rebase' not in kwargs
def test_remote_args_fetch_head(mock_context):
"""Fetch handles the implicit FETCH_HEAD ref"""
# When FETCH_HEAD is used then we should not specify a tracking branch target.
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
FETCH,
local_branch=FETCH_HEAD,
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'remote']
def test_remote_args_fetch_tags(mock_context):
# Fetch tags
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
FETCH,
tags=True,
local_branch=LOCAL_BRANCH,
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'remote:local']
assert kwargs['verbose']
assert kwargs['tags']
assert 'rebase' not in kwargs
def test_remote_args_fetch_into_tracking_branch(mock_context):
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
FETCH,
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'remote:refs/remotes/server/remote']
def test_remote_args_pull(mock_context):
# Pull
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
PULL,
local_branch='',
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'remote']
assert kwargs['verbose']
assert 'rebase' not in kwargs
assert 'tags' not in kwargs
def test_remote_args_pull_rebase(mock_context):
# Rebasing pull
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
PULL,
rebase=True,
local_branch='',
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'remote']
assert kwargs['verbose']
assert kwargs['rebase']
assert 'tags' not in kwargs
def test_remote_args_push(mock_context):
"""PUSH swaps local and remote branches"""
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
PUSH,
local_branch=LOCAL_BRANCH,
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'local:remote']
assert kwargs['verbose']
assert 'tags' not in kwargs
assert 'rebase' not in kwargs
def test_remote_args_push_tags(mock_context):
"""Pushing tags uses --tags"""
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
PUSH,
tags=True,
local_branch=LOCAL_BRANCH,
remote_branch=REMOTE_BRANCH,
)
assert args == [REMOTE, 'local:remote']
assert kwargs['verbose']
assert kwargs['tags']
assert 'rebase' not in kwargs
def test_remote_args_push_same_remote_and_local(mock_context):
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
PUSH,
tags=True,
local_branch=LOCAL_BRANCH,
remote_branch=LOCAL_BRANCH,
)
assert args == [REMOTE, 'local']
assert kwargs['verbose']
assert kwargs['tags']
assert 'rebase' not in kwargs
def test_remote_args_push_set_upstream(mock_context):
(args, kwargs) = main.remote_args(
mock_context,
REMOTE,
PUSH,
tags=True,
local_branch=LOCAL_BRANCH,
remote_branch=LOCAL_BRANCH,
set_upstream=True,
)
assert args == [REMOTE, 'local']
assert kwargs['verbose']
assert kwargs['tags']
assert kwargs['set_upstream']
assert 'rebase' not in kwargs
def test_remote_args_rebase_only(mock_context):
(_, kwargs) = main.remote_args(
mock_context, REMOTE, PULL, rebase=True, ff_only=True
)
assert kwargs['rebase']
assert 'ff_only' not in kwargs
def test_run_remote_action(mock_context):
"""Test running a remote action"""
(args, kwargs) = main.run_remote_action(
mock_context,
lambda *args, **kwargs: (args, kwargs),
REMOTE,
FETCH,
local_branch=LOCAL_BRANCH,
remote_branch=REMOTE_BRANCH,
)
assert args == (REMOTE, 'remote:local')
assert kwargs['verbose']
assert 'tags' not in kwargs
assert 'rebase' not in kwargs
| 7,183 | Python | .py | 222 | 26.689189 | 82 | 0.655522 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
6 | app_test.py | git-cola_git-cola/test/app_test.py | import argparse
from cola import app
def test_setup_environment():
# If the function doesn't throw an exception we are happy.
assert hasattr(app, 'setup_environment')
app.setup_environment()
def test_add_common_arguments():
# If the function doesn't throw an exception we are happy.
parser = argparse.ArgumentParser()
assert hasattr(app, 'add_common_arguments')
app.add_common_arguments(parser)
| 428 | Python | .py | 11 | 34.909091 | 62 | 0.75 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
7 | cmds_test.py | git-cola_git-cola/test/cmds_test.py | """Test the cmds module"""
from cola import cmds
from cola.compat import uchr
from .helper import Mock, patch
def test_Commit_strip_comments():
"""Ensure that commit messages are stripped of comments"""
msg = 'subject\n\n#comment\nbody'
expect = 'subject\n\nbody\n'
actual = cmds.Commit.strip_comments(msg)
assert expect == actual
def test_commit_strip_comments_unicode():
"""Ensure that unicode is preserved in stripped commit messages"""
msg = uchr(0x1234) + '\n\n#comment\nbody'
expect = uchr(0x1234) + '\n\nbody\n'
actual = cmds.Commit.strip_comments(msg)
assert expect == actual
def test_unix_path_win32():
path = r'Z:\Program Files\git-cola\bin\git-dag'
expect = '/Z/Program Files/git-cola/bin/git-dag'
actual = cmds.unix_path(path, is_win32=lambda: True)
assert expect == actual
def test_unix_path_network_win32():
path = r'\\Z\Program Files\git-cola\bin\git-dag'
expect = '//Z/Program Files/git-cola/bin/git-dag'
actual = cmds.unix_path(path, is_win32=lambda: True)
assert expect == actual
def test_unix_path_is_a_noop_on_sane_platforms():
path = r'/:we/don\t/need/no/stinking/badgers!'
expect = path
actual = cmds.unix_path(path, is_win32=lambda: False)
assert expect == actual
def test_context_edit_command():
context = Mock()
model = context.model
cmd = cmds.EditModel(context)
cmd.new_diff_text = 'test_diff_text'
cmd.new_diff_type = 'test_diff_type'
cmd.new_mode = 'test_mode'
cmd.new_filename = 'test_filename'
cmd.do()
model.set_diff_text.assert_called_once_with('test_diff_text')
model.set_diff_type.assert_called_once_with('test_diff_type')
model.set_mode.assert_called_once_with('test_mode')
assert model.filename == 'test_filename'
@patch('cola.interaction.Interaction.confirm')
def test_submodule_add(confirm):
# "git submodule" should not be called if the answer is "no"
context = Mock()
url = 'url'
path = ''
reference = ''
branch = ''
depth = 0
cmd = cmds.SubmoduleAdd(context, url, path, branch, depth, reference)
confirm.return_value = False
cmd.do()
assert not context.git.submodule.called
expect = ['--', 'url']
actual = cmd.get_args()
assert expect == actual
cmd.path = 'path'
expect = ['--', 'url', 'path']
actual = cmd.get_args()
assert expect == actual
cmd.reference = 'ref'
expect = ['--reference', 'ref', '--', 'url', 'path']
actual = cmd.get_args()
assert expect == actual
cmd.branch = 'branch'
expect = ['--branch', 'branch', '--reference', 'ref', '--', 'url', 'path']
actual = cmd.get_args()
assert expect == actual
cmd.reference = ''
cmd.branch = ''
cmd.depth = 1
expect = ['--depth', '1', '--', 'url', 'path']
actual = cmd.get_args()
assert expect == actual
# Run the command and assert that "git submodule" was called.
confirm.return_value = True
context.git.submodule.return_value = (0, '', '')
cmd.do()
context.git.submodule.assert_called_once_with('add', *expect)
assert context.model.update_file_status.called
assert context.model.update_submodules_list.called
@patch('cola.version.check_git')
@patch('cola.interaction.Interaction.confirm')
def test_submodule_update(confirm, check_git):
context = Mock()
path = 'sub/path'
update_path_cmd = cmds.SubmoduleUpdate(context, path)
update_all_cmd = cmds.SubmodulesUpdate(context)
# Nothing is called when confirm() returns False.
confirm.return_value = False
update_path_cmd.do()
assert not context.git.submodule.called
update_all_cmd.do()
assert not context.git.submodule.called
# Confirm command execution.
confirm.return_value = True
# Test the old command-line arguments first
check_git.return_value = False
expect = ['update', '--', 'sub/path']
actual = update_path_cmd.get_args()
assert expect == actual
context.model.update_file_status = Mock()
context.git.submodule = Mock(return_value=(0, '', ''))
update_path_cmd.do()
context.git.submodule.assert_called_once_with(*expect)
assert context.model.update_file_status.called
expect = ['update']
actual = update_all_cmd.get_args()
assert expect == actual
context.model.update_file_status = Mock()
context.git.submodule = Mock(return_value=(0, '', ''))
update_all_cmd.do()
context.git.submodule.assert_called_once_with(*expect)
assert context.model.update_file_status.called
# Test the new command-line arguments (git v1.6.5+)
check_git.return_value = True
expect = ['update', '--recursive', '--', 'sub/path']
actual = update_path_cmd.get_args()
assert expect == actual
context.model.update_file_status = Mock()
context.git.submodule = Mock(return_value=(0, '', ''))
update_path_cmd.do()
context.git.submodule.assert_called_once_with(*expect)
assert context.model.update_file_status.called
expect = ['update', '--recursive']
actual = update_all_cmd.get_args()
assert expect == actual
context.model.update_file_status = Mock()
context.git.submodule = Mock(return_value=(0, '', ''))
update_all_cmd.do()
context.git.submodule.assert_called_once_with(*expect)
assert context.model.update_file_status.called
@patch('cola.cmds.Interaction')
@patch('cola.cmds.prefs')
def test_undo_last_commit_confirms_action(prefs, interaction):
"""Test the behavior around confirmation of UndoLastCommit actions"""
context = Mock()
context.model = Mock()
# First, test what happens when the commit is published and we say "yes".
prefs.check_published_commits = Mock(return_value=True)
context.model.is_commit_published = Mock(return_value=True)
interaction.confirm = Mock(return_value=True)
cmd = cmds.UndoLastCommit(context)
assert cmd.confirm()
context.model.is_commit_published.assert_called_once()
interaction.confirm.assert_called_once()
# Now, test what happens when we say "no".
interaction.confirm = Mock(return_value=False)
assert not cmd.confirm()
interaction.confirm.assert_called_once()
# Now check what happens when the commit is published but our preferences
# say to not check for published commits.
prefs.check_published_commits = Mock(return_value=False)
context.model.is_commit_published = Mock(return_value=True)
interaction.confirm = Mock(return_value=True)
assert cmd.confirm()
context.model.is_commit_published.assert_not_called()
interaction.confirm.assert_called_once()
# Lastly, check what when the commit is not published and we do check
# for published commits.
prefs.check_published_commits = Mock(return_value=True)
context.model.is_commit_published = Mock(return_value=False)
interaction.confirm = Mock(return_value=True)
assert cmd.confirm()
context.model.is_commit_published.assert_called_once()
interaction.confirm.assert_called_once()
| 7,046 | Python | .py | 170 | 36.582353 | 78 | 0.692105 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
8 | display_test.py | git-cola_git-cola/test/display_test.py | from cola import display
def test_shorten_paths():
paths = (
'/usr/src/git-cola/src',
'/usr/src/example/src',
'/usr/src/super/lib/src',
'/usr/src/super/tools/src',
'/usr/src/super/example/src',
'/lib/src',
)
actual = display.shorten_paths(paths)
assert actual[paths[0]] == 'git-cola/src'
assert actual[paths[1]] == 'src/example/src'
assert actual[paths[2]] == 'super/lib/src'
assert actual[paths[3]] == 'tools/src'
assert actual[paths[4]] == 'super/example/src'
assert actual[paths[5]] == '/lib/src'
def test_normalize_path():
path = r'C:\games\doom2'
expect = 'C:/games/doom2'
actual = display.normalize_path(path)
assert expect == actual
| 744 | Python | .py | 22 | 28.090909 | 50 | 0.615599 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
9 | gitcmds_test.py | git-cola_git-cola/test/gitcmds_test.py | """Test the cola.gitcmds module"""
import os
from cola import core
from cola import gitcmds
from cola.widgets.remote import get_default_remote
from . import helper
from .helper import app_context
# Prevent unused imports lint errors.
assert app_context is not None
def test_currentbranch(app_context):
"""Test current_branch()."""
assert gitcmds.current_branch(app_context) == 'main'
def test_branch_list_local(app_context):
"""Test branch_list(remote=False)."""
helper.commit_files()
expect = ['main']
actual = gitcmds.branch_list(app_context, remote=False)
assert expect == actual
def test_branch_list_remote(app_context):
"""Test branch_list(remote=False)."""
expect = []
actual = gitcmds.branch_list(app_context, remote=True)
assert expect == actual
helper.commit_files()
helper.run_git('remote', 'add', 'origin', '.')
helper.run_git('fetch', 'origin')
expect = ['origin/main']
actual = gitcmds.branch_list(app_context, remote=True)
assert expect == actual
helper.run_git('remote', 'rm', 'origin')
expect = []
actual = gitcmds.branch_list(app_context, remote=True)
assert expect == actual
def test_upstream_remote(app_context):
"""Test getting the configured upstream remote"""
assert gitcmds.upstream_remote(app_context) is None
helper.run_git('config', 'branch.main.remote', 'test')
app_context.cfg.reset()
assert gitcmds.upstream_remote(app_context) == 'test'
def test_default_push(app_context):
"""Test getting what default branch to push to"""
# no default push, no remote branch configured
assert get_default_remote(app_context) == 'origin'
# default push set, no remote branch configured
helper.run_git('config', 'remote.pushDefault', 'test')
app_context.cfg.reset()
assert get_default_remote(app_context) == 'test'
# default push set, default remote branch configured
helper.run_git('config', 'branch.main.remote', 'test2')
app_context.cfg.reset()
assert get_default_remote(app_context) == 'test2'
# default push set, default remote branch configured, on different branch
helper.run_git('checkout', '-b', 'other-branch')
assert get_default_remote(app_context) == 'test'
def test_tracked_branch(app_context):
"""Test tracked_branch()."""
assert gitcmds.tracked_branch(app_context) is None
helper.run_git('config', 'branch.main.remote', 'test')
helper.run_git('config', 'branch.main.merge', 'refs/heads/main')
app_context.cfg.reset()
assert gitcmds.tracked_branch(app_context) == 'test/main'
def test_tracked_branch_other(app_context):
"""Test tracked_branch('other')"""
assert gitcmds.tracked_branch(app_context, 'other') is None
helper.run_git('config', 'branch.other.remote', 'test')
helper.run_git('config', 'branch.other.merge', 'refs/heads/other/branch')
app_context.cfg.reset()
assert gitcmds.tracked_branch(app_context, 'other') == 'test/other/branch'
def test_untracked_files(app_context):
"""Test untracked_files()."""
helper.touch('C', 'D', 'E')
assert gitcmds.untracked_files(app_context) == ['C', 'D', 'E']
def test_all_files(app_context):
helper.touch('other-file')
all_files = gitcmds.all_files(app_context)
assert 'A' in all_files
assert 'B' in all_files
assert 'other-file' in all_files
def test_tag_list(app_context):
"""Test tag_list()"""
helper.commit_files()
helper.run_git('tag', 'a')
helper.run_git('tag', 'b')
helper.run_git('tag', 'c')
assert gitcmds.tag_list(app_context) == ['c', 'b', 'a']
def test_merge_message_path(app_context):
"""Test merge_message_path()."""
helper.touch('.git/SQUASH_MSG')
assert gitcmds.merge_message_path(app_context) == os.path.abspath('.git/SQUASH_MSG')
helper.touch('.git/MERGE_MSG')
assert gitcmds.merge_message_path(app_context) == os.path.abspath('.git/MERGE_MSG')
os.unlink(gitcmds.merge_message_path(app_context))
assert gitcmds.merge_message_path(app_context) == os.path.abspath('.git/SQUASH_MSG')
os.unlink(gitcmds.merge_message_path(app_context))
assert gitcmds.merge_message_path(app_context) is None
def test_all_refs(app_context):
helper.commit_files()
helper.run_git('branch', 'a')
helper.run_git('branch', 'b')
helper.run_git('branch', 'c')
helper.run_git('tag', 'd')
helper.run_git('tag', 'e')
helper.run_git('tag', 'f')
helper.run_git('remote', 'add', 'origin', '.')
helper.run_git('fetch', 'origin')
refs = gitcmds.all_refs(app_context)
assert refs == [
'a',
'b',
'c',
'main',
'origin/a',
'origin/b',
'origin/c',
'origin/main',
'f',
'e',
'd',
]
def test_all_refs_split(app_context):
helper.commit_files()
helper.run_git('branch', 'a')
helper.run_git('branch', 'b')
helper.run_git('branch', 'c')
helper.run_git('tag', 'd')
helper.run_git('tag', 'e')
helper.run_git('tag', 'f')
helper.run_git('remote', 'add', 'origin', '.')
helper.run_git('fetch', 'origin')
local, remote, tags = gitcmds.all_refs(app_context, split=True)
assert local == ['a', 'b', 'c', 'main']
assert remote == ['origin/a', 'origin/b', 'origin/c', 'origin/main']
assert tags == ['f', 'e', 'd']
def test_binary_files(app_context):
# Create a binary file and ensure that it's detected as binary.
with core.xopen('binary-file.txt', 'wb') as f:
f.write(b'hello\0world\n')
assert gitcmds.is_binary(app_context, 'binary-file.txt')
# Create a text file and ensure that it's not detected as binary.
with core.open_write('text-file.txt') as f:
f.write('hello world\n')
assert not gitcmds.is_binary(app_context, 'text-file.txt')
# Create a .gitattributes file and mark text-file.txt as binary.
app_context.cfg.reset()
with core.open_write('.gitattributes') as f:
f.write('text-file.txt binary\n')
assert gitcmds.is_binary(app_context, 'text-file.txt')
# Remove the "binary" attribute using "-binary" from binary-file.txt.
# Ensure that we do not flag this file as binary.
with core.open_write('.gitattributes') as f:
f.write('binary-file.txt -binary\n')
assert not gitcmds.is_binary(app_context, 'binary-file.txt')
def test_is_valid_ref(app_context):
"""Verify the behavior of is_valid_ref()"""
# We are initially in a "git init" state. HEAD must be invalid.
assert not gitcmds.is_valid_ref(app_context, 'HEAD')
# Create the first commit onto the "test" branch.
app_context.git.symbolic_ref('HEAD', 'refs/heads/test')
app_context.git.commit(m='initial commit')
assert gitcmds.is_valid_ref(app_context, 'HEAD')
assert gitcmds.is_valid_ref(app_context, 'test')
assert gitcmds.is_valid_ref(app_context, 'refs/heads/test')
def test_diff_helper(app_context):
helper.commit_files()
with core.open_write('A') as f:
f.write('A change\n')
helper.run_git('add', 'A')
expect_n = '+A change\n'
expect_rn = '+A change\r\n'
actual = gitcmds.diff_helper(app_context, ref='HEAD', cached=True)
assert expect_n in actual or expect_rn in actual
| 7,264 | Python | .py | 171 | 37.391813 | 88 | 0.66856 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
10 | gitops_test.py | git-cola_git-cola/test/gitops_test.py | """Tests basic git operations: commit, log, config"""
from . import helper
from .helper import app_context
# Prevent unused imports lint errors.
assert app_context is not None
def test_git_commit(app_context):
"""Test running 'git commit' via cola.git"""
helper.write_file('A', 'A')
helper.write_file('B', 'B')
helper.run_git('add', 'A', 'B')
app_context.git.commit(m='initial commit')
log = helper.run_git('-c', 'log.showsignature=false', 'log', '--pretty=oneline')
expect = 1
actual = len(log.splitlines())
assert expect == actual
def test_git_config(app_context):
"""Test cola.git.config()"""
helper.run_git('config', 'section.key', 'value')
expect = (0, 'value', '')
actual = app_context.git.config('section.key', get=True)
assert expect == actual
| 816 | Python | .py | 21 | 34.809524 | 84 | 0.664549 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
11 | branch_test.py | git-cola_git-cola/test/branch_test.py | """Tests related to the branches widget"""
from cola.widgets import branch
from .helper import Mock
def test_create_tree_entries():
names = [
'abc',
'cat/abc',
'cat/def',
'xyz/xyz',
]
root = branch.create_tree_entries(names)
expect = 3
actual = len(root.children)
assert expect == actual
# 'abc'
abc = root.children[0]
expect = 'abc'
actual = abc.basename
assert expect == actual
expect = 'abc'
actual = abc.refname
assert expect == actual
expect = []
actual = abc.children
assert expect == actual
# 'cat'
cat = root.children[1]
expect = 'cat'
actual = 'cat'
assert expect == actual
assert cat.refname is None
expect = 2
actual = len(cat.children)
assert expect == actual
# 'cat/abc'
cat_abc = cat.children[0]
expect = 'abc'
actual = cat_abc.basename
assert expect == actual
expect = 'cat/abc'
actual = cat_abc.refname
assert expect == actual
expect = []
actual = cat_abc.children
assert expect == actual
# 'cat/def'
cat_def = cat.children[1]
expect = 'def'
actual = cat_def.basename
assert expect == actual
expect = 'cat/def'
actual = cat_def.refname
assert expect == actual
expect = []
actual = cat_def.children
assert expect == actual
# 'xyz'
xyz = root.children[2]
expect = 'xyz'
actual = xyz.basename
assert expect == actual
assert xyz.refname is None
expect = 1
actual = len(xyz.children)
assert expect == actual
# 'xyz/xyz'
xyz_xyz = xyz.children[0]
expect = 'xyz'
actual = xyz_xyz.basename
assert expect == actual
expect = 'xyz/xyz'
actual = xyz_xyz.refname
assert expect == actual
expect = []
actual = xyz_xyz.children
assert expect == actual
def test_create_name_dict():
"""Test transforming unix path-like names into a nested dict"""
branches = [
'top_1/child_1/child_1_1',
'top_1/child_1/child_1_2',
'top_1/child_2/child_2_1/child_2_1_1',
'top_1/child_2/child_2_1/child_2_1_2',
]
inner_child = {'child_2_1_2': {}, 'child_2_1_1': {}}
expect = {
'top_1': {
'child_1': {'child_1_2': {}, 'child_1_1': {}},
'child_2': {'child_2_1': inner_child},
}
}
actual = branch.create_name_dict(branches)
assert expect == actual
def test_create_toplevel_item():
names = [
'child_1',
'child_2/child_2_1',
'child_2/child_2_2',
]
tree = branch.create_tree_entries(names)
tree.basename = 'top'
top = branch.create_toplevel_item(tree)
expect = 'top'
actual = top.name
assert expect == actual
expect = 2
actual = top.childCount()
assert expect == actual
expect = 'child_1'
actual = top.child(0).name
assert expect == actual
expect = 'child_1'
actual = top.child(0).refname
assert expect == actual
expect = 'child_2'
actual = top.child(1).name
assert expect == actual
assert top.child(1).refname is None
expect = 2
actual = top.child(1).childCount()
assert expect == actual
expect = 'child_2_1'
actual = top.child(1).child(0).name
assert expect == actual
expect = 'child_2_2'
actual = top.child(1).child(1).name
assert expect == actual
expect = 'child_2/child_2_1'
actual = top.child(1).child(0).refname
assert expect == actual
expect = 'child_2/child_2_2'
actual = top.child(1).child(1).refname
assert expect == actual
def test_get_toplevel_item():
items = _create_top_item()
actual = branch.get_toplevel_item(items['child_1'])
assert items['top'] is actual
actual = branch.get_toplevel_item(items['sub_child_2_1'])
assert items['top'] is actual
def test_refname_attribute():
items = _create_top_item()
actual = items['child_1'].refname
expect = 'child_1'
assert expect == actual
actual = items['sub_child_2_2'].refname
expect = 'child_2/sub_child_2_2'
assert expect == actual
def test_should_return_a_valid_child_on_find_child():
"""Test the find_child function."""
items = _create_top_item()
child = branch.find_by_refname(items['top'], 'child_1')
assert child.refname == 'child_1'
child = branch.find_by_refname(items['top'], 'child_2/sub_child_2_2')
assert child.name == 'sub_child_2_2'
def test_should_return_empty_state_on_save_state():
"""Test the save_state function."""
top = _create_item('top', None, False)
tree_helper = branch.BranchesTreeHelper(Mock())
actual = tree_helper.save_state(top)
assert {'top': {'children': {}, 'expanded': False, 'selected': False}} == actual
def test_should_return_a_valid_state_on_save_state():
"""Test the save_state function."""
items = _create_top_item()
tree_helper = branch.BranchesTreeHelper(Mock())
actual = tree_helper.save_state(items['top'])
expect = {
'top': {
'children': {
'child_1': {
'children': {},
'expanded': False,
'selected': False,
},
'child_2': {
'children': {
'sub_child_2_1': {
'children': {},
'expanded': False,
'selected': False,
},
'sub_child_2_2': {
'children': {},
'expanded': False,
'selected': False,
},
},
'expanded': True,
'selected': False,
},
},
'expanded': True,
'selected': False,
}
}
assert expect == actual
def _create_top_item():
top = _create_item('top', None, True)
child_1 = _create_item('child_1', 'child_1', False)
child_2 = _create_item('child_2', None, True)
sub_child_2_1 = _create_item('sub_child_2_1', 'child_2/sub_child_2_1', False)
sub_child_2_2 = _create_item('sub_child_2_2', 'child_2/sub_child_2_2', False)
child_2.addChildren([sub_child_2_1, sub_child_2_2])
top.addChildren([child_1, child_2])
return {
'top': top,
'child_1': child_1,
'sub_child_2_1': sub_child_2_1,
'sub_child_2_2': sub_child_2_2,
}
def _create_item(name, refname, expanded):
item = branch.BranchTreeWidgetItem(name, refname=refname)
item.isExpanded = Mock(return_value=expanded)
return item
| 6,703 | Python | .py | 213 | 24.107981 | 84 | 0.569921 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
12 | resources_test.py | git-cola_git-cola/test/resources_test.py | from cola import resources
from . import helper
from .helper import patch
@patch('cola.resources.compat')
@patch('cola.resources.get_prefix')
def test_command_unix(mock_prefix, mock_compat):
"""Test the behavior of resources.command() on unix platforms"""
mock_compat.WIN32 = False
mock_prefix.return_value = helper.fixture()
expect = helper.fixture('bin', 'bare-cmd')
actual = resources.command('bare-cmd')
assert expect == actual
expect = helper.fixture('bin', 'exe-cmd')
actual = resources.command('exe-cmd')
assert expect == actual
@patch('cola.resources.compat')
@patch('cola.resources.get_prefix')
def test_command_win32(mock_prefix, mock_compat):
"""Test the behavior of resources.command() on unix platforms"""
mock_compat.WIN32 = True
mock_prefix.return_value = helper.fixture()
expect = helper.fixture('bin', 'bare-cmd')
actual = resources.command('bare-cmd')
assert expect == actual
# Windows will return exe-cmd.exe because the path exists.
expect = helper.fixture('bin', 'exe-cmd.exe')
actual = resources.command('exe-cmd')
assert expect == actual
| 1,146 | Python | .py | 28 | 36.892857 | 68 | 0.713255 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
13 | icons_test.py | git-cola_git-cola/test/icons_test.py | from cola import compat
from cola import core
from cola import icons
def test_from_filename_unicode():
filename = compat.uchr(0x400) + '.py'
expect = 'file-code.svg'
actual = icons.basename_from_filename(filename)
assert expect == actual
actual = icons.basename_from_filename(core.encode(filename))
assert expect == actual
| 350 | Python | .py | 10 | 31.3 | 64 | 0.738872 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
14 | gravatar_test.py | git-cola_git-cola/test/gravatar_test.py | from cola import gravatar
from cola.compat import ustr
def test_url_for_email_():
email = '[email protected]'
expect = (
'https://gravatar.com/avatar/5658ffccee7f0ebfda2b226238b1eb6e?s=64'
+ r'&d=https%3A%2F%2Fgit-cola.github.io%2Fimages%2Fgit-64x64.jpg'
)
actual = gravatar.Gravatar.url_for_email(email, 64)
assert expect == actual
assert isinstance(actual, ustr)
| 407 | Python | .py | 11 | 32.181818 | 75 | 0.71066 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
15 | git_test.py | git-cola_git-cola/test/git_test.py | """Test the cola.git module"""
import os
import pathlib
from cola import git
from cola.git import STDOUT
from .helper import patch
# 16k+1 bytes to exhaust any output buffers.
BUFFER_SIZE = (16 * 1024) + 1
@patch('cola.git.is_git_dir')
def test_find_git_dir_None(is_git_dir):
paths = git.find_git_directory(None)
assert not is_git_dir.called
assert paths.git_dir is None
assert paths.git_file is None
assert paths.worktree is None
@patch('cola.git.is_git_dir')
def test_find_git_dir_empty_string(is_git_dir):
paths = git.find_git_directory('')
assert not is_git_dir.called
assert paths.git_dir is None
assert paths.git_file is None
assert paths.worktree is None
@patch('cola.git.is_git_dir')
def test_find_git_dir_never_found(is_git_dir):
is_git_dir.return_value = False
paths = git.find_git_directory(str(pathlib.Path('/does/not/exist').resolve()))
assert is_git_dir.called
assert paths.git_dir is None
assert paths.git_file is None
assert paths.worktree is None
expect = 8
actual = is_git_dir.call_count
assert expect == actual
is_git_dir.assert_has_calls([
((str(pathlib.Path('/does/not/exist').resolve()),), {}),
((str(pathlib.Path('/does/not/exist/.git').resolve()),), {}),
((str(pathlib.Path('/does/not').resolve()),), {}),
((str(pathlib.Path('/does/not/.git').resolve()),), {}),
((str(pathlib.Path('/does').resolve()),), {}),
((str(pathlib.Path('/does/.git').resolve()),), {}),
((str(pathlib.Path('/').resolve()),), {}),
((str(pathlib.Path('/.git').resolve()),), {}),
])
@patch('cola.git.is_git_dir')
def test_find_git_dir_found_right_away(is_git_dir):
git_dir = str(pathlib.Path('/seems/to/exist/.git').resolve())
worktree = str(pathlib.Path('/seems/to/exist').resolve())
is_git_dir.return_value = True
paths = git.find_git_directory(git_dir)
assert is_git_dir.called
assert git_dir == paths.git_dir
assert paths.git_file is None
assert worktree == paths.worktree
@patch('cola.git.is_git_dir')
def test_find_git_does_discovery(is_git_dir):
git_dir = str(pathlib.Path('/the/root/.git').resolve())
worktree = str(pathlib.Path('/the/root').resolve())
is_git_dir.side_effect = lambda x: x == git_dir
paths = git.find_git_directory('/the/root/sub/dir')
assert git_dir == paths.git_dir
assert paths.git_file is None
assert worktree == paths.worktree
@patch('cola.git.read_git_file')
@patch('cola.git.is_git_file')
@patch('cola.git.is_git_dir')
def test_find_git_honors_git_files(is_git_dir, is_git_file, read_git_file):
git_file = str(pathlib.Path('/the/root/.git').resolve())
worktree = str(pathlib.Path('/the/root').resolve())
git_dir = str(pathlib.Path('/super/module/.git/modules/root').resolve())
is_git_dir.side_effect = lambda x: x == git_file
is_git_file.side_effect = lambda x: x == git_file
read_git_file.return_value = git_dir
paths = git.find_git_directory(str(pathlib.Path('/the/root/sub/dir').resolve()))
assert git_dir == paths.git_dir
assert git_file == paths.git_file
assert worktree == paths.worktree
expect = 6
actual = is_git_dir.call_count
assert expect == actual
is_git_dir.assert_has_calls([
((str(pathlib.Path('/the/root/sub/dir').resolve()),), {}),
((str(pathlib.Path('/the/root/sub/dir/.git').resolve()),), {}),
((str(pathlib.Path('/the/root/sub').resolve()),), {}),
((str(pathlib.Path('/the/root/sub/.git').resolve()),), {}),
((str(pathlib.Path('/the/root').resolve()),), {}),
((str(pathlib.Path('/the/root/.git').resolve()),), {}),
])
read_git_file.assert_called_once_with(git_file)
@patch('cola.core.getenv')
@patch('cola.git.is_git_dir')
def test_find_git_honors_ceiling_dirs(is_git_dir, getenv):
git_dir = str(pathlib.Path('/ceiling/.git').resolve())
ceiling = os.pathsep.join(
str(pathlib.Path(path).resolve())
for path in ('/tmp', '/ceiling', '/other/ceiling')
)
is_git_dir.side_effect = lambda x: x == git_dir
def mock_getenv(k, v=None):
if k == 'GIT_CEILING_DIRECTORIES':
return ceiling
return v
getenv.side_effect = mock_getenv
paths = git.find_git_directory(str(pathlib.Path('/ceiling/sub/dir').resolve()))
assert paths.git_dir is None
assert paths.git_file is None
assert paths.worktree is None
assert is_git_dir.call_count == 4
is_git_dir.assert_has_calls([
((str(pathlib.Path('/ceiling/sub/dir').resolve()),), {}),
((str(pathlib.Path('/ceiling/sub/dir/.git').resolve()),), {}),
((str(pathlib.Path('/ceiling/sub').resolve()),), {}),
((str(pathlib.Path('/ceiling/sub/.git').resolve()),), {}),
])
@patch('cola.core.islink')
@patch('cola.core.isdir')
@patch('cola.core.isfile')
def test_is_git_dir_finds_linked_repository(isfile, isdir, islink):
dirs = {
str(pathlib.Path(directory).resolve())
for directory in [
'/foo',
'/foo/.git',
'/foo/.git/refs',
'/foo/.git/objects',
'/foo/.git/worktrees',
'/foo/.git/worktrees/foo',
]
}
files = {
str(pathlib.Path(file).resolve())
for file in [
'/foo/.git/HEAD',
'/foo/.git/worktrees/foo/HEAD',
'/foo/.git/worktrees/foo/index',
'/foo/.git/worktrees/foo/commondir',
'/foo/.git/worktrees/foo/gitdir',
]
}
islink.return_value = False
isfile.side_effect = lambda x: x in files
isdir.side_effect = lambda x: x in dirs
assert git.is_git_dir(str(pathlib.Path('/foo/.git/worktrees/foo').resolve()))
assert git.is_git_dir(str(pathlib.Path('/foo/.git').resolve()))
@patch('cola.core.getenv')
@patch('cola.git.is_git_dir')
def test_find_git_worktree_from_GIT_DIR(is_git_dir, getenv):
git_dir = str(pathlib.Path('/repo/.git').resolve())
worktree = str(pathlib.Path('/repo').resolve())
is_git_dir.return_value = True
getenv.side_effect = lambda x: x == 'GIT_DIR' and git_dir or None
paths = git.find_git_directory(git_dir)
assert is_git_dir.called
assert git_dir == paths.git_dir
assert paths.git_file is None
assert worktree == paths.worktree
@patch('cola.git.is_git_dir')
def test_finds_no_worktree_from_bare_repo(is_git_dir):
git_dir = str(pathlib.Path('/repos/bare.git').resolve())
worktree = None
is_git_dir.return_value = True
paths = git.find_git_directory(git_dir)
assert is_git_dir.called
assert git_dir == paths.git_dir
assert paths.git_file is None
assert worktree == paths.worktree
@patch('cola.core.getenv')
@patch('cola.git.is_git_dir')
def test_find_git_directory_uses_GIT_WORK_TREE(is_git_dir, getenv):
git_dir = str(pathlib.Path('/repo/worktree/.git').resolve())
worktree = str(pathlib.Path('/repo/worktree').resolve())
def is_git_dir_func(path):
return path == git_dir
is_git_dir.side_effect = is_git_dir_func
def getenv_func(name):
if name == 'GIT_WORK_TREE':
return worktree
return None
getenv.side_effect = getenv_func
paths = git.find_git_directory(worktree)
assert is_git_dir.called
assert git_dir == paths.git_dir
assert paths.git_file is None
assert worktree == paths.worktree
@patch('cola.core.getenv')
@patch('cola.git.is_git_dir')
def test_uses_cwd_for_worktree_with_GIT_DIR(is_git_dir, getenv):
git_dir = str(pathlib.Path('/repo/.yadm/repo.git').resolve())
worktree = str(pathlib.Path('/repo').resolve())
def getenv_func(name):
if name == 'GIT_DIR':
return git_dir
return None
getenv.side_effect = getenv_func
def is_git_dir_func(path):
return path == git_dir
is_git_dir.side_effect = is_git_dir_func
paths = git.find_git_directory(worktree)
assert is_git_dir.called
assert getenv.called
assert git_dir == paths.git_dir
assert paths.git_file is None
assert worktree == paths.worktree
def test_transform_kwargs_empty():
expect = []
actual = git.transform_kwargs(foo=None, bar=False)
assert expect == actual
def test_transform_kwargs_single_dash_from_True():
"""Single dash for one-character True"""
expect = ['-a']
actual = git.transform_kwargs(a=True)
assert expect == actual
def test_transform_kwargs_no_single_dash_from_False():
"""No single-dash for False"""
expect = []
actual = git.transform_kwargs(a=False)
assert expect == actual
def test_transform_kwargs_double_dash_from_True():
"""Double-dash for longer True"""
expect = ['--abc']
actual = git.transform_kwargs(abc=True)
assert expect == actual
def test_transform_kwargs_no_double_dash_from_True():
"""No double-dash for False"""
expect = []
actual = git.transform_kwargs(abc=False)
assert expect == actual
def test_transform_kwargs_single_dash_int():
expect = ['-a1']
actual = git.transform_kwargs(a=1)
assert expect == actual
def test_transform_kwargs_double_dash_int():
expect = ['--abc=1']
actual = git.transform_kwargs(abc=1)
assert expect == actual
def test_transform_kwargs_single_dash_float():
expect = ['-a1.5']
actual = git.transform_kwargs(a=1.5)
assert expect == actual
def test_transform_kwargs_double_dash_float():
expect = ['--abc=1.5']
actual = git.transform_kwargs(abc=1.5)
assert expect == actual
def test_transform_kwargs_single_dash_string():
expect = ['-abc']
actual = git.transform_kwargs(a='bc')
assert expect == actual
def test_transform_double_single_dash_string():
expect = ['--abc=def']
actual = git.transform_kwargs(abc='def')
assert expect == actual
def test_version():
"""Test running 'git version'"""
gitcmd = git.Git()
version = gitcmd.version()[STDOUT]
assert version.startswith('git version')
def test_stdout():
"""Test overflowing the stdout buffer"""
# Write to stdout only
code = r'import sys; value = "\0" * %d; sys.stdout.write(value);' % BUFFER_SIZE
status, out, err = git.Git.execute(['python', '-c', code], _raw=True)
assert status == 0
expect = BUFFER_SIZE
actual = len(out)
assert expect == actual
expect = 0
actual = len(err)
assert expect == actual
def test_stderr():
"""Test that stderr is seen"""
# Write to stderr and capture it
code = (
r'import sys;' r'value = "\0" * %d;' r'sys.stderr.write(value);'
) % BUFFER_SIZE
status, out, err = git.Git.execute(['python', '-c', code], _raw=True)
expect = 0
actual = status
assert expect == actual
expect = 0
actual = len(out)
assert expect == actual
expect = BUFFER_SIZE
actual = len(err)
assert expect == actual
def test_stdout_and_stderr():
"""Test ignoring stderr when stdout+stderr are provided (v2)"""
# Write to stdout and stderr but only capture stdout
code = (
r'import sys;'
r'value = "\0" * %d;'
r'sys.stdout.write(value);'
r'sys.stderr.write(value);'
) % BUFFER_SIZE
status, out, err = git.Git.execute(['python', '-c', code], _raw=True)
expect = 0
actual = status
assert expect == actual
expect = BUFFER_SIZE
actual = len(out)
assert expect == actual
actual = len(err)
assert expect == actual
def test_it_doesnt_deadlock():
"""Test that we don't deadlock with both stderr and stdout"""
code = (
r'import sys;'
r'value = "\0" * %d;'
r'sys.stderr.write(value);'
r'sys.stdout.write(value);'
) % BUFFER_SIZE
status, out, err = git.Git.execute(['python', '-c', code], _raw=True)
expect = 0
actual = status
assert expect == actual
expect = '\0' * BUFFER_SIZE
actual = out
assert expect == actual
actual = err
assert expect == actual
| 12,019 | Python | .py | 318 | 32.283019 | 84 | 0.640024 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
16 | settings_test.py | git-cola_git-cola/test/settings_test.py | """Test the cola.settings module"""
import os
import pytest
from cola.settings import Settings
from . import helper
@pytest.fixture(autouse=True)
def settings_fixture():
"""Provide Settings that save into a temporary location to all tests"""
filename = helper.tmp_path('settings')
Settings.config_path = filename
yield Settings.read()
if os.path.exists(filename):
os.remove(filename)
def test_gui_save_restore(settings_fixture):
"""Test saving and restoring gui state"""
settings = settings_fixture
settings.gui_state['test-gui'] = {'foo': 'bar'}
settings.save()
settings = Settings.read()
state = settings.gui_state.get('test-gui', {})
assert 'foo' in state
assert state['foo'] == 'bar'
def test_bookmarks_save_restore():
"""Test the bookmark save/restore feature"""
# We automatically purge missing entries so we mock-out
# git.is_git_worktree() so that this bookmark is kept.
bookmark = {'path': '/tmp/python/thinks/this/exists', 'name': 'exists'}
def mock_verify(path):
return path == bookmark['path']
settings = Settings.read()
settings.add_bookmark(bookmark['path'], bookmark['name'])
settings.save()
settings = Settings.read(verify=mock_verify)
bookmarks = settings.bookmarks
assert len(settings.bookmarks) == 1
assert bookmark in bookmarks
settings.remove_bookmark(bookmark['path'], bookmark['name'])
bookmarks = settings.bookmarks
expect = 0
actual = len(bookmarks)
assert expect == actual
assert bookmark not in bookmarks
def test_bookmarks_removes_missing_entries():
"""Test that missing entries are removed after a reload"""
# verify returns False so all entries will be removed.
bookmark = {'path': '.', 'name': 'does-not-exist'}
settings = Settings.read(verify=lambda x: False)
settings.add_bookmark(bookmark['path'], bookmark['name'])
settings.remove_missing_bookmarks()
settings.save()
settings = Settings.read()
bookmarks = settings.bookmarks
expect = 0
actual = len(bookmarks)
assert expect == actual
assert bookmark not in bookmarks
def test_rename_bookmark():
settings = Settings.read()
settings.add_bookmark('/tmp/repo', 'a')
settings.add_bookmark('/tmp/repo', 'b')
settings.add_bookmark('/tmp/repo', 'c')
settings.rename_bookmark('/tmp/repo', 'b', 'test')
expect = ['a', 'test', 'c']
actual = [i['name'] for i in settings.bookmarks]
assert expect == actual
| 2,527 | Python | .py | 65 | 34.061538 | 75 | 0.691961 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
17 | utils_test.py | git-cola_git-cola/test/utils_test.py | """Tests the cola.utils module."""
import os
from cola import core
from cola import utils
def test_basename():
"""Test the utils.basename function."""
assert utils.basename('bar') == 'bar'
assert utils.basename('/bar') == 'bar'
assert utils.basename('/bar ') == 'bar '
assert utils.basename('foo/bar') == 'bar'
assert utils.basename('/foo/bar') == 'bar'
assert utils.basename('foo/foo/bar') == 'bar'
assert utils.basename('/foo/foo/bar') == 'bar'
assert utils.basename('/foo/foo//bar') == 'bar'
assert utils.basename('////foo //foo//bar') == 'bar'
def test_dirname():
"""Test the utils.dirname function."""
assert utils.dirname('bar') == ''
assert utils.dirname('/bar') == ''
assert utils.dirname('//bar') == ''
assert utils.dirname('///bar') == ''
assert utils.dirname('foo/bar') == 'foo'
assert utils.dirname('foo//bar') == 'foo'
assert utils.dirname('foo /bar') == 'foo '
assert utils.dirname('/foo//bar') == '/foo'
assert utils.dirname('/foo /bar') == '/foo '
assert utils.dirname('//foo//bar') == '/foo'
assert utils.dirname('///foo///bar') == '/foo'
def test_add_parents():
"""Test the utils.add_parents() function."""
paths = {'foo///bar///baz'}
path_set = utils.add_parents(paths)
assert 'foo/bar/baz' in path_set
assert 'foo/bar' in path_set
assert 'foo' in path_set
assert 'foo///bar///baz' not in path_set
# Ensure that the original set is unchanged
expect = {'foo///bar///baz'}
assert expect == paths
def test_tmp_filename_gives_good_file():
try:
first = utils.tmp_filename('test')
assert core.exists(first)
assert os.path.basename(first).startswith('git-cola-test')
finally:
os.remove(first)
try:
second = utils.tmp_filename('test')
assert core.exists(second)
assert os.path.basename(second).startswith('git-cola-test')
finally:
os.remove(second)
assert first != second
def test_strip_one_abspath():
expect = 'bin/git'
actual = utils.strip_one('/usr/bin/git')
assert expect == actual
def test_strip_one_relpath():
expect = 'git'
actual = utils.strip_one('bin/git')
assert expect == actual
def test_strip_one_nested_relpath():
expect = 'bin/git'
actual = utils.strip_one('local/bin/git')
assert expect == actual
def test_strip_one_basename():
expect = 'git'
actual = utils.strip_one('git')
assert expect == actual
def test_select_directory():
filename = utils.tmp_filename('test')
try:
expect = os.path.dirname(filename)
actual = utils.select_directory([filename])
assert expect == actual
finally:
os.remove(filename)
def test_select_directory_prefers_directories():
filename = utils.tmp_filename('test')
try:
expect = '.'
actual = utils.select_directory([filename, '.'])
assert expect == actual
finally:
os.remove(filename)
| 3,010 | Python | .py | 85 | 30.023529 | 67 | 0.630345 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
18 | browse_model_test.py | git-cola_git-cola/test/browse_model_test.py | """Test interfaces used by the browser (git cola browse)"""
from cola import core
from cola import gitcmds
from . import helper
from .helper import app_context
# Prevent unused imports lint errors.
assert app_context is not None
def test_stage_paths_untracked(app_context):
"""Test stage_paths() with an untracked file."""
model = app_context.model
core.makedirs('foo/bar')
helper.touch('foo/bar/baz')
gitcmds.add(app_context, ['foo'])
app_context.model.update_file_status()
assert 'foo/bar/baz' in model.staged
assert 'foo/bar/baz' not in model.modified
assert 'foo/bar/baz' not in model.untracked
def test_unstage_paths(app_context):
"""Test a simple usage of unstage_paths()."""
helper.commit_files()
helper.write_file('A', 'change')
helper.run_git('add', 'A')
model = app_context.model
gitcmds.unstage_paths(app_context, ['A'])
model.update_status()
assert 'A' not in model.staged
assert 'A' in model.modified
def test_unstage_paths_init(app_context):
"""Test unstage_paths() on the root commit."""
model = app_context.model
gitcmds.unstage_paths(app_context, ['A'])
model.update_status()
assert 'A' not in model.staged
assert 'A' in model.untracked
def test_unstage_paths_subdir(app_context):
"""Test unstage_paths() in a subdirectory."""
helper.run_git('commit', '-m', 'initial commit')
core.makedirs('foo/bar')
helper.touch('foo/bar/baz')
helper.run_git('add', 'foo/bar/baz')
model = app_context.model
gitcmds.unstage_paths(app_context, ['foo'])
model.update_status()
assert 'foo/bar/baz' in model.untracked
assert 'foo/bar/baz' not in model.staged
| 1,709 | Python | .py | 45 | 33.577778 | 59 | 0.697632 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
19 | dag_test.py | git-cola_git-cola/test/dag_test.py | """Tests DAG functionality"""
import pytest
from cola.models import dag
from .helper import app_context
from .helper import patch
# Prevent unused imports lint errors.
assert app_context is not None
LOG_TEXT = """
23e7eab4ba2c94e3155f5d261c693ccac1342eb9^Af4fb8fd5baaa55d9b41faca79be289bb4407281e^A^ADavid Aguilar^AThu Dec 6 18:59:20 2007 -0800^[email protected]^AMerged diffdisplay into main
f4fb8fd5baaa55d9b41faca79be289bb4407281e^Ae3f5a2d0248de6197d6e0e63c901810b8a9af2f8^A^ADavid Aguilar^ATue Dec 4 03:14:56 2007 -0800^[email protected]^ASquashed commit of the following:
e3f5a2d0248de6197d6e0e63c901810b8a9af2f8^Afa5ad6c38be603e2ffd1f9b722a3a5c675f63de2^A^ADavid Aguilar^AMon Dec 3 02:36:06 2007 -0800^[email protected]^AMerged qlistwidgets into main.
103766573cd4e6799d3ee792bcd632b92cf7c6c0^Afa5ad6c38be603e2ffd1f9b722a3a5c675f63de2^A^ADavid Aguilar^ATue Dec 11 05:13:21 2007 -0800^[email protected]^AAdded TODO
fa5ad6c38be603e2ffd1f9b722a3a5c675f63de2^A1ba04ad185cf9f04c56c8482e9a73ef1bd35c695^A^ADavid Aguilar^AFri Nov 30 05:19:05 2007 -0800^[email protected]^AAvoid multiple signoffs
1ba04ad185cf9f04c56c8482e9a73ef1bd35c695^Aad454b189fe5785af397fd6067cf103268b6626e^A^ADavid Aguilar^AFri Nov 30 05:07:47 2007 -0800^[email protected]^Aupdated model/view/controller api
ad454b189fe5785af397fd6067cf103268b6626e^A^A (tag: refs/tags/v0.0)^ADavid Aguilar^AFri Nov 30 00:03:28 2007 -0800^[email protected]^Afirst cut of ugit
""".strip().replace( # noqa
'^A', chr(0x01)
)
LOG_LINES = LOG_TEXT.split('\n')
class DAGTestData:
"""Test data provided by the dag_context fixture"""
def __init__(self, app_context, head='HEAD', count=1000):
self.context = app_context
self.params = dag.DAG(head, count)
self.reader = dag.RepoReader(app_context, self.params)
@pytest.fixture
def dag_context(app_context):
"""Provide DAGTestData for use by tests"""
return DAGTestData(app_context)
@patch('cola.models.dag.core')
def test_repo_reader(core, dag_context):
expect = len(LOG_LINES)
actual = 0
core.run_command.return_value = (0, LOG_TEXT, '')
for idx, _ in enumerate(dag_context.reader.get()):
actual += 1
assert expect == actual
@patch('cola.models.dag.core')
def test_repo_reader_order(core, dag_context):
commits = [
'ad454b189fe5785af397fd6067cf103268b6626e',
'1ba04ad185cf9f04c56c8482e9a73ef1bd35c695',
'fa5ad6c38be603e2ffd1f9b722a3a5c675f63de2',
'103766573cd4e6799d3ee792bcd632b92cf7c6c0',
'e3f5a2d0248de6197d6e0e63c901810b8a9af2f8',
'f4fb8fd5baaa55d9b41faca79be289bb4407281e',
'23e7eab4ba2c94e3155f5d261c693ccac1342eb9',
]
core.run_command.return_value = (0, LOG_TEXT, '')
for idx, commit in enumerate(dag_context.reader.get()):
assert commits[idx] == commit.oid
@patch('cola.models.dag.core')
def test_repo_reader_parents(core, dag_context):
parents = [
[],
['ad454b189fe5785af397fd6067cf103268b6626e'],
['1ba04ad185cf9f04c56c8482e9a73ef1bd35c695'],
['fa5ad6c38be603e2ffd1f9b722a3a5c675f63de2'],
['fa5ad6c38be603e2ffd1f9b722a3a5c675f63de2'],
['e3f5a2d0248de6197d6e0e63c901810b8a9af2f8'],
['f4fb8fd5baaa55d9b41faca79be289bb4407281e'],
]
core.run_command.return_value = (0, LOG_TEXT, '')
for idx, commit in enumerate(dag_context.reader.get()):
assert parents[idx] == [p.oid for p in commit.parents]
@patch('cola.models.dag.core')
def test_repo_reader_contract(core, dag_context):
core.exists.return_value = True
core.run_command.return_value = (0, LOG_TEXT, '')
for idx, _ in enumerate(dag_context.reader.get()):
pass
core.run_command.assert_called()
call_args = core.run_command.call_args
assert 'log.abbrevCommit=false' in call_args[0][0]
assert 'log.showSignature=false' in call_args[0][0]
| 3,882 | Python | .py | 75 | 46.88 | 184 | 0.759778 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
20 | switcher_test.py | git-cola_git-cola/test/switcher_test.py | """Test Quick Switcher"""
from cola import icons
from cola.widgets import switcher
def test_switcher_item_with_only_key():
"""item text would be key by building item without name"""
key = 'item-key'
actual = switcher.switcher_item(key)
assert actual.key == key
assert actual.text() == key
def test_switcher_item_with_key_name_icon():
"""item text would be name by building item with key and name"""
key = 'item-key'
name = 'item-name'
icon = icons.folder()
actual = switcher.switcher_item(key, icon, name)
assert actual.key == key
assert actual.text() == name
| 615 | Python | .py | 17 | 31.941176 | 68 | 0.688663 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
21 | helper.py | git-cola_git-cola/test/helper.py | import os
import shutil
import stat
import tempfile
from unittest.mock import Mock, patch
import pytest
from cola import core
from cola import git
from cola import gitcfg
from cola import gitcmds
from cola.models import main
# prevent unused imports lint errors.
assert patch is not None
def tmp_path(*paths):
"""Returns a path relative to the test/tmp directory"""
dirname = core.decode(os.path.dirname(__file__))
return os.path.join(dirname, 'tmp', *paths)
def fixture(*paths):
dirname = core.decode(os.path.dirname(__file__))
return os.path.join(dirname, 'fixtures', *paths)
# shutil.rmtree() can't remove read-only files on Windows. This onerror
# handler, adapted from <http://stackoverflow.com/a/1889686/357338>, works
# around this by changing such files to be writable and then re-trying.
def remove_readonly(func, path, _exc_info):
if func is os.unlink and not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWRITE)
func(path)
else:
raise AssertionError('Should not happen')
def touch(*paths):
"""Open and close a file to either create it or update its mtime"""
for path in paths:
core.open_append(path).close()
def write_file(path, content):
"""Write content to the specified file path"""
with core.open_write(path) as f:
f.write(content)
def append_file(path, content):
"""Open a file in append mode and write content to it"""
with core.open_append(path) as f:
f.write(content)
def run_git(*args):
"""Run git with the specified arguments"""
status, out, _ = core.run_command(['git'] + list(args))
assert status == 0
return out
def commit_files():
"""Commit the current state as the initial commit"""
run_git('commit', '-m', 'initial commit')
def initialize_repo():
"""Initialize a git repository in the current directory"""
run_git('init')
run_git('symbolic-ref', 'HEAD', 'refs/heads/main')
run_git('config', '--local', 'user.name', 'Your Name')
run_git('config', '--local', 'user.email', '[email protected]')
run_git('config', '--local', 'commit.gpgsign', 'false')
run_git('config', '--local', 'tag.gpgsign', 'false')
touch('A', 'B')
run_git('add', 'A', 'B')
@pytest.fixture
def app_context():
"""Create a repository in a temporary directory and return its ApplicationContext"""
tmp_directory = tempfile.mkdtemp('-cola-test')
current_directory = os.getcwd()
os.chdir(tmp_directory)
initialize_repo()
context = Mock()
context.git = git.create()
context.git.set_worktree(core.getcwd())
context.cfg = gitcfg.create(context)
context.model = main.create(context)
context.cfg.reset()
gitcmds.reset()
yield context
os.chdir(current_directory)
shutil.rmtree(tmp_directory, onerror=remove_readonly)
| 2,850 | Python | .py | 76 | 33.236842 | 88 | 0.691551 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
22 | i18n_test.py | git-cola_git-cola/test/i18n_test.py | """Tests for the i18n translation module"""
import os
import pytest
from cola import i18n
from cola.i18n import N_
from cola.compat import uchr
@pytest.fixture(autouse=True)
def i18n_context():
"""Perform cleanup/teardown of the i18n module"""
yield
i18n.uninstall()
def test_translates_noun():
"""Test that strings with @@noun are translated"""
i18n.install('ja_JP')
expect = uchr(0x30B3) + uchr(0x30DF) + uchr(0x30C3) + uchr(0x30C8)
actual = N_('Commit@@verb')
assert expect == actual
def test_translates_verb():
"""Test that strings with @@verb are translated"""
i18n.install('de_DE')
expect = 'Commit aufnehmen'
actual = N_('Commit@@verb')
assert expect == actual
def test_translates_english_noun():
"""Test that English strings with @@noun are properly handled"""
i18n.install('en_US.UTF-8')
expect = 'Commit'
actual = N_('Commit@@noun')
assert expect == actual
def test_translates_english_verb():
"""Test that English strings with @@verb are properly handled"""
i18n.install('en_US.UTF-8')
expect = 'Commit'
actual = N_('Commit@@verb')
assert expect == actual
def test_translates_random_english():
"""Test that random English strings are passed through as-is"""
i18n.install('en_US.UTF-8')
expect = 'Random'
actual = N_('Random')
assert expect == actual
def test_translate_push_pull_french():
i18n.install('fr_FR')
expect = 'Tirer'
actual = N_('Pull')
assert expect == actual
expect = 'Pousser'
actual = N_('Push')
assert expect == actual
def test_get_filename_for_locale():
"""Ensure that the appropriate .po files are found"""
actual = i18n.get_filename_for_locale('does_not_exist')
assert actual is None
actual = i18n.get_filename_for_locale('id_ID')
assert os.path.basename(actual) == 'id_ID.po'
actual = i18n.get_filename_for_locale('ja_JP')
assert os.path.basename(actual) == 'ja.po'
| 1,985 | Python | .py | 57 | 30.508772 | 70 | 0.678553 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
23 | stash_model_test.py | git-cola_git-cola/test/stash_model_test.py | from cola.models.stash import StashModel
from . import helper
from .helper import app_context
# Prevent unused imports lint errors.
assert app_context is not None
def test_stash_info_for_message_without_slash(app_context):
helper.commit_files()
helper.write_file('A', 'change')
helper.run_git('stash', 'save', 'some message')
assert StashModel(app_context).stash_info()[0] == [
r'stash@{0}: On main: some message'
]
def test_stash_info_for_message_with_slash(app_context):
helper.commit_files()
helper.write_file('A', 'change')
helper.run_git('stash', 'save', 'some message/something')
model = StashModel(app_context)
stash_details = model.stash_info()[0]
assert stash_details == [r'stash@{0}: On main: some message/something']
def test_stash_info_on_branch_with_slash(app_context):
helper.commit_files()
helper.run_git('checkout', '-b', 'feature/a')
helper.write_file('A', 'change')
helper.run_git('stash', 'save', 'some message')
model = StashModel(app_context)
stash_info = model.stash_info()
stash_details = stash_info[0][0]
assert stash_details in (
'stash@{0}: On feature/a: some message',
# Some versions of Git do not report the full branch name
'stash@{0}: On a: some message',
)
stash_rev = stash_info[1][0]
assert stash_rev == r'stash@{0}'
stash_message = stash_info[3][0]
assert stash_message in (
'On feature/a: some message',
'On a: some message',
)
| 1,525 | Python | .py | 39 | 33.974359 | 75 | 0.667346 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
24 | models_selection_test.py | git-cola_git-cola/test/models_selection_test.py | from cola.models import selection
from .helper import Mock
def test_union():
t = Mock()
t.staged = ['a']
t.unmerged = ['a', 'b']
t.modified = ['b', 'a', 'c']
t.untracked = ['d']
expect = ['a', 'b', 'c', 'd']
actual = selection.union(t)
assert expect == actual
| 296 | Python | .py | 11 | 22.636364 | 33 | 0.558719 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
25 | diffparse_test.py | git-cola_git-cola/test/diffparse_test.py | """Tests for the diffparse module"""
import pytest
from cola import core
from cola import diffparse
from . import helper
class DiffLinesTestData:
"""Test data used by DiffLines tests"""
def __init__(self):
self.parser = diffparse.DiffLines()
fixture_path = helper.fixture('diff.txt')
self.text = core.read(fixture_path)
@pytest.fixture
def difflines_data():
"""Return test data for diffparse.DiffLines tests"""
return DiffLinesTestData()
def test_diff():
fixture_path = helper.fixture('diff.txt')
patch = diffparse.Patch.parse('cola/diffparse.py', core.read(fixture_path))
hunks = patch.hunks
assert len(hunks) == 3
assert len(hunks[0].lines) == 23
assert hunks[0].lines[0] == '@@ -6,10 +6,21 @@ from cola import gitcmds\n'
assert hunks[0].lines[1] == ' from cola import gitcfg\n'
assert hunks[0].lines[2] == ' \n'
assert hunks[0].lines[3] == ' \n'
assert hunks[0].lines[4] == '+class DiffSource(object):\n'
assert hunks[0].lines[-1] == (
r" self._header_start_re = re.compile('^@@ -(\d+)"
r" \+(\d+),(\d+) @@.*')"
'\n'
)
assert len(hunks[1].lines) == 18
assert hunks[1].lines[0] == '@@ -29,13 +40,11 @@ class DiffParser(object):\n'
assert hunks[1].lines[1] == ' self.diff_sel = []\n'
assert hunks[1].lines[2] == ' self.selected = []\n'
assert hunks[1].lines[3] == ' self.filename = filename\n'
assert hunks[1].lines[4] == (
'+ self.diff_source = diff_source or DiffSource()\n'
)
assert hunks[1].lines[-1] == ' self.header = header\n'
assert len(hunks[2].lines) == 16
assert hunks[2].lines[0] == '@@ -43,11 +52,10 @@ class DiffParser(object):\n'
assert hunks[2].lines[-1] == (
' """Writes a new diff corresponding to the user\'s' ' selection."""\n'
)
def test_diff_at_start():
fixture_path = helper.fixture('diff-start.txt')
patch = diffparse.Patch.parse('foo bar/a', core.read(fixture_path))
hunks = patch.hunks
assert hunks[0].lines[0] == '@@ -1 +1,4 @@\n'
assert hunks[-1].lines[-1] == '+c\n'
assert hunks[0].old_start == 1
assert hunks[0].old_count == 1
assert hunks[0].new_start == 1
assert hunks[0].new_count == 4
assert patch.extract_subset(1, 3).as_text() == (
'--- a/foo bar/a\n' '+++ b/foo bar/a\n' '@@ -1 +1,3 @@\n' ' bar\n' '+a\n' '+b\n'
)
assert patch.extract_subset(0, 4).as_text() == (
'--- a/foo bar/a\n'
'+++ b/foo bar/a\n'
'@@ -1 +1,4 @@\n'
' bar\n'
'+a\n'
'+b\n'
'+c\n'
)
def test_diff_at_end():
fixture_path = helper.fixture('diff-end.txt')
patch = diffparse.Patch.parse('rijndael.js', core.read(fixture_path))
hunks = patch.hunks
assert hunks[0].lines[0] == '@@ -1,39 +1 @@\n'
assert hunks[-1].lines[-1] == (
"+module.exports = require('./build/Release/rijndael');\n"
)
assert hunks[0].old_start == 1
assert hunks[0].old_count == 39
assert hunks[0].new_start == 1
assert hunks[0].new_count == 1
def test_diff_that_empties_file():
fixture_path = helper.fixture('diff-empty.txt')
patch = diffparse.Patch.parse('filename', core.read(fixture_path))
hunks = patch.hunks
assert hunks[0].lines[0] == '@@ -1,2 +0,0 @@\n'
assert hunks[-1].lines[-1] == '-second\n'
assert hunks[0].old_start == 1
assert hunks[0].old_count == 2
assert hunks[0].new_start == 0
assert hunks[0].new_count == 0
assert patch.extract_subset(1, 1).as_text() == (
'--- a/filename\n' '+++ b/filename\n' '@@ -1,2 +1 @@\n' '-first\n' ' second\n'
)
assert patch.extract_subset(0, 2).as_text() == (
'--- a/filename\n' '+++ b/filename\n' '@@ -1,2 +0,0 @@\n' '-first\n' '-second\n'
)
def test_diff_file_removal():
diff_text = """\
deleted file mode 100755
@@ -1,1 +0,0 @@
-#!/bin/sh
"""
patch = diffparse.Patch.parse('deleted.txt', diff_text)
expect = 1
actual = len(patch.hunks)
assert expect == actual
# Selecting the first two lines generate no diff
expect = ''
actual = patch.extract_subset(0, 1).as_text()
assert expect == actual
# Selecting the last line should generate a line removal
expect = """\
--- a/deleted.txt
+++ b/deleted.txt
@@ -1 +0,0 @@
-#!/bin/sh
"""
actual = patch.extract_subset(1, 2).as_text()
assert expect == actual
# All three lines should map to the same hunk diff
actual = patch.extract_hunk(0).as_text()
assert expect == actual
actual = patch.extract_hunk(1).as_text()
assert expect == actual
actual = patch.extract_hunk(2).as_text()
assert expect == actual
def test_basic_diff_line_count(difflines_data):
"""Verify the basic line counts"""
lines = difflines_data.parser.parse(difflines_data.text)
expect = len(difflines_data.text.splitlines())
actual = len(lines)
assert expect == actual
def test_diff_line_count_ranges(difflines_data):
parser = difflines_data.parser
lines = parser.parse(difflines_data.text)
# Diff header
line = 0
count = 1
assert lines[line][0] == parser.DASH
assert lines[line][1] == parser.DASH
line += count
# 3 lines of context
count = 3
current_old = 6
current_new = 6
for i in range(count):
assert lines[line + i][0] == current_old + i
assert lines[line + i][1] == current_new + i
line += count
current_old += count
current_new += count
# 10 lines of new text
count = 10
for i in range(count):
assert lines[line + i][0] == parser.EMPTY
assert lines[line + i][1] == current_new + i
line += count
current_new += count
# 3 more lines of context
count = 3
for i in range(count):
assert lines[line + i][0] == current_old + i
assert lines[line + i][1] == current_new + i
line += count
current_new += count
current_old += count
# 1 line of removal
count = 1
for i in range(count):
assert lines[line + i][0] == current_old + i
assert lines[line + i][1] == parser.EMPTY
line += count
current_old += count
# 2 lines of addition
count = 2
for i in range(count):
assert lines[line + i][0] == parser.EMPTY
assert lines[line + i][1] == current_new + i
line += count
current_new += count
# 3 more lines of context
count = 3
for i in range(count):
assert lines[line + i][0] == current_old + i
assert lines[line + i][1] == current_new + i
line += count
current_new += count
current_old += count
# 1 line of header
count = 1
for i in range(count):
assert lines[line + i][0] == parser.DASH
assert lines[line + i][1] == parser.DASH
line += count
# 3 more lines of context
current_old = 29
current_new = 40
count = 3
for i in range(count):
assert lines[line + i][0] == current_old + i
assert lines[line + i][1] == current_new + i
line += count
current_new += count
current_old += count
expect_max_old = 53
assert expect_max_old == parser.old.max_value
expect_max_new = 61
assert expect_max_new == parser.new.max_value
assert parser.digits() == 2
def test_diff_line_for_merge(difflines_data):
"""Verify the basic line counts"""
text = """@@@ -1,23 -1,33 +1,75 @@@
++<<<<<<< upstream
+
+Ok
"""
parser = difflines_data.parser
lines = parser.parse(text)
assert len(lines) == 4
assert len(lines[0]) == 3
assert len(lines[1]) == 3
assert len(lines[2]) == 3
assert len(lines[3]) == 3
assert lines[0][0] == parser.DASH
assert lines[0][1] == parser.DASH
assert lines[0][2] == parser.DASH
assert lines[1][0] == parser.EMPTY
assert lines[1][1] == parser.EMPTY
assert lines[1][2] == 1
assert lines[2][0] == 1
assert lines[2][1] == parser.EMPTY
assert lines[2][2] == 2
assert lines[3][0] == 2
assert lines[3][1] == parser.EMPTY
assert lines[3][2] == 3
def test_diff_line_digits(difflines_data):
parser = difflines_data.parser
text = """@@ -1,99 +1,99 @@"""
parser.parse(text)
assert parser.digits() == 2
text = """@@ -2,99 +2,99 @@"""
parser.parse(text)
assert parser.digits() == 3
def test_format_basic():
fmt = diffparse.FormatDigits()
fmt.set_digits(2)
expect = '01 99'
actual = fmt.value(1, 99)
assert expect == actual
def test_format_reuse():
fmt = diffparse.FormatDigits()
fmt.set_digits(3)
expect = '001 099'
actual = fmt.value(1, 99)
assert expect == actual
fmt.set_digits(4)
expect = '0001 0099'
actual = fmt.value(1, 99)
assert expect == actual
def test_format_special_values():
fmt = diffparse.FormatDigits(dash='-')
fmt.set_digits(3)
expect = ' 099'
actual = fmt.value(fmt.EMPTY, 99)
assert expect == actual
expect = '001 '
actual = fmt.value(1, fmt.EMPTY)
assert expect == actual
expect = ' '
actual = fmt.value(fmt.EMPTY, fmt.EMPTY)
assert expect == actual
expect = '--- 001'
actual = fmt.value(fmt.DASH, 1)
assert expect == actual
expect = '099 ---'
actual = fmt.value(99, fmt.DASH)
assert expect == actual
expect = '--- ---'
actual = fmt.value(fmt.DASH, fmt.DASH)
assert expect == actual
expect = ' ---'
actual = fmt.value(fmt.EMPTY, fmt.DASH)
assert expect == actual
expect = '--- '
actual = fmt.value(fmt.DASH, fmt.EMPTY)
assert expect == actual
def test_parse_range_str():
start, count = diffparse.parse_range_str('1,2')
assert start == 1
assert count == 2
def test_parse_range_str_single_line():
start, count = diffparse.parse_range_str('2')
assert start == 2
assert count == 1
def test_parse_range_str_empty():
start, count = diffparse.parse_range_str('0,0')
assert start == 0
assert count == 0
| 10,053 | Python | .py | 297 | 28.592593 | 88 | 0.598367 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
26 | textwrap_test.py | git-cola_git-cola/test/textwrap_test.py | """Test the textwrap module"""
import pytest
from cola import textwrap
class WordWrapDefaults:
def __init__(self):
self.tabwidth = 8
self.limit = None
def wrap(self, text, break_on_hyphens=True):
return textwrap.word_wrap(
text, self.tabwidth, self.limit, break_on_hyphens=break_on_hyphens
)
@pytest.fixture
def wordwrap():
"""Provide default word wrap options for tests"""
return WordWrapDefaults()
def test_word_wrap(wordwrap):
wordwrap.limit = 16
text = """
12345678901 3 56 8 01 3 5 7
1 3 5"""
expect = """
12345678901 3 56
8 01 3 5 7
1 3 5"""
assert expect == wordwrap.wrap(text)
def test_word_wrap_dashes(wordwrap):
wordwrap.limit = 4
text = '123-5'
expect = '123-5'
assert expect == wordwrap.wrap(text)
def test_word_wrap_leading_spaces(wordwrap):
wordwrap.limit = 4
expect = '1234\n5'
assert expect == wordwrap.wrap('1234 5')
assert expect == wordwrap.wrap('1234 5')
assert expect == wordwrap.wrap('1234 5')
assert expect == wordwrap.wrap('1234 5')
assert expect == wordwrap.wrap('1234 5')
expect = '123\n4'
assert expect == wordwrap.wrap('123 4')
assert expect == wordwrap.wrap('123 4')
assert expect == wordwrap.wrap('123 4')
assert expect == wordwrap.wrap('123 4')
assert expect == wordwrap.wrap('123 4')
def test_word_wrap_double_dashes(wordwrap):
wordwrap.limit = 4
text = '12--5'
expect = '12--\n5'
actual = wordwrap.wrap(text, break_on_hyphens=True)
assert expect == actual
expect = '12--5'
actual = wordwrap.wrap(text, break_on_hyphens=False)
assert expect == actual
def test_word_wrap_many_lines(wordwrap):
wordwrap.limit = 2
text = """
aa
bb cc dd"""
expect = """
aa
bb
cc
dd"""
actual = wordwrap.wrap(text)
assert expect == actual
def test_word_python_code(wordwrap):
wordwrap.limit = 78
text = """
if True:
print "hello world"
else:
print "hello world"
"""
expect = text
actual = wordwrap.wrap(text)
assert expect == actual
def test_word_wrap_spaces(wordwrap):
wordwrap.limit = 2
text = ' ' * 6
expect = ''
actual = wordwrap.wrap(text)
assert expect == actual
def test_word_wrap_special_tag(wordwrap):
wordwrap.limit = 2
text = """
This test is so meta, even this sentence
Cheered-on-by: Avoids word-wrap
C.f. This also avoids word-wrap
References: This also avoids word-wrap
See-also: This also avoids word-wrap
Related-to: This also avoids word-wrap
Link: This also avoids word-wrap
"""
expect = """
This
test
is
so
meta,
even
this
sentence
Cheered-on-by: Avoids word-wrap
C.f. This also avoids word-wrap
References: This also avoids word-wrap
See-also: This also avoids word-wrap
Related-to: This also avoids word-wrap
Link: This also avoids word-wrap
"""
actual = wordwrap.wrap(text)
assert expect == actual
def test_word_wrap_space_at_start_of_wrap(wordwrap):
inputs = """0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 """
expect = """0 1 2 3 4 5 6 7 8 9\n0 1 2 3 4 5 6 7 8"""
wordwrap.limit = 20
actual = wordwrap.wrap(inputs)
assert expect == actual
def test_word_wrap_keeps_tabs_at_start(wordwrap):
inputs = """\tfirst line\n\n\tsecond line"""
expect = """\tfirst line\n\n\tsecond line"""
wordwrap.limit = 20
actual = wordwrap.wrap(inputs)
assert expect == actual
def test_word_wrap_keeps_twospace_indents(wordwrap):
inputs = """first line\n\n* branch:\n line1\n line2\n"""
expect = """first line\n\n* branch:\n line1\n line2\n"""
wordwrap.limit = 20
actual = wordwrap.wrap(inputs)
assert expect == actual
def test_word_wrap_ranges():
text = 'a bb ccc dddd\neeeee'
expect = 'a\nbb\nccc\ndddd\neeeee'
actual = textwrap.word_wrap(text, 8, 2)
assert expect == actual
expect = 'a bb\nccc\ndddd\neeeee'
actual = textwrap.word_wrap(text, 8, 4)
assert expect == actual
text = 'a bb ccc dddd\n\teeeee'
expect = 'a bb\nccc\ndddd\n\t\neeeee'
actual = textwrap.word_wrap(text, 8, 4)
assert expect == actual
def test_triplets():
text = 'xx0 xx1 xx2 xx3 xx4 xx5 xx6 xx7 xx8 xx9 xxa xxb'
expect = 'xx0 xx1 xx2 xx3 xx4 xx5 xx6\nxx7 xx8 xx9 xxa xxb'
actual = textwrap.word_wrap(text, 8, 27)
assert expect == actual
expect = 'xx0 xx1 xx2 xx3 xx4 xx5\nxx6 xx7 xx8 xx9 xxa xxb'
actual = textwrap.word_wrap(text, 8, 26)
assert expect == actual
actual = textwrap.word_wrap(text, 8, 25)
assert expect == actual
actual = textwrap.word_wrap(text, 8, 24)
assert expect == actual
actual = textwrap.word_wrap(text, 8, 23)
assert expect == actual
expect = 'xx0 xx1 xx2 xx3 xx4\nxx5 xx6 xx7 xx8 xx9\nxxa xxb'
actual = textwrap.word_wrap(text, 8, 22)
assert expect == actual
| 4,877 | Python | .py | 158 | 26.772152 | 78 | 0.669455 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
27 | _activate_cola.py | git-cola_git-cola/bin/_activate_cola.py | # Developer wrapper script helper functions
import configparser
import datetime
import os
import sys
def activate():
"""Activate the cola development environment"""
initialize_python()
initialize_version()
def get_prefix():
"""Return the path to the source tree"""
realpath = os.path.abspath(os.path.realpath(__file__))
return os.path.dirname(os.path.dirname(realpath))
def initialize_python():
"""Add the source directory to the python sys.path."""
sys.path.insert(1, get_prefix())
def initialize_version():
"""Replace version.SCM_VERSION when running from the source tree"""
scm_version = get_version()
if scm_version:
# version.SCM_VERSION = version
update_pkginfo_version(scm_version)
def get_version():
"""Calculate a setuptools-scm compatible version number from the git worktree"""
from cola import git
worktree = git.Git(worktree=get_prefix())
if not worktree.is_valid():
return None
status, out, _ = worktree.describe(dirty=True, long=True, match='v[0-9]*.[0-9]*')
if status != 0 or not out:
return None
# We cap the number of splits to 3 (4-parts) but only 2 splits (3-parts) are also
# accepted. Anything less is not a "git describe" output we support.
parts = out.lstrip('v').split('-', 3)
num_parts = len(parts)
if num_parts < 3:
return None
# If we are clean and we are pointing at a tag then setuptools-scm will report
# just the version number without any extra version details.
if num_parts == 3 and parts[1] == '0':
return parts[0]
# Transform v4.8.2-24-gd7b743a2 into 4.8.3.dev28+gd7b743a2
# Transform v4.8.2-24-gd7b743a2-dirty into 4.8.3.dev28+gd7b743a2.d20241005
numbers = parts[0].split('.')
# Increment the last number.
if numbers:
try:
last_number = f'{int(numbers[-1]) + 1}'
except ValueError:
last_number = '1'
numbers[-1] = last_number
parts[0] = '.'.join(numbers)
version = f'{parts[0]}.dev{parts[1]}+{parts[2]}'
# Worktree is dirty. Append the current date.
if num_parts == 4:
now = datetime.datetime.now()
date_string = now.strftime('.d%Y%m%d')
version += date_string
return version
def update_pkginfo_version(scm_version):
"""Update git_cola.egg_info/PKG-INFO with the specified version"""
from cola import version
pkginfo = os.path.join(get_prefix(), 'git_cola.egg-info', 'PKG-INFO')
content, pkginfo_version = get_pkginfo_version(pkginfo)
# If there's nothing to update then we can set the SCM_VERSION.
if not content or not pkginfo_version:
version.SCM_VERSION = scm_version
return
# If the versions match then there's nothing to do.
if scm_version == pkginfo_version:
return
# Rewrite the PKG-INFO file to reflect the current version.
new_lines = []
replaced = False
token = 'Version: '
new_version = f'Version: {scm_version}'
for line in content.splitlines():
if not replaced and line.startswith(token):
new_lines.append(new_version)
replaced = True
else:
new_lines.append(line)
new_lines.append('')
try:
with open(pkginfo, 'w', encoding='utf-8') as pkginfo_file:
pkginfo_file.write('\n'.join(new_lines))
except OSError:
pass
def get_pkginfo_version(pkginfo):
"""Return the version from the PKG-INFO file"""
version = None
content = None
try:
with open(pkginfo, encoding='utf-8') as pkginfo_file:
content = pkginfo_file.read()
except OSError:
return (content, version)
token = 'Version: '
for line in content.splitlines():
if line.startswith(token):
version = line[len(token) :]
break
return (content, version)
activate()
| 3,910 | Python | .py | 104 | 31.288462 | 85 | 0.651772 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
28 | sphinxtogithub.py | git-cola_git-cola/extras/sphinxtogithub/sphinxtogithub.py | #! /usr/bin/env python
from optparse import OptionParser
import os
import sys
import shutil
import codecs
def stdout(msg):
sys.stdout.write(msg + '\n')
class DirHelper:
def __init__(self, is_dir, list_dir, walk, rmtree):
self.is_dir = is_dir
self.list_dir = list_dir
self.walk = walk
self.rmtree = rmtree
class FileSystemHelper:
def __init__(self, open_, path_join, move, exists):
self.open_ = open_
self.path_join = path_join
self.move = move
self.exists = exists
class Replacer:
"""Encapsulates a simple text replace"""
def __init__(self, from_, to):
self.from_ = from_
self.to = to
def process(self, text):
return text.replace(self.from_, self.to)
class FileHandler:
"""Applies a series of replacements the contents of a file inplace"""
def __init__(self, name, replacers, opener):
self.name = name
self.replacers = replacers
self.opener = opener
def process(self):
text = self.opener(self.name, 'r').read()
for replacer in self.replacers:
text = replacer.process(text)
self.opener(self.name, 'w').write(text)
class Remover:
def __init__(self, exists, remove):
self.exists = exists
self.remove = remove
def __call__(self, name):
if self.exists(name):
self.remove(name)
class ForceRename:
def __init__(self, renamer, remove):
self.renamer = renamer
self.remove = remove
def __call__(self, from_, to):
self.remove(to)
self.renamer(from_, to)
class VerboseRename:
def __init__(self, renamer, stream):
self.renamer = renamer
self.stream = stream
def __call__(self, from_, to):
self.stream.write(
"Renaming directory '%s' -> '%s'\n"
% (os.path.basename(from_), os.path.basename(to))
)
self.renamer(from_, to)
class DirectoryHandler:
"""Encapsulates renaming a directory by removing its first character"""
def __init__(self, name, root, renamer):
self.name = name
self.new_name = name[1:]
self.root = str(root) + os.sep
self.renamer = renamer
def path(self):
return os.path.join(self.root, self.name)
def relative_path(self, directory, filename):
path = directory.replace(self.root, '', 1)
return os.path.join(path, filename)
def new_relative_path(self, directory, filename):
path = self.relative_path(directory, filename)
return path.replace(self.name, self.new_name, 1)
def process(self):
from_ = os.path.join(self.root, self.name)
to = os.path.join(self.root, self.new_name)
self.renamer(from_, to)
class HandlerFactory:
def create_file_handler(self, name, replacers, opener):
return FileHandler(name, replacers, opener)
def create_dir_handler(self, name, root, renamer):
return DirectoryHandler(name, root, renamer)
class OperationsFactory:
def create_force_rename(self, renamer, remover):
return ForceRename(renamer, remover)
def create_verbose_rename(self, renamer, stream):
return VerboseRename(renamer, stream)
def create_replacer(self, from_, to):
return Replacer(from_, to)
def create_remover(self, exists, remove):
return Remover(exists, remove)
class Layout:
"""
Applies a set of operations which result in the layout
of a directory changing
"""
def __init__(self, directory_handlers, file_handlers):
self.directory_handlers = directory_handlers
self.file_handlers = file_handlers
def process(self):
for handler in self.file_handlers:
handler.process()
for handler in self.directory_handlers:
handler.process()
class NullLayout:
"""
Layout class that does nothing when asked to process
"""
def process(self):
pass
class LayoutFactory:
"""Creates a layout object"""
def __init__(
self,
operations_factory,
handler_factory,
file_helper,
dir_helper,
verbose,
stream,
force,
):
self.operations_factory = operations_factory
self.handler_factory = handler_factory
self.file_helper = file_helper
self.dir_helper = dir_helper
self.verbose = verbose
self.output_stream = stream
self.force = force
def create_layout(self, path):
contents = self.dir_helper.list_dir(path)
renamer = self.file_helper.move
if self.force:
remove = self.operations_factory.create_remover(
self.file_helper.exists, self.dir_helper.rmtree
)
renamer = self.operations_factory.create_force_rename(renamer, remove)
if self.verbose:
renamer = self.operations_factory.create_verbose_rename(
renamer, self.output_stream
)
# Build list of directories to process
directories = [d for d in contents if self.is_underscore_dir(path, d)]
underscore_directories = [
self.handler_factory.create_dir_handler(d, path, renamer)
for d in directories
]
if not underscore_directories:
if self.verbose:
self.output_stream.write(
'No top level directories starting with an underscore '
"were found in '%s'\n" % path
)
return NullLayout()
# Build list of files that are in those directories
replacers = []
for handler in underscore_directories:
for directory, _, files in self.dir_helper.walk(handler.path()):
for f in files:
replacers.append(
self.operations_factory.create_replacer(
handler.relative_path(directory, f),
handler.new_relative_path(directory, f),
)
)
# Build list of handlers to process all files
filelist = []
for root, _, files in self.dir_helper.walk(path):
for f in files:
if f.endswith('.html'):
filelist.append(
self.handler_factory.create_file_handler(
self.file_helper.path_join(root, f),
replacers,
self.file_helper.open_,
)
)
if f.endswith('.js'):
filelist.append(
self.handler_factory.create_file_handler(
self.file_helper.path_join(root, f),
[
self.operations_factory.create_replacer(
"'_sources/'", "'sources/'"
)
],
self.file_helper.open_,
)
)
return Layout(underscore_directories, filelist)
def is_underscore_dir(self, path, directory):
return self.dir_helper.is_dir(
self.file_helper.path_join(path, directory)
) and directory.startswith('_')
def sphinx_extension(app, exception):
"""Wrapped up as a Sphinx Extension"""
if app.builder.name not in ('html', 'dirhtml'):
return
if not app.config.sphinx_to_github:
if app.config.sphinx_to_github_verbose:
stdout('Sphinx-to-github: Disabled, doing nothing.')
return
if exception:
if app.config.sphinx_to_github_verbose:
msg = 'Sphinx-to-github: ' 'Exception raised in main build, doing nothing.'
stdout(msg)
return
dir_helper = DirHelper(os.path.isdir, os.listdir, os.walk, shutil.rmtree)
file_helper = FileSystemHelper(
lambda f, mode: codecs.open(f, mode, app.config.sphinx_to_github_encoding),
os.path.join,
shutil.move,
os.path.exists,
)
operations_factory = OperationsFactory()
handler_factory = HandlerFactory()
layout_factory = LayoutFactory(
operations_factory,
handler_factory,
file_helper,
dir_helper,
app.config.sphinx_to_github_verbose,
sys.stdout,
force=True,
)
layout = layout_factory.create_layout(app.outdir)
layout.process()
def setup(app):
"""Setup function for Sphinx Extension"""
app.add_config_value('sphinx_to_github', True, '')
app.add_config_value('sphinx_to_github_verbose', True, '')
app.add_config_value('sphinx_to_github_encoding', 'utf-8', '')
app.connect('build-finished', sphinx_extension)
def main(args):
usage = 'usage: %prog [options] <html directory>'
parser = OptionParser(usage=usage)
parser.add_option(
'-v',
'--verbose',
action='store_true',
dest='verbose',
default=False,
help='Provides verbose output',
)
parser.add_option(
'-e',
'--encoding',
action='store',
dest='encoding',
default='utf-8',
help='Encoding for reading and writing files',
)
opts, args = parser.parse_args(args)
try:
path = args[0]
except IndexError:
sys.stderr.write(
'Error - Expecting path to html directory:' 'sphinx-to-github <path>\n'
)
return
dir_helper = DirHelper(os.path.isdir, os.listdir, os.walk, shutil.rmtree)
file_helper = FileSystemHelper(
lambda f, mode: codecs.open(f, mode, opts.encoding),
os.path.join,
shutil.move,
os.path.exists,
)
operations_factory = OperationsFactory()
handler_factory = HandlerFactory()
layout_factory = LayoutFactory(
operations_factory,
handler_factory,
file_helper,
dir_helper,
opts.verbose,
sys.stdout,
force=False,
)
layout = layout_factory.create_layout(path)
layout.process()
if __name__ == '__main__':
main(sys.argv[1:])
| 10,273 | Python | .py | 286 | 26.307692 | 87 | 0.588824 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
29 | __init__.py | git-cola_git-cola/extras/sphinxtogithub/__init__.py | """Script for preparing the html output of the Sphinx documentation system for
github pages. """
VERSION = (1, 1, 0, 'dev')
__version__ = '.'.join(map(str, VERSION[:-1]))
__release__ = '.'.join(map(str, VERSION))
__author__ = 'Michael Jones'
__contact__ = 'http://github.com/michaeljones'
__homepage__ = 'http://github.com/michaeljones/sphinx-to-github'
__docformat__ = 'restructuredtext'
from .sphinxtogithub import (
setup,
sphinx_extension,
LayoutFactory,
Layout,
DirectoryHandler,
VerboseRename,
ForceRename,
Remover,
FileHandler,
Replacer,
DirHelper,
FileSystemHelper,
OperationsFactory,
HandlerFactory,
)
| 670 | Python | .py | 25 | 23.44 | 78 | 0.691589 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
30 | conf.py | git-cola_git-cola/docs/conf.py | import os
import sys
try:
import furo
except ImportError:
furo = None
try:
import sphinx_rtd_theme
except ImportError:
sphinx_rtd_theme = None
try:
import rst.linker as rst_linker
except ImportError:
rst_linker = None
# Add the source tree and extras/ to sys.path.
srcdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
extrasdir = os.path.join(srcdir, 'extras')
sys.path.insert(0, srcdir)
sys.path.insert(1, extrasdir)
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinxtogithub',
]
master_doc = 'index'
html_theme = 'default'
# {package_url} can be provided py jaraco.packaging.sphinx but we
# expand the value manually to avoid the dependency.
package_url = 'https://gitlab.com/git-cola/git-cola'
project = 'Git Cola'
# Link dates and other references in the changelog
if rst_linker is not None:
extensions += ['rst.linker']
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com', package_url=package_url),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
# Be strict about any broken references
nitpicky = True
# Preserve authored syntax for defaults
autodoc_preserve_defaults = True
# Get the version from cola/_version.py.
versionfile = os.path.join(srcdir, 'cola', '_version.py')
scope = {}
with open(versionfile) as f:
exec(f.read(), scope)
version = scope['VERSION'] # The short X.Y version.
release = version # The full version, including alpha/beta/rc tags.
authors = 'David Aguilar and contributors'
man_pages = [
('git-cola', 'git-cola', 'The highly caffeinated Git GUI', authors, '1'),
('git-dag', 'git-dag', 'The sleek and powerful Git history browser', authors, '1'),
]
# Sphinx 4.0 creates sub-directories for each man section.
# Disable this feature for consistency across Sphinx versions.
man_make_section_directory = False
# furo overwrites "_static/pygments.css" so we monkey-patch
# "def _overwrite_pygments_css()" to use "static/pygments.css" instead.
def _overwrite_pygments_css(app, exception):
"""Replacement for furo._overwrite_pygments_css to handle sphinxtogithub"""
if exception is not None:
return
assert app.builder
with open(
os.path.join(app.builder.outdir, 'static', 'pygments.css'),
'w',
encoding='utf-8',
) as f:
f.write(furo.get_pygments_stylesheet())
# Enable custom themes.
if furo is not None and hasattr(furo, '_overwrite_pygments_css'):
furo._overwrite_pygments_css = _overwrite_pygments_css
html_theme = 'furo'
elif sphinx_rtd_theme is not None:
extensions += ['sphinx_rtd_theme']
html_theme = 'sphinx_rtd_theme'
| 3,186 | Python | .py | 93 | 29.451613 | 87 | 0.658862 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
31 | pynsist-preamble.py | git-cola_git-cola/contrib/win32/pynsist-preamble.py | import os
pythondir = os.path.join(installdir, 'Python') # noqa
path = os.environ.get('PATH', '')
os.environ['PATH'] = os.pathsep.join([pythondir, pkgdir, path]) # noqa
| 172 | Python | .py | 4 | 41.75 | 71 | 0.694611 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
32 | run-pynsist.sh | git-cola_git-cola/contrib/win32/run-pynsist.sh | #!/bin/sh
rm -rf build/nsis &&
make all &&
make doc &&
make htmldir="$PWD/share/doc/git-cola/html" install-doc &&
pynsist pynsist.cfg &&
rm -r share/doc/git-cola/html
| 167 | Python | .py | 7 | 22.857143 | 58 | 0.7125 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
33 | difftool.py | git-cola_git-cola/cola/difftool.py | import os
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from . import cmds
from . import core
from . import gitcmds
from . import hotkeys
from . import icons
from . import qtutils
from . import utils
from .git import EMPTY_TREE_OID
from .i18n import N_
from .interaction import Interaction
from .widgets import completion
from .widgets import defs
from .widgets import filetree
from .widgets import standard
class LaunchDifftool(cmds.ContextCommand):
"""Launch "git difftool" with the currently selected files"""
@staticmethod
def name():
return N_('Launch Diff Tool')
def do(self):
s = self.selection.selection()
if s.unmerged:
paths = s.unmerged
if utils.is_win32():
core.fork(['git', 'mergetool', '--no-prompt', '--'] + paths)
else:
cfg = self.cfg
cmd = cfg.terminal()
argv = utils.shell_split(cmd)
terminal = os.path.basename(argv[0])
shellquote_terms = {'xfce4-terminal'}
shellquote_default = terminal in shellquote_terms
mergetool = ['git', 'mergetool', '--no-prompt', '--']
mergetool.extend(paths)
needs_shellquote = cfg.get(
'cola.terminalshellquote', shellquote_default
)
if needs_shellquote:
argv.append(core.list2cmdline(mergetool))
else:
argv.extend(mergetool)
core.fork(argv)
else:
difftool_run(self.context)
class Difftool(standard.Dialog):
def __init__(
self,
context,
parent,
a=None,
b=None,
expr=None,
title=None,
hide_expr=False,
focus_tree=False,
):
"""Show files with differences and launch difftool"""
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.a = a
self.b = b
self.diff_expr = expr
if title is None:
title = N_('git-cola diff')
self.setWindowTitle(title)
self.setWindowModality(Qt.WindowModal)
self.expr = completion.GitRefLineEdit(context, parent=self)
if expr is not None:
self.expr.setText(expr)
if expr is None or hide_expr:
self.expr.hide()
self.tree = filetree.FileTree(parent=self)
self.diff_button = qtutils.create_button(
text=N_('Compare'), icon=icons.diff(), enabled=False, default=True
)
self.diff_button.setShortcut(hotkeys.DIFF)
self.diff_all_button = qtutils.create_button(
text=N_('Compare All'), icon=icons.diff()
)
self.edit_button = qtutils.edit_button()
self.edit_button.setShortcut(hotkeys.EDIT)
self.close_button = qtutils.close_button()
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
qtutils.STRETCH,
self.close_button,
self.edit_button,
self.diff_all_button,
self.diff_button,
)
self.main_layout = qtutils.vbox(
defs.margin, defs.spacing, self.expr, self.tree, self.button_layout
)
self.setLayout(self.main_layout)
self.tree.itemSelectionChanged.connect(self.tree_selection_changed)
self.tree.itemDoubleClicked.connect(self.tree_double_clicked)
self.tree.up.connect(self.focus_input)
self.expr.textChanged.connect(self.text_changed)
self.expr.activated.connect(self.focus_tree)
self.expr.down.connect(self.focus_tree)
self.expr.enter.connect(self.focus_tree)
qtutils.connect_button(self.diff_button, self.diff)
qtutils.connect_button(self.diff_all_button, lambda: self.diff(dir_diff=True))
qtutils.connect_button(self.edit_button, self.edit)
qtutils.connect_button(self.close_button, self.close)
qtutils.add_action(self, 'Focus Input', self.focus_input, hotkeys.FOCUS)
qtutils.add_action(
self,
'Diff All',
lambda: self.diff(dir_diff=True),
hotkeys.CTRL_ENTER,
hotkeys.CTRL_RETURN,
)
qtutils.add_close_action(self)
self.init_state(None, self.resize_widget, parent)
self.refresh()
if focus_tree:
self.focus_tree()
def resize_widget(self, parent):
"""Set the initial size of the widget"""
width, height = qtutils.default_size(parent, 720, 420)
self.resize(width, height)
def focus_tree(self):
"""Focus the files tree"""
self.tree.setFocus()
def focus_input(self):
"""Focus the expression input"""
self.expr.setFocus()
def text_changed(self, txt):
self.diff_expr = txt
self.refresh()
def refresh(self):
"""Redo the diff when the expression changes"""
if self.diff_expr is not None:
self.diff_arg = utils.shell_split(self.diff_expr)
elif self.b is None:
self.diff_arg = [self.a]
else:
self.diff_arg = [self.a, self.b]
self.refresh_filenames()
def refresh_filenames(self):
context = self.context
if self.a and self.b is None:
filenames = gitcmds.diff_index_filenames(context, self.a)
else:
filenames = gitcmds.diff(context, self.diff_arg)
self.tree.set_filenames(filenames, select=True)
def tree_selection_changed(self):
has_selection = self.tree.has_selection()
self.diff_button.setEnabled(has_selection)
self.diff_all_button.setEnabled(has_selection)
def tree_double_clicked(self, item, _column):
path = filetree.filename_from_item(item)
left, right = self._left_right_args()
difftool_launch(self.context, left=left, right=right, paths=[path])
def diff(self, dir_diff=False):
paths = self.tree.selected_filenames()
left, right = self._left_right_args()
difftool_launch(
self.context, left=left, right=right, paths=paths, dir_diff=dir_diff
)
def _left_right_args(self):
if self.diff_arg:
left = self.diff_arg[0]
else:
left = None
if len(self.diff_arg) > 1:
right = self.diff_arg[1]
else:
right = None
return (left, right)
def edit(self):
paths = self.tree.selected_filenames()
cmds.do(cmds.Edit, self.context, paths)
def diff_commits(context, parent, a, b):
"""Show a dialog for diffing two commits"""
dlg = Difftool(context, parent, a=a, b=b)
dlg.show()
dlg.raise_()
return dlg.exec_() == QtWidgets.QDialog.Accepted
def diff_expression(
context, parent, expr, create_widget=False, hide_expr=False, focus_tree=False
):
"""Show a diff dialog for diff expressions"""
dlg = Difftool(
context, parent, expr=expr, hide_expr=hide_expr, focus_tree=focus_tree
)
if create_widget:
return dlg
dlg.show()
dlg.raise_()
return dlg.exec_() == QtWidgets.QDialog.Accepted
def difftool_run(context):
"""Start a default difftool session"""
selection = context.selection
files = selection.group()
if not files:
return
s = selection.selection()
head = context.model.head
difftool_launch_with_head(context, files, bool(s.staged), head)
def difftool_launch_with_head(context, filenames, staged, head):
"""Launch difftool against the provided head"""
if head == 'HEAD':
left = None
else:
left = head
difftool_launch(context, left=left, staged=staged, paths=filenames)
def difftool_launch(
context,
left=None,
right=None,
paths=None,
staged=False,
dir_diff=False,
left_take_magic=False,
left_take_parent=False,
):
"""Launches 'git difftool' with given parameters
:param left: first argument to difftool
:param right: second argument to difftool_args
:param paths: paths to diff
:param staged: activate `git difftool --staged`
:param dir_diff: activate `git difftool --dir-diff`
:param left_take_magic: whether to append the magic "^!" diff expression
:param left_take_parent: whether to append the first-parent ~ for diffing
"""
difftool_args = ['git', 'difftool', '--no-prompt']
if staged:
difftool_args.append('--cached')
if dir_diff:
difftool_args.append('--dir-diff')
if left:
if left_take_parent or left_take_magic:
suffix = '^!' if left_take_magic else '~'
# Check root commit (no parents and thus cannot execute '~')
git = context.git
status, out, err = git.rev_list(left, parents=True, n=1, _readonly=True)
Interaction.log_status(status, out, err)
if status:
raise OSError('git rev-list command failed')
if len(out.split()) >= 2:
# Commit has a parent, so we can take its child as requested
left += suffix
else:
# No parent, assume it's the root commit, so we have to diff
# against the empty tree.
left = EMPTY_TREE_OID
if not right and left_take_magic:
right = left
difftool_args.append(left)
if right:
difftool_args.append(right)
if paths:
difftool_args.append('--')
difftool_args.extend(paths)
runtask = context.runtask
if runtask:
Interaction.async_command(N_('Difftool'), difftool_args, runtask)
else:
core.fork(difftool_args)
| 9,801 | Python | .py | 265 | 28.120755 | 86 | 0.612073 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
34 | resources.py | git-cola_git-cola/cola/resources.py | """Functions for finding cola resources"""
import os
import sys
import webbrowser
from . import core
from . import compat
# Default git-cola icon theme
_default_icon_theme = 'light'
_resources = core.abspath(core.realpath(__file__))
_package = os.path.dirname(_resources)
if _package.endswith(os.path.join('site-packages', 'cola')):
# Unix release tree
# __file__ = '$prefix/lib/pythonX.Y/site-packages/cola/__file__.py'
# _package = '$prefix/lib/pythonX.Y/site-packages/cola'
_prefix = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(_package)))
)
elif _package.endswith(os.path.join('pkgs', 'cola')):
# Windows release tree
# __file__ = $installdir/pkgs/cola
_prefix = os.path.dirname(os.path.dirname(_package))
else:
# this is the source tree
# __file__ = '$prefix/cola/__file__.py'
_prefix = os.path.dirname(_package)
def get_prefix():
"""Return the installation prefix"""
return _prefix
def prefix(*args):
"""Return a path relative to cola's installation prefix"""
return os.path.join(get_prefix(), *args)
def sibling_bindir(*args):
"""Return a command sibling to sys.argv[0]"""
relative_bindir = os.path.dirname(sys.argv[0])
return os.path.join(relative_bindir, *args)
def command(name):
"""Return a command from the bin/ directory"""
if compat.WIN32:
# On Windows we have to support being installed via the pynsist installation
# layout and the pip-installed layout. We also have check for .exe launchers
# and prefer them when present.
sibling = sibling_bindir(name)
scripts = prefix('Scripts', name)
bindir = prefix('bin', name)
# Check for "${name}.exe" on Windows.
exe = f'{name}.exe'
sibling_exe = sibling_bindir(exe)
scripts_exe = prefix('Scripts', exe)
bindir_exe = prefix('bin', exe)
if core.exists(sibling_exe):
result = sibling_exe
elif core.exists(sibling):
result = sibling
elif core.exists(bindir_exe):
result = bindir_exe
elif core.exists(scripts_exe):
result = scripts_exe
elif core.exists(scripts):
result = scripts
else:
result = bindir
else:
result = sibling_bindir(name)
if not core.exists(result):
result = prefix('bin', name)
return result
def doc(*args):
"""Return a path relative to cola's /usr/share/doc/ directory or the docs/ directory"""
# pyproject.toml does not support data_files in pyproject.toml so we install the
# hotkey files as cola/data/ package data. This is a fallback location for when
# users did not use the garden.yaml or Makefile to install cola.
path = share('doc', 'git-cola', *args)
if not os.path.exists(path):
path = prefix('docs', *args)
return path
def i18n(*args):
"""Return a path relative to cola's i18n locale directory, e.g. cola/i18n"""
return package_data('i18n', *args)
def html_docs():
"""Return the path to the cola html documentation."""
# html/index.html only exists after the install-docs target is run.
# Fallback to the source tree and lastly git-cola.rst.
paths_to_try = (('html', 'index.html'), ('_build', 'html', 'index.html'))
for paths in paths_to_try:
docdir = doc(*paths)
if core.exists(docdir):
return docdir
return doc('git-cola.rst')
def show_html_docs():
"""Open the HTML documentation in a browser"""
url = html_docs()
webbrowser.open_new_tab('file://' + url)
def share(*args):
"""Return a path relative to cola's /usr/share/ directory"""
return prefix('share', *args)
def package_data(*args):
"""Return a path relative to cola's Python modules"""
return os.path.join(_package, *args)
def data_path(*args):
"""Return a path relative to cola's data directory"""
return package_data('data', *args)
def icon_path(*args):
"""Return a path relative to cola's icons directory"""
return package_data('icons', *args)
def package_command(*args):
"""Return a path relative to cola's private bin/ directory"""
return package_data('bin', *args)
def icon_dir(theme):
"""Return the icons directory for the specified theme
This returns the ``icons`` directory inside the ``cola`` Python package.
When theme is defined then it will return a subdirectory of the icons/
directory, e.g. "dark" for the dark icon theme.
When theme is set to an absolute directory path, that directory will be
returned, which effectively makes git-cola use those icons.
"""
if not theme or theme == _default_icon_theme:
icons = package_data('icons')
else:
theme_dir = package_data('icons', theme)
if os.path.isabs(theme) and os.path.isdir(theme):
icons = theme
elif os.path.isdir(theme_dir):
icons = theme_dir
else:
icons = package_data('icons')
return icons
def xdg_config_home(*args):
"""Return the XDG_CONFIG_HOME configuration directory, eg. ~/.config"""
config = core.getenv(
'XDG_CONFIG_HOME', os.path.join(core.expanduser('~'), '.config')
)
return os.path.join(config, *args)
def xdg_data_home(*args):
"""Return the XDG_DATA_HOME configuration directory, e.g. ~/.local/share"""
config = core.getenv(
'XDG_DATA_HOME', os.path.join(core.expanduser('~'), '.local', 'share')
)
return os.path.join(config, *args)
def xdg_data_dirs():
"""Return the current set of XDG data directories
Returns the values from $XDG_DATA_DIRS when defined in the environment.
If $XDG_DATA_DIRS is either not set or empty, a value equal to
/usr/local/share:/usr/share is used.
"""
paths = []
xdg_data_home_dir = xdg_data_home()
if os.path.isdir(xdg_data_home_dir):
paths.append(xdg_data_home_dir)
xdg_data_dirs_env = core.getenv('XDG_DATA_DIRS', '')
if not xdg_data_dirs_env:
xdg_data_dirs_env = '/usr/local/share:/usr/share'
paths.extend(path for path in xdg_data_dirs_env.split(':') if os.path.isdir(path))
return paths
def find_first(subpath, paths, validate=os.path.isfile):
"""Return the first `subpath` found in the specified directory paths"""
if os.path.isabs(subpath):
return subpath
for path in paths:
candidate = os.path.join(path, subpath)
if validate(candidate):
return candidate
# Nothing was found so return None.
return None
def config_home(*args):
"""Return git-cola's configuration directory, e.g. ~/.config/git-cola"""
return xdg_config_home('git-cola', *args)
| 6,746 | Python | .py | 166 | 34.692771 | 91 | 0.657786 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
35 | sequenceeditor.py | git-cola_git-cola/cola/sequenceeditor.py | import sys
import re
from argparse import ArgumentParser
from functools import partial
from cola import app # prints a message if Qt cannot be found
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from cola import core
from cola import difftool
from cola import gitcmds
from cola import hotkeys
from cola import icons
from cola import qtutils
from cola import utils
from cola.i18n import N_
from cola.models import dag
from cola.models import prefs
from cola.widgets import defs
from cola.widgets import filelist
from cola.widgets import diff
from cola.widgets import standard
from cola.widgets import text
BREAK = 'break'
DROP = 'drop'
EDIT = 'edit'
EXEC = 'exec'
FIXUP = 'fixup'
LABEL = 'label'
MERGE = 'merge'
PICK = 'pick'
RESET = 'reset'
REWORD = 'reword'
SQUASH = 'squash'
UPDATE_REF = 'update-ref'
COMMANDS = (
EDIT,
DROP,
FIXUP,
PICK,
REWORD,
SQUASH,
)
COMMAND_IDX = {cmd_: idx_ for idx_, cmd_ in enumerate(COMMANDS)}
ABBREV = {
'b': BREAK,
'd': DROP,
'e': EDIT,
'f': FIXUP,
'p': PICK,
'r': REWORD,
's': SQUASH,
'u': UPDATE_REF,
'x': EXEC,
}
def main():
"""Start a git-cola-sequence-editor session"""
args = parse_args()
context = app.application_init(args)
view = new_window(context, args.filename)
app.application_run(context, view, start=view.start, stop=stop)
return view.status
def stop(context, _view):
"""All done, cleanup"""
context.view.stop()
context.runtask.wait()
def parse_args():
parser = ArgumentParser()
parser.add_argument(
'filename', metavar='<filename>', help='git-rebase-todo file to edit'
)
app.add_common_arguments(parser)
return parser.parse_args()
def new_window(context, filename):
window = MainWindow(context)
editor = Editor(context, filename, parent=window)
window.set_editor(editor)
return window
def unabbrev(cmd):
"""Expand shorthand commands into their full name"""
return ABBREV.get(cmd, cmd)
class MainWindow(standard.MainWindow):
"""The main git-cola application window"""
def __init__(self, context, parent=None):
super().__init__(parent)
self.context = context
self.status = 1
# If the user closes the window without confirmation it's considered cancelled.
self.cancelled = True
self.editor = None
default_title = '%s - git cola sequence editor' % core.getcwd()
title = core.getenv('GIT_COLA_SEQ_EDITOR_TITLE', default_title)
self.setWindowTitle(title)
self.show_help_action = qtutils.add_action(
self, N_('Show Help'), partial(show_help, context), hotkeys.QUESTION
)
self.menubar = QtWidgets.QMenuBar(self)
self.help_menu = self.menubar.addMenu(N_('Help'))
self.help_menu.addAction(self.show_help_action)
self.setMenuBar(self.menubar)
qtutils.add_close_action(self)
self.init_state(context.settings, self.init_window_size)
def init_window_size(self):
"""Set the window size on the first initial view"""
if utils.is_darwin():
width, height = qtutils.desktop_size()
self.resize(width, height)
else:
self.showMaximized()
def set_editor(self, editor):
self.editor = editor
self.setCentralWidget(editor)
editor.cancel.connect(self.close)
editor.rebase.connect(self.rebase)
editor.setFocus()
def start(self, _context, _view):
"""Start background tasks"""
self.editor.start()
def stop(self):
"""Stop background tasks"""
self.editor.stop()
def rebase(self):
"""Exit the editor and initiate a rebase"""
self.status = self.editor.save()
self.close()
class Editor(QtWidgets.QWidget):
cancel = Signal()
rebase = Signal()
def __init__(self, context, filename, parent=None):
super().__init__(parent)
self.widget_version = 1
self.context = context
self.filename = filename
self.comment_char = comment_char = prefs.comment_char(context)
self.diff = diff.DiffWidget(context, self)
self.tree = RebaseTreeWidget(context, comment_char, self)
self.filewidget = filelist.FileWidget(context, self, remarks=True)
self.setFocusProxy(self.tree)
self.rebase_button = qtutils.create_button(
text=core.getenv('GIT_COLA_SEQ_EDITOR_ACTION', N_('Rebase')),
tooltip=N_('Accept changes and rebase\nShortcut: Ctrl+Enter'),
icon=icons.ok(),
default=True,
)
self.extdiff_button = qtutils.create_button(
text=N_('Launch Diff Tool'),
tooltip=N_('Launch external diff tool\nShortcut: Ctrl+D'),
)
self.extdiff_button.setEnabled(False)
self.help_button = qtutils.create_button(
text=N_('Help'), tooltip=N_('Show help\nShortcut: ?'), icon=icons.question()
)
self.cancel_button = qtutils.create_button(
text=N_('Cancel'),
tooltip=N_('Cancel rebase\nShortcut: Ctrl+Q'),
icon=icons.close(),
)
top = qtutils.splitter(Qt.Horizontal, self.tree, self.filewidget)
top.setSizes([75, 25])
main_split = qtutils.splitter(Qt.Vertical, top, self.diff)
main_split.setSizes([25, 75])
controls_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.cancel_button,
qtutils.STRETCH,
self.help_button,
self.extdiff_button,
self.rebase_button,
)
layout = qtutils.vbox(defs.no_margin, defs.spacing, main_split, controls_layout)
self.setLayout(layout)
self.action_rebase = qtutils.add_action(
self,
N_('Rebase'),
self.rebase.emit,
hotkeys.CTRL_RETURN,
hotkeys.CTRL_ENTER,
)
self.tree.commits_selected.connect(self.commits_selected)
self.tree.commits_selected.connect(self.filewidget.commits_selected)
self.tree.commits_selected.connect(self.diff.commits_selected)
self.tree.external_diff.connect(self.external_diff)
self.filewidget.files_selected.connect(self.diff.files_selected)
self.filewidget.remark_toggled.connect(self.remark_toggled_for_files)
# `git` calls are expensive. When user toggles a remark of all commits touching
# selected paths the GUI freezes for a while on a big enough sequence. This
# cache is used (commit ID to paths tuple) to minimize calls to git.
self.oid_to_paths = {}
self.task = None # A task fills the cache in the background.
self.running = False # This flag stops it.
qtutils.connect_button(self.rebase_button, self.rebase.emit)
qtutils.connect_button(self.extdiff_button, self.external_diff)
qtutils.connect_button(self.help_button, partial(show_help, context))
qtutils.connect_button(self.cancel_button, self.cancel.emit)
def start(self):
insns = core.read(self.filename)
self.parse_sequencer_instructions(insns)
# Assume that the tree is filled at this point.
self.running = True
self.task = qtutils.SimpleTask(self.calculate_oid_to_paths)
self.context.runtask.start(self.task)
def stop(self):
self.running = False
# signal callbacks
def commits_selected(self, commits):
self.extdiff_button.setEnabled(bool(commits))
def remark_toggled_for_files(self, remark, filenames):
filenames = set(filenames)
items = self.tree.items()
touching_items = []
for item in items:
if not item.is_commit():
continue
oid = item.oid
paths = self.paths_touched_by_oid(oid)
if filenames.intersection(paths):
touching_items.append(item)
self.tree.toggle_remark_of_items(remark, touching_items)
def external_diff(self):
items = self.tree.selected_items()
if not items:
return
item = items[0]
difftool.diff_expression(self.context, self, item.oid + '^!', hide_expr=True)
# helpers
def paths_touched_by_oid(self, oid):
try:
return self.oid_to_paths[oid]
except KeyError:
pass
paths = gitcmds.changed_files(self.context, oid)
self.oid_to_paths[oid] = paths
return paths
def calculate_oid_to_paths(self):
"""Fills the oid_to_paths cache in the background"""
for item in self.tree.items():
if not self.running:
return
self.paths_touched_by_oid(item.oid)
def parse_sequencer_instructions(self, insns):
idx = 1
re_comment_char = re.escape(self.comment_char)
break_rgx = re.compile(r'^\s*(%s)?\s*(b|break)$' % re_comment_char)
exec_rgx = re.compile(r'^\s*(%s)?\s*(x|exec)\s+(.+)$' % re_comment_char)
update_ref_rgx = re.compile(
r'^\s*(%s)?\s*(u|update-ref)\s+(.+)$' % re_comment_char
)
# The upper bound of 40 below must match git.OID_LENGTH.
# We'll have to update this to the new hash length when that happens.
pick_rgx = re.compile(
(
r'^\s*(%s)?\s*'
+ r'(d|drop|e|edit|f|fixup|p|pick|r|reword|s|squash)'
+ r'\s+([0-9a-f]{7,40})'
+ r'\s+(.+)$'
)
% re_comment_char
)
label_rgx = re.compile(
r'^\s*(%s)?\s*(l|label|m|merge|t|reset)\s+(.+)$' % re_comment_char
)
for line in insns.splitlines():
match = pick_rgx.match(line)
if match:
enabled = match.group(1) is None
command = unabbrev(match.group(2))
oid = match.group(3)
summary = match.group(4)
self.tree.add_item(idx, enabled, command, oid=oid, summary=summary)
idx += 1
continue
match = exec_rgx.match(line)
if match:
enabled = match.group(1) is None
command = unabbrev(match.group(2))
cmdexec = match.group(3)
self.tree.add_item(idx, enabled, command, cmdexec=cmdexec)
idx += 1
continue
match = update_ref_rgx.match(line)
if match:
enabled = match.group(1) is None
command = unabbrev(match.group(2))
branch = match.group(3)
self.tree.add_item(idx, enabled, command, branch=branch)
idx += 1
continue
match = label_rgx.match(line)
if match:
enabled = match.group(1) is None
command = unabbrev(match.group(2))
label = match.group(3)
self.tree.add_item(idx, enabled, command, label=label)
idx += 1
continue
match = break_rgx.match(line)
if match:
enabled = match.group(1) is None
command = unabbrev(match.group(2))
self.tree.add_item(idx, enabled, command)
idx += 1
continue
self.tree.decorate(self.tree.items())
self.tree.refit()
self.tree.select_first()
def save(self, string=None):
"""Save the instruction sheet"""
if string is None:
lines = [item.value() for item in self.tree.items()]
# sequencer instructions
string = '\n'.join(lines) + '\n'
try:
core.write(self.filename, string)
status = 0
except (OSError, ValueError) as exc:
msg, details = utils.format_exception(exc)
sys.stderr.write(msg + '\n\n' + details)
status = 128
return status
class RebaseTreeWidget(standard.DraggableTreeWidget):
commits_selected = Signal(object)
external_diff = Signal()
move_rows = Signal(object, object)
def __init__(self, context, comment_char, parent):
super().__init__(parent=parent)
self.context = context
self.comment_char = comment_char
# header
self.setHeaderLabels([
N_('#'),
N_('Enabled'),
N_('Command'),
N_('Commit@@noun'),
N_('Remarks'),
N_('Summary'),
])
self.header().setStretchLastSection(True)
self.setColumnCount(6)
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
# actions
self.copy_oid_action = qtutils.add_action(
self, N_('Copy Commit'), self.copy_oid, QtGui.QKeySequence.Copy
)
self.external_diff_action = qtutils.add_action(
self, N_('Launch Diff Tool'), self.external_diff.emit, hotkeys.DIFF
)
self.toggle_enabled_action = qtutils.add_action(
self, N_('Toggle Enabled'), self.toggle_enabled, hotkeys.PRIMARY_ACTION
)
self.action_pick = qtutils.add_action(
self, N_('Pick'), lambda: self.set_selected_to(PICK), *hotkeys.REBASE_PICK
)
self.action_reword = qtutils.add_action(
self,
N_('Reword'),
lambda: self.set_selected_to(REWORD),
*hotkeys.REBASE_REWORD,
)
self.action_edit = qtutils.add_action(
self, N_('Edit'), lambda: self.set_selected_to(EDIT), *hotkeys.REBASE_EDIT
)
self.action_fixup = qtutils.add_action(
self,
N_('Fixup'),
lambda: self.set_selected_to(FIXUP),
*hotkeys.REBASE_FIXUP,
)
self.action_squash = qtutils.add_action(
self,
N_('Squash'),
lambda: self.set_selected_to(SQUASH),
*hotkeys.REBASE_SQUASH,
)
self.action_drop = qtutils.add_action(
self,
N_('Drop'),
lambda: self.set_selected_to(DROP),
*hotkeys.REBASE_DROP,
)
self.action_shift_down = qtutils.add_action(
self, N_('Shift Down'), self.shift_down, hotkeys.MOVE_DOWN_TERTIARY
)
self.action_shift_up = qtutils.add_action(
self, N_('Shift Up'), self.shift_up, hotkeys.MOVE_UP_TERTIARY
)
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))
)
self.itemChanged.connect(self.item_changed)
self.itemSelectionChanged.connect(self.selection_changed)
self.move_rows.connect(self.move)
self.items_moved.connect(self.decorate)
def add_item(
self, idx, enabled, command, oid='', summary='', cmdexec='', branch='', label=''
):
comment_char = self.comment_char
item = RebaseTreeWidgetItem(
idx,
enabled,
command,
oid=oid,
summary=summary,
cmdexec=cmdexec,
branch=branch,
comment_char=comment_char,
label=label,
parent=self,
)
self.invisibleRootItem().addChild(item)
def decorate(self, items):
for item in items:
item.decorate(self)
def refit(self):
"""Resize columns to fit content"""
for i in range(RebaseTreeWidgetItem.COLUMN_COUNT - 1):
self.resizeColumnToContents(i)
def item_changed(self, item, column):
"""Validate item ordering when toggling their enabled state"""
if column == item.ENABLED_COLUMN:
self.validate()
def validate(self):
invalid_first_choice = {FIXUP, SQUASH}
for item in self.items():
if item.is_enabled() and item.is_commit():
if item.command in invalid_first_choice:
item.reset_command(PICK)
break
def set_selected_to(self, command):
for i in self.selected_items():
i.reset_command(command)
self.validate()
def set_command(self, item, command):
item.reset_command(command)
self.validate()
def copy_oid(self):
item = self.selected_item()
if item is None:
return
clipboard = item.oid or item.cmdexec
qtutils.set_clipboard(clipboard)
def selection_changed(self):
item = self.selected_item()
if item is None or not item.is_commit():
return
context = self.context
oid = item.oid
params = dag.DAG(oid, 2)
repo = dag.RepoReader(context, params)
commits = []
for commit in repo.get():
commits.append(commit)
if commits:
commits = commits[-1:]
self.commits_selected.emit(commits)
def toggle_enabled(self):
"""Toggle the enabled state of each selected item"""
items = self.selected_items()
enable = should_enable(items, lambda item: item.is_enabled())
for item in items:
if enable:
needs_update = not item.is_enabled()
else:
needs_update = item.is_enabled()
if needs_update:
item.set_enabled(enable)
def select_first(self):
items = self.items()
if not items:
return
idx = self.model().index(0, 0)
if idx.isValid():
self.setCurrentIndex(idx)
def shift_down(self):
sel_items = self.selected_items()
all_items = self.items()
sel_idx = sorted([all_items.index(item) for item in sel_items])
if not sel_idx:
return
idx = sel_idx[0] + 1
if not (
idx > len(all_items) - len(sel_items)
or all_items[sel_idx[-1]] is all_items[-1]
):
self.move_rows.emit(sel_idx, idx)
def shift_up(self):
sel_items = self.selected_items()
all_items = self.items()
sel_idx = sorted([all_items.index(item) for item in sel_items])
if not sel_idx:
return
idx = sel_idx[0] - 1
if idx >= 0:
self.move_rows.emit(sel_idx, idx)
def toggle_remark(self, remark):
"""Toggle remarks for all selected items"""
items = self.selected_items()
self.toggle_remark_of_items(remark, items)
def toggle_remark_of_items(self, remark, items):
"""Toggle remarks for the selected items"""
enable = should_enable(items, lambda item: remark in item.remarks)
for item in items:
needs_update = enable ^ (remark in item.remarks)
if needs_update:
if enable:
item.add_remark(remark)
else:
item.remove_remark(remark)
def move(self, src_idxs, dst_idx):
moved_items = []
src_base = sorted(src_idxs)[0]
for idx in reversed(sorted(src_idxs)):
item = self.invisibleRootItem().takeChild(idx)
moved_items.insert(0, [dst_idx + (idx - src_base), item])
for item in moved_items:
self.invisibleRootItem().insertChild(item[0], item[1])
self.setCurrentItem(item[1])
if moved_items:
moved_items = [item[1] for item in moved_items]
# If we've moved to the top then we need to re-decorate all items.
# Otherwise, we can decorate just the new items.
if dst_idx == 0:
self.decorate(self.items())
else:
self.decorate(moved_items)
for item in moved_items:
item.setSelected(True)
self.validate()
# Qt events
def dropEvent(self, event):
super().dropEvent(event)
self.validate()
def contextMenuEvent(self, event):
items = self.selected_items()
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.action_pick)
menu.addAction(self.action_reword)
menu.addAction(self.action_edit)
menu.addAction(self.action_fixup)
menu.addAction(self.action_squash)
menu.addAction(self.action_drop)
menu.addSeparator()
menu.addAction(self.toggle_enabled_action)
menu.addSeparator()
menu.addAction(self.copy_oid_action)
self.copy_oid_action.setDisabled(len(items) > 1)
menu.addAction(self.external_diff_action)
self.external_diff_action.setDisabled(len(items) > 1)
menu.addSeparator()
menu_toggle_remark = menu.addMenu(N_('Toggle Remark'))
for action in self.toggle_remark_actions:
menu_toggle_remark.addAction(action)
menu.exec_(self.mapToGlobal(event.pos()))
def should_enable(items, predicate):
"""Calculate whether items should be toggled on or off.
If all items are enabled then return False.
If all items are disabled then return True.
If more items are enabled then return True, otherwise return False.
"""
count = len(items)
enabled = sum(predicate(item) for item in items)
disabled = len(items) - enabled
enable = count > enabled >= disabled or disabled == count
return enable
class ComboBox(QtWidgets.QComboBox):
validate = Signal()
class RebaseTreeWidgetItem(QtWidgets.QTreeWidgetItem):
"""A single data row in the rebase tree widget"""
NUMBER_COLUMN = 0
ENABLED_COLUMN = 1
COMMAND_COLUMN = 2
COMMIT_COLUMN = 3
REMARKS_COLUMN = 4
SUMMARY_COLUMN = 5
COLUMN_COUNT = 6
OID_LENGTH = 7
COLORS = {
'0': ('white', 'darkred'),
'1': ('black', 'salmon'),
'2': ('black', 'sandybrown'),
'3': ('black', 'yellow'),
'4': ('black', 'yellowgreen'),
'5': ('white', 'forestgreen'),
'6': ('white', 'dodgerblue'),
'7': ('white', 'royalblue'),
'8': ('white', 'slateblue'),
'9': ('black', 'rosybrown'),
}
def __init__(
self,
idx,
enabled,
command,
oid='',
summary='',
cmdexec='',
branch='',
label='',
comment_char='#',
remarks=(),
parent=None,
):
QtWidgets.QTreeWidgetItem.__init__(self, parent)
self.combo = None
self.command = command
self.idx = idx
self.oid = oid
self.summary = summary
self.cmdexec = cmdexec
self.branch = branch
self.label = label
self.comment_char = comment_char
self.remarks = remarks
self.remarks_label = None
self._parent = parent
# if core.abbrev is set to a higher value then we will notice by
# simply tracking the longest oid we've seen
oid_len = self.OID_LENGTH
self.__class__.OID_LENGTH = max(len(oid), oid_len)
self.setText(self.NUMBER_COLUMN, '%02d' % idx)
self.set_enabled(enabled)
# checkbox on 1
# combo box on 2
if self.is_exec():
self.setText(self.COMMIT_COLUMN, '')
self.setText(self.SUMMARY_COLUMN, cmdexec)
elif self.is_update_ref():
self.setText(self.COMMIT_COLUMN, '')
self.setText(self.SUMMARY_COLUMN, branch)
elif self.is_label() or self.is_reset() or self.is_merge():
self.setText(self.COMMIT_COLUMN, '')
self.setText(self.SUMMARY_COLUMN, label)
elif self.is_break():
self.setText(self.COMMIT_COLUMN, '')
self.setText(self.SUMMARY_COLUMN, '')
else:
self.setText(self.COMMIT_COLUMN, oid)
self.setText(self.SUMMARY_COLUMN, summary)
self.set_remarks(remarks)
flags = self.flags() | Qt.ItemIsUserCheckable
flags = flags | Qt.ItemIsDragEnabled
flags = flags & ~Qt.ItemIsDropEnabled
self.setFlags(flags)
def __eq__(self, other):
return self is other
def __hash__(self):
return self.oid
def copy(self):
return self.__class__(
self.idx,
self.is_enabled(),
self.command,
oid=self.oid,
summary=self.summary,
cmdexec=self.cmdexec,
branch=self.branch,
comment_char=self.comment_char,
remarks=self.remarks,
)
def decorate(self, parent):
if self.is_exec():
items = [EXEC]
idx = 0
elif self.is_update_ref():
items = [UPDATE_REF]
idx = 0
elif self.is_label():
items = [LABEL]
idx = 0
elif self.is_merge():
items = [MERGE]
idx = 0
elif self.is_reset():
items = [RESET]
idx = 0
elif self.is_break():
items = [BREAK]
idx = 0
else:
items = COMMANDS
idx = COMMAND_IDX[self.command]
combo = self.combo = ComboBox()
combo.setEditable(False)
combo.addItems(items)
combo.setCurrentIndex(idx)
combo.setEnabled(self.is_commit())
signal = combo.currentIndexChanged
signal.connect(lambda x: self.set_command_and_validate(combo))
combo.validate.connect(parent.validate)
parent.setItemWidget(self, self.COMMAND_COLUMN, combo)
self.remarks_label = remarks_label = QtWidgets.QLabel()
parent.setItemWidget(self, self.REMARKS_COLUMN, remarks_label)
self.update_remarks()
def is_break(self):
return self.command == BREAK
def is_exec(self):
return self.command == EXEC
def is_update_ref(self):
return self.command == UPDATE_REF
def is_label(self):
return self.command == LABEL
def is_reset(self):
return self.command == RESET
def is_merge(self):
return self.command == MERGE
def is_commit(self):
return bool(
not (self.is_exec() or self.is_update_ref()) and self.oid and self.summary
)
def value(self):
"""Return the serialized representation of an item"""
if self.is_enabled():
comment = ''
else:
comment = self.comment_char + ' '
if self.is_exec():
return f'{comment}{self.command} {self.cmdexec}'
if self.is_update_ref():
return f'{comment}{self.command} {self.branch}'
if self.is_label() or self.is_merge() or self.is_reset():
return f'{comment}{self.command} {self.label}'
if self.is_break():
return f'{comment}{self.command}'
return f'{comment}{self.command} {self.oid} {self.summary}'
def is_enabled(self):
"""Is the item enabled?"""
return self.checkState(self.ENABLED_COLUMN) == Qt.Checked
def set_enabled(self, enabled):
"""Enable the item by checking its enabled checkbox"""
self.setCheckState(self.ENABLED_COLUMN, enabled and Qt.Checked or Qt.Unchecked)
def toggle_enabled(self):
"""Toggle the enabled state of the item"""
self.set_enabled(not self.is_enabled())
def add_remark(self, remark):
"""Add a remark to the item"""
self.set_remarks(tuple(sorted(set(self.remarks + (remark,)))))
def remove_remark(self, remark):
"""Remove a remark from the item"""
self.set_remarks(tuple(r for r in self.remarks if r != remark))
def set_remarks(self, remarks):
"""Set the remarks and update the remark display"""
if remarks == self.remarks:
return
self.remarks = remarks
self.update_remarks()
self._parent.resizeColumnToContents(self.REMARKS_COLUMN)
def update_remarks(self):
"""Update the remarks label display to match the current remarks"""
label = self.remarks_label
if label is None:
return
label_text = ''
for remark in self.remarks:
fg_color, bg_color = self.COLORS[remark]
label_text += f"""
<span style="
color: {fg_color};
background-color: {bg_color};
"> {remark} </span>
"""
label.setText(label_text)
def set_command(self, command):
"""Set the item to a different command, no-op for exec items"""
if self.is_exec():
return
self.command = command
def refresh(self):
"""Update the view to match the updated state"""
if self.is_commit():
command = self.command
self.combo.setCurrentIndex(COMMAND_IDX[command])
def reset_command(self, command):
"""Set and refresh the item in one shot"""
self.set_command(command)
self.refresh()
def set_command_and_validate(self, combo):
"""Set the command and validate the command order"""
command = COMMANDS[combo.currentIndex()]
self.set_command(command)
self.combo.validate.emit()
def show_help(context):
help_text = N_(
"""
Commands
--------
pick = use commit
reword = use commit, but edit the commit message
edit = use commit, but stop for amending
squash = use commit, but meld into previous commit
fixup = like "squash", but discard this commit's log message
exec = run command (the rest of the line) using shell
break = stop here (continue rebase later)
drop = remove commit
label = label current HEAD with a name
reset = reset HEAD to a label
merge = create a merge commit
update-ref = update branches that point to commits
These lines can be re-ordered; they are executed from top to bottom.
If you disable a line here THAT COMMIT WILL BE LOST.
However, if you disable everything, the rebase will be aborted.
Keyboard Shortcuts
------------------
? = show help
j = move down
k = move up
J = shift row down
K = shift row up
1, p = pick
2, r = reword
3, e = edit
4, f = fixup
5, s = squash
6, d = drop
spacebar = toggle enabled
ctrl+enter = accept changes and rebase
ctrl+q = cancel and abort the rebase
ctrl+d = launch difftool
"""
)
title = N_('Help - git-cola-sequence-editor')
return text.text_dialog(context, help_text, title)
| 30,613 | Python | .py | 828 | 27.822464 | 88 | 0.592962 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
36 | __main__.py | git-cola_git-cola/cola/__main__.py | """Run cola as a Python module.
Usage: python -m cola
"""
from cola import main
def run():
"""Start the command-line interface."""
main.main()
if __name__ == '__main__':
run()
| 194 | Python | .py | 9 | 18.555556 | 43 | 0.620112 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
37 | interaction.py | git-cola_git-cola/cola/interaction.py | import os
import sys
from . import core
from .i18n import N_
class Interaction:
"""Prompts the user and answers questions"""
VERBOSE = bool(os.getenv('GIT_COLA_VERBOSE'))
@classmethod
def command(cls, title, cmd, status, out, err):
"""Log a command and display error messages on failure"""
cls.log_status(status, out, err)
if status != 0:
cls.command_error(title, cmd, status, out, err)
@classmethod
def command_error(cls, title, cmd, status, out, err):
"""Display an error message for a failed command"""
core.print_stderr(title)
core.print_stderr('-' * len(title))
core.print_stderr(cls.format_command_status(cmd, status))
core.print_stdout('')
if out:
core.print_stdout(out)
if err:
core.print_stderr(err)
@staticmethod
def format_command_status(cmd, status):
return N_('"%(command)s" returned exit status %(status)d') % {
'command': cmd,
'status': status,
}
@staticmethod
def format_out_err(out, err):
"""Format stdout and stderr into a single string"""
details = out or ''
if err:
if details and not details.endswith('\n'):
details += '\n'
details += err
return details
@staticmethod
def information(title, message=None, details=None, informative_text=None):
if message is None:
message = title
scope = {}
scope['title'] = title
scope['title_dashes'] = '-' * len(title)
scope['message'] = message
scope['details'] = ('\n' + details) if details else ''
scope['informative_text'] = (
('\n' + informative_text) if informative_text else ''
)
sys.stdout.write(
"""
%(title)s
%(title_dashes)s
%(message)s%(informative_text)s%(details)s\n"""
% scope
)
sys.stdout.flush()
@classmethod
def critical(cls, title, message=None, details=None):
"""Show a warning with the provided title and message."""
cls.information(title, message=message, details=details)
@classmethod
def confirm(
cls,
title,
text,
informative_text,
ok_text,
icon=None,
default=True,
cancel_text=None,
):
cancel_text = cancel_text or 'Cancel'
icon = icon or '?'
cls.information(title, message=text, informative_text=informative_text)
if default:
prompt = '%s? [Y/n] ' % ok_text
else:
prompt = '%s? [y/N] ' % ok_text
sys.stdout.write(prompt)
sys.stdout.flush()
answer = sys.stdin.readline().strip()
if answer:
result = answer.lower().startswith('y')
else:
result = default
return result
@classmethod
def question(cls, title, message, default=True):
return cls.confirm(title, message, '', ok_text=N_('Continue'), default=default)
@classmethod
def run_command(cls, title, cmd):
cls.log('# ' + title)
cls.log('$ ' + core.list2cmdline(cmd))
status, out, err = core.run_command(cmd)
cls.log_status(status, out, err)
return status, out, err
@classmethod
def confirm_config_action(cls, _context, name, _opts):
return cls.confirm(
N_('Run %s?') % name,
N_('Run the "%s" command?') % name,
'',
ok_text=N_('Run'),
)
@classmethod
def log_status(cls, status, out, err=None):
msg = ((out + '\n') if out else '') + ((err + '\n') if err else '')
cls.log(msg)
cls.log('exit status %s' % status)
@classmethod
def log(cls, message):
if cls.VERBOSE:
core.print_stdout(message)
@classmethod
def save_as(cls, filename, title):
if cls.confirm(title, 'Save as %s?' % filename, '', ok_text='Save'):
return filename
return None
@staticmethod
def async_command(title, command, runtask):
pass
@classmethod
def choose_ref(cls, _context, title, button_text, default=None, icon=None):
icon = icon or '?'
cls.information(title, button_text)
return sys.stdin.readline().strip() or default
| 4,367 | Python | .py | 129 | 25.503876 | 87 | 0.572783 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
38 | settings.py | git-cola_git-cola/cola/settings.py | """Save settings, bookmarks, etc."""
import json
import os
import sys
from . import core
from . import display
from . import git
from . import resources
def mkdict(obj):
"""Transform None and non-dicts into dicts"""
if isinstance(obj, dict):
value = obj
else:
value = {}
return value
def mklist(obj):
"""Transform None and non-lists into lists"""
if isinstance(obj, list):
value = obj
elif isinstance(obj, tuple):
value = list(obj)
else:
value = []
return value
def read_json(path):
try:
with core.open_read(path) as f:
return mkdict(json.load(f))
except (ValueError, TypeError, OSError): # bad path or json
return {}
def write_json(values, path, sync=True):
"""Write the specified values dict to a JSON file at the specified path"""
try:
parent = os.path.dirname(path)
if not core.isdir(parent):
core.makedirs(parent)
with core.open_write(path) as fp:
json.dump(values, fp, indent=4)
if sync:
core.fsync(fp.fileno())
except (ValueError, TypeError, OSError):
sys.stderr.write('git-cola: error writing "%s"\n' % path)
return False
return True
def rename_path(old, new):
"""Rename a filename. Catch exceptions and return False on error."""
try:
core.rename(old, new)
except OSError:
sys.stderr.write(f'git-cola: error renaming "{old}" to "{new}"\n')
return False
return True
def remove_path(path):
"""Remove a filename. Report errors to stderr."""
try:
core.remove(path)
except OSError:
sys.stderr.write('git-cola: error removing "%s"\n' % path)
class Settings:
config_path = resources.config_home('settings')
bookmarks = property(lambda self: mklist(self.values['bookmarks']))
gui_state = property(lambda self: mkdict(self.values['gui_state']))
recent = property(lambda self: mklist(self.values['recent']))
copy_formats = property(lambda self: mklist(self.values['copy_formats']))
def __init__(self, verify=git.is_git_worktree):
"""Load existing settings if they exist"""
self.values = {
'bookmarks': [],
'gui_state': {},
'recent': [],
'copy_formats': [],
}
self.verify = verify
def remove_missing_bookmarks(self):
"""Remove "favorites" bookmarks that no longer exist"""
missing_bookmarks = []
for bookmark in self.bookmarks:
if not self.verify(bookmark['path']):
missing_bookmarks.append(bookmark)
for bookmark in missing_bookmarks:
try:
self.bookmarks.remove(bookmark)
except ValueError:
pass
def remove_missing_recent(self):
"""Remove "recent" repositories that no longer exist"""
missing_recent = []
for recent in self.recent:
if not self.verify(recent['path']):
missing_recent.append(recent)
for recent in missing_recent:
try:
self.recent.remove(recent)
except ValueError:
pass
def add_bookmark(self, path, name):
"""Adds a bookmark to the saved settings"""
bookmark = {'path': display.normalize_path(path), 'name': name}
if bookmark not in self.bookmarks:
self.bookmarks.append(bookmark)
def remove_bookmark(self, path, name):
"""Remove a bookmark"""
bookmark = {'path': display.normalize_path(path), 'name': name}
try:
self.bookmarks.remove(bookmark)
except ValueError:
pass
def rename_bookmark(self, path, name, new_name):
return rename_entry(self.bookmarks, path, name, new_name)
def add_recent(self, path, max_recent):
normalize = display.normalize_path
path = normalize(path)
try:
index = [normalize(recent['path']) for recent in self.recent].index(path)
entry = self.recent.pop(index)
except (IndexError, ValueError):
entry = {
'name': os.path.basename(path),
'path': path,
}
self.recent.insert(0, entry)
if len(self.recent) > max_recent:
self.recent.pop()
def remove_recent(self, path):
"""Removes an item from the recent items list"""
normalize = display.normalize_path
path = normalize(path)
try:
index = [normalize(recent.get('path', '')) for recent in self.recent].index(
path
)
except ValueError:
return
try:
self.recent.pop(index)
except IndexError:
return
def rename_recent(self, path, name, new_name):
return rename_entry(self.recent, path, name, new_name)
def path(self):
return self.config_path
def save(self, sync=True):
"""Write settings robustly to avoid losing data during a forced shutdown.
To save robustly we take these steps:
* Write the new settings to a .tmp file.
* Rename the current settings to a .bak file.
* Rename the new settings from .tmp to the settings file.
* Flush the data to disk
* Delete the .bak file.
Cf. https://github.com/git-cola/git-cola/issues/1241
"""
path = self.path()
path_tmp = path + '.tmp'
path_bak = path + '.bak'
# Write the new settings to the .tmp file.
if not write_json(self.values, path_tmp, sync=sync):
return
# Rename the current settings to a .bak file.
if core.exists(path) and not rename_path(path, path_bak):
return
# Rename the new settings from .tmp to the settings file.
if not rename_path(path_tmp, path):
return
# Delete the .bak file.
if core.exists(path_bak):
remove_path(path_bak)
def load(self, path=None):
"""Load settings robustly.
Attempt to load settings from the .bak file if it exists since it indicates
that the program terminated before the data was flushed to disk. This can
happen when a machine is force-shutdown, for example.
This follows the strategy outlined in issue #1241. If the .bak file exists
we use it, otherwise we fallback to the actual path or the .tmp path as a
final last-ditch attempt to recover settings.
"""
path = self.path()
path_bak = path + '.bak'
path_tmp = path + '.tmp'
if core.exists(path_bak):
self.values.update(self.asdict(path=path_bak))
elif core.exists(path):
self.values.update(self.asdict(path=path))
elif core.exists(path_tmp):
# This is potentially dangerous, but it's guarded by the fact that the
# file must be valid JSON in order otherwise the reader will return an
# empty string, thus making this a no-op.
self.values.update(self.asdict(path=path_tmp))
else:
# This is either a new installation or the settings were lost.
pass
# We could try to remove the .bak and .tmp files, but it's better to set save()
# handle that the next time it succeeds.
self.upgrade_settings()
return True
@staticmethod
def read(verify=git.is_git_worktree):
"""Load settings from disk"""
settings = Settings(verify=verify)
settings.load()
return settings
def upgrade_settings(self):
"""Upgrade git-cola settings"""
# Upgrade bookmarks to the new dict-based bookmarks format.
normalize = display.normalize_path
if self.bookmarks and not isinstance(self.bookmarks[0], dict):
bookmarks = [
{'name': os.path.basename(path), 'path': normalize(path)}
for path in self.bookmarks
]
self.values['bookmarks'] = bookmarks
if self.recent and not isinstance(self.recent[0], dict):
recent = [
{'name': os.path.basename(path), 'path': normalize(path)}
for path in self.recent
]
self.values['recent'] = recent
def asdict(self, path=None):
if not path:
path = self.path()
if core.exists(path):
return read_json(path)
# We couldn't find ~/.config/git-cola, try ~/.cola
values = {}
path = os.path.join(core.expanduser('~'), '.cola')
if core.exists(path):
json_values = read_json(path)
for key in self.values:
try:
values[key] = json_values[key]
except KeyError:
pass
# Ensure that all stored bookmarks use normalized paths ("/" only).
normalize = display.normalize_path
for entry in values.get('bookmarks', []):
entry['path'] = normalize(entry['path'])
for entry in values.get('recent', []):
entry['path'] = normalize(entry['path'])
return values
def save_gui_state(self, gui, sync=True):
"""Saves settings for a widget"""
name = gui.name()
self.gui_state[name] = mkdict(gui.export_state())
self.save(sync=sync)
def get_gui_state(self, gui):
"""Returns the saved state for a tool"""
return self.get(gui.name())
def get(self, gui_name):
"""Returns the saved state for a tool by name"""
try:
state = mkdict(self.gui_state[gui_name])
except KeyError:
state = self.gui_state[gui_name] = {}
return state
def get_value(self, name, key, default=None):
"""Return a specific setting value for the specified tool and setting key"""
return self.get(name).get(key, default)
def set_value(self, name, key, value, save=True, sync=True):
"""Store a specific setting value for the specified tool and setting key value"""
values = self.get(name)
values[key] = value
if save:
self.save(sync=sync)
def rename_entry(entries, path, name, new_name):
normalize = display.normalize_path
path = normalize(path)
entry = {'name': name, 'path': path}
try:
index = entries.index(entry)
except ValueError:
return False
if all(item['name'] != new_name for item in entries):
entries[index]['name'] = new_name
result = True
else:
result = False
return result
class Session(Settings):
"""Store per-session settings
XDG sessions are created by the QApplication::commitData() callback.
These sessions are stored once, and loaded once. They are deleted once
loaded. The behavior of path() is such that it forgets its session path()
and behaves like a return Settings object after the session has been
loaded once.
Once the session is loaded, it is removed and further calls to save()
will save to the usual $XDG_CONFIG_HOME/git-cola/settings location.
"""
_sessions_dir = resources.config_home('sessions')
repo = property(lambda self: self.values['local'])
def __init__(self, session_id, repo=None):
Settings.__init__(self)
self.session_id = session_id
self.values.update({'local': repo})
self.expired = False
def session_path(self):
"""The session-specific session file"""
return os.path.join(self._sessions_dir, self.session_id)
def path(self):
base_path = super().path()
if self.expired:
path = base_path
else:
path = self.session_path()
if not os.path.exists(path):
path = base_path
return path
def load(self, path=None):
"""Load the session and expire it for future loads
The session should be loaded only once. We remove the session file
when it's loaded, and set the session to be expired. This results in
future calls to load() and save() using the default Settings path
rather than the session-specific path.
The use case for sessions is when the user logs out with apps running.
We will restore their state, and if they then shutdown, it'll be just
like a normal shutdown and settings will be stored to
~/.config/git-cola/settings instead of the session path.
This is accomplished by "expiring" the session after it has
been loaded initially.
"""
result = super().load(path=path)
# This is the initial load, so expire the session and remove the
# session state file. Future calls will be equivalent to
# Settings.load().
if not self.expired:
self.expired = True
path = self.session_path()
if core.exists(path):
try:
os.unlink(path)
except (OSError, ValueError):
pass
return True
return False
return result
def update(self):
"""Reload settings from the base settings path"""
# This method does not expire the session.
path = super().path()
return super().load(path=path)
| 13,449 | Python | .py | 338 | 30.488166 | 89 | 0.602361 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
39 | cmds.py | git-cola_git-cola/cola/cmds.py | """Editor commands"""
import os
import re
import sys
from fnmatch import fnmatch
from io import StringIO
try:
from send2trash import send2trash
except ImportError:
send2trash = None
from . import compat
from . import core
from . import gitcmds
from . import icons
from . import resources
from . import textwrap
from . import utils
from . import version
from .cmd import ContextCommand
from .git import STDOUT
from .git import MISSING_BLOB_OID
from .i18n import N_
from .interaction import Interaction
from .models import main
from .models import prefs
class UsageError(Exception):
"""Exception class for usage errors."""
def __init__(self, title, message):
Exception.__init__(self, message)
self.title = title
self.msg = message
class EditModel(ContextCommand):
"""Commands that mutate the main model diff data"""
UNDOABLE = True
def __init__(self, context):
"""Common edit operations on the main model"""
super().__init__(context)
self.old_diff_text = self.model.diff_text
self.old_filename = self.model.filename
self.old_mode = self.model.mode
self.old_diff_type = self.model.diff_type
self.old_file_type = self.model.file_type
self.new_diff_text = self.old_diff_text
self.new_filename = self.old_filename
self.new_mode = self.old_mode
self.new_diff_type = self.old_diff_type
self.new_file_type = self.old_file_type
def do(self):
"""Perform the operation."""
self.model.filename = self.new_filename
self.model.set_mode(self.new_mode)
self.model.set_diff_text(self.new_diff_text)
self.model.set_diff_type(self.new_diff_type)
self.model.set_file_type(self.new_file_type)
def undo(self):
"""Undo the operation."""
self.model.filename = self.old_filename
self.model.set_mode(self.old_mode)
self.model.set_diff_text(self.old_diff_text)
self.model.set_diff_type(self.old_diff_type)
self.model.set_file_type(self.old_file_type)
class ConfirmAction(ContextCommand):
"""Confirm an action before running it"""
def ok_to_run(self):
"""Return True when the command is okay to run"""
return True
def confirm(self):
"""Prompt for confirmation"""
return True
def action(self):
"""Run the command and return (status, out, err)"""
return (-1, '', '')
def success(self):
"""Callback run on success"""
return
def command(self):
"""Command name, for error messages"""
return 'git'
def error_message(self):
"""Command error message"""
return ''
def do(self):
"""Prompt for confirmation before running a command"""
status = -1
out = err = ''
ok = self.ok_to_run() and self.confirm()
if ok:
status, out, err = self.action()
if status == 0:
self.success()
title = self.error_message()
cmd = self.command()
Interaction.command(title, cmd, status, out, err)
return ok, status, out, err
class AbortApplyPatch(ConfirmAction):
"""Reset an in-progress "git am" patch application"""
def confirm(self):
title = N_('Abort Applying Patch...')
question = N_('Aborting applying the current patch?')
info = N_(
'Aborting a patch can cause uncommitted changes to be lost.\n'
'Recovering uncommitted changes is not possible.'
)
ok_txt = N_('Abort Applying Patch')
return Interaction.confirm(
title, question, info, ok_txt, default=False, icon=icons.undo()
)
def action(self):
status, out, err = gitcmds.abort_apply_patch(self.context)
self.model.update_file_merge_status()
return status, out, err
def success(self):
self.model.set_commitmsg('')
def error_message(self):
return N_('Error')
def command(self):
return 'git am --abort'
class AbortCherryPick(ConfirmAction):
"""Reset an in-progress cherry-pick"""
def confirm(self):
title = N_('Abort Cherry-Pick...')
question = N_('Aborting the current cherry-pick?')
info = N_(
'Aborting a cherry-pick can cause uncommitted changes to be lost.\n'
'Recovering uncommitted changes is not possible.'
)
ok_txt = N_('Abort Cherry-Pick')
return Interaction.confirm(
title, question, info, ok_txt, default=False, icon=icons.undo()
)
def action(self):
status, out, err = gitcmds.abort_cherry_pick(self.context)
self.model.update_file_merge_status()
return status, out, err
def success(self):
self.model.set_commitmsg('')
def error_message(self):
return N_('Error')
def command(self):
return 'git cherry-pick --abort'
class AbortMerge(ConfirmAction):
"""Reset an in-progress merge back to HEAD"""
def confirm(self):
title = N_('Abort Merge...')
question = N_('Aborting the current merge?')
info = N_(
'Aborting the current merge will cause '
'*ALL* uncommitted changes to be lost.\n'
'Recovering uncommitted changes is not possible.'
)
ok_txt = N_('Abort Merge')
return Interaction.confirm(
title, question, info, ok_txt, default=False, icon=icons.undo()
)
def action(self):
status, out, err = gitcmds.abort_merge(self.context)
self.model.update_file_merge_status()
return status, out, err
def success(self):
self.model.set_commitmsg('')
def error_message(self):
return N_('Error')
def command(self):
return 'git merge'
class AmendMode(EditModel):
"""Try to amend a commit."""
UNDOABLE = True
LAST_MESSAGE = None
@staticmethod
def name():
return N_('Amend')
def __init__(self, context, amend=True):
super().__init__(context)
self.skip = False
self.amending = amend
self.old_commitmsg = self.model.commitmsg
self.old_mode = self.model.mode
if self.amending:
self.new_mode = self.model.mode_amend
self.new_commitmsg = gitcmds.prev_commitmsg(context)
AmendMode.LAST_MESSAGE = self.model.commitmsg
return
# else, amend unchecked, regular commit
self.new_mode = self.model.mode_none
self.new_diff_text = ''
self.new_commitmsg = self.model.commitmsg
# If we're going back into new-commit-mode then search the
# undo stack for a previous amend-commit-mode and grab the
# commit message at that point in time.
if AmendMode.LAST_MESSAGE is not None:
self.new_commitmsg = AmendMode.LAST_MESSAGE
AmendMode.LAST_MESSAGE = None
def do(self):
"""Leave/enter amend mode."""
# Attempt to enter amend mode. Do not allow this when merging.
if self.amending:
if self.model.is_merging:
self.skip = True
self.model.set_mode(self.old_mode)
Interaction.information(
N_('Cannot Amend'),
N_(
'You are in the middle of a merge.\n'
'Cannot amend while merging.'
),
)
return
self.skip = False
super().do()
self.model.set_commitmsg(self.new_commitmsg)
self.model.update_file_status()
self.context.selection.reset(emit=True)
def undo(self):
if self.skip:
return
self.model.set_commitmsg(self.old_commitmsg)
super().undo()
self.model.update_file_status()
self.context.selection.reset(emit=True)
class AnnexAdd(ContextCommand):
"""Add to Git Annex"""
def __init__(self, context):
super().__init__(context)
self.filename = self.selection.filename()
def do(self):
status, out, err = self.git.annex('add', self.filename)
Interaction.command(N_('Error'), 'git annex add', status, out, err)
self.model.update_status()
class AnnexInit(ContextCommand):
"""Initialize Git Annex"""
def do(self):
status, out, err = self.git.annex('init')
Interaction.command(N_('Error'), 'git annex init', status, out, err)
self.model.cfg.reset()
self.model.emit_updated()
class LFSTrack(ContextCommand):
"""Add a file to git lfs"""
def __init__(self, context):
super().__init__(context)
self.filename = self.selection.filename()
self.stage_cmd = Stage(context, [self.filename])
def do(self):
status, out, err = self.git.lfs('track', self.filename)
Interaction.command(N_('Error'), 'git lfs track', status, out, err)
if status == 0:
self.stage_cmd.do()
class LFSInstall(ContextCommand):
"""Initialize git lfs"""
def do(self):
status, out, err = self.git.lfs('install')
Interaction.command(N_('Error'), 'git lfs install', status, out, err)
self.model.update_config(reset=True, emit=True)
class ApplyPatch(ContextCommand):
"""Apply the specified patch to the worktree or index"""
def __init__(
self,
context,
patch,
encoding,
apply_to_worktree,
):
super().__init__(context)
self.patch = patch
self.encoding = encoding
self.apply_to_worktree = apply_to_worktree
def do(self):
context = self.context
tmp_file = utils.tmp_filename('apply', suffix='.patch')
try:
core.write(tmp_file, self.patch.as_text(), encoding=self.encoding)
if self.apply_to_worktree:
status, out, err = gitcmds.apply_diff_to_worktree(context, tmp_file)
else:
status, out, err = gitcmds.apply_diff(context, tmp_file)
finally:
core.unlink(tmp_file)
Interaction.log_status(status, out, err)
self.model.update_file_status(update_index=True)
class ApplyPatches(ContextCommand):
"""Apply patches using the "git am" command"""
def __init__(self, context, patches):
super().__init__(context)
self.patches = patches
def do(self):
status, output, err = self.git.am('-3', *self.patches)
out = f'# git am -3 {core.list2cmdline(self.patches)}\n\n{output}'
Interaction.command(N_('Patch failed to apply'), 'git am -3', status, out, err)
# Display a diffstat
self.model.update_file_status()
patch_basenames = [os.path.basename(p) for p in self.patches]
if len(patch_basenames) > 25:
patch_basenames = patch_basenames[:25]
patch_basenames.append('...')
basenames = '\n'.join(patch_basenames)
if status == 0:
Interaction.information(
N_('Patch(es) Applied'),
(N_('%d patch(es) applied.') + '\n\n%s')
% (len(self.patches), basenames),
)
class ApplyPatchesContinue(ContextCommand):
"""Run "git am --continue" to continue on the next patch in a "git am" session"""
def do(self):
status, out, err = self.git.am('--continue')
Interaction.command(
N_('Failed to commit and continue applying patches'),
'git am --continue',
status,
out,
err,
)
self.model.update_status()
return status, out, err
class ApplyPatchesSkip(ContextCommand):
"""Run "git am --skip" to continue on the next patch in a "git am" session"""
def do(self):
status, out, err = self.git.am(skip=True)
Interaction.command(
N_('Failed to continue applying patches after skipping the current patch'),
'git am --skip',
status,
out,
err,
)
self.model.update_status()
return status, out, err
class Archive(ContextCommand):
""" "Export archives using the "git archive" command"""
def __init__(self, context, ref, fmt, prefix, filename):
super().__init__(context)
self.ref = ref
self.fmt = fmt
self.prefix = prefix
self.filename = filename
def do(self):
fp = core.xopen(self.filename, 'wb')
cmd = ['git', 'archive', '--format=' + self.fmt]
if self.fmt in ('tgz', 'tar.gz'):
cmd.append('-9')
if self.prefix:
cmd.append('--prefix=' + self.prefix)
cmd.append(self.ref)
proc = core.start_command(cmd, stdout=fp)
out, err = proc.communicate()
fp.close()
status = proc.returncode
Interaction.log_status(status, out or '', err or '')
class Checkout(EditModel):
"""A command object for git-checkout.
The argv list is forwarded directly to git.
"""
def __init__(self, context, argv, checkout_branch=False):
super().__init__(context)
self.argv = argv
self.checkout_branch = checkout_branch
self.new_diff_text = ''
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
def do(self):
super().do()
status, out, err = self.git.checkout(*self.argv)
if self.checkout_branch:
self.model.update_status()
else:
self.model.update_file_status()
Interaction.command(N_('Error'), 'git checkout', status, out, err)
return status, out, err
class CheckoutTheirs(ConfirmAction):
"""Checkout "their" version of a file when performing a merge"""
@staticmethod
def name():
return N_('Checkout files from their branch (MERGE_HEAD)')
def confirm(self):
title = self.name()
question = N_('Checkout files from their branch?')
info = N_(
'This operation will replace the selected unmerged files with content '
'from the branch being merged using "git checkout --theirs".\n'
'*ALL* uncommitted changes will be lost.\n'
'Recovering uncommitted changes is not possible.'
)
ok_txt = N_('Checkout Files')
return Interaction.confirm(
title, question, info, ok_txt, default=True, icon=icons.merge()
)
def action(self):
selection = self.selection.selection()
paths = selection.unmerged
if not paths:
return 0, '', ''
argv = ['--theirs', '--'] + paths
cmd = Checkout(self.context, argv)
return cmd.do()
def error_message(self):
return N_('Error')
def command(self):
return 'git checkout --theirs'
class CheckoutOurs(ConfirmAction):
"""Checkout "our" version of a file when performing a merge"""
@staticmethod
def name():
return N_('Checkout files from our branch (HEAD)')
def confirm(self):
title = self.name()
question = N_('Checkout files from our branch?')
info = N_(
'This operation will replace the selected unmerged files with content '
'from your current branch using "git checkout --ours".\n'
'*ALL* uncommitted changes will be lost.\n'
'Recovering uncommitted changes is not possible.'
)
ok_txt = N_('Checkout Files')
return Interaction.confirm(
title, question, info, ok_txt, default=True, icon=icons.merge()
)
def action(self):
selection = self.selection.selection()
paths = selection.unmerged
if not paths:
return 0, '', ''
argv = ['--ours', '--'] + paths
cmd = Checkout(self.context, argv)
return cmd.do()
def error_message(self):
return N_('Error')
def command(self):
return 'git checkout --ours'
class BlamePaths(ContextCommand):
"""Blame view for paths."""
@staticmethod
def name():
return N_('Blame...')
def __init__(self, context, paths=None):
super().__init__(context)
if not paths:
paths = context.selection.union()
viewer = utils.shell_split(prefs.blame_viewer(context))
self.argv = viewer + list(paths)
def do(self):
try:
core.fork(self.argv)
except OSError as e:
_, details = utils.format_exception(e)
title = N_('Error Launching Blame Viewer')
msg = N_('Cannot exec "%s": please configure a blame viewer') % ' '.join(
self.argv
)
Interaction.critical(title, message=msg, details=details)
class CheckoutBranch(Checkout):
"""Checkout a branch."""
def __init__(self, context, branch):
args = [branch]
super().__init__(context, args, checkout_branch=True)
class CherryPick(ContextCommand):
"""Cherry pick commits into the current branch."""
def __init__(self, context, commits):
super().__init__(context)
self.commits = commits
def do(self):
status, out, err = gitcmds.cherry_pick(self.context, self.commits)
self.model.update_file_merge_status()
title = N_('Cherry-pick failed')
Interaction.command(title, 'git cherry-pick', status, out, err)
class Revert(ContextCommand):
"""Revert a commit"""
def __init__(self, context, oid):
super().__init__(context)
self.oid = oid
def do(self):
status, out, err = self.git.revert(self.oid, no_edit=True)
self.model.update_file_status()
title = N_('Revert failed')
out = '# git revert %s\n\n' % self.oid
Interaction.command(title, 'git revert', status, out, err)
class ResetMode(EditModel):
"""Reset the mode and clear the model's diff text."""
def __init__(self, context):
super().__init__(context)
self.new_mode = self.model.mode_none
self.new_diff_text = ''
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
self.new_filename = ''
def do(self):
super().do()
self.model.update_file_status()
self.context.selection.reset(emit=True)
class ResetCommand(ConfirmAction):
"""Reset state using the "git reset" command"""
def __init__(self, context, ref):
super().__init__(context)
self.ref = ref
def action(self):
return self.reset()
def command(self):
return 'git reset'
def error_message(self):
return N_('Error')
def success(self):
self.model.update_file_status()
def confirm(self):
raise NotImplementedError('confirm() must be overridden')
def reset(self):
raise NotImplementedError('reset() must be overridden')
class ResetMixed(ResetCommand):
@staticmethod
def tooltip(ref):
tooltip = N_('The branch will be reset using "git reset --mixed %s"')
return tooltip % ref
def confirm(self):
title = N_('Reset Branch and Stage (Mixed)')
question = N_('Point the current branch head to a new commit?')
info = self.tooltip(self.ref)
ok_text = N_('Reset Branch')
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.git.reset(self.ref, '--', mixed=True)
class ResetKeep(ResetCommand):
@staticmethod
def tooltip(ref):
tooltip = N_('The repository will be reset using "git reset --keep %s"')
return tooltip % ref
def confirm(self):
title = N_('Restore Worktree and Reset All (Keep Unstaged Changes)')
question = N_('Restore worktree, reset, and preserve unstaged edits?')
info = self.tooltip(self.ref)
ok_text = N_('Reset and Restore')
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.git.reset(self.ref, '--', keep=True)
class ResetMerge(ResetCommand):
@staticmethod
def tooltip(ref):
tooltip = N_('The repository will be reset using "git reset --merge %s"')
return tooltip % ref
def confirm(self):
title = N_('Restore Worktree and Reset All (Merge)')
question = N_('Reset Worktree and Reset All?')
info = self.tooltip(self.ref)
ok_text = N_('Reset and Restore')
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.git.reset(self.ref, '--', merge=True)
class ResetSoft(ResetCommand):
@staticmethod
def tooltip(ref):
tooltip = N_('The branch will be reset using "git reset --soft %s"')
return tooltip % ref
def confirm(self):
title = N_('Reset Branch (Soft)')
question = N_('Reset branch?')
info = self.tooltip(self.ref)
ok_text = N_('Reset Branch')
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.git.reset(self.ref, '--', soft=True)
class ResetHard(ResetCommand):
@staticmethod
def tooltip(ref):
tooltip = N_('The repository will be reset using "git reset --hard %s"')
return tooltip % ref
def confirm(self):
title = N_('Restore Worktree and Reset All (Hard)')
question = N_('Restore Worktree and Reset All?')
info = self.tooltip(self.ref)
ok_text = N_('Reset and Restore')
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.git.reset(self.ref, '--', hard=True)
class RestoreWorktree(ConfirmAction):
"""Reset the worktree using the "git read-tree" command"""
@staticmethod
def tooltip(ref):
tooltip = N_(
'The worktree will be restored using "git read-tree --reset -u %s"'
)
return tooltip % ref
def __init__(self, context, ref):
super().__init__(context)
self.ref = ref
def action(self):
return self.git.read_tree(self.ref, reset=True, u=True)
def command(self):
return 'git read-tree --reset -u %s' % self.ref
def error_message(self):
return N_('Error')
def success(self):
self.model.update_file_status()
def confirm(self):
title = N_('Restore Worktree')
question = N_('Restore Worktree to %s?') % self.ref
info = self.tooltip(self.ref)
ok_text = N_('Restore Worktree')
return Interaction.confirm(title, question, info, ok_text)
class UndoLastCommit(ResetCommand):
"""Undo the last commit"""
# NOTE: this is the similar to ResetSoft() with an additional check for
# published commits and different messages.
def __init__(self, context):
super().__init__(context, 'HEAD^')
def confirm(self):
check_published = prefs.check_published_commits(self.context)
if check_published and self.model.is_commit_published():
return 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_('Undo the published commit?'),
N_('Undo Last Commit'),
default=False,
icon=icons.save(),
)
title = N_('Undo Last Commit')
question = N_('Undo last commit?')
info = N_('The branch will be reset using "git reset --soft %s"')
ok_text = N_('Undo Last Commit')
info_text = info % self.ref
return Interaction.confirm(title, question, info_text, ok_text)
def reset(self):
return self.git.reset('HEAD^', '--', soft=True)
class Commit(ResetMode):
"""Attempt to create a new commit."""
def __init__(self, context, amend, msg, sign, no_verify=False, date=None):
super().__init__(context)
self.amend = amend
self.msg = msg
self.sign = sign
self.no_verify = no_verify
self.old_commitmsg = self.model.commitmsg
self.new_commitmsg = ''
self.date = date
def do(self):
# Create the commit message file
context = self.context
msg = self.msg
tmp_file = utils.tmp_filename('commit-message')
add_env = {
'NO_COLOR': '1',
'TERM': 'dumb',
}
kwargs = {}
if self.date:
add_env['GIT_AUTHOR_DATE'] = self.date
add_env['GIT_COMMITTER_DATE'] = self.date
kwargs['date'] = self.date
try:
core.write(tmp_file, msg)
# Run 'git commit'
status, out, err = self.git.commit(
_add_env=add_env,
F=tmp_file,
v=True,
gpg_sign=self.sign,
amend=self.amend,
no_verify=self.no_verify,
**kwargs,
)
finally:
core.unlink(tmp_file)
if status == 0:
super().do()
if context.cfg.get(prefs.AUTOTEMPLATE):
template_loader = LoadCommitMessageFromTemplate(context)
template_loader.do()
else:
self.model.set_commitmsg(self.new_commitmsg)
return status, out, err
@staticmethod
def strip_comments(msg, comment_char='#'):
# Strip off comments
message_lines = [
line for line in msg.split('\n') if not line.startswith(comment_char)
]
msg = '\n'.join(message_lines)
if not msg.endswith('\n'):
msg += '\n'
return msg
class CycleReferenceSort(ContextCommand):
"""Choose the next reference sort type"""
def do(self):
self.model.cycle_ref_sort()
class Ignore(ContextCommand):
"""Add files to an exclusion file"""
def __init__(self, context, filenames, local=False):
super().__init__(context)
self.filenames = list(filenames)
self.local = local
def do(self):
if not self.filenames:
return
new_additions = '\n'.join(self.filenames) + '\n'
for_status = new_additions
if self.local:
filename = self.git.git_path('info', 'exclude')
else:
filename = '.gitignore'
if core.exists(filename):
current_list = core.read(filename)
new_additions = current_list.rstrip() + '\n' + new_additions
core.write(filename, new_additions)
Interaction.log_status(0, f'Added to {filename}:\n{for_status}', '')
self.model.update_file_status()
def file_summary(files):
txt = core.list2cmdline(files)
if len(txt) > 768:
txt = txt[:768].rstrip() + '...'
wrap = textwrap.TextWrapper()
return '\n'.join(wrap.wrap(txt))
class RemoteCommand(ConfirmAction):
def __init__(self, context, remote):
super().__init__(context)
self.remote = remote
def success(self):
self.cfg.reset()
self.model.update_remotes()
class RemoteAdd(RemoteCommand):
def __init__(self, context, remote, url):
super().__init__(context, remote)
self.url = url
def action(self):
return self.git.remote('add', self.remote, self.url)
def error_message(self):
return N_('Error creating remote "%s"') % self.remote
def command(self):
return f'git remote add "{self.remote}" "{self.url}"'
class RemoteRemove(RemoteCommand):
def confirm(self):
title = N_('Delete Remote')
question = N_('Delete remote?')
info = N_('Delete remote "%s"') % self.remote
ok_text = N_('Delete')
return Interaction.confirm(title, question, info, ok_text)
def action(self):
return self.git.remote('rm', self.remote)
def error_message(self):
return N_('Error deleting remote "%s"') % self.remote
def command(self):
return 'git remote rm "%s"' % self.remote
class RemoteRename(RemoteCommand):
def __init__(self, context, remote, new_name):
super().__init__(context, remote)
self.new_name = new_name
def confirm(self):
title = N_('Rename Remote')
text = N_('Rename remote "%(current)s" to "%(new)s"?') % {
'current': self.remote,
'new': self.new_name,
}
info_text = ''
ok_text = title
return Interaction.confirm(title, text, info_text, ok_text)
def action(self):
return self.git.remote('rename', self.remote, self.new_name)
def error_message(self):
return N_('Error renaming "%(name)s" to "%(new_name)s"') % {
'name': self.remote,
'new_name': self.new_name,
}
def command(self):
return f'git remote rename "{self.remote}" "{self.new_name}"'
class RemoteSetURL(RemoteCommand):
def __init__(self, context, remote, url):
super().__init__(context, remote)
self.url = url
def action(self):
return self.git.remote('set-url', self.remote, self.url)
def error_message(self):
return N_('Unable to set URL for "%(name)s" to "%(url)s"') % {
'name': self.remote,
'url': self.url,
}
def command(self):
return f'git remote set-url "{self.remote}" "{self.url}"'
class RemoteEdit(ContextCommand):
"""Combine RemoteRename and RemoteSetURL"""
def __init__(self, context, old_name, remote, url):
super().__init__(context)
self.rename = RemoteRename(context, old_name, remote)
self.set_url = RemoteSetURL(context, remote, url)
def do(self):
result = self.rename.do()
name_ok = result[0]
url_ok = False
if name_ok:
result = self.set_url.do()
url_ok = result[0]
return name_ok, url_ok
class RemoveFromSettings(ConfirmAction):
def __init__(self, context, repo, entry, icon=None):
super().__init__(context)
self.context = context
self.repo = repo
self.entry = entry
self.icon = icon
def success(self):
self.context.settings.save()
class RemoveBookmark(RemoveFromSettings):
def confirm(self):
entry = self.entry
title = msg = N_('Delete Bookmark?')
info = N_('%s will be removed from your bookmarks.') % entry
ok_text = N_('Delete Bookmark')
return Interaction.confirm(title, msg, info, ok_text, icon=self.icon)
def action(self):
self.context.settings.remove_bookmark(self.repo, self.entry)
return (0, '', '')
class RemoveRecent(RemoveFromSettings):
def confirm(self):
repo = self.repo
title = msg = N_('Remove %s from the recent list?') % repo
info = N_('%s will be removed from your recent repositories.') % repo
ok_text = N_('Remove')
return Interaction.confirm(title, msg, info, ok_text, icon=self.icon)
def action(self):
self.context.settings.remove_recent(self.repo)
return (0, '', '')
class RemoveFiles(ContextCommand):
"""Removes files"""
def __init__(self, context, remover, filenames):
super().__init__(context)
if remover is None:
remover = os.remove
self.remover = remover
self.filenames = filenames
# We could git-hash-object stuff and provide undo-ability
# as an option. Heh.
def do(self):
files = self.filenames
if not files:
return
rescan = False
bad_filenames = []
remove = self.remover
for filename in files:
if filename:
try:
remove(filename)
rescan = True
except OSError:
bad_filenames.append(filename)
if bad_filenames:
Interaction.information(
N_('Error'), N_('Deleting "%s" failed') % file_summary(bad_filenames)
)
if rescan:
self.model.update_file_status()
class Delete(RemoveFiles):
"""Delete files."""
def __init__(self, context, filenames):
super().__init__(context, os.remove, filenames)
def do(self):
files = self.filenames
if not files:
return
title = N_('Delete Files?')
msg = N_('The following files will be deleted:') + '\n\n'
msg += file_summary(files)
info_txt = N_('Delete %d file(s)?') % len(files)
ok_txt = N_('Delete Files')
if Interaction.confirm(
title, msg, info_txt, ok_txt, default=True, icon=icons.remove()
):
super().do()
class MoveToTrash(RemoveFiles):
"""Move files to the trash using send2trash"""
AVAILABLE = send2trash is not None
def __init__(self, context, filenames):
super().__init__(context, send2trash, filenames)
class DeleteBranch(ConfirmAction):
"""Delete a git branch."""
def __init__(self, context, branch):
super().__init__(context)
self.branch = branch
def confirm(self):
title = N_('Delete Branch')
question = N_('Delete branch "%s"?') % self.branch
info = N_('The branch will be no longer available.')
ok_txt = N_('Delete Branch')
return Interaction.confirm(
title, question, info, ok_txt, default=True, icon=icons.discard()
)
def action(self):
return self.model.delete_branch(self.branch)
def error_message(self):
return N_('Error deleting branch "%s"' % self.branch)
def command(self):
command = 'git branch -D %s'
return command % self.branch
class Rename(ContextCommand):
"""Rename a set of paths."""
def __init__(self, context, paths):
super().__init__(context)
self.paths = paths
def do(self):
msg = N_('Untracking: %s') % (', '.join(self.paths))
Interaction.log(msg)
for path in self.paths:
ok = self.rename(path)
if not ok:
return
self.model.update_status()
def rename(self, path):
git = self.git
title = N_('Rename "%s"') % path
if os.path.isdir(path):
base_path = os.path.dirname(path)
else:
base_path = path
new_path = Interaction.save_as(base_path, title)
if not new_path:
return False
status, out, err = git.mv(path, new_path, force=True, verbose=True)
Interaction.command(N_('Error'), 'git mv', status, out, err)
return status == 0
class RenameBranch(ContextCommand):
"""Rename a git branch."""
def __init__(self, context, branch, new_branch):
super().__init__(context)
self.branch = branch
self.new_branch = new_branch
def do(self):
branch = self.branch
new_branch = self.new_branch
status, out, err = self.model.rename_branch(branch, new_branch)
Interaction.log_status(status, out, err)
class DeleteRemoteBranch(DeleteBranch):
"""Delete a remote git branch."""
def __init__(self, context, remote, branch):
super().__init__(context, branch)
self.remote = remote
def action(self):
kwargs = {}
main.autodetect_proxy(self.context, kwargs)
main.no_color(kwargs)
return self.git.push(self.remote, self.branch, delete=True, **kwargs)
def success(self):
self.model.update_status()
Interaction.information(
N_('Remote Branch Deleted'),
N_('"%(branch)s" has been deleted from "%(remote)s".')
% {
'branch': self.branch,
'remote': self.remote,
},
)
def error_message(self):
return N_('Error Deleting Remote Branch')
def command(self):
command = 'git push --delete %s %s'
return command % (self.remote, self.branch)
def get_mode(context, filename, staged, modified, unmerged, untracked):
model = context.model
if staged:
mode = model.mode_index
elif modified or unmerged:
mode = model.mode_worktree
elif untracked:
if gitcmds.is_binary(context, filename):
mode = model.mode_untracked
else:
mode = model.mode_untracked_diff
else:
mode = model.mode
return mode
class DiffAgainstCommitMode(ContextCommand):
"""Diff against arbitrary commits"""
def __init__(self, context, oid):
super().__init__(context)
self.oid = oid
def do(self):
self.model.set_mode(self.model.mode_diff, head=self.oid)
self.model.update_file_status()
class DiffText(EditModel):
"""Set the diff type to text"""
def __init__(self, context):
super().__init__(context)
self.new_file_type = main.Types.TEXT
self.new_diff_type = main.Types.TEXT
class ToggleDiffType(ContextCommand):
"""Toggle the diff type between image and text"""
def __init__(self, context):
super().__init__(context)
if self.model.diff_type == main.Types.IMAGE:
self.new_diff_type = main.Types.TEXT
self.new_value = False
else:
self.new_diff_type = main.Types.IMAGE
self.new_value = True
def do(self):
diff_type = self.new_diff_type
value = self.new_value
self.model.set_diff_type(diff_type)
filename = self.model.filename
_, ext = os.path.splitext(filename)
if ext.startswith('.'):
cfg = 'cola.imagediff' + ext
self.cfg.set_repo(cfg, value)
class DiffImage(EditModel):
def __init__(
self, context, filename, deleted, staged, modified, unmerged, untracked
):
super().__init__(context)
self.new_filename = filename
self.new_diff_type = self.get_diff_type(filename)
self.new_file_type = main.Types.IMAGE
self.new_mode = get_mode(
context, filename, staged, modified, unmerged, untracked
)
self.staged = staged
self.modified = modified
self.unmerged = unmerged
self.untracked = untracked
self.deleted = deleted
self.annex = self.cfg.is_annex()
def get_diff_type(self, filename):
"""Query the diff type to use based on cola.imagediff.<extension>"""
_, ext = os.path.splitext(filename)
if ext.startswith('.'):
# Check e.g. "cola.imagediff.svg" to see if we should imagediff.
cfg = 'cola.imagediff' + ext
if self.cfg.get(cfg, True):
result = main.Types.IMAGE
else:
result = main.Types.TEXT
else:
result = main.Types.IMAGE
return result
def do(self):
filename = self.new_filename
if self.staged:
images = self.staged_images()
elif self.modified:
images = self.modified_images()
elif self.unmerged:
images = self.unmerged_images()
elif self.untracked:
images = [(filename, False)]
else:
images = []
self.model.set_images(images)
super().do()
def staged_images(self):
context = self.context
git = self.git
head = self.model.head
filename = self.new_filename
annex = self.annex
images = []
index = git.diff_index(head, '--', filename, cached=True)[STDOUT]
if index:
# Example:
# :100644 100644 fabadb8... 4866510... M describe.c
parts = index.split(' ')
if len(parts) > 3:
old_oid = parts[2]
new_oid = parts[3]
if old_oid != MISSING_BLOB_OID:
# First, check if we can get a pre-image from git-annex
annex_image = None
if annex:
annex_image = gitcmds.annex_path(context, head, filename)
if annex_image:
images.append((annex_image, False)) # git annex HEAD
else:
image = gitcmds.write_blob_path(context, head, old_oid, filename)
if image:
images.append((image, True))
if new_oid != MISSING_BLOB_OID:
found_in_annex = False
if annex and core.islink(filename):
status, out, _ = git.annex('status', '--', filename)
if status == 0:
details = out.split(' ')
if details and details[0] == 'A': # newly added file
images.append((filename, False))
found_in_annex = True
if not found_in_annex:
image = gitcmds.write_blob(context, new_oid, filename)
if image:
images.append((image, True))
return images
def unmerged_images(self):
context = self.context
git = self.git
head = self.model.head
filename = self.new_filename
annex = self.annex
candidate_merge_heads = ('HEAD', 'CHERRY_HEAD', 'MERGE_HEAD')
merge_heads = [
merge_head
for merge_head in candidate_merge_heads
if core.exists(git.git_path(merge_head))
]
if annex: # Attempt to find files in git-annex
annex_images = []
for merge_head in merge_heads:
image = gitcmds.annex_path(context, merge_head, filename)
if image:
annex_images.append((image, False))
if annex_images:
annex_images.append((filename, False))
return annex_images
# DIFF FORMAT FOR MERGES
# "git-diff-tree", "git-diff-files" and "git-diff --raw"
# can take -c or --cc option to generate diff output also
# for merge commits. The output differs from the format
# described above in the following way:
#
# 1. there is a colon for each parent
# 2. there are more "src" modes and "src" sha1
# 3. status is concatenated status characters for each parent
# 4. no optional "score" number
# 5. single path, only for "dst"
# Example:
# ::100644 100644 100644 fabadb8... cc95eb0... 4866510... \
# MM describe.c
images = []
index = git.diff_index(head, '--', filename, cached=True, cc=True)[STDOUT]
if index:
parts = index.split(' ')
if len(parts) > 3:
first_mode = parts[0]
num_parents = first_mode.count(':')
# colon for each parent, but for the index, the "parents"
# are really entries in stages 1,2,3 (head, base, remote)
# remote, base, head
for i in range(num_parents):
offset = num_parents + i + 1
oid = parts[offset]
try:
merge_head = merge_heads[i]
except IndexError:
merge_head = 'HEAD'
if oid != MISSING_BLOB_OID:
image = gitcmds.write_blob_path(
context, merge_head, oid, filename
)
if image:
images.append((image, True))
images.append((filename, False))
return images
def modified_images(self):
context = self.context
git = self.git
head = self.model.head
filename = self.new_filename
annex = self.annex
images = []
annex_image = None
if annex: # Check for a pre-image from git-annex
annex_image = gitcmds.annex_path(context, head, filename)
if annex_image:
images.append((annex_image, False)) # git annex HEAD
else:
worktree = git.diff_files('--', filename)[STDOUT]
parts = worktree.split(' ')
if len(parts) > 3:
oid = parts[2]
if oid != MISSING_BLOB_OID:
image = gitcmds.write_blob_path(context, head, oid, filename)
if image:
images.append((image, True)) # HEAD
images.append((filename, False)) # worktree
return images
class Diff(EditModel):
"""Perform a diff and set the model's current text."""
def __init__(self, context, filename, cached=False, deleted=False):
super().__init__(context)
opts = {}
if cached and gitcmds.is_valid_ref(context, self.model.head):
opts['ref'] = self.model.head
self.new_filename = filename
self.new_mode = self.model.mode_worktree
self.new_diff_text = gitcmds.diff_helper(
self.context, filename=filename, cached=cached, deleted=deleted, **opts
)
class Diffstat(EditModel):
"""Perform a diffstat and set the model's diff text."""
def __init__(self, context):
super().__init__(context)
cfg = self.cfg
diff_context = cfg.get('diff.context', 3)
diff = self.git.diff(
self.model.head,
unified=diff_context,
no_ext_diff=True,
no_color=True,
M=True,
stat=True,
)[STDOUT]
self.new_diff_text = diff
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
self.new_mode = self.model.mode_diffstat
class DiffStaged(Diff):
"""Perform a staged diff on a file."""
def __init__(self, context, filename, deleted=None):
super().__init__(context, filename, cached=True, deleted=deleted)
self.new_mode = self.model.mode_index
class DiffStagedSummary(EditModel):
def __init__(self, context):
super().__init__(context)
diff = self.git.diff(
self.model.head,
cached=True,
no_color=True,
no_ext_diff=True,
patch_with_stat=True,
M=True,
)[STDOUT]
self.new_diff_text = diff
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
self.new_mode = self.model.mode_index
class Edit(ContextCommand):
"""Edit a file using the configured gui.editor."""
@staticmethod
def name():
return N_('Launch Editor')
def __init__(self, context, filenames, line_number=None, background_editor=False):
super().__init__(context)
self.filenames = filenames
self.line_number = line_number
self.background_editor = background_editor
def do(self):
context = self.context
if not self.filenames:
return
filename = self.filenames[0]
if not core.exists(filename):
return
if self.background_editor:
editor = prefs.background_editor(context)
else:
editor = prefs.editor(context)
opts = []
if self.line_number is None:
opts = self.filenames
else:
# Single-file w/ line-numbers (likely from grep)
editor_opts = {
'*vim*': [filename, '+%s' % self.line_number],
'*emacs*': ['+%s' % self.line_number, filename],
'*textpad*': [f'{filename}({self.line_number},0)'],
'*notepad++*': ['-n%s' % self.line_number, filename],
'*subl*': [f'{filename}:{self.line_number}'],
}
opts = self.filenames
for pattern, opt in editor_opts.items():
if fnmatch(editor, pattern):
opts = opt
break
try:
core.fork(utils.shell_split(editor) + opts)
except (OSError, ValueError) as e:
message = N_('Cannot exec "%s": please configure your editor') % editor
_, details = utils.format_exception(e)
Interaction.critical(N_('Error Editing File'), message, details)
class FormatPatch(ContextCommand):
"""Output a patch series given all revisions and a selected subset."""
def __init__(self, context, to_export, revs, output='patches'):
super().__init__(context)
self.to_export = list(to_export)
self.revs = list(revs)
self.output = output
def do(self):
context = self.context
status, out, err = gitcmds.format_patchsets(
context, self.to_export, self.revs, self.output
)
Interaction.log_status(status, out, err)
class LaunchTerminal(ContextCommand):
@staticmethod
def name():
return N_('Launch Terminal')
@staticmethod
def is_available(context):
return context.cfg.terminal() is not None
def __init__(self, context, path):
super().__init__(context)
self.path = path
def do(self):
cmd = self.context.cfg.terminal()
if cmd is None:
return
if utils.is_win32():
argv = ['start', '', cmd, '--login']
shell = True
else:
argv = utils.shell_split(cmd)
command = '/bin/sh'
shells = ('zsh', 'fish', 'bash', 'sh')
for basename in shells:
executable = core.find_executable(basename)
if executable:
command = executable
break
argv.append(os.getenv('SHELL', command))
shell = False
core.fork(argv, cwd=self.path, shell=shell)
class LaunchEditor(Edit):
@staticmethod
def name():
return N_('Launch Editor')
def __init__(self, context):
s = context.selection.selection()
filenames = s.staged + s.unmerged + s.modified + s.untracked
super().__init__(context, filenames, background_editor=True)
class LaunchEditorAtLine(LaunchEditor):
"""Launch an editor at the specified line"""
def __init__(self, context):
super().__init__(context)
self.line_number = context.selection.line_number
class LoadCommitMessageFromFile(ContextCommand):
"""Loads a commit message from a path."""
UNDOABLE = True
def __init__(self, context, path):
super().__init__(context)
self.path = path
self.old_commitmsg = self.model.commitmsg
self.old_directory = self.model.directory
def do(self):
path = os.path.expanduser(self.path)
if not path or not core.isfile(path):
Interaction.log(N_('Error: Cannot find commit template'))
Interaction.log(N_('%s: No such file or directory.') % path)
return
self.model.set_directory(os.path.dirname(path))
self.model.set_commitmsg(core.read(path))
def undo(self):
self.model.set_commitmsg(self.old_commitmsg)
self.model.set_directory(self.old_directory)
class LoadCommitMessageFromTemplate(LoadCommitMessageFromFile):
"""Loads the commit message template specified by commit.template."""
def __init__(self, context):
cfg = context.cfg
template = cfg.get('commit.template')
super().__init__(context, template)
def do(self):
if self.path is None:
Interaction.log(N_('Error: Unconfigured commit template'))
Interaction.log(
N_(
'A commit template has not been configured.\n'
'Use "git config" to define "commit.template"\n'
'so that it points to a commit template.'
)
)
return
return LoadCommitMessageFromFile.do(self)
class LoadCommitMessageFromOID(ContextCommand):
"""Load a previous commit message"""
UNDOABLE = True
def __init__(self, context, oid, prefix=''):
super().__init__(context)
self.oid = oid
self.old_commitmsg = self.model.commitmsg
self.new_commitmsg = prefix + gitcmds.prev_commitmsg(context, oid)
def do(self):
self.model.set_commitmsg(self.new_commitmsg)
def undo(self):
self.model.set_commitmsg(self.old_commitmsg)
class PrepareCommitMessageHook(ContextCommand):
"""Use the cola-prepare-commit-msg hook to prepare the commit message"""
UNDOABLE = True
def __init__(self, context):
super().__init__(context)
self.old_commitmsg = self.model.commitmsg
def get_message(self):
title = N_('Error running prepare-commitmsg hook')
hook = gitcmds.prepare_commit_message_hook(self.context)
if os.path.exists(hook):
filename = self.model.save_commitmsg()
status, out, err = core.run_command([hook, filename])
if status == 0:
result = core.read(filename)
else:
result = self.old_commitmsg
Interaction.command_error(title, hook, status, out, err)
else:
message = N_('A hook must be provided at "%s"') % hook
Interaction.critical(title, message=message)
result = self.old_commitmsg
return result
def do(self):
msg = self.get_message()
self.model.set_commitmsg(msg)
def undo(self):
self.model.set_commitmsg(self.old_commitmsg)
class LoadFixupMessage(LoadCommitMessageFromOID):
"""Load a fixup message"""
def __init__(self, context, oid):
super().__init__(context, oid, prefix='fixup! ')
if self.new_commitmsg:
self.new_commitmsg = self.new_commitmsg.splitlines()[0]
class Merge(ContextCommand):
"""Merge commits"""
def __init__(self, context, revision, no_commit, squash, no_ff, sign):
super().__init__(context)
self.revision = revision
self.no_ff = no_ff
self.no_commit = no_commit
self.squash = squash
self.sign = sign
def do(self):
squash = self.squash
revision = self.revision
no_ff = self.no_ff
no_commit = self.no_commit
sign = self.sign
status, out, err = self.git.merge(
revision, gpg_sign=sign, no_ff=no_ff, no_commit=no_commit, squash=squash
)
self.model.update_status()
title = N_('Merge failed. Conflict resolution is required.')
Interaction.command(title, 'git merge', status, out, err)
return status, out, err
class OpenDefaultApp(ContextCommand):
"""Open a file using the OS default."""
@staticmethod
def name():
return N_('Open Using Default Application')
def __init__(self, context, filenames):
super().__init__(context)
self.filenames = filenames
def do(self):
if not self.filenames:
return
utils.launch_default_app(self.filenames)
class OpenDir(OpenDefaultApp):
"""Open directories using the OS default."""
@staticmethod
def name():
return N_('Open Directory')
@property
def _dirnames(self):
return self.filenames
def do(self):
dirnames = self._dirnames
if not dirnames:
return
# An empty dirname defaults to to the current directory.
dirs = [(dirname or core.getcwd()) for dirname in dirnames]
utils.launch_default_app(dirs)
class OpenParentDir(OpenDir):
"""Open parent directories using the OS default."""
@staticmethod
def name():
return N_('Open Parent Directory')
@property
def _dirnames(self):
dirnames = list({os.path.dirname(x) for x in self.filenames})
return dirnames
class OpenWorktree(OpenDir):
"""Open worktree directory using the OS default."""
@staticmethod
def name():
return N_('Open Worktree')
# The _unused parameter is needed by worktree_dir_action() -> common.cmd_action().
def __init__(self, context, _unused=None):
dirnames = [context.git.worktree()]
super().__init__(context, dirnames)
class OpenNewRepo(ContextCommand):
"""Launches git-cola on a repo."""
def __init__(self, context, repo_path):
super().__init__(context)
self.repo_path = repo_path
def do(self):
self.model.set_directory(self.repo_path)
core.fork([sys.executable, sys.argv[0], '--repo', self.repo_path])
class OpenRepo(EditModel):
def __init__(self, context, repo_path):
super().__init__(context)
self.repo_path = repo_path
self.new_mode = self.model.mode_none
self.new_diff_text = ''
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
self.new_commitmsg = ''
self.new_filename = ''
def do(self):
old_repo = self.git.getcwd()
if self.model.set_worktree(self.repo_path):
self.fsmonitor.stop()
self.fsmonitor.start()
self.model.update_status(reset=True)
# Check if template should be loaded
if self.context.cfg.get(prefs.AUTOTEMPLATE):
template_loader = LoadCommitMessageFromTemplate(self.context)
template_loader.do()
else:
self.model.set_commitmsg(self.new_commitmsg)
settings = self.context.settings
settings.load()
settings.add_recent(self.repo_path, prefs.maxrecent(self.context))
settings.save()
super().do()
else:
self.model.set_worktree(old_repo)
class OpenParentRepo(OpenRepo):
def __init__(self, context):
path = ''
if version.check_git(context, 'show-superproject-working-tree'):
status, out, _ = context.git.rev_parse(show_superproject_working_tree=True)
if status == 0:
path = out
if not path:
path = os.path.dirname(core.getcwd())
super().__init__(context, path)
class Clone(ContextCommand):
"""Clones a repository and optionally spawns a new cola session."""
def __init__(
self, context, url, new_directory, submodules=False, shallow=False, spawn=True
):
super().__init__(context)
self.url = url
self.new_directory = new_directory
self.submodules = submodules
self.shallow = shallow
self.spawn = spawn
self.status = -1
self.out = ''
self.err = ''
def do(self):
kwargs = {}
if self.shallow:
kwargs['depth'] = 1
recurse_submodules = self.submodules
shallow_submodules = self.submodules and self.shallow
status, out, err = self.git.clone(
self.url,
self.new_directory,
recurse_submodules=recurse_submodules,
shallow_submodules=shallow_submodules,
**kwargs,
)
self.status = status
self.out = out
self.err = err
if status == 0 and self.spawn:
executable = sys.executable
core.fork([executable, sys.argv[0], '--repo', self.new_directory])
return self
class NewBareRepo(ContextCommand):
"""Create a new shared bare repository"""
def __init__(self, context, path):
super().__init__(context)
self.path = path
def do(self):
path = self.path
status, out, err = self.git.init(path, bare=True, shared=True)
Interaction.command(
N_('Error'), 'git init --bare --shared "%s"' % path, status, out, err
)
return status == 0
def unix_path(path, is_win32=utils.is_win32):
"""Git for Windows requires Unix paths, so force them here"""
if is_win32():
path = path.replace('\\', '/')
first = path[0]
second = path[1]
if second == ':': # sanity check, this better be a Windows-style path
path = '/' + first + path[2:]
return path
def sequence_editor():
"""Set GIT_SEQUENCE_EDITOR for running git-cola-sequence-editor"""
xbase = unix_path(resources.command('git-cola-sequence-editor'))
if utils.is_win32():
editor = core.list2cmdline([unix_path(sys.executable), xbase])
else:
editor = core.list2cmdline([xbase])
return editor
class SequenceEditorEnvironment:
"""Set environment variables to enable git-cola-sequence-editor"""
def __init__(self, context, **kwargs):
self.env = {
'GIT_EDITOR': prefs.editor(context),
'GIT_SEQUENCE_EDITOR': sequence_editor(),
}
self.env.update(kwargs)
def __enter__(self):
for var, value in self.env.items():
compat.setenv(var, value)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
for var in self.env:
compat.unsetenv(var)
class Rebase(ContextCommand):
def __init__(self, context, upstream=None, branch=None, **kwargs):
"""Start an interactive rebase session
:param upstream: upstream branch
:param branch: optional branch to checkout
:param kwargs: forwarded directly to `git.rebase()`
"""
super().__init__(context)
self.upstream = upstream
self.branch = branch
self.kwargs = kwargs
def prepare_arguments(self, upstream):
args = []
kwargs = {}
# Rebase actions must be the only option specified
for action in ('continue', 'abort', 'skip', 'edit_todo'):
if self.kwargs.get(action, False):
kwargs[action] = self.kwargs[action]
return args, kwargs
kwargs['interactive'] = True
kwargs['autosquash'] = self.kwargs.get('autosquash', True)
kwargs.update(self.kwargs)
# Prompt to determine whether or not to use "git rebase --update-refs".
has_update_refs = version.check_git(self.context, 'rebase-update-refs')
if has_update_refs and not kwargs.get('update_refs', False):
title = N_('Update stacked branches when rebasing?')
text = N_(
'"git rebase --update-refs" automatically force-updates any\n'
'branches that point to commits that are being rebased.\n\n'
'Any branches that are checked out in a worktree are not updated.\n\n'
'Using this feature is helpful for "stacked" branch workflows.'
)
info = N_('Update stacked branches when rebasing?')
ok_text = N_('Update stacked branches')
cancel_text = N_('Do not update stacked branches')
update_refs = Interaction.confirm(
title,
text,
info,
ok_text,
default=True,
cancel_text=cancel_text,
)
if update_refs:
kwargs['update_refs'] = True
if upstream:
args.append(upstream)
if self.branch:
args.append(self.branch)
return args, kwargs
def do(self):
(status, out, err) = (1, '', '')
context = self.context
cfg = self.cfg
model = self.model
if not cfg.get('rebase.autostash', False):
if model.staged or model.unmerged or model.modified:
Interaction.information(
N_('Unable to rebase'),
N_('You cannot rebase with uncommitted changes.'),
)
return status, out, err
upstream = self.upstream or Interaction.choose_ref(
context,
N_('Select New Upstream'),
N_('Interactive Rebase'),
default='@{upstream}',
)
if not upstream:
return status, out, err
self.model.is_rebasing = True
self.model.emit_updated()
args, kwargs = self.prepare_arguments(upstream)
upstream_title = upstream or '@{upstream}'
with SequenceEditorEnvironment(
self.context,
GIT_COLA_SEQ_EDITOR_TITLE=N_('Rebase onto %s') % upstream_title,
GIT_COLA_SEQ_EDITOR_ACTION=N_('Rebase'),
):
# This blocks the user interface window for the duration
# of git-cola-sequence-editor. We would need to run the command
# in a QRunnable task to avoid blocking the main thread.
# Alternatively, we can hide the main window while rebasing,
# which doesn't require as much effort.
status, out, err = self.git.rebase(
*args, _no_win32_startupinfo=True, **kwargs
)
self.model.update_status()
if err.strip() != 'Nothing to do':
title = N_('Rebase stopped')
Interaction.command(title, 'git rebase', status, out, err)
return status, out, err
class RebaseEditTodo(ContextCommand):
def do(self):
(status, out, err) = (1, '', '')
with SequenceEditorEnvironment(
self.context,
GIT_COLA_SEQ_EDITOR_TITLE=N_('Edit Rebase'),
GIT_COLA_SEQ_EDITOR_ACTION=N_('Save'),
):
status, out, err = self.git.rebase(edit_todo=True)
Interaction.log_status(status, out, err)
self.model.update_status()
return status, out, err
class RebaseContinue(ContextCommand):
def do(self):
(status, out, err) = (1, '', '')
with SequenceEditorEnvironment(
self.context,
GIT_COLA_SEQ_EDITOR_TITLE=N_('Rebase'),
GIT_COLA_SEQ_EDITOR_ACTION=N_('Rebase'),
):
status, out, err = self.git.rebase('--continue')
Interaction.log_status(status, out, err)
self.model.update_status()
return status, out, err
class RebaseSkip(ContextCommand):
def do(self):
(status, out, err) = (1, '', '')
with SequenceEditorEnvironment(
self.context,
GIT_COLA_SEQ_EDITOR_TITLE=N_('Rebase'),
GIT_COLA_SEQ_EDITOR_ACTION=N_('Rebase'),
):
status, out, err = self.git.rebase(skip=True)
Interaction.log_status(status, out, err)
self.model.update_status()
return status, out, err
class RebaseAbort(ContextCommand):
def do(self):
status, out, err = self.git.rebase(abort=True)
Interaction.log_status(status, out, err)
self.model.update_status()
class Rescan(ContextCommand):
"""Rescan for changes"""
def do(self):
self.model.update_status()
class Refresh(ContextCommand):
"""Update refs, refresh the index, and update config"""
@staticmethod
def name():
return N_('Refresh')
def do(self):
self.model.update_status(update_index=True)
self.cfg.update()
self.fsmonitor.refresh()
self.selection.selection_changed.emit()
class RefreshConfig(ContextCommand):
"""Refresh the git config cache"""
def do(self):
self.cfg.update()
class RevertEditsCommand(ConfirmAction):
def __init__(self, context):
super().__init__(context)
self.icon = icons.undo()
def ok_to_run(self):
return self.model.is_undoable()
def checkout_from_head(self):
return False
def checkout_args(self):
args = []
s = self.selection.selection()
if self.checkout_from_head():
args.append(self.model.head)
args.append('--')
if s.staged:
items = s.staged
else:
items = s.modified
args.extend(items)
return args
def action(self):
checkout_args = self.checkout_args()
return self.git.checkout(*checkout_args)
def success(self):
self.model.set_diff_type(main.Types.TEXT)
self.model.update_file_status()
class RevertUnstagedEdits(RevertEditsCommand):
@staticmethod
def name():
return N_('Revert Unstaged Edits...')
def checkout_from_head(self):
# Being in amend mode should not affect the behavior of this command.
# The only sensible thing to do is to checkout from the index.
return False
def confirm(self):
title = N_('Revert Unstaged Changes?')
text = N_(
'This operation removes unstaged edits from selected files.\n'
'These changes cannot be recovered.'
)
info = N_('Revert the unstaged changes?')
ok_text = N_('Revert Unstaged Changes')
return Interaction.confirm(
title, text, info, ok_text, default=True, icon=self.icon
)
class RevertUncommittedEdits(RevertEditsCommand):
@staticmethod
def name():
return N_('Revert Uncommitted Edits...')
def checkout_from_head(self):
return True
def confirm(self):
"""Prompt for reverting changes"""
title = N_('Revert Uncommitted Changes?')
text = N_(
'This operation removes uncommitted edits from selected files.\n'
'These changes cannot be recovered.'
)
info = N_('Revert the uncommitted changes?')
ok_text = N_('Revert Uncommitted Changes')
return Interaction.confirm(
title, text, info, ok_text, default=True, icon=self.icon
)
class RunConfigAction(ContextCommand):
"""Run a user-configured action, typically from the "Tools" menu"""
def __init__(self, context, action_name):
super().__init__(context)
self.action_name = action_name
def do(self):
"""Run the user-configured action"""
for env in ('ARGS', 'DIRNAME', 'FILENAME', 'REVISION'):
try:
compat.unsetenv(env)
except KeyError:
pass
rev = None
args = None
context = self.context
cfg = self.cfg
opts = cfg.get_guitool_opts(self.action_name)
cmd = opts.get('cmd')
if 'title' not in opts:
opts['title'] = cmd
if 'prompt' not in opts or opts.get('prompt') is True:
prompt = N_('Run "%s"?') % cmd
opts['prompt'] = prompt
if opts.get('needsfile'):
filename = self.selection.filename()
if not filename:
Interaction.information(
N_('Please select a file'),
N_('"%s" requires a selected file.') % cmd,
)
return False
dirname = utils.dirname(filename, current_dir='.')
compat.setenv('FILENAME', filename)
compat.setenv('DIRNAME', dirname)
if opts.get('revprompt') or opts.get('argprompt'):
while True:
ok = Interaction.confirm_config_action(context, cmd, opts)
if not ok:
return False
rev = opts.get('revision')
args = opts.get('args')
if opts.get('revprompt') and not rev:
title = N_('Invalid Revision')
msg = N_('The revision expression cannot be empty.')
Interaction.critical(title, msg)
continue
break
elif opts.get('confirm'):
title = os.path.expandvars(opts.get('title'))
prompt = os.path.expandvars(opts.get('prompt'))
if not Interaction.question(title, prompt):
return False
if rev:
compat.setenv('REVISION', rev)
if args:
compat.setenv('ARGS', args)
title = os.path.expandvars(cmd)
Interaction.log(N_('Running command: %s') % title)
cmd = ['sh', '-c', cmd]
if opts.get('background'):
core.fork(cmd)
status, out, err = (0, '', '')
elif opts.get('noconsole'):
status, out, err = core.run_command(cmd)
else:
status, out, err = Interaction.run_command(title, cmd)
if not opts.get('background') and not opts.get('norescan'):
self.model.update_status()
title = N_('Error')
Interaction.command(title, cmd, status, out, err)
return status == 0
class SetDefaultRepo(ContextCommand):
"""Set the default repository"""
def __init__(self, context, repo):
super().__init__(context)
self.repo = repo
def do(self):
self.cfg.set_user('cola.defaultrepo', self.repo)
class SetDiffText(EditModel):
"""Set the diff text"""
UNDOABLE = True
def __init__(self, context, text):
super().__init__(context)
self.new_diff_text = text
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
class SetUpstreamBranch(ContextCommand):
"""Set the upstream branch"""
def __init__(self, context, branch, remote, remote_branch):
super().__init__(context)
self.branch = branch
self.remote = remote
self.remote_branch = remote_branch
def do(self):
cfg = self.cfg
remote = self.remote
branch = self.branch
remote_branch = self.remote_branch
cfg.set_repo('branch.%s.remote' % branch, remote)
cfg.set_repo('branch.%s.merge' % branch, 'refs/heads/' + remote_branch)
def format_hex(data):
"""Translate binary data into a hex dump"""
hexdigits = '0123456789ABCDEF'
result = ''
offset = 0
byte_offset_to_int = compat.byte_offset_to_int_converter()
while offset < len(data):
result += '%04u |' % offset
textpart = ''
for i in range(0, 16):
if i > 0 and i % 4 == 0:
result += ' '
if offset < len(data):
v = byte_offset_to_int(data[offset])
result += ' ' + hexdigits[v >> 4] + hexdigits[v & 0xF]
textpart += chr(v) if 32 <= v < 127 else '.'
offset += 1
else:
result += ' '
textpart += ' '
result += ' | ' + textpart + ' |\n'
return result
class ShowUntracked(EditModel):
"""Show an untracked file."""
def __init__(self, context, filename):
super().__init__(context)
self.new_filename = filename
if gitcmds.is_binary(context, filename):
self.new_mode = self.model.mode_untracked
self.new_diff_text = self.read(filename)
else:
self.new_mode = self.model.mode_untracked_diff
self.new_diff_text = gitcmds.diff_helper(
self.context, filename=filename, cached=False, untracked=True
)
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
def read(self, filename):
"""Read file contents"""
cfg = self.cfg
size = cfg.get('cola.readsize', 2048)
try:
result = core.read(filename, size=size, encoding='bytes')
except OSError:
result = ''
truncated = len(result) == size
encoding = cfg.file_encoding(filename) or core.ENCODING
try:
text_result = core.decode_maybe(result, encoding)
except UnicodeError:
text_result = format_hex(result)
if truncated:
text_result += '...'
return text_result
class SignOff(ContextCommand):
"""Append a sign-off to the commit message"""
UNDOABLE = True
@staticmethod
def name():
return N_('Sign Off')
def __init__(self, context):
super().__init__(context)
self.old_commitmsg = self.model.commitmsg
def do(self):
"""Add a sign-off to the commit message"""
signoff = self.signoff()
if signoff in self.model.commitmsg:
return
msg = self.model.commitmsg.rstrip()
self.model.set_commitmsg(msg + '\n' + signoff)
def undo(self):
"""Restore the commit message"""
self.model.set_commitmsg(self.old_commitmsg)
def signoff(self):
"""Generate the sign-off string"""
name, email = self.cfg.get_author()
return f'\nSigned-off-by: {name} <{email}>'
def check_conflicts(context, unmerged):
"""Check paths for conflicts
Conflicting files can be filtered out one-by-one.
"""
if prefs.check_conflicts(context):
unmerged = [path for path in unmerged if is_conflict_free(path)]
return unmerged
def is_conflict_free(path):
"""Return True if `path` contains no conflict markers"""
rgx = re.compile(r'^(<<<<<<<|\|\|\|\|\|\|\||>>>>>>>) ')
try:
with core.xopen(path, 'rb') as f:
for line in f:
line = core.decode(line, errors='ignore')
if rgx.match(line):
return should_stage_conflicts(path)
except OSError:
# We can't read this file ~ we may be staging a removal
pass
return True
def should_stage_conflicts(path):
"""Inform the user that a file contains merge conflicts
Return `True` if we should stage the path nonetheless.
"""
title = msg = N_('Stage conflicts?')
info = (
N_(
'%s appears to contain merge conflicts.\n\n'
'You should probably skip this file.\n'
'Stage it anyways?'
)
% path
)
ok_text = N_('Stage conflicts')
cancel_text = N_('Skip')
return Interaction.confirm(
title, msg, info, ok_text, default=False, cancel_text=cancel_text
)
class Stage(ContextCommand):
"""Stage a set of paths."""
@staticmethod
def name():
return N_('Stage')
def __init__(self, context, paths):
super().__init__(context)
self.paths = paths
def do(self):
msg = N_('Staging: %s') % (', '.join(self.paths))
Interaction.log(msg)
return self.stage_paths()
def stage_paths(self):
"""Stages add/removals to git."""
context = self.context
paths = self.paths
if not paths:
if self.model.cfg.get('cola.safemode', False):
return (0, '', '')
return self.stage_all()
add = []
remove = []
status = 0
out = ''
err = ''
for path in set(paths):
if core.exists(path) or core.islink(path):
if path.endswith('/'):
path = path.rstrip('/')
add.append(path)
else:
remove.append(path)
self.model.emit_about_to_update()
# `git add -u` doesn't work on untracked files
if add:
status, out, err = gitcmds.add(context, add)
Interaction.command(N_('Error'), 'git add', status, out, err)
# If a path doesn't exist then that means it should be removed
# from the index. We use `git add -u` for that.
if remove:
status, out, err = gitcmds.add(context, remove, u=True)
Interaction.command(N_('Error'), 'git add -u', status, out, err)
self.model.update_files(emit=True)
return status, out, err
def stage_all(self):
"""Stage all files"""
status, out, err = self.git.add(v=True, u=True)
Interaction.command(N_('Error'), 'git add -u', status, out, err)
self.model.update_file_status()
return (status, out, err)
class StageCarefully(Stage):
"""Only stage when the path list is non-empty
We use "git add -u -- <pathspec>" to stage, and it stages everything by
default when no pathspec is specified, so this class ensures that paths
are specified before calling git.
When no paths are specified, the command does nothing.
"""
def __init__(self, context):
super().__init__(context, None)
self.init_paths()
def init_paths(self):
"""Initialize path data"""
return
def ok_to_run(self):
"""Prevent catch-all "git add -u" from adding unmerged files"""
return self.paths or not self.model.unmerged
def do(self):
"""Stage files when ok_to_run() return True"""
if self.ok_to_run():
return super().do()
return (0, '', '')
class StageModified(StageCarefully):
"""Stage all modified files."""
@staticmethod
def name():
return N_('Stage Modified')
def init_paths(self):
self.paths = self.model.modified
class StageUnmerged(StageCarefully):
"""Stage unmerged files."""
@staticmethod
def name():
return N_('Stage Unmerged')
def init_paths(self):
self.paths = check_conflicts(self.context, self.model.unmerged)
class StageUntracked(StageCarefully):
"""Stage all untracked files."""
@staticmethod
def name():
return N_('Stage Untracked')
def init_paths(self):
self.paths = self.model.untracked
def stage_all(self):
"""Disable the stage_all() behavior for untracked files"""
return (0, '', '')
class StageModifiedAndUntracked(StageCarefully):
"""Stage all untracked files."""
@staticmethod
def name():
return N_('Stage Modified and Untracked')
def init_paths(self):
self.paths = self.model.modified + self.model.untracked
class StageOrUnstageAll(ContextCommand):
"""If the selection is staged, unstage it, otherwise stage"""
@staticmethod
def name():
return N_('Stage / Unstage All')
def do(self):
if self.model.staged:
do(Unstage, self.context, self.model.staged)
else:
if self.cfg.get('cola.safemode', False):
unstaged = self.model.modified
else:
unstaged = self.model.modified + self.model.untracked
do(Stage, self.context, unstaged)
class StageOrUnstage(ContextCommand):
"""If the selection is staged, unstage it, otherwise stage"""
@staticmethod
def name():
return N_('Stage / Unstage')
def do(self):
s = self.selection.selection()
if s.staged:
do(Unstage, self.context, s.staged)
unstaged = []
unmerged = check_conflicts(self.context, s.unmerged)
if unmerged:
unstaged.extend(unmerged)
if s.modified:
unstaged.extend(s.modified)
if s.untracked:
unstaged.extend(s.untracked)
if unstaged:
do(Stage, self.context, unstaged)
class Tag(ContextCommand):
"""Create a tag object."""
def __init__(self, context, name, revision, sign=False, message=''):
super().__init__(context)
self._name = name
self._message = message
self._revision = revision
self._sign = sign
def do(self):
result = False
git = self.git
revision = self._revision
tag_name = self._name
tag_message = self._message
if not revision:
Interaction.critical(
N_('Missing Revision'), N_('Please specify a revision to tag.')
)
return result
if not tag_name:
Interaction.critical(
N_('Missing Name'), N_('Please specify a name for the new tag.')
)
return result
title = N_('Missing Tag Message')
message = N_('Tag-signing was requested but the tag message is empty.')
info = N_(
'An unsigned, lightweight tag will be created instead.\n'
'Create an unsigned tag?'
)
ok_text = N_('Create Unsigned Tag')
sign = self._sign
if sign and not tag_message:
# We require a message in order to sign the tag, so if they
# choose to create an unsigned tag we have to clear the sign flag.
if not Interaction.confirm(
title, message, info, ok_text, default=False, icon=icons.save()
):
return result
sign = False
opts = {}
tmp_file = None
try:
if tag_message:
tmp_file = utils.tmp_filename('tag-message')
opts['file'] = tmp_file
core.write(tmp_file, tag_message)
if sign:
opts['sign'] = True
if tag_message:
opts['annotate'] = True
status, out, err = git.tag(tag_name, revision, **opts)
finally:
if tmp_file:
core.unlink(tmp_file)
title = N_('Error: could not create tag "%s"') % tag_name
Interaction.command(title, 'git tag', status, out, err)
if status == 0:
result = True
self.model.update_status()
Interaction.information(
N_('Tag Created'),
N_('Created a new tag named "%s"') % tag_name,
details=tag_message or None,
)
return result
class Unstage(ContextCommand):
"""Unstage a set of paths."""
@staticmethod
def name():
return N_('Unstage')
def __init__(self, context, paths):
super().__init__(context)
self.paths = paths
def do(self):
"""Unstage paths"""
context = self.context
head = self.model.head
paths = self.paths
msg = N_('Unstaging: %s') % (', '.join(paths))
Interaction.log(msg)
if not paths:
return unstage_all(context)
status, out, err = gitcmds.unstage_paths(context, paths, head=head)
Interaction.command(N_('Error'), 'git reset', status, out, err)
self.model.update_file_status()
return (status, out, err)
class UnstageAll(ContextCommand):
"""Unstage all files; resets the index."""
def do(self):
return unstage_all(self.context)
def unstage_all(context):
"""Unstage all files, even while amending"""
model = context.model
git = context.git
head = model.head
status, out, err = git.reset(head, '--', '.')
Interaction.command(N_('Error'), 'git reset', status, out, err)
model.update_file_status()
return (status, out, err)
class StageSelected(ContextCommand):
"""Stage selected files, or all files if no selection exists."""
def do(self):
context = self.context
paths = self.selection.unstaged
if paths:
do(Stage, context, paths)
elif self.cfg.get('cola.safemode', False):
do(StageModified, context)
class UnstageSelected(Unstage):
"""Unstage selected files."""
def __init__(self, context):
staged = context.selection.staged
super().__init__(context, staged)
class Untrack(ContextCommand):
"""Unstage a set of paths."""
def __init__(self, context, paths):
super().__init__(context)
self.paths = paths
def do(self):
msg = N_('Untracking: %s') % (', '.join(self.paths))
Interaction.log(msg)
status, out, err = self.model.untrack_paths(self.paths)
Interaction.log_status(status, out, err)
class UnmergedSummary(EditModel):
"""List unmerged files in the diff text."""
def __init__(self, context):
super().__init__(context)
unmerged = self.model.unmerged
io = StringIO()
io.write('# %s unmerged file(s)\n' % len(unmerged))
if unmerged:
io.write('\n'.join(unmerged) + '\n')
self.new_diff_text = io.getvalue()
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
self.new_mode = self.model.mode_display
class UntrackedSummary(EditModel):
"""List possible .gitignore rules as the diff text."""
def __init__(self, context):
super().__init__(context)
untracked = self.model.untracked
io = StringIO()
io.write('# %s untracked file(s)\n' % len(untracked))
if untracked:
io.write('# Add these lines to ".gitignore" to ignore these files:\n')
io.write('\n'.join('/' + filename for filename in untracked) + '\n')
self.new_diff_text = io.getvalue()
self.new_diff_type = main.Types.TEXT
self.new_file_type = main.Types.TEXT
self.new_mode = self.model.mode_display
class VisualizeAll(ContextCommand):
"""Visualize all branches."""
def do(self):
context = self.context
browser = utils.shell_split(prefs.history_browser(context))
launch_history_browser(browser + ['--all'])
class VisualizeCurrent(ContextCommand):
"""Visualize all branches."""
def do(self):
context = self.context
browser = utils.shell_split(prefs.history_browser(context))
launch_history_browser(browser + [self.model.currentbranch] + ['--'])
class VisualizePaths(ContextCommand):
"""Path-limited visualization."""
def __init__(self, context, paths):
super().__init__(context)
context = self.context
browser = utils.shell_split(prefs.history_browser(context))
if paths:
self.argv = browser + ['--'] + list(paths)
else:
self.argv = browser
def do(self):
launch_history_browser(self.argv)
class VisualizeRevision(ContextCommand):
"""Visualize a specific revision."""
def __init__(self, context, revision, paths=None):
super().__init__(context)
self.revision = revision
self.paths = paths
def do(self):
context = self.context
argv = utils.shell_split(prefs.history_browser(context))
if self.revision:
argv.append(self.revision)
if self.paths:
argv.append('--')
argv.extend(self.paths)
launch_history_browser(argv)
class SubmoduleAdd(ConfirmAction):
"""Add specified submodules"""
def __init__(self, context, url, path, branch, depth, reference):
super().__init__(context)
self.url = url
self.path = path
self.branch = branch
self.depth = depth
self.reference = reference
def confirm(self):
title = N_('Add Submodule...')
question = N_('Add this submodule?')
info = N_('The submodule will be added using\n' '"%s"' % self.command())
ok_txt = N_('Add Submodule')
return Interaction.confirm(title, question, info, ok_txt, icon=icons.ok())
def action(self):
context = self.context
args = self.get_args()
return context.git.submodule('add', *args)
def success(self):
self.model.update_file_status()
self.model.update_submodules_list()
def error_message(self):
return N_('Error updating submodule %s' % self.path)
def command(self):
cmd = ['git', 'submodule', 'add']
cmd.extend(self.get_args())
return core.list2cmdline(cmd)
def get_args(self):
args = []
if self.branch:
args.extend(['--branch', self.branch])
if self.reference:
args.extend(['--reference', self.reference])
if self.depth:
args.extend(['--depth', '%d' % self.depth])
args.extend(['--', self.url])
if self.path:
args.append(self.path)
return args
class SubmoduleUpdate(ConfirmAction):
"""Update specified submodule"""
def __init__(self, context, path):
super().__init__(context)
self.path = path
def confirm(self):
title = N_('Update Submodule...')
question = N_('Update this submodule?')
info = N_('The submodule will be updated using\n' '"%s"' % self.command())
ok_txt = N_('Update Submodule')
return Interaction.confirm(
title, question, info, ok_txt, default=False, icon=icons.pull()
)
def action(self):
context = self.context
args = self.get_args()
return context.git.submodule(*args)
def success(self):
self.model.update_file_status()
def error_message(self):
return N_('Error updating submodule %s' % self.path)
def command(self):
cmd = ['git', 'submodule']
cmd.extend(self.get_args())
return core.list2cmdline(cmd)
def get_args(self):
cmd = ['update']
if version.check_git(self.context, 'submodule-update-recursive'):
cmd.append('--recursive')
cmd.extend(['--', self.path])
return cmd
class SubmodulesUpdate(ConfirmAction):
"""Update all submodules"""
def confirm(self):
title = N_('Update submodules...')
question = N_('Update all submodules?')
info = N_('All submodules will be updated using\n' '"%s"' % self.command())
ok_txt = N_('Update Submodules')
return Interaction.confirm(
title, question, info, ok_txt, default=False, icon=icons.pull()
)
def action(self):
context = self.context
args = self.get_args()
return context.git.submodule(*args)
def success(self):
self.model.update_file_status()
def error_message(self):
return N_('Error updating submodules')
def command(self):
cmd = ['git', 'submodule']
cmd.extend(self.get_args())
return core.list2cmdline(cmd)
def get_args(self):
cmd = ['update']
if version.check_git(self.context, 'submodule-update-recursive'):
cmd.append('--recursive')
return cmd
def launch_history_browser(argv):
"""Launch the configured history browser"""
try:
core.fork(argv)
except OSError as e:
_, details = utils.format_exception(e)
title = N_('Error Launching History Browser')
msg = N_('Cannot exec "%s": please configure a history browser') % ' '.join(
argv
)
Interaction.critical(title, message=msg, details=details)
def run(cls, *args, **opts):
"""
Returns a callback that runs a command
If the caller of run() provides args or opts then those are
used instead of the ones provided by the invoker of the callback.
"""
def runner(*local_args, **local_opts):
"""Closure return by run() which runs the command"""
if args or opts:
return do(cls, *args, **opts)
return do(cls, *local_args, **local_opts)
return runner
def do(cls, *args, **opts):
"""Run a command in-place"""
try:
cmd = cls(*args, **opts)
return cmd.do()
except Exception as e:
msg, details = utils.format_exception(e)
if hasattr(cls, '__name__'):
msg = f'{cls.__name__} exception:\n{msg}'
Interaction.critical(N_('Error'), message=msg, details=details)
return None
| 94,958 | Python | .py | 2,476 | 29.057754 | 87 | 0.585685 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
40 | spellcheck.py | git-cola_git-cola/cola/spellcheck.py | import codecs
import collections
import os
from . import resources
__copyright__ = """
2012 Peter Norvig (http://norvig.com/spell-correct.html)
2013-2018 David Aguilar <[email protected]>
"""
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
def train(features, model):
for f in features:
model[f] += 1
return model
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b) > 1]
replaces = [a + c + b[1:] for a, b in splits for c in ALPHABET if b]
inserts = [a + c + b for a, b in splits for c in ALPHABET]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word, words):
return {e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in words}
def known(word, words):
return {w for w in word if w in words}
def suggest(word, words):
candidates = (
known([word], words)
or known(edits1(word), words)
or known_edits2(word, words)
or [word]
)
return candidates
def correct(word, words):
candidates = suggest(word, words)
return max(candidates, key=words.get)
class NorvigSpellCheck:
def __init__(
self,
words='dict/words',
propernames='dict/propernames',
):
data_dirs = resources.xdg_data_dirs()
self.dictwords = resources.find_first(words, data_dirs)
self.propernames = resources.find_first(propernames, data_dirs)
self.words = collections.defaultdict(lambda: 1)
self.extra_words = set()
self.dictionary = None
self.initialized = False
def set_dictionary(self, dictionary):
self.dictionary = dictionary
def init(self):
if self.initialized:
return
self.initialized = True
train(self.read(), self.words)
train(self.extra_words, self.words)
def add_word(self, word):
self.extra_words.add(word)
def suggest(self, word):
self.init()
return suggest(word, self.words)
def check(self, word):
self.init()
return word.replace('.', '') in self.words
def read(self):
"""Read dictionary words"""
paths = []
words = self.dictwords
propernames = self.propernames
cfg_dictionary = self.dictionary
if words and os.path.exists(words):
paths.append((words, True))
if propernames and os.path.exists(propernames):
paths.append((propernames, False))
if cfg_dictionary and os.path.exists(cfg_dictionary):
paths.append((cfg_dictionary, False))
for path, title in paths:
try:
with codecs.open(
path, 'r', encoding='utf-8', errors='ignore'
) as words_file:
for line in words_file:
word = line.rstrip()
yield word
if title:
yield word.title()
except OSError:
pass
| 3,130 | Python | .py | 88 | 27.159091 | 75 | 0.596549 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
41 | qtutils.py | git-cola_git-cola/cola/qtutils.py | """Miscellaneous Qt utility functions."""
import os
from qtpy import compat
from qtpy import QtGui
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from . import core
from . import hotkeys
from . import icons
from . import utils
from .i18n import N_
from .compat import int_types
from .compat import ustr
from .models import prefs
from .widgets import defs
STRETCH = object()
SKIPPED = object()
def active_window():
"""Return the active window for the current application"""
return QtWidgets.QApplication.activeWindow()
def current_palette():
"""Return the QPalette for the current application"""
return QtWidgets.QApplication.instance().palette()
def connect_action(action, func):
"""Connect an action to a function"""
action.triggered[bool].connect(lambda x: func(), type=Qt.QueuedConnection)
def connect_action_bool(action, func):
"""Connect a triggered(bool) action to a function"""
action.triggered[bool].connect(func, type=Qt.QueuedConnection)
def connect_button(button, func):
"""Connect a button to a function"""
# Some versions of Qt send the `bool` argument to the clicked callback,
# and some do not. The lambda consumes all callback-provided arguments.
button.clicked.connect(lambda *args, **kwargs: func(), type=Qt.QueuedConnection)
def connect_checkbox(widget, func):
"""Connect a checkbox to a function taking bool"""
widget.clicked.connect(
lambda *args, **kwargs: func(get(checkbox)), type=Qt.QueuedConnection
)
def connect_released(button, func):
"""Connect a button to a function"""
button.released.connect(func, type=Qt.QueuedConnection)
def button_action(button, action):
"""Make a button trigger an action"""
connect_button(button, action.trigger)
def connect_toggle(toggle, func):
"""Connect a toggle button to a function"""
toggle.toggled.connect(func, type=Qt.QueuedConnection)
def disconnect(signal):
"""Disconnect signal from all slots"""
try:
signal.disconnect()
except TypeError: # allow unconnected slots
pass
def get(widget, default=None):
"""Query a widget for its python value"""
if hasattr(widget, 'isChecked'):
value = widget.isChecked()
elif hasattr(widget, 'value'):
value = widget.value()
elif hasattr(widget, 'text'):
value = widget.text()
elif hasattr(widget, 'toPlainText'):
value = widget.toPlainText()
elif hasattr(widget, 'sizes'):
value = widget.sizes()
elif hasattr(widget, 'date'):
value = widget.date().toString(Qt.ISODate)
else:
value = default
return value
def hbox(margin, spacing, *items):
"""Create an HBoxLayout with the specified sizes and items"""
return box(QtWidgets.QHBoxLayout, margin, spacing, *items)
def vbox(margin, spacing, *items):
"""Create a VBoxLayout with the specified sizes and items"""
return box(QtWidgets.QVBoxLayout, margin, spacing, *items)
def buttongroup(*items):
"""Create a QButtonGroup for the specified items"""
group = QtWidgets.QButtonGroup()
for i in items:
group.addButton(i)
return group
def set_margin(layout, margin):
"""Set the content margins for a layout"""
layout.setContentsMargins(margin, margin, margin, margin)
def box(cls, margin, spacing, *items):
"""Create a QBoxLayout with the specified sizes and items"""
stretch = STRETCH
skipped = SKIPPED
layout = cls()
layout.setSpacing(spacing)
set_margin(layout, margin)
for i in items:
if isinstance(i, QtWidgets.QWidget):
layout.addWidget(i)
elif isinstance(
i,
(
QtWidgets.QHBoxLayout,
QtWidgets.QVBoxLayout,
QtWidgets.QFormLayout,
QtWidgets.QLayout,
),
):
layout.addLayout(i)
elif i is stretch:
layout.addStretch()
elif i is skipped:
continue
elif isinstance(i, int_types):
layout.addSpacing(i)
return layout
def form(margin, spacing, *widgets):
"""Create a QFormLayout with the specified sizes and items"""
layout = QtWidgets.QFormLayout()
layout.setSpacing(spacing)
layout.setFieldGrowthPolicy(QtWidgets.QFormLayout.ExpandingFieldsGrow)
set_margin(layout, margin)
for idx, (name, widget) in enumerate(widgets):
if isinstance(name, (str, ustr)):
layout.addRow(name, widget)
else:
layout.setWidget(idx, QtWidgets.QFormLayout.LabelRole, name)
layout.setWidget(idx, QtWidgets.QFormLayout.FieldRole, widget)
return layout
def grid(margin, spacing, *widgets):
"""Create a QGridLayout with the specified sizes and items"""
layout = QtWidgets.QGridLayout()
layout.setSpacing(spacing)
set_margin(layout, margin)
for row in widgets:
item = row[0]
if isinstance(item, QtWidgets.QWidget):
layout.addWidget(*row)
elif isinstance(item, QtWidgets.QLayoutItem):
layout.addItem(*row)
return layout
def splitter(orientation, *widgets):
"""Create a splitter over the specified widgets
:param orientation: Qt.Horizontal or Qt.Vertical
"""
layout = QtWidgets.QSplitter()
layout.setOrientation(orientation)
layout.setHandleWidth(defs.handle_width)
layout.setChildrenCollapsible(True)
for idx, widget in enumerate(widgets):
layout.addWidget(widget)
layout.setStretchFactor(idx, 1)
# Workaround for Qt not setting the WA_Hover property for QSplitter
# Cf. https://bugreports.qt.io/browse/QTBUG-13768
layout.handle(1).setAttribute(Qt.WA_Hover)
return layout
def label(text=None, align=None, fmt=None, selectable=True):
"""Create a QLabel with the specified properties"""
widget = QtWidgets.QLabel()
if align is not None:
widget.setAlignment(align)
if fmt is not None:
widget.setTextFormat(fmt)
if selectable:
widget.setTextInteractionFlags(Qt.TextBrowserInteraction)
widget.setOpenExternalLinks(True)
if text:
widget.setText(text)
return widget
class ComboBox(QtWidgets.QComboBox):
"""Custom read-only combo box with a convenient API"""
def __init__(self, items=None, editable=False, parent=None, transform=None):
super().__init__(parent)
self.setEditable(editable)
self.transform = transform
self.item_data = []
if items:
self.addItems(items)
self.item_data.extend(items)
def set_index(self, idx):
idx = utils.clamp(idx, 0, self.count() - 1)
self.setCurrentIndex(idx)
def add_item(self, text, data):
self.addItem(text)
self.item_data.append(data)
def current_data(self):
return self.item_data[self.currentIndex()]
def set_value(self, value):
if self.transform:
value = self.transform(value)
try:
index = self.item_data.index(value)
except ValueError:
index = 0
self.setCurrentIndex(index)
def combo(items, editable=False, tooltip='', parent=None):
"""Create a readonly (by default) combo box from a list of items"""
combobox = ComboBox(editable=editable, items=items, parent=parent)
if tooltip:
combobox.setToolTip(tooltip)
return combobox
def combo_mapped(data, editable=False, transform=None, parent=None):
"""Create a readonly (by default) combo box from a list of items"""
widget = ComboBox(editable=editable, transform=transform, parent=parent)
for k, v in data:
widget.add_item(k, v)
return widget
def textbrowser(text=None):
"""Create a QTextBrowser for the specified text"""
widget = QtWidgets.QTextBrowser()
widget.setOpenExternalLinks(True)
if text:
widget.setText(text)
return widget
def link(url, text, palette=None):
if palette is None:
palette = QtGui.QPalette()
color = palette.color(QtGui.QPalette.WindowText)
rgb_color = f'rgb({color.red()}, {color.green()}, {color.blue()})'
scope = {'rgb': rgb_color, 'text': text, 'url': url}
return (
"""
<a style="font-style: italic; text-decoration: none; color: %(rgb)s;"
href="%(url)s">
%(text)s
</a>
"""
% scope
)
def add_completer(widget, items):
"""Add simple completion to a widget"""
completer = QtWidgets.QCompleter(items, widget)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setCompletionMode(QtWidgets.QCompleter.InlineCompletion)
widget.setCompleter(completer)
def prompt(msg, title=None, text='', parent=None):
"""Presents the user with an input widget and returns the input."""
if title is None:
title = msg
if parent is None:
parent = active_window()
result = QtWidgets.QInputDialog.getText(
parent, title, msg, QtWidgets.QLineEdit.Normal, text
)
return (result[0], result[1])
def prompt_n(msg, inputs):
"""Presents the user with N input widgets and returns the results"""
dialog = QtWidgets.QDialog(active_window())
dialog.setWindowModality(Qt.WindowModal)
dialog.setWindowTitle(msg)
long_value = msg
for k, v in inputs:
if len(k + v) > len(long_value):
long_value = k + v
min_width = min(720, text_width(dialog.font(), long_value) + 100)
dialog.setMinimumWidth(min_width)
ok_b = ok_button(msg, enabled=False)
close_b = close_button()
form_widgets = []
def get_values():
return [pair[1].text().strip() for pair in form_widgets]
for name, value in inputs:
lineedit = QtWidgets.QLineEdit()
# Enable the OK button only when all fields have been populated
lineedit.textChanged.connect(
lambda x: ok_b.setEnabled(all(get_values())), type=Qt.QueuedConnection
)
if value:
lineedit.setText(value)
form_widgets.append((name, lineedit))
# layouts
form_layout = form(defs.no_margin, defs.button_spacing, *form_widgets)
button_layout = hbox(defs.no_margin, defs.button_spacing, STRETCH, close_b, ok_b)
main_layout = vbox(defs.margin, defs.button_spacing, form_layout, button_layout)
dialog.setLayout(main_layout)
# connections
connect_button(ok_b, dialog.accept)
connect_button(close_b, dialog.reject)
accepted = dialog.exec_() == QtWidgets.QDialog.Accepted
text = get_values()
success = accepted and all(text)
return (success, text)
def standard_item_type_value(value):
"""Return a custom UserType for use in QTreeWidgetItem.type() overrides"""
return custom_item_type_value(QtGui.QStandardItem, value)
def graphics_item_type_value(value):
"""Return a custom UserType for use in QGraphicsItem.type() overrides"""
return custom_item_type_value(QtWidgets.QGraphicsItem, value)
def custom_item_type_value(cls, value):
"""Return a custom cls.UserType for use in cls.type() overrides"""
user_type = enum_value(cls.UserType)
return user_type + value
def enum_value(value):
"""Qt6 has enums with an inner '.value' attribute."""
if hasattr(value, 'value'):
value = value.value
return value
class TreeWidgetItem(QtWidgets.QTreeWidgetItem):
TYPE = standard_item_type_value(101)
def __init__(self, path, icon, deleted):
QtWidgets.QTreeWidgetItem.__init__(self)
self.path = path
self.deleted = deleted
self.setIcon(0, icons.from_name(icon))
self.setText(0, path)
def type(self):
return self.TYPE
def paths_from_indexes(model, indexes, item_type=TreeWidgetItem.TYPE, item_filter=None):
"""Return paths from a list of QStandardItemModel indexes"""
items = [model.itemFromIndex(i) for i in indexes]
return paths_from_items(items, item_type=item_type, item_filter=item_filter)
def _true_filter(_value):
return True
def paths_from_items(items, item_type=TreeWidgetItem.TYPE, item_filter=None):
"""Return a list of paths from a list of items"""
if item_filter is None:
item_filter = _true_filter
return [i.path for i in items if i.type() == item_type and item_filter(i)]
def tree_selection(tree_item, items):
"""Returns an array of model items that correspond to the selected
QTreeWidgetItem children"""
selected = []
count = min(tree_item.childCount(), len(items))
for idx in range(count):
if tree_item.child(idx).isSelected():
selected.append(items[idx])
return selected
def tree_selection_items(tree_item):
"""Returns selected widget items"""
selected = []
for idx in range(tree_item.childCount()):
child = tree_item.child(idx)
if child.isSelected():
selected.append(child)
return selected
def selected_item(list_widget, items):
"""Returns the model item that corresponds to the selected QListWidget
row."""
widget_items = list_widget.selectedItems()
if not widget_items:
return None
widget_item = widget_items[0]
row = list_widget.row(widget_item)
if row < len(items):
item = items[row]
else:
item = None
return item
def selected_items(list_widget, items):
"""Returns an array of model items that correspond to the selected
QListWidget rows."""
item_count = len(items)
selected = []
for widget_item in list_widget.selectedItems():
row = list_widget.row(widget_item)
if row < item_count:
selected.append(items[row])
return selected
def open_file(title, directory=None):
"""Creates an Open File dialog and returns a filename."""
result = compat.getopenfilename(
parent=active_window(), caption=title, basedir=directory
)
return result[0]
def open_files(title, directory=None, filters=''):
"""Creates an Open File dialog and returns a list of filenames."""
result = compat.getopenfilenames(
parent=active_window(), caption=title, basedir=directory, filters=filters
)
return result[0]
def _enum_value(value):
"""Resolve Qt6 enum values"""
if hasattr(value, 'value'):
return value.value
return value
def opendir_dialog(caption, path):
"""Prompts for a directory path"""
options = QtWidgets.QFileDialog.Option(
_enum_value(QtWidgets.QFileDialog.Directory)
| _enum_value(QtWidgets.QFileDialog.DontResolveSymlinks)
| _enum_value(QtWidgets.QFileDialog.ReadOnly)
| _enum_value(QtWidgets.QFileDialog.ShowDirsOnly)
)
return compat.getexistingdirectory(
parent=active_window(), caption=caption, basedir=path, options=options
)
def save_as(filename, title='Save As...'):
"""Creates a Save File dialog and returns a filename."""
result = compat.getsavefilename(
parent=active_window(), caption=title, basedir=filename
)
return result[0]
def existing_file(directory, title='Append...'):
"""Creates a Save File dialog and returns a filename."""
result = compat.getopenfilename(
parent=active_window(), caption=title, basedir=directory
)
return result[0]
def copy_path(filename, absolute=True):
"""Copy a filename to the clipboard"""
if filename is None:
return
if absolute:
filename = core.abspath(filename)
set_clipboard(filename)
def set_clipboard(text):
"""Sets the copy/paste buffer to text."""
if not text:
return
clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(text, QtGui.QClipboard.Clipboard)
if not utils.is_darwin() and not utils.is_win32():
clipboard.setText(text, QtGui.QClipboard.Selection)
persist_clipboard()
def persist_clipboard():
"""Persist the clipboard
X11 stores only a reference to the clipboard data.
Send a clipboard event to force a copy of the clipboard to occur.
This ensures that the clipboard is present after git-cola exits.
Otherwise, the reference is destroyed on exit.
C.f. https://stackoverflow.com/questions/2007103/how-can-i-disable-clear-of-clipboard-on-exit-of-pyqt4-application
""" # noqa
clipboard = QtWidgets.QApplication.clipboard()
event = QtCore.QEvent(QtCore.QEvent.Clipboard)
QtWidgets.QApplication.sendEvent(clipboard, event)
def add_action_bool(widget, text, func, checked, *shortcuts):
tip = text
action = _add_action(widget, text, tip, func, connect_action_bool, *shortcuts)
action.setCheckable(True)
action.setChecked(checked)
return action
def add_action(widget, text, func, *shortcuts):
"""Create a QAction and bind it to the `func` callback and hotkeys"""
tip = text
return _add_action(widget, text, tip, func, connect_action, *shortcuts)
def add_action_with_icon(widget, icon, text, func, *shortcuts):
"""Create a QAction using a custom icon bound to the `func` callback and hotkeys"""
tip = text
action = _add_action(widget, text, tip, func, connect_action, *shortcuts)
action.setIcon(icon)
return action
def add_action_with_tooltip(widget, text, tip, func, *shortcuts):
"""Create an action with a tooltip"""
return _add_action(widget, text, tip, func, connect_action, *shortcuts)
def menu_separator(widget, text=''):
"""Return a QAction whose isSeparator() returns true. Used in context menus"""
action = QtWidgets.QAction(text, widget)
action.setSeparator(True)
return action
def _add_action(widget, text, tip, func, connect, *shortcuts):
action = QtWidgets.QAction(text, widget)
if hasattr(action, 'setIconVisibleInMenu'):
action.setIconVisibleInMenu(True)
if tip:
action.setStatusTip(tip)
connect(action, func)
if shortcuts:
action.setShortcuts(shortcuts)
if hasattr(Qt, 'WidgetWithChildrenShortcut'):
action.setShortcutContext(Qt.WidgetWithChildrenShortcut)
widget.addAction(action)
return action
def set_selected_item(widget, idx):
"""Sets the currently selected item to the item at index idx."""
if isinstance(widget, QtWidgets.QTreeWidget):
item = widget.topLevelItem(idx)
if item:
item.setSelected(True)
widget.setCurrentItem(item)
def add_items(widget, items):
"""Adds items to a widget."""
for item in items:
if item is None:
continue
widget.addItem(item)
def set_items(widget, items):
"""Clear the existing widget contents and set the new items."""
widget.clear()
add_items(widget, items)
def create_treeitem(filename, staged=False, deleted=False, untracked=False):
"""Given a filename, return a TreeWidgetItem for a status widget
"staged", "deleted, and "untracked" control which icon is used.
"""
icon_name = icons.status(filename, deleted, staged, untracked)
icon = icons.name_from_basename(icon_name)
return TreeWidgetItem(filename, icon, deleted=deleted)
def add_close_action(widget):
"""Adds close action and shortcuts to a widget."""
return add_action(widget, N_('Close...'), widget.close, hotkeys.CLOSE, hotkeys.QUIT)
def app():
"""Return the current application"""
return QtWidgets.QApplication.instance()
def desktop_size():
rect = app().primaryScreen().geometry()
return (rect.width(), rect.height())
def center_on_screen(widget):
"""Move widget to the center of the default screen"""
width, height = desktop_size()
center_x = width // 2
center_y = height // 2
widget.move(center_x - widget.width() // 2, center_y - widget.height() // 2)
def default_size(parent, width, height, use_parent_height=True):
"""Return the parent's size, or the provided defaults"""
if parent is not None:
width = parent.width()
if use_parent_height:
height = parent.height()
return (width, height)
def default_monospace_font():
if utils.is_darwin():
family = 'Monaco'
elif utils.is_win32():
family = 'Courier'
else:
family = 'Monospace'
mfont = QtGui.QFont()
mfont.setFamily(family)
return mfont
def diff_font_str(context):
cfg = context.cfg
font_str = cfg.get(prefs.FONTDIFF)
if not font_str:
font_str = default_monospace_font().toString()
return font_str
def diff_font(context):
return font_from_string(diff_font_str(context))
def font_from_string(string):
qfont = QtGui.QFont()
qfont.fromString(string)
return qfont
def create_button(
text='', layout=None, tooltip=None, icon=None, enabled=True, default=False
):
"""Create a button, set its title, and add it to the parent."""
button = QtWidgets.QPushButton()
button.setCursor(Qt.PointingHandCursor)
button.setFocusPolicy(Qt.NoFocus)
if text:
button.setText(' ' + text)
if icon is not None:
button.setIcon(icon)
button.setIconSize(QtCore.QSize(defs.small_icon, defs.small_icon))
if tooltip is not None:
button.setToolTip(tooltip)
if layout is not None:
layout.addWidget(button)
if not enabled:
button.setEnabled(False)
if default:
button.setDefault(True)
return button
def tool_button():
"""Create a flat border-less button"""
button = QtWidgets.QToolButton()
button.setPopupMode(QtWidgets.QToolButton.InstantPopup)
button.setCursor(Qt.PointingHandCursor)
button.setFocusPolicy(Qt.NoFocus)
# Highlight colors
palette = QtGui.QPalette()
highlight = palette.color(QtGui.QPalette.Highlight)
highlight_rgb = rgb_css(highlight)
button.setStyleSheet(
"""
/* No borders */
QToolButton {
border: none;
background-color: none;
}
/* Hide the menu indicator */
QToolButton::menu-indicator {
image: none;
}
QToolButton:hover {
border: %(border)spx solid %(highlight_rgb)s;
}
"""
% {
'border': defs.border,
'highlight_rgb': highlight_rgb,
}
)
return button
def create_action_button(tooltip=None, icon=None, visible=None):
"""Create a small tool button for use in dock title widgets"""
button = tool_button()
if tooltip is not None:
button.setToolTip(tooltip)
if icon is not None:
button.setIcon(icon)
button.setIconSize(QtCore.QSize(defs.small_icon, defs.small_icon))
if visible is not None:
button.setVisible(visible)
return button
def ok_button(text, default=True, enabled=True, icon=None):
if icon is None:
icon = icons.ok()
return create_button(text=text, icon=icon, default=default, enabled=enabled)
def close_button(text=None, icon=None):
text = text or N_('Close')
icon = icons.mkicon(icon, icons.close)
return create_button(text=text, icon=icon)
def edit_button(enabled=True, default=False):
return create_button(
text=N_('Edit'), icon=icons.edit(), enabled=enabled, default=default
)
def refresh_button(enabled=True, default=False):
return create_button(
text=N_('Refresh'), icon=icons.sync(), enabled=enabled, default=default
)
def checkbox(text='', tooltip='', checked=None):
"""Create a checkbox"""
return _checkbox(QtWidgets.QCheckBox, text, tooltip, checked)
def radio(text='', tooltip='', checked=None):
"""Create a radio button"""
return _checkbox(QtWidgets.QRadioButton, text, tooltip, checked)
def _checkbox(cls, text, tooltip, checked):
"""Create a widget and apply properties"""
widget = cls()
if text:
widget.setText(text)
if tooltip:
widget.setToolTip(tooltip)
if checked is not None:
widget.setChecked(checked)
return widget
class DockTitleBarWidget(QtWidgets.QFrame):
def __init__(self, parent, title, stretch=True):
QtWidgets.QFrame.__init__(self, parent)
self.setAutoFillBackground(True)
self.label = qlabel = QtWidgets.QLabel(title, self)
qfont = qlabel.font()
qfont.setBold(True)
qlabel.setFont(qfont)
qlabel.setCursor(Qt.OpenHandCursor)
self.close_button = create_action_button(
tooltip=N_('Close'), icon=icons.close()
)
self.toggle_button = create_action_button(
tooltip=N_('Detach'), icon=icons.external()
)
self.corner_layout = hbox(defs.no_margin, defs.spacing)
self.title_layout = hbox(defs.no_margin, defs.button_spacing, qlabel)
if stretch:
separator = STRETCH
else:
separator = SKIPPED
self.main_layout = hbox(
defs.small_margin,
defs.titlebar_spacing,
self.title_layout,
separator,
self.corner_layout,
self.toggle_button,
self.close_button,
)
self.setLayout(self.main_layout)
connect_button(self.toggle_button, self.toggle_floating)
connect_button(self.close_button, self.toggle_visibility)
def toggle_floating(self):
self.parent().setFloating(not self.parent().isFloating())
self.update_tooltips()
def toggle_visibility(self):
self.parent().toggleViewAction().trigger()
def set_title(self, title):
self.label.setText(title)
def add_title_widget(self, widget):
"""Add widgets to the title area"""
self.title_layout.addWidget(widget)
def add_corner_widget(self, widget):
"""Add widgets to the corner area"""
self.corner_layout.addWidget(widget)
def update_tooltips(self):
if self.parent().isFloating():
tooltip = N_('Attach')
else:
tooltip = N_('Detach')
self.toggle_button.setToolTip(tooltip)
def create_dock(name, title, parent, stretch=True, widget=None, func=None):
"""Create a dock widget and set it up accordingly."""
dock = QtWidgets.QDockWidget(parent)
dock.setWindowTitle(title)
dock.setObjectName(name)
titlebar = DockTitleBarWidget(dock, title, stretch=stretch)
dock.setTitleBarWidget(titlebar)
dock.setAutoFillBackground(True)
if hasattr(parent, 'dockwidgets'):
parent.dockwidgets.append(dock)
if func:
widget = func(dock)
if widget:
dock.setWidget(widget)
return dock
def hide_dock(widget):
widget.toggleViewAction().setChecked(False)
widget.hide()
def create_menu(title, parent):
"""Create a menu and set its title."""
qmenu = DebouncingMenu(title, parent)
return qmenu
class DebouncingMenu(QtWidgets.QMenu):
"""Menu that debounces mouse release action i.e. stops it if occurred
right after menu creation.
Disables annoying behaviour when RMB is pressed to show menu, cursor is
moved accidentally 1 px onto newly created menu and released causing to
execute menu action
"""
threshold_ms = 400
def __init__(self, title, parent):
QtWidgets.QMenu.__init__(self, title, parent)
self.created_at = utils.epoch_millis()
if hasattr(self, 'setToolTipsVisible'):
self.setToolTipsVisible(True)
def mouseReleaseEvent(self, event):
threshold = DebouncingMenu.threshold_ms
if (utils.epoch_millis() - self.created_at) > threshold:
QtWidgets.QMenu.mouseReleaseEvent(self, event)
def add_menu(title, parent):
"""Create a menu and set its title."""
menu = create_menu(title, parent)
if hasattr(parent, 'addMenu'):
parent.addMenu(menu)
else:
parent.addAction(menu.menuAction())
return menu
def create_toolbutton(text=None, layout=None, tooltip=None, icon=None):
button = tool_button()
if icon is not None:
button.setIcon(icon)
button.setIconSize(QtCore.QSize(defs.default_icon, defs.default_icon))
if text is not None:
button.setText(' ' + text)
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
if tooltip is not None:
button.setToolTip(tooltip)
if layout is not None:
layout.addWidget(button)
return button
def create_toolbutton_with_callback(callback, text, icon, tooltip, layout=None):
"""Create a tool button that runs the specified callback"""
toolbutton = create_toolbutton(text=text, layout=layout, tooltip=tooltip, icon=icon)
connect_button(toolbutton, callback)
return toolbutton
def mimedata_from_paths(context, paths, include_urls=True):
"""Return mime data with a list of absolute path URLs
Set `include_urls` to False to prevent URLs from being included
in the mime data. This is useful in some terminals that do not gracefully handle
multiple URLs being included in the payload.
This allows the mime data to contain just plain a plain text value that we
are able to format ourselves.
Older versions of gnome-terminal expected a UTF-16 encoding, but that
behavior is no longer needed.
""" # noqa
abspaths = [core.abspath(path) for path in paths]
paths_text = core.list2cmdline(abspaths)
# The text/x-moz-list format is always included by Qt, and doing
# mimedata.removeFormat('text/x-moz-url') has no effect.
# http://www.qtcentre.org/threads/44643-Dragging-text-uri-list-Qt-inserts-garbage
#
# Older versions of gnome-terminal expect UTF-16 encoded text, but other terminals,
# e.g. terminator, expect UTF-8, so use cola.dragencoding to override the default.
# NOTE: text/x-moz-url does not seem to be used/needed by modern versions of
# gnome-terminal, kitty, and terminator.
mimedata = QtCore.QMimeData()
mimedata.setText(paths_text)
if include_urls:
urls = [QtCore.QUrl.fromLocalFile(path) for path in abspaths]
encoding = context.cfg.get('cola.dragencoding', 'utf-16')
encoded_text = core.encode(paths_text, encoding=encoding)
mimedata.setUrls(urls)
mimedata.setData('text/x-moz-url', encoded_text)
return mimedata
def path_mimetypes(include_urls=True):
"""Return a list of mime types that we generate"""
mime_types = [
'text/plain',
'text/plain;charset=utf-8',
]
if include_urls:
mime_types.append('text/uri-list')
mime_types.append('text/x-moz-url')
return mime_types
class BlockSignals:
"""Context manager for blocking a signals on a widget"""
def __init__(self, *widgets):
self.widgets = widgets
self.values = []
def __enter__(self):
"""Block Qt signals for all of the captured widgets"""
self.values = [widget.blockSignals(True) for widget in self.widgets]
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Restore Qt signals when we exit the scope"""
for widget, value in zip(self.widgets, self.values):
widget.blockSignals(value)
class Channel(QtCore.QObject):
finished = Signal(object)
result = Signal(object)
class Task(QtCore.QRunnable):
"""Run a task in the background and return the result using a Channel"""
def __init__(self):
QtCore.QRunnable.__init__(self)
self.channel = Channel()
self.result = None
# Python's garbage collector will try to double-free the task
# once it's finished so disable the Qt auto-deletion.
self.setAutoDelete(False)
def run(self):
self.result = self.task()
self.channel.result.emit(self.result)
self.channel.finished.emit(self)
def task(self):
"""Perform a long-running task"""
return ()
def connect(self, handler):
self.channel.result.connect(handler, type=Qt.QueuedConnection)
class SimpleTask(Task):
"""Run a simple callable as a task"""
def __init__(self, func, *args, **kwargs):
Task.__init__(self)
self.func = func
self.args = args
self.kwargs = kwargs
def task(self):
return self.func(*self.args, **self.kwargs)
class RunTask(QtCore.QObject):
"""Runs QRunnable instances and transfers control when they finish"""
def __init__(self, parent=None):
QtCore.QObject.__init__(self, parent)
self.tasks = []
self.task_details = {}
self.threadpool = QtCore.QThreadPool.globalInstance()
self.result_func = None
def start(self, task, progress=None, finish=None, result=None):
"""Start the task and register a callback"""
self.result_func = result
if progress is not None:
if hasattr(progress, 'start'):
progress.start()
# prevents garbage collection bugs in certain PyQt4 versions
self.tasks.append(task)
task_id = id(task)
self.task_details[task_id] = (progress, finish, result)
task.channel.finished.connect(self.finish, type=Qt.QueuedConnection)
self.threadpool.start(task)
def finish(self, task):
"""The task has finished. Run the finish and result callbacks"""
task_id = id(task)
try:
self.tasks.remove(task)
except ValueError:
pass
try:
progress, finish, result = self.task_details[task_id]
del self.task_details[task_id]
except KeyError:
finish = progress = result = None
if progress is not None:
if hasattr(progress, 'stop'):
progress.stop()
progress.hide()
if result is not None:
result(task.result)
if finish is not None:
finish(task)
def wait(self):
"""Wait until all tasks have finished processing"""
self.threadpool.waitForDone()
# Syntax highlighting
def rgb(red, green, blue):
"""Create a QColor from r, g, b arguments"""
color = QtGui.QColor()
color.setRgb(red, green, blue)
return color
def rgba(red, green, blue, alpha=255):
"""Create a QColor with alpha from r, g, b, a arguments"""
color = rgb(red, green, blue)
color.setAlpha(alpha)
return color
def rgb_triple(args):
"""Create a QColor from an argument with an [r, g, b] triple"""
return rgb(*args)
def rgb_css(color):
"""Convert a QColor into an rgb #abcdef CSS string"""
return '#%s' % rgb_hex(color)
def rgb_hex(color):
"""Convert a QColor into a hex aabbcc string"""
return f'{color.red():02x}{color.green():02x}{color.blue():02x}'
def clamp_color(value):
"""Clamp an integer value between 0 and 255"""
return min(255, max(value, 0))
def css_color(value):
"""Convert a #abcdef hex string into a QColor"""
if value.startswith('#'):
value = value[1:]
try:
red = clamp_color(int(value[:2], base=16)) # ab
except ValueError:
red = 255
try:
green = clamp_color(int(value[2:4], base=16)) # cd
except ValueError:
green = 255
try:
blue = clamp_color(int(value[4:6], base=16)) # ef
except ValueError:
blue = 255
return rgb(red, green, blue)
def hsl(hue, saturation, lightness):
"""Return a QColor from an hue, saturation and lightness"""
return QtGui.QColor.fromHslF(
utils.clamp(hue, 0.0, 1.0),
utils.clamp(saturation, 0.0, 1.0),
utils.clamp(lightness, 0.0, 1.0),
)
def hsl_css(hue, saturation, lightness):
"""Convert HSL values to a CSS #abcdef color string"""
return rgb_css(hsl(hue, saturation, lightness))
def make_format(foreground=None, background=None, bold=False):
"""Create a QTextFormat from the provided foreground, background and bold values"""
fmt = QtGui.QTextCharFormat()
if foreground:
fmt.setForeground(foreground)
if background:
fmt.setBackground(background)
if bold:
fmt.setFontWeight(QtGui.QFont.Bold)
return fmt
class ImageFormats:
def __init__(self):
# returns a list of QByteArray objects
formats_qba = QtGui.QImageReader.supportedImageFormats()
# portability: python3 data() returns bytes, python2 returns str
decode = core.decode
formats = [decode(x.data()) for x in formats_qba]
self.extensions = {'.' + fmt for fmt in formats}
def ok(self, filename):
_, ext = os.path.splitext(filename)
return ext.lower() in self.extensions
def set_scrollbar_values(widget, hscroll_value, vscroll_value):
"""Set scrollbars to the specified values"""
hscroll = widget.horizontalScrollBar()
if hscroll and hscroll_value is not None:
hscroll.setValue(hscroll_value)
vscroll = widget.verticalScrollBar()
if vscroll and vscroll_value is not None:
vscroll.setValue(vscroll_value)
def get_scrollbar_values(widget):
"""Return the current (hscroll, vscroll) scrollbar values for a widget"""
hscroll = widget.horizontalScrollBar()
if hscroll:
hscroll_value = get(hscroll)
else:
hscroll_value = None
vscroll = widget.verticalScrollBar()
if vscroll:
vscroll_value = get(vscroll)
else:
vscroll_value = None
return (hscroll_value, vscroll_value)
def scroll_to_item(widget, item):
"""Scroll to an item while retaining the horizontal scroll position"""
hscroll = None
hscrollbar = widget.horizontalScrollBar()
if hscrollbar:
hscroll = get(hscrollbar)
widget.scrollToItem(item)
if hscroll is not None:
hscrollbar.setValue(hscroll)
def select_item(widget, item):
"""Scroll to and make a QTreeWidget item selected and current"""
scroll_to_item(widget, item)
widget.setCurrentItem(item)
item.setSelected(True)
def get_selected_values(widget, top_level_idx, values):
"""Map the selected items under the top-level item to the values list"""
# Get the top-level item
item = widget.topLevelItem(top_level_idx)
return tree_selection(item, values)
def get_selected_items(widget, idx):
"""Return the selected items under the top-level item"""
item = widget.topLevelItem(idx)
return tree_selection_items(item)
def add_menu_actions(menu, menu_actions):
"""Add actions to a menu, treating None as a separator"""
current_actions = menu.actions()
if current_actions:
first_action = current_actions[0]
else:
first_action = None
menu.addSeparator()
for action in menu_actions:
if action is None:
action = menu_separator(menu)
menu.insertAction(first_action, action)
def fontmetrics_width(metrics, text):
"""Get the width in pixels of specified text
Calls QFontMetrics.horizontalAdvance() when available.
QFontMetricswidth() is deprecated. Qt 5.11 added horizontalAdvance().
"""
if hasattr(metrics, 'horizontalAdvance'):
return metrics.horizontalAdvance(text)
return metrics.width(text)
def text_width(font, text):
"""Get the width in pixels for the QFont and text"""
metrics = QtGui.QFontMetrics(font)
return fontmetrics_width(metrics, text)
def text_size(font, text):
"""Return the width in pixels for the specified text
:param font_or_widget: The QFont or widget providing the font to use.
:param text: The text to measure.
"""
metrics = QtGui.QFontMetrics(font)
return (fontmetrics_width(metrics, text), metrics.height())
| 39,535 | Python | .py | 1,012 | 32.623518 | 118 | 0.67718 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
42 | polib.py | git-cola_git-cola/cola/polib.py | #
# License: MIT (see extras/polib/LICENSE file provided)
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
"""
**polib** allows you to manipulate, create, modify gettext files (pot, po and
mo files). You can load existing files, iterate through it's entries, add,
modify entries, comments or metadata, etc. or create new po files from scratch.
**polib** provides a simple and pythonic API via the :func:`~polib.pofile` and
:func:`~polib.mofile` convenience functions.
"""
import array
import codecs
import os
import re
import struct
import sys
import textwrap
import io
from . import compat
__author__ = 'David Jean Louis <[email protected]>'
__version__ = '1.1.1'
__all__ = [
'pofile',
'POFile',
'POEntry',
'mofile',
'MOFile',
'MOEntry',
'default_encoding',
'escape',
'unescape',
'detect_encoding',
]
# the default encoding to use when encoding cannot be detected
default_encoding = 'utf-8'
# python 2/3 compatibility helpers {{{
PY3 = True
text_type = str
def b(s):
return s.encode('utf-8')
def u(s):
return s
# }}}
# _pofile_or_mofile {{{
def _pofile_or_mofile(f, filetype, **kwargs):
"""
Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to
honor the DRY concept.
"""
# get the file encoding
enc = kwargs.get('encoding')
if enc is None:
enc = detect_encoding(f, filetype == 'mofile')
# parse the file
kls = _POFileParser if filetype == 'pofile' else _MOFileParser
parser = kls(
f,
encoding=enc,
check_for_duplicates=kwargs.get('check_for_duplicates', False),
klass=kwargs.get('klass'),
)
instance = parser.parse()
instance.wrapwidth = kwargs.get('wrapwidth', 78)
return instance
# }}}
# _is_file {{{
def _is_file(filename_or_contents):
"""
Safely returns the value of os.path.exists(filename_or_contents).
Arguments:
``filename_or_contents``
either a filename, or a string holding the contents of some file.
In the latter case, this function will always return False.
"""
try:
return os.path.isfile(filename_or_contents)
except (TypeError, ValueError, UnicodeEncodeError):
return False
# }}}
# function pofile() {{{
def pofile(pofile, **kwargs):
"""
Convenience function that parses the po or pot file ``pofile`` and returns
a :class:`~polib.POFile` instance.
Arguments:
``pofile``
string, full or relative path to the po/pot file or its content (data).
``wrapwidth``
integer, the wrap width, only useful when the ``-w`` option was passed
to xgettext (optional, default: ``78``).
``encoding``
string, the encoding to use (e.g. "utf-8") (default: ``None``, the
encoding will be auto-detected).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file (optional, default: ``False``).
``klass``
class which is used to instantiate the return value (optional,
default: ``None``, the return value with be a :class:`~polib.POFile`
instance).
"""
return _pofile_or_mofile(pofile, 'pofile', **kwargs)
# }}}
# function mofile() {{{
def mofile(mofile, **kwargs):
"""
Convenience function that parses the mo file ``mofile`` and returns a
:class:`~polib.MOFile` instance.
Arguments:
``mofile``
string, full or relative path to the mo file or its content (string
or bytes).
``wrapwidth``
integer, the wrap width, only useful when the ``-w`` option was passed
to xgettext to generate the po file that was used to format the mo file
(optional, default: ``78``).
``encoding``
string, the encoding to use (e.g. "utf-8") (default: ``None``, the
encoding will be auto-detected).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file (optional, default: ``False``).
``klass``
class which is used to instantiate the return value (optional,
default: ``None``, the return value with be a :class:`~polib.POFile`
instance).
"""
return _pofile_or_mofile(mofile, 'mofile', **kwargs)
# }}}
# function detect_encoding() {{{
def detect_encoding(file, binary_mode=False):
"""
Try to detect the encoding used by the ``file``. The ``file`` argument can
be a PO or MO file path or a string containing the contents of the file.
If the encoding cannot be detected, the function will return the value of
``default_encoding``.
Arguments:
``file``
string, full or relative path to the po/mo file or its content.
``binary_mode``
boolean, set this to True if ``file`` is a mo file.
"""
PATTERN = r'"?Content-Type:.+? charset=([\w_\-:\.]+)'
rxt = re.compile(u(PATTERN))
rxb = re.compile(b(PATTERN))
def charset_exists(charset):
"""Check whether ``charset`` is valid or not."""
try:
codecs.lookup(charset)
except LookupError:
return False
return True
if not _is_file(file):
try:
match = rxt.search(file)
except TypeError:
match = rxb.search(file)
if match:
enc = match.group(1).strip()
if not isinstance(enc, text_type):
enc = enc.decode('utf-8')
if charset_exists(enc):
return enc
else:
# For PY3, always treat as binary
if binary_mode or PY3:
mode = 'rb'
rx = rxb
else:
mode = 'r'
rx = rxt
f = open(file, mode)
for line in f.readlines():
match = rx.search(line)
if match:
f.close()
enc = match.group(1).strip()
if not isinstance(enc, text_type):
enc = enc.decode('utf-8')
if charset_exists(enc):
return enc
f.close()
return default_encoding
# }}}
# function escape() {{{
def escape(st):
"""
Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
the given string ``st`` and returns it.
"""
return (
st.replace('\\', r'\\')
.replace('\t', r'\t')
.replace('\r', r'\r')
.replace('\n', r'\n')
.replace('"', r'\"')
)
# }}}
# function unescape() {{{
def unescape(st):
"""
Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
the given string ``st`` and returns it.
"""
def unescape_repl(m):
m = m.group(1)
if m == 'n':
return '\n'
if m == 't':
return '\t'
if m == 'r':
return '\r'
if m == '\\':
return '\\'
return m # handles escaped double quote
return re.sub(r'\\(\\|n|t|r|")', unescape_repl, st)
# }}}
# function natural_sort() {{{
def natural_sort(lst):
"""
Sort naturally the given list.
Credits: http://stackoverflow.com/a/4836734
"""
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(lst, key=alphanum_key)
# }}}
# class _BaseFile {{{
class _BaseFile(list):
"""
Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile`
classes. This class should **not** be instantiated directly.
"""
def __init__(self, *_args, **kwargs):
"""
Constructor, accepts the following keyword arguments:
``pofile``
string, the path to the po or mo file, or its content as a string.
``wrapwidth``
integer, the wrap width, only useful when the ``-w`` option was
passed to xgettext (optional, default: ``78``).
``encoding``
string, the encoding to use, defaults to ``default_encoding``
global variable (optional).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file, (optional, default: ``False``).
"""
list.__init__(self)
# the opened file handle
pofile = kwargs.get('pofile', None)
if pofile and _is_file(pofile):
self.fpath = pofile
else:
self.fpath = kwargs.get('fpath')
# the width at which lines should be wrapped
self.wrapwidth = kwargs.get('wrapwidth', 78)
# the file encoding
self.encoding = kwargs.get('encoding', default_encoding)
# whether to check for duplicate entries or not
self.check_for_duplicates = kwargs.get('check_for_duplicates', False)
# header
self.header = ''
# both po and mo files have metadata
self.metadata = {}
self.metadata_is_fuzzy = 0
def __unicode__(self):
"""
Returns the unicode representation of the file.
"""
ret = []
entries = [self.metadata_as_entry()] + [e for e in self if not e.obsolete]
for entry in entries:
ret.append(entry.__unicode__(self.wrapwidth))
for entry in self.obsolete_entries():
ret.append(entry.__unicode__(self.wrapwidth))
ret = u('\n').join(ret)
return ret
if PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
"""
Returns the string representation of the file.
"""
return compat.ustr(self).encode(self.encoding)
def __contains__(self, entry):
"""
Overridden ``list`` method to implement the membership test (in and
not in).
The method considers that an entry is in the file if it finds an entry
that has the same msgid (the test is **case sensitive**) and the same
msgctxt (or none for both entries).
Argument:
``entry``
an instance of :class:`~polib._BaseEntry`.
"""
return self.find(entry.msgid, by='msgid', msgctxt=entry.msgctxt) is not None
def __eq__(self, other):
return str(self) == str(other)
def __hash__(self):
return hash(str(self))
def append(self, entry):
"""
Overridden method to check for duplicates entries, if a user tries to
add an entry that is already in the file, the method will raise a
``ValueError`` exception.
Argument:
``entry``
an instance of :class:`~polib._BaseEntry`.
"""
# check_for_duplicates may not be defined (yet) when unpickling.
# But if pickling, we never want to check for duplicates anyway.
if getattr(self, 'check_for_duplicates', False) and entry in self:
raise ValueError('Entry "%s" already exists' % entry.msgid)
super().append(entry)
def insert(self, index, entry):
"""
Overridden method to check for duplicates entries, if a user tries to
add an entry that is already in the file, the method will raise a
``ValueError`` exception.
Arguments:
``index``
index at which the entry should be inserted.
``entry``
an instance of :class:`~polib._BaseEntry`.
"""
if self.check_for_duplicates and entry in self:
raise ValueError('Entry "%s" already exists' % entry.msgid)
super().insert(index, entry)
def metadata_as_entry(self):
"""
Returns the file metadata as a :class:`~polib.POFile` instance.
"""
e = POEntry(msgid='')
mdata = self.ordered_metadata()
if mdata:
strs = []
for name, value in mdata:
# Strip whitespace off each line in a multi-line entry
strs.append(f'{name}: {value}')
e.msgstr = '\n'.join(strs) + '\n'
if self.metadata_is_fuzzy:
e.flags.append('fuzzy')
return e
def save(self, fpath=None, repr_method='__unicode__', newline=None):
"""
Saves the po file to ``fpath``.
If it is an existing file and no ``fpath`` is provided, then the
existing file is rewritten with the modified data.
Keyword arguments:
``fpath``
string, full or relative path to the file.
``repr_method``
string, the method to use for output.
``newline``
string, controls how universal newlines works
"""
if self.fpath is None and fpath is None:
raise OSError('You must provide a file path to save() method')
contents = getattr(self, repr_method)()
if fpath is None:
fpath = self.fpath
if repr_method == 'to_binary':
fhandle = open(fpath, 'wb')
else:
fhandle = open(fpath, 'w', encoding=self.encoding, newline=newline)
if not isinstance(contents, text_type):
contents = contents.decode(self.encoding)
fhandle.write(contents)
fhandle.close()
# set the file path if not set
if self.fpath is None and fpath:
self.fpath = fpath
def find(self, st, by='msgid', include_obsolete_entries=False, msgctxt=False):
"""
Find the entry which msgid (or property identified by the ``by``
argument) matches the string ``st``.
Keyword arguments:
``st``
string, the string to search for.
``by``
string, the property to use for comparison (default: ``msgid``).
``include_obsolete_entries``
boolean, whether to also search in entries that are obsolete.
``msgctxt``
string, allows specifying a specific message context for the
search.
"""
if include_obsolete_entries:
entries = self[:]
else:
entries = [e for e in self if not e.obsolete]
matches = []
for e in entries:
if getattr(e, by) == st:
if msgctxt is not False and e.msgctxt != msgctxt:
continue
matches.append(e)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
if not msgctxt:
# find the entry with no msgctx
e = None
for m in matches:
if not m.msgctxt:
e = m
if e:
return e
# fallback to the first entry found
return matches[0]
return None
def ordered_metadata(self):
"""
Convenience method that returns an ordered version of the metadata
dictionary. The return value is list of tuples (metadata name,
metadata_value).
"""
# copy the dict first
metadata = self.metadata.copy()
data_order = [
'Project-Id-Version',
'Report-Msgid-Bugs-To',
'POT-Creation-Date',
'PO-Revision-Date',
'Last-Translator',
'Language-Team',
'Language',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding',
'Plural-Forms',
]
ordered_data = []
for data in data_order:
try:
value = metadata.pop(data)
ordered_data.append((data, value))
except KeyError:
pass
# the rest of the metadata will be alphabetically ordered since there
# are no specs for this AFAIK
for data in natural_sort(metadata.keys()):
value = metadata[data]
ordered_data.append((data, value))
return ordered_data
def to_binary(self):
"""
Return the binary representation of the file.
"""
offsets = []
entries = self.translated_entries()
# the keys are sorted in the .mo file
def cmp(_self, other):
# msgfmt compares entries with msgctxt if it exists
self_msgid = _self.msgctxt or _self.msgid
other_msgid = other.msgctxt or other.msgid
if self_msgid > other_msgid:
return 1
elif self_msgid < other_msgid:
return -1
else:
return 0
# add metadata entry
entries.sort(key=lambda o: o.msgid_with_context.encode('utf-8'))
mentry = self.metadata_as_entry()
entries = [mentry] + entries
entries_len = len(entries)
ids, strs = b(''), b('')
for e in entries:
# For each string, we need size and file offset. Each string is
# NUL terminated; the NUL does not count into the size.
msgid = b('')
if e.msgctxt:
# Contexts are stored by storing the concatenation of the
# context, a <EOT> byte, and the original string
msgid = self._encode(e.msgctxt + '\4')
if e.msgid_plural:
msgstr = []
for index in sorted(e.msgstr_plural.keys()):
msgstr.append(e.msgstr_plural[index])
msgid += self._encode(e.msgid + '\0' + e.msgid_plural)
msgstr = self._encode('\0'.join(msgstr))
else:
msgid += self._encode(e.msgid)
msgstr = self._encode(e.msgstr)
offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
ids += msgid + b('\0')
strs += msgstr + b('\0')
# The header is 7 32-bit unsigned integers.
keystart = 7 * 4 + 16 * entries_len
# and the values start after the keys
valuestart = keystart + len(ids)
koffsets = []
voffsets = []
# The string table first has the list of keys, then the list of values.
# Each entry has first the size of the string, then the file offset.
for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1 + keystart]
voffsets += [l2, o2 + valuestart]
offsets = koffsets + voffsets
output = struct.pack(
'Iiiiiii',
# Magic number
MOFile.MAGIC,
# Version
0,
# number of entries
entries_len,
# start of key index
7 * 4,
# start of value index
7 * 4 + entries_len * 8,
# size and offset of hash table, we don't use hash tables
0,
keystart,
)
if PY3 and sys.version_info.minor > 1: # python 3.2 or newer
output += array.array('i', offsets).tobytes()
else:
output += array.array('i', offsets).tostring()
output += ids
output += strs
return output
def _encode(self, mixed):
"""
Encodes the given ``mixed`` argument with the file encoding if and
only if it's an unicode string and returns the encoded string.
"""
if isinstance(mixed, text_type):
mixed = mixed.encode(self.encoding)
return mixed
# }}}
# class POFile {{{
class POFile(_BaseFile):
"""
Po (or Pot) file reader/writer.
This class inherits the :class:`~polib._BaseFile` class and, by extension,
the python ``list`` type.
"""
def __unicode__(self):
"""
Returns the unicode representation of the po file.
"""
ret, headers = '', self.header.split('\n')
for header in headers:
if not header:
ret += '#\n'
elif header[:1] in [',', ':']:
ret += '#%s\n' % header
else:
ret += '# %s\n' % header
if not isinstance(ret, text_type):
ret = ret.decode(self.encoding)
return ret + _BaseFile.__unicode__(self)
def save_as_mofile(self, fpath):
"""
Saves the binary representation of the file to given ``fpath``.
Keyword argument:
``fpath``
string, full or relative path to the mo file.
"""
_BaseFile.save(self, fpath, 'to_binary')
def percent_translated(self):
"""
Convenience method that returns the percentage of translated
messages.
"""
total = len([e for e in self if not e.obsolete])
if total == 0:
return 100
translated = len(self.translated_entries())
return int(translated * 100 / float(total))
def translated_entries(self):
"""
Convenience method that returns the list of translated entries.
"""
return [e for e in self if e.translated()]
def untranslated_entries(self):
"""
Convenience method that returns the list of untranslated entries.
"""
return [
e for e in self if not e.translated() and not e.obsolete and not e.fuzzy
]
def fuzzy_entries(self):
"""
Convenience method that returns the list of fuzzy entries.
"""
return [e for e in self if e.fuzzy and not e.obsolete]
def obsolete_entries(self):
"""
Convenience method that returns the list of obsolete entries.
"""
return [e for e in self if e.obsolete]
def merge(self, refpot):
"""
Convenience method that merges the current pofile with the pot file
provided. It behaves exactly as the gettext msgmerge utility:
* comments of this file will be preserved, but extracted comments and
occurrences will be discarded;
* any translations or comments in the file will be discarded, however,
dot comments and file positions will be preserved;
* the fuzzy flags are preserved.
Keyword argument:
``refpot``
object POFile, the reference catalog.
"""
# Store entries in dict/set for faster access
self_entries = {entry.msgid_with_context: entry for entry in self}
refpot_msgids = {entry.msgid_with_context for entry in refpot}
# Merge entries that are in the refpot
for entry in refpot:
e = self_entries.get(entry.msgid_with_context)
if e is None:
e = POEntry()
self.append(e)
e.merge(entry)
# ok, now we must "obsolete" entries that are not in the refpot anymore
for entry in self:
if entry.msgid_with_context not in refpot_msgids:
entry.obsolete = True
# }}}
# class MOFile {{{
class MOFile(_BaseFile):
"""
Mo file reader/writer.
This class inherits the :class:`~polib._BaseFile` class and, by
extension, the python ``list`` type.
"""
MAGIC = 0x950412DE
MAGIC_SWAPPED = 0xDE120495
def __init__(self, *args, **kwargs):
"""
Constructor, accepts all keywords arguments accepted by
:class:`~polib._BaseFile` class.
"""
_BaseFile.__init__(self, *args, **kwargs)
self.magic_number = None
self.version = 0
def save_as_pofile(self, fpath):
"""
Saves the mofile as a pofile to ``fpath``.
Keyword argument:
``fpath``
string, full or relative path to the file.
"""
_BaseFile.save(self, fpath)
def save(self, fpath=None):
"""
Saves the mofile to ``fpath``.
Keyword argument:
``fpath``
string, full or relative path to the file.
"""
_BaseFile.save(self, fpath, 'to_binary')
def percent_translated(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return 100
def translated_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return self
def untranslated_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return []
def fuzzy_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return []
def obsolete_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return []
# }}}
# class _BaseEntry {{{
class _BaseEntry:
"""
Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes.
This class should **not** be instantiated directly.
"""
def __init__(self, *_args, **kwargs):
"""
Constructor, accepts the following keyword arguments:
``msgid``
string, the entry msgid.
``msgstr``
string, the entry msgstr.
``msgid_plural``
string, the entry msgid_plural.
``msgstr_plural``
dict, the entry msgstr_plural lines.
``msgctxt``
string, the entry context (msgctxt).
``obsolete``
bool, whether the entry is "obsolete" or not.
``encoding``
string, the encoding to use, defaults to ``default_encoding``
global variable (optional).
"""
self.msgid = kwargs.get('msgid', '')
self.msgstr = kwargs.get('msgstr', '')
self.msgid_plural = kwargs.get('msgid_plural', '')
self.msgstr_plural = kwargs.get('msgstr_plural', {})
self.msgctxt = kwargs.get('msgctxt', None)
self.obsolete = kwargs.get('obsolete', False)
self.encoding = kwargs.get('encoding', default_encoding)
def __unicode__(self, wrapwidth=78):
"""
Returns the unicode representation of the entry.
"""
if self.obsolete:
delflag = '#~ '
else:
delflag = ''
ret = []
# write the msgctxt if any
if self.msgctxt is not None:
ret += self._str_field('msgctxt', delflag, '', self.msgctxt, wrapwidth)
# write the msgid
ret += self._str_field('msgid', delflag, '', self.msgid, wrapwidth)
# write the msgid_plural if any
if self.msgid_plural:
ret += self._str_field(
'msgid_plural', delflag, '', self.msgid_plural, wrapwidth
)
if self.msgstr_plural:
# write the msgstr_plural if any
msgstrs = self.msgstr_plural
keys = list(msgstrs)
keys.sort()
for index in keys:
msgstr = msgstrs[index]
plural_index = '[%s]' % index
ret += self._str_field(
'msgstr', delflag, plural_index, msgstr, wrapwidth
)
else:
# otherwise write the msgstr
ret += self._str_field('msgstr', delflag, '', self.msgstr, wrapwidth)
ret.append('')
ret = u('\n').join(ret)
return ret
if PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
"""
Returns the string representation of the entry.
"""
return compat.ustr(self).encode(self.encoding)
def __eq__(self, other):
return str(self) == str(other)
def __hash__(self):
return hash(str(self))
def _str_field(self, fieldname, delflag, plural_index, field, wrapwidth=78):
lines = field.splitlines(True)
if len(lines) > 1:
lines = [''] + lines # start with initial empty line
else:
escaped_field = escape(field)
specialchars_count = 0
for c in ['\\', '\n', '\r', '\t', '"']:
specialchars_count += field.count(c)
# comparison must take into account fieldname length + one space
# + 2 quotes (eg. msgid "<string>")
flength = len(fieldname) + 3
if plural_index:
flength += len(plural_index)
real_wrapwidth = wrapwidth - flength + specialchars_count
if wrapwidth > 0 and len(field) > real_wrapwidth:
# Wrap the line but take field name into account
lines = [''] + [
unescape(item)
for item in textwrap.wrap(
escaped_field,
wrapwidth - 2, # 2 for quotes ""
drop_whitespace=False,
break_long_words=False,
)
]
else:
lines = [field]
if fieldname.startswith('previous_'):
# quick and dirty trick to get the real field name
fieldname = fieldname[9:]
ret = [f'{delflag}{fieldname}{plural_index} "{escape(lines.pop(0))}"']
for line in lines:
ret.append(f'{delflag}"{escape(line)}"')
return ret
@property
def msgid_with_context(self):
if self.msgctxt:
return '{}{}{}'.format(self.msgctxt, '\x04', self.msgid)
return self.msgid
# }}}
# class POEntry {{{
class POEntry(_BaseEntry):
"""
Represents a po file entry.
"""
def __init__(self, *args, **kwargs):
"""
Constructor, accepts the following keyword arguments:
``comment``
string, the entry comment.
``tcomment``
string, the entry translator comment.
``occurrences``
list, the entry occurrences.
``flags``
list, the entry flags.
``previous_msgctxt``
string, the entry previous context.
``previous_msgid``
string, the entry previous msgid.
``previous_msgid_plural``
string, the entry previous msgid_plural.
``linenum``
integer, the line number of the entry
"""
_BaseEntry.__init__(self, *args, **kwargs)
self.comment = kwargs.get('comment', '')
self.tcomment = kwargs.get('tcomment', '')
self.occurrences = kwargs.get('occurrences', [])
self.flags = kwargs.get('flags', [])
self.previous_msgctxt = kwargs.get('previous_msgctxt', None)
self.previous_msgid = kwargs.get('previous_msgid', None)
self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None)
self.linenum = kwargs.get('linenum', None)
def __unicode__(self, wrapwidth=78):
"""
Returns the unicode representation of the entry.
"""
ret = []
# comments first, if any (with text wrapping as xgettext does)
if self.obsolete:
comments = [('tcomment', '# ')]
else:
comments = [('comment', '#. '), ('tcomment', '# ')]
for c in comments:
val = getattr(self, c[0])
if val:
for comment in val.split('\n'):
if len(comment) + len(c[1]) > wrapwidth > 0:
ret += textwrap.wrap(
comment,
wrapwidth,
initial_indent=c[1],
subsequent_indent=c[1],
break_long_words=False,
)
else:
ret.append(f'{c[1]}{comment}')
# occurrences (with text wrapping as xgettext does)
if not self.obsolete and self.occurrences:
filelist = []
for fpath, lineno in self.occurrences:
if lineno:
filelist.append(f'{fpath}:{lineno}')
else:
filelist.append(fpath)
filestr = ' '.join(filelist)
if len(filestr) + 3 > wrapwidth > 0:
# textwrap split words that contain hyphen, this is not
# what we want for filenames, so the dirty hack is to
# temporally replace hyphens with a char that a file cannot
# contain, like "*"
ret += [
line.replace('*', '-')
for line in textwrap.wrap(
filestr.replace('-', '*'),
wrapwidth,
initial_indent='#: ',
subsequent_indent='#: ',
break_long_words=False,
)
]
else:
ret.append('#: ' + filestr)
# flags (TODO: wrapping ?)
if self.flags:
ret.append('#, %s' % ', '.join(self.flags))
# previous context and previous msgid/msgid_plural
fields = ['previous_msgctxt', 'previous_msgid', 'previous_msgid_plural']
if self.obsolete:
prefix = '#~| '
else:
prefix = '#| '
for f in fields:
val = getattr(self, f)
if val is not None:
ret += self._str_field(f, prefix, '', val, wrapwidth)
ret.append(_BaseEntry.__unicode__(self, wrapwidth))
ret = u('\n').join(ret)
return ret
def __cmp__(self, other):
"""
Called by comparison operations if rich comparison is not defined.
"""
# First: Obsolete test
if self.obsolete != other.obsolete:
if self.obsolete:
return -1
else:
return 1
# Work on a copy to protect original
occ1 = sorted(self.occurrences[:])
occ2 = sorted(other.occurrences[:])
if occ1 > occ2:
return 1
if occ1 < occ2:
return -1
# Compare context
msgctxt = self.msgctxt or '0'
othermsgctxt = other.msgctxt or '0'
if msgctxt > othermsgctxt:
return 1
elif msgctxt < othermsgctxt:
return -1
# Compare msgid_plural
msgid_plural = self.msgid_plural or '0'
othermsgid_plural = other.msgid_plural or '0'
if msgid_plural > othermsgid_plural:
return 1
elif msgid_plural < othermsgid_plural:
return -1
# Compare msgstr_plural
if self.msgstr_plural and isinstance(self.msgstr_plural, dict):
msgstr_plural = list(self.msgstr_plural.values())
else:
msgstr_plural = []
if other.msgstr_plural and isinstance(other.msgstr_plural, dict):
othermsgstr_plural = list(other.msgstr_plural.values())
else:
othermsgstr_plural = []
if msgstr_plural > othermsgstr_plural:
return 1
elif msgstr_plural < othermsgstr_plural:
return -1
# Compare msgid
if self.msgid > other.msgid:
return 1
elif self.msgid < other.msgid:
return -1
# Compare msgstr
if self.msgstr > other.msgstr:
return 1
elif self.msgstr < other.msgstr:
return -1
return 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def translated(self):
"""
Returns ``True`` if the entry has been translated or ``False``
otherwise.
"""
if self.obsolete or self.fuzzy:
return False
if self.msgstr != '':
return True
if self.msgstr_plural:
for pos in self.msgstr_plural:
if self.msgstr_plural[pos] == '':
return False
return True
return False
def merge(self, other):
"""
Merge the current entry with the given pot entry.
"""
self.msgid = other.msgid
self.msgctxt = other.msgctxt
self.occurrences = other.occurrences
self.comment = other.comment
fuzzy = self.fuzzy
self.flags = other.flags[:] # clone flags
if fuzzy:
self.flags.append('fuzzy')
self.msgid_plural = other.msgid_plural
self.obsolete = other.obsolete
self.previous_msgctxt = other.previous_msgctxt
self.previous_msgid = other.previous_msgid
self.previous_msgid_plural = other.previous_msgid_plural
if other.msgstr_plural:
for pos in other.msgstr_plural:
try:
# keep existing translation at pos if any
self.msgstr_plural[pos]
except KeyError:
self.msgstr_plural[pos] = ''
@property
def fuzzy(self):
return 'fuzzy' in self.flags
def __hash__(self):
return hash((self.msgid, self.msgstr))
# }}}
# class MOEntry {{{
class MOEntry(_BaseEntry):
"""
Represents a mo file entry.
"""
def __init__(self, *args, **kwargs):
"""
Constructor, accepts the following keyword arguments,
for consistency with :class:`~polib.POEntry`:
``comment``
``tcomment``
``occurrences``
``flags``
``previous_msgctxt``
``previous_msgid``
``previous_msgid_plural``
Note: even though these keyword arguments are accepted,
they hold no real meaning in the context of MO files
and are simply ignored.
"""
_BaseEntry.__init__(self, *args, **kwargs)
self.comment = ''
self.tcomment = ''
self.occurrences = []
self.flags = []
self.previous_msgctxt = None
self.previous_msgid = None
self.previous_msgid_plural = None
def __hash__(self):
return hash((self.msgid, self.msgstr))
# }}}
# class _POFileParser {{{
class _POFileParser:
"""
A finite state machine to parse efficiently and correctly po
file format.
"""
def __init__(self, pofile, *_args, **kwargs):
"""
Constructor.
Keyword arguments:
``pofile``
string, path to the po file or its content
``encoding``
string, the encoding to use, defaults to ``default_encoding``
global variable (optional).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file (optional, default: ``False``).
"""
enc = kwargs.get('encoding', default_encoding)
if _is_file(pofile):
try:
self.fhandle = open(pofile, encoding=enc)
except LookupError:
enc = default_encoding
self.fhandle = open(pofile, encoding=enc)
else:
self.fhandle = pofile.splitlines()
klass = kwargs.get('klass')
if klass is None:
klass = POFile
self.instance = klass(
pofile=pofile,
encoding=enc,
check_for_duplicates=kwargs.get('check_for_duplicates', False),
)
self.transitions = {}
self.current_line = 0
self.current_entry = POEntry(linenum=self.current_line)
self.current_state = 'st'
self.current_token = None
# two memo flags used in handlers
self.msgstr_index = 0
self.entry_obsolete = 0
# Configure the state machine, by adding transitions.
# Signification of symbols:
# * ST: Beginning of the file (start)
# * HE: Header
# * TC: a translation comment
# * GC: a generated comment
# * OC: a file/line occurrence
# * FL: a flags line
# * CT: a message context
# * PC: a previous msgctxt
# * PM: a previous msgid
# * PP: a previous msgid_plural
# * MI: a msgid
# * MP: a msgid plural
# * MS: a msgstr
# * MX: a msgstr plural
# * MC: a msgid or msgstr continuation line
all = [
'st',
'he',
'gc',
'oc',
'fl',
'ct',
'pc',
'pm',
'pp',
'tc',
'ms',
'mp',
'mx',
'mi',
]
self.add('tc', ['st', 'he'], 'he')
self.add(
'tc',
['gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms', 'mp', 'mx', 'mi'],
'tc',
)
self.add('gc', all, 'gc')
self.add('oc', all, 'oc')
self.add('fl', all, 'fl')
self.add('pc', all, 'pc')
self.add('pm', all, 'pm')
self.add('pp', all, 'pp')
self.add(
'ct',
['st', 'he', 'gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms', 'mx'],
'ct',
)
self.add(
'mi',
['st', 'he', 'gc', 'oc', 'fl', 'ct', 'tc', 'pc', 'pm', 'pp', 'ms', 'mx'],
'mi',
)
self.add('mp', ['tc', 'gc', 'pc', 'pm', 'pp', 'mi'], 'mp')
self.add('ms', ['mi', 'mp', 'tc'], 'ms')
self.add('mx', ['mi', 'mx', 'mp', 'tc'], 'mx')
self.add('mc', ['ct', 'mi', 'mp', 'ms', 'mx', 'pm', 'pp', 'pc'], 'mc')
def parse(self):
"""
Run the state machine, parse the file line by line and call process()
with the current matched symbol.
"""
keywords = {
'msgctxt': 'ct',
'msgid': 'mi',
'msgstr': 'ms',
'msgid_plural': 'mp',
}
prev_keywords = {
'msgid_plural': 'pp',
'msgid': 'pm',
'msgctxt': 'pc',
}
tokens = []
fpath = '%s ' % self.instance.fpath if self.instance.fpath else ''
for line in self.fhandle:
self.current_line += 1
if self.current_line == 1:
BOM = codecs.BOM_UTF8.decode('utf-8')
if line.startswith(BOM):
line = line[len(BOM) :]
line = line.strip()
if line == '':
continue
tokens = line.split(None, 2)
nb_tokens = len(tokens)
if tokens[0] == '#~|':
continue
if tokens[0] == '#~' and nb_tokens > 1:
line = line[3:].strip()
tokens = tokens[1:]
nb_tokens -= 1
self.entry_obsolete = 1
else:
self.entry_obsolete = 0
# Take care of keywords like
# msgid, msgid_plural, msgctxt & msgstr.
if tokens[0] in keywords and nb_tokens > 1:
line = line[len(tokens[0]) :].lstrip()
if re.search(r'([^\\]|^)"', line[1:-1]):
raise OSError(
'Syntax error in po file %s(line %s): '
'unescaped double quote found' % (fpath, self.current_line)
)
self.current_token = line
self.process(keywords[tokens[0]])
continue
self.current_token = line
if tokens[0] == '#:':
if nb_tokens <= 1:
continue
# we are on a occurrences line
self.process('oc')
elif line[:1] == '"':
# we are on a continuation line
if re.search(r'([^\\]|^)"', line[1:-1]):
raise OSError(
'Syntax error in po file %s(line %s): '
'unescaped double quote found' % (fpath, self.current_line)
)
self.process('mc')
elif line[:7] == 'msgstr[':
# we are on a msgstr plural
self.process('mx')
elif tokens[0] == '#,':
if nb_tokens <= 1:
continue
# we are on a flags line
self.process('fl')
elif tokens[0] == '#' or tokens[0].startswith('##'):
if line == '#':
line += ' '
# we are on a translator comment line
self.process('tc')
elif tokens[0] == '#.':
if nb_tokens <= 1:
continue
# we are on a generated comment line
self.process('gc')
elif tokens[0] == '#|':
if nb_tokens <= 1:
raise OSError(
'Syntax error in po file %s(line %s)'
% (fpath, self.current_line)
)
# Remove the marker and any whitespace right after that.
line = line[2:].lstrip()
self.current_token = line
if tokens[1].startswith('"'):
# Continuation of previous metadata.
self.process('mc')
continue
if nb_tokens == 2:
# Invalid continuation line.
raise OSError(
'Syntax error in po file %s(line %s): '
'invalid continuation line' % (fpath, self.current_line)
)
# we are on a "previous translation" comment line,
if tokens[1] not in prev_keywords:
# Unknown keyword in previous translation comment.
raise OSError(
'Syntax error in po file %s(line %s): '
'unknown keyword %s' % (fpath, self.current_line, tokens[1])
)
# Remove the keyword and any whitespace
# between it and the starting quote.
line = line[len(tokens[1]) :].lstrip()
self.current_token = line
self.process(prev_keywords[tokens[1]])
else:
raise OSError(
f'Syntax error in po file {fpath}(line {self.current_line})'
)
if self.current_entry and len(tokens) > 0 and not tokens[0].startswith('#'):
# since entries are added when another entry is found, we must add
# the last entry here (only if there are lines). Trailing comments
# are ignored
self.instance.append(self.current_entry)
# before returning the instance, check if there's metadata and if
# so extract it in a dict
metadataentry = self.instance.find('')
if metadataentry: # metadata found
# remove the entry
self.instance.remove(metadataentry)
self.instance.metadata_is_fuzzy = metadataentry.flags
key = None
for msg in metadataentry.msgstr.splitlines():
try:
key, val = msg.split(':', 1)
self.instance.metadata[key] = val.strip()
except (ValueError, KeyError):
if key is not None:
self.instance.metadata[key] += '\n' + msg.strip()
# close opened file
if not isinstance(self.fhandle, list): # must be file
self.fhandle.close()
return self.instance
def add(self, symbol, states, next_state):
"""
Add a transition to the state machine.
Keywords arguments:
``symbol``
string, the matched token (two chars symbol).
``states``
list, a list of states (two chars symbols).
``next_state``
the next state the fsm will have after the action.
"""
for state in states:
action = getattr(self, 'handle_%s' % next_state)
self.transitions[(symbol, state)] = (action, next_state)
def process(self, symbol):
"""
Process the transition corresponding to the current state and the
symbol provided.
Keywords arguments:
``symbol``
string, the matched token (two chars symbol).
``linenum``
integer, the current line number of the parsed file.
"""
try:
(action, state) = self.transitions[(symbol, self.current_state)]
if action():
self.current_state = state
except Exception:
fpath = '%s ' % self.instance.fpath if self.instance.fpath else ''
if hasattr(self.fhandle, 'close'):
self.fhandle.close()
raise OSError(f'Syntax error in po file {fpath}(line {self.current_line})')
# state handlers
def handle_he(self):
"""Handle a header comment."""
if self.instance.header != '':
self.instance.header += '\n'
self.instance.header += self.current_token[2:]
return 1
def handle_tc(self):
"""Handle a translator comment."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
if self.current_entry.tcomment != '':
self.current_entry.tcomment += '\n'
tcomment = self.current_token.lstrip('#')
if tcomment.startswith(' '):
tcomment = tcomment[1:]
self.current_entry.tcomment += tcomment
return True
def handle_gc(self):
"""Handle a generated comment."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
if self.current_entry.comment != '':
self.current_entry.comment += '\n'
self.current_entry.comment += self.current_token[3:]
return True
def handle_oc(self):
"""Handle a file:num occurrence."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
occurrences = self.current_token[3:].split()
for occurrence in occurrences:
if occurrence != '':
try:
fil, line = occurrence.rsplit(':', 1)
if not line.isdigit():
fil = occurrence
line = ''
self.current_entry.occurrences.append((fil, line))
except (ValueError, AttributeError):
self.current_entry.occurrences.append((occurrence, ''))
return True
def handle_fl(self):
"""Handle a flags line."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
self.current_entry.flags += [
c.strip() for c in self.current_token[3:].split(',')
]
return True
def handle_pp(self):
"""Handle a previous msgid_plural line."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
self.current_entry.previous_msgid_plural = unescape(self.current_token[1:-1])
return True
def handle_pm(self):
"""Handle a previous msgid line."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
self.current_entry.previous_msgid = unescape(self.current_token[1:-1])
return True
def handle_pc(self):
"""Handle a previous msgctxt line."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
self.current_entry.previous_msgctxt = unescape(self.current_token[1:-1])
return True
def handle_ct(self):
"""Handle a msgctxt."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
self.current_entry.msgctxt = unescape(self.current_token[1:-1])
return True
def handle_mi(self):
"""Handle a msgid."""
if self.current_state in ['mc', 'ms', 'mx']:
self.instance.append(self.current_entry)
self.current_entry = POEntry(linenum=self.current_line)
self.current_entry.obsolete = self.entry_obsolete
self.current_entry.msgid = unescape(self.current_token[1:-1])
return True
def handle_mp(self):
"""Handle a msgid plural."""
self.current_entry.msgid_plural = unescape(self.current_token[1:-1])
return True
def handle_ms(self):
"""Handle a msgstr."""
self.current_entry.msgstr = unescape(self.current_token[1:-1])
return True
def handle_mx(self):
"""Handle a msgstr plural."""
index = self.current_token[7]
value = self.current_token[self.current_token.find('"') + 1 : -1]
self.current_entry.msgstr_plural[int(index)] = unescape(value)
self.msgstr_index = int(index)
return True
def handle_mc(self):
"""Handle a msgid or msgstr continuation line."""
token = unescape(self.current_token[1:-1])
if self.current_state == 'ct':
self.current_entry.msgctxt += token
elif self.current_state == 'mi':
self.current_entry.msgid += token
elif self.current_state == 'mp':
self.current_entry.msgid_plural += token
elif self.current_state == 'ms':
self.current_entry.msgstr += token
elif self.current_state == 'mx':
self.current_entry.msgstr_plural[self.msgstr_index] += token
elif self.current_state == 'pp':
self.current_entry.previous_msgid_plural += token
elif self.current_state == 'pm':
self.current_entry.previous_msgid += token
elif self.current_state == 'pc':
self.current_entry.previous_msgctxt += token
# don't change the current state
return False
# }}}
# class _MOFileParser {{{
class _MOFileParser:
"""
A class to parse binary mo files.
"""
def __init__(self, mofile, *_args, **kwargs):
"""
Constructor.
Keyword arguments:
``mofile``
string, path to the mo file or its content
``encoding``
string, the encoding to use, defaults to ``default_encoding``
global variable (optional).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file (optional, default: ``False``).
"""
if _is_file(mofile):
self.fhandle = open(mofile, 'rb')
else:
self.fhandle = io.BytesIO(mofile)
klass = kwargs.get('klass')
if klass is None:
klass = MOFile
self.instance = klass(
fpath=mofile,
encoding=kwargs.get('encoding', default_encoding),
check_for_duplicates=kwargs.get('check_for_duplicates', False),
)
def __del__(self):
"""
Make sure the file is closed, this prevents warnings on unclosed file
when running tests with python >= 3.2.
"""
if self.fhandle and hasattr(self.fhandle, 'close'):
self.fhandle.close()
def parse(self):
"""
Build the instance with the file handle provided in the
constructor.
"""
# parse magic number
magic_number = self._readbinary('<I', 4)
if magic_number == MOFile.MAGIC:
ii = '<II'
elif magic_number == MOFile.MAGIC_SWAPPED:
ii = '>II'
else:
raise OSError('Invalid mo file, magic number is incorrect !')
self.instance.magic_number = magic_number
# parse the version number and the number of strings
version, numofstrings = self._readbinary(ii, 8)
# from MO file format specs: "A program seeing an unexpected major
# revision number should stop reading the MO file entirely"
if version >> 16 not in (0, 1):
raise OSError('Invalid mo file, unexpected major revision number')
self.instance.version = version
# original strings and translation strings hash table offset
msgids_hash_offset, msgstrs_hash_offset = self._readbinary(ii, 8)
# move to msgid hash table and read length and offset of msgids
self.fhandle.seek(msgids_hash_offset)
msgids_index = []
for i in range(numofstrings):
msgids_index.append(self._readbinary(ii, 8))
# move to msgstr hash table and read length and offset of msgstrs
self.fhandle.seek(msgstrs_hash_offset)
msgstrs_index = []
for i in range(numofstrings):
msgstrs_index.append(self._readbinary(ii, 8))
# build entries
encoding = self.instance.encoding
for i in range(numofstrings):
self.fhandle.seek(msgids_index[i][1])
msgid = self.fhandle.read(msgids_index[i][0])
self.fhandle.seek(msgstrs_index[i][1])
msgstr = self.fhandle.read(msgstrs_index[i][0])
if i == 0 and not msgid: # metadata
raw_metadata, metadata = msgstr.split(b('\n')), {}
for line in raw_metadata:
tokens = line.split(b(':'), 1)
if tokens[0] != b(''):
try:
k = tokens[0].decode(encoding)
v = tokens[1].decode(encoding)
metadata[k] = v.strip()
except IndexError:
metadata[k] = u('')
self.instance.metadata = metadata
continue
# test if we have a plural entry
msgid_tokens = msgid.split(b('\0'))
if len(msgid_tokens) > 1:
entry = self._build_entry(
msgid=msgid_tokens[0],
msgid_plural=msgid_tokens[1],
msgstr_plural=dict(enumerate(msgstr.split(b('\x00')))),
)
else:
entry = self._build_entry(msgid=msgid, msgstr=msgstr)
self.instance.append(entry)
# close opened file
self.fhandle.close()
return self.instance
def _build_entry(self, msgid, msgstr=None, msgid_plural=None, msgstr_plural=None):
msgctxt_msgid = msgid.split(b('\x04'))
encoding = self.instance.encoding
if len(msgctxt_msgid) > 1:
kwargs = {
'msgctxt': msgctxt_msgid[0].decode(encoding),
'msgid': msgctxt_msgid[1].decode(encoding),
}
else:
kwargs = {'msgid': msgid.decode(encoding)}
if msgstr:
kwargs['msgstr'] = msgstr.decode(encoding)
if msgid_plural:
kwargs['msgid_plural'] = msgid_plural.decode(encoding)
if msgstr_plural:
for k in msgstr_plural:
msgstr_plural[k] = msgstr_plural[k].decode(encoding)
kwargs['msgstr_plural'] = msgstr_plural
return MOEntry(**kwargs)
def _readbinary(self, fmt, numbytes):
"""
Private method that unpack n bytes of data using format <fmt>.
It returns a tuple or a mixed value if the tuple length is 1.
"""
content = self.fhandle.read(numbytes)
tup = struct.unpack(fmt, content)
if len(tup) == 1:
return tup[0]
return tup
# }}}
| 60,104 | Python | .py | 1,589 | 27.178099 | 87 | 0.542504 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
43 | guicmds.py | git-cola_git-cola/cola/guicmds.py | import os
from qtpy import QtGui
from . import cmds
from . import core
from . import difftool
from . import display
from . import gitcmds
from . import icons
from . import qtutils
from .i18n import N_
from .interaction import Interaction
from .widgets import completion
from .widgets import editremotes
from .widgets import switcher
from .widgets.browse import BrowseBranch
from .widgets.selectcommits import select_commits
from .widgets.selectcommits import select_commits_and_output
def delete_branch(context):
"""Launch the 'Delete Branch' dialog."""
icon = icons.discard()
branch = choose_branch(context, N_('Delete Branch'), N_('Delete'), icon=icon)
if not branch:
return
cmds.do(cmds.DeleteBranch, context, branch)
def delete_remote_branch(context):
"""Launch the 'Delete Remote Branch' dialog."""
remote_branch = choose_remote_branch(
context, N_('Delete Remote Branch'), N_('Delete'), icon=icons.discard()
)
if not remote_branch:
return
remote, branch = gitcmds.parse_remote_branch(remote_branch)
if remote and branch:
cmds.do(cmds.DeleteRemoteBranch, context, remote, branch)
def browse_current(context):
"""Launch the 'Browse Current Branch' dialog."""
branch = gitcmds.current_branch(context)
BrowseBranch.browse(context, branch)
def browse_other(context):
"""Prompt for a branch and inspect content at that point in time."""
# Prompt for a branch to browse
branch = choose_ref(context, N_('Browse Commits...'), N_('Browse'))
if not branch:
return
BrowseBranch.browse(context, branch)
def checkout_branch(context, default=None):
"""Launch the 'Checkout Branch' dialog."""
branch = choose_potential_branch(
context, N_('Checkout Branch'), N_('Checkout'), default=default
)
if not branch:
return
cmds.do(cmds.CheckoutBranch, context, branch)
def cherry_pick(context):
"""Launch the 'Cherry-Pick' dialog."""
revs, summaries = gitcmds.log_helper(context, all=True)
commits = select_commits(
context, N_('Cherry-Pick Commit'), revs, summaries, multiselect=False
)
if not commits:
return
cmds.do(cmds.CherryPick, context, commits)
def new_repo(context):
"""Prompt for a new directory and create a new Git repository
:returns str: repository path or None if no repository was created.
"""
git = context.git
path = qtutils.opendir_dialog(N_('New Repository...'), core.getcwd())
if not path:
return None
# Avoid needlessly calling `git init`.
if git.is_git_repository(path):
# We could prompt here and confirm that they really didn't
# mean to open an existing repository, but I think
# treating it like an "Open" is a sensible DWIM answer.
return path
status, out, err = git.init(path)
if status == 0:
return path
title = N_('Error Creating Repository')
Interaction.command_error(title, 'git init', status, out, err)
return None
def open_new_repo(context):
"""Create a new repository and open it"""
dirname = new_repo(context)
if not dirname:
return
cmds.do(cmds.OpenRepo, context, dirname)
def new_bare_repo(context):
"""Create a bare repository and configure a remote pointing to it"""
result = None
repo = prompt_for_new_bare_repo()
if not repo:
return result
# Create bare repo
ok = cmds.do(cmds.NewBareRepo, context, repo)
if not ok:
return result
# Add a new remote pointing to the bare repo
parent = qtutils.active_window()
add_remote = editremotes.add_remote(
context, parent, name=os.path.basename(repo), url=repo, readonly_url=True
)
if add_remote:
result = repo
return result
def prompt_for_new_bare_repo():
"""Prompt for a directory and name for a new bare repository"""
path = qtutils.opendir_dialog(N_('Select Directory...'), core.getcwd())
if not path:
return None
bare_repo = None
default = os.path.basename(core.getcwd())
if not default.endswith('.git'):
default += '.git'
while not bare_repo:
name, ok = qtutils.prompt(
N_('Enter a name for the new bare repo'),
title=N_('New Bare Repository...'),
text=default,
)
if not name or not ok:
return None
if not name.endswith('.git'):
name += '.git'
repo = os.path.join(path, name)
if core.isdir(repo):
Interaction.critical(N_('Error'), N_('"%s" already exists') % repo)
else:
bare_repo = repo
return bare_repo
def export_patches(context):
"""Run 'git format-patch' on a list of commits."""
revs, summaries = gitcmds.log_helper(context)
to_export_and_output = select_commits_and_output(
context, N_('Export Patches'), revs, summaries
)
if not to_export_and_output['to_export']:
return
cmds.do(
cmds.FormatPatch,
context,
reversed(to_export_and_output['to_export']),
reversed(revs),
output=to_export_and_output['output'],
)
def diff_against_commit(context):
"""Diff against any commit and checkout changes using the Diff Editor"""
icon = icons.compare()
ref = choose_ref(context, N_('Diff Against Commit'), N_('Diff'), icon=icon)
if not ref:
return
cmds.do(cmds.DiffAgainstCommitMode, context, ref)
def diff_expression(context):
"""Diff using an arbitrary expression."""
tracked = gitcmds.tracked_branch(context)
current = gitcmds.current_branch(context)
if tracked and current:
ref = tracked + '..' + current
else:
ref = '@{upstream}..'
difftool.diff_expression(context, qtutils.active_window(), ref)
def open_repo(context):
"""Open a repository in the current window"""
model = context.model
dirname = qtutils.opendir_dialog(N_('Open Git Repository'), model.getcwd())
if not dirname:
return
cmds.do(cmds.OpenRepo, context, dirname)
def open_repo_in_new_window(context):
"""Spawn a new cola session."""
model = context.model
dirname = qtutils.opendir_dialog(N_('Open Git Repository'), model.getcwd())
if not dirname:
return
cmds.do(cmds.OpenNewRepo, context, dirname)
def open_quick_repo_search(context, parent=None):
"""Open a Quick Repository Search dialog"""
if parent is None:
parent = qtutils.active_window()
settings = context.settings
items = settings.bookmarks + settings.recent
if items:
cfg = context.cfg
default_repo = cfg.get('cola.defaultrepo')
entries = QtGui.QStandardItemModel()
added = set()
normalize = display.normalize_path
star_icon = icons.star()
folder_icon = icons.folder()
for item in items:
key = normalize(item['path'])
if key in added:
continue
name = item['name']
if default_repo == item['path']:
icon = star_icon
else:
icon = folder_icon
entry = switcher.switcher_item(key, icon, name)
entries.appendRow(entry)
added.add(key)
title = N_('Quick Open Repository')
place_holder = N_('Search repositories by name...')
switcher.switcher_inner_view(
context,
entries,
title,
place_holder=place_holder,
enter_action=lambda entry: cmds.do(cmds.OpenRepo, context, entry.key),
parent=parent,
)
def load_commitmsg(context):
"""Load a commit message from a file."""
model = context.model
filename = qtutils.open_file(N_('Load Commit Message'), directory=model.getcwd())
if filename:
cmds.do(cmds.LoadCommitMessageFromFile, context, filename)
def choose_from_dialog(get, context, title, button_text, default, icon=None):
"""Choose a value from a dialog using the `get` method"""
parent = qtutils.active_window()
return get(context, title, button_text, parent, default=default, icon=icon)
def choose_ref(context, title, button_text, default=None, icon=None):
"""Choose a Git ref and return it"""
return choose_from_dialog(
completion.GitRefDialog.get, context, title, button_text, default, icon=icon
)
def choose_branch(context, title, button_text, default=None, icon=None):
"""Choose a branch and return either the chosen branch or an empty value"""
return choose_from_dialog(
completion.GitBranchDialog.get, context, title, button_text, default, icon=icon
)
def choose_potential_branch(context, title, button_text, default=None, icon=None):
"""Choose a "potential" branch for checking out.
This dialog includes remote branches from which new local branches can be created.
"""
return choose_from_dialog(
completion.GitCheckoutBranchDialog.get,
context,
title,
button_text,
default,
icon=icon,
)
def choose_remote_branch(context, title, button_text, default=None, icon=None):
"""Choose a remote branch"""
return choose_from_dialog(
completion.GitRemoteBranchDialog.get,
context,
title,
button_text,
default,
icon=icon,
)
def review_branch(context):
"""Diff against an arbitrary revision, branch, tag, etc."""
branch = choose_ref(context, N_('Select Branch to Review'), N_('Review'))
if not branch:
return
merge_base = gitcmds.merge_base_parent(context, branch)
difftool.diff_commits(context, qtutils.active_window(), merge_base, branch)
def rename_branch(context):
"""Launch the 'Rename Branch' dialogs."""
branch = choose_branch(context, N_('Rename Existing Branch'), N_('Select'))
if not branch:
return
new_branch = choose_branch(context, N_('Enter New Branch Name'), N_('Rename'))
if not new_branch:
return
cmds.do(cmds.RenameBranch, context, branch, new_branch)
def reset_soft(context):
"""Run "git reset --soft" to reset the branch HEAD"""
title = N_('Reset Branch (Soft)')
ok_text = N_('Reset Branch')
default = context.settings.get_value('reset::soft', 'ref', default='HEAD^')
ref = choose_ref(context, title, ok_text, default=default)
if ref:
cmds.do(cmds.ResetSoft, context, ref)
context.settings.set_value('reset::soft', 'ref', ref)
def reset_mixed(context):
"""Run "git reset --mixed" to reset the branch HEAD and staging area"""
title = N_('Reset Branch and Stage (Mixed)')
ok_text = N_('Reset')
default = context.settings.get_value('reset::mixed', 'ref', default='HEAD^')
ref = choose_ref(context, title, ok_text, default=default)
if ref:
cmds.do(cmds.ResetMixed, context, ref)
context.settings.set_value('reset::mixed', 'ref', ref)
def reset_keep(context):
"""Run "git reset --keep" safe reset to avoid clobbering local changes"""
title = N_('Reset All (Keep Unstaged Changes)')
default = context.settings.get_value('reset::keep', 'ref', default='HEAD^')
ref = choose_ref(context, title, N_('Reset and Restore'), default=default)
if ref:
cmds.do(cmds.ResetKeep, context, ref)
context.settings.set_value('reset::keep', 'ref', ref)
def reset_merge(context):
"""Run "git reset --merge" to reset the working tree and staging area
The staging area is allowed to carry forward unmerged index entries,
but if any unstaged changes would be clobbered by the reset then the
reset is aborted.
"""
title = N_('Restore Worktree and Reset All (Merge)')
ok_text = N_('Reset and Restore')
default = context.settings.get_value('reset::merge', 'ref', default='HEAD^')
ref = choose_ref(context, title, ok_text, default=default)
if ref:
cmds.do(cmds.ResetMerge, context, ref)
context.settings.set_value('reset::merge', 'ref', ref)
def reset_hard(context):
"""Run "git reset --hard" to fully reset the working tree and staging area"""
title = N_('Restore Worktree and Reset All (Hard)')
ok_text = N_('Reset and Restore')
default = context.settings.get_value('reset::hard', 'ref', default='HEAD^')
ref = choose_ref(context, title, ok_text, default=default)
if ref:
cmds.do(cmds.ResetHard, context, ref)
context.settings.set_value('reset::hard', 'ref', ref)
def restore_worktree(context):
"""Restore the worktree to the content from the specified commit"""
title = N_('Restore Worktree')
ok_text = N_('Restore Worktree')
default = context.settings.get_value('restore::worktree', 'ref', default='HEAD^')
ref = choose_ref(context, title, ok_text, default=default)
if ref:
cmds.do(cmds.RestoreWorktree, context, ref)
context.settings.set_value('restore::worktree', 'ref', ref)
def install():
"""Install the GUI-model interaction hooks"""
Interaction.choose_ref = staticmethod(choose_ref)
| 13,106 | Python | .py | 330 | 33.418182 | 87 | 0.663043 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
44 | dag.py | git-cola_git-cola/cola/dag.py | import argparse
import sys
from cola import app
from cola.widgets.dag import git_dag
def main(argv=None):
"""Run git-dag"""
app.initialize()
args = parse_args(argv=argv)
return args.func(args)
def shortcut_launch():
"""Run git-dag from a Windows shortcut"""
return main(argv=['--prompt'])
def parse_args(argv=None):
"""Parse command-line arguments"""
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.set_defaults(func=cmd_dag)
app.add_common_arguments(parser)
parser.add_argument(
'-c',
'--count',
'--max-count',
metavar='<count>',
type=int,
default=1000,
help='number of commits to display',
)
parser.add_argument(
'args', nargs=argparse.REMAINDER, metavar='<args>', help='git log arguments'
)
args, rest = parser.parse_known_args(args=argv)
if rest:
# splice unknown arguments to the beginning ~
# these are forwarded to git-log(1).
args.args[:0] = rest
return args
def cmd_dag(args):
"""Run git-dag via the `git cola dag` sub-command"""
context = app.application_init(args, app_name='Git DAG')
view = git_dag(context, args=args, show=False)
return app.application_start(context, view)
| 1,312 | Python | .py | 42 | 25.619048 | 84 | 0.644444 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
45 | git.py | git-cola_git-cola/cola/git.py | from functools import partial
import errno
import os
from os.path import join
import subprocess
import threading
import time
from . import core
from .compat import int_types
from .compat import ustr
from .compat import WIN32
from .decorators import memoize
from .interaction import Interaction
GIT_COLA_TRACE = core.getenv('GIT_COLA_TRACE', '')
GIT = core.getenv('GIT_COLA_GIT', 'git')
STATUS = 0
STDOUT = 1
STDERR = 2
# Object ID / SHA-1 / SHA-256-related constants
# Git's empty tree is a built-in constant object name.
EMPTY_TREE_OID = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
# Git's diff machinery returns zeroes for modified files whose content exists
# in the worktree only.
MISSING_BLOB_OID = '0000000000000000000000000000000000000000'
# Git's SHA-1 object IDs are 40 characters long (20 bytes).
# Git's SHA-256 object IDs are 64 characters long (32 bytes).
# This will need to change when Git moves away from SHA-1.
# When that happens we'll have to detect and update this at runtime in
# order to support both old and new git.
OID_LENGTH = 40
OID_LENGTH_SHA256 = 64
_index_lock = threading.Lock()
def dashify(value):
return value.replace('_', '-')
def is_git_dir(git_dir):
"""From git's setup.c:is_git_directory()."""
result = False
if git_dir:
headref = join(git_dir, 'HEAD')
if (
core.isdir(git_dir)
and (
core.isdir(join(git_dir, 'objects'))
and core.isdir(join(git_dir, 'refs'))
)
or (
core.isfile(join(git_dir, 'gitdir'))
and core.isfile(join(git_dir, 'commondir'))
)
):
result = core.isfile(headref) or (
core.islink(headref) and core.readlink(headref).startswith('refs/')
)
else:
result = is_git_file(git_dir)
return result
def is_git_file(filename):
return core.isfile(filename) and os.path.basename(filename) == '.git'
def is_git_worktree(dirname):
return is_git_dir(join(dirname, '.git'))
def is_git_repository(path):
return is_git_worktree(path) or is_git_dir(path)
def read_git_file(path):
"""Read the path from a .git-file
`None` is returned when <path> is not a .git-file.
"""
result = None
if path and is_git_file(path):
header = 'gitdir: '
data = core.read(path).strip()
if data.startswith(header):
result = data[len(header) :]
if result and not os.path.isabs(result):
path_folder = os.path.dirname(path)
repo_relative = join(path_folder, result)
result = os.path.normpath(repo_relative)
return result
class Paths:
"""Git repository paths of interest"""
def __init__(self, git_dir=None, git_file=None, worktree=None, common_dir=None):
if git_dir and not is_git_dir(git_dir):
git_dir = None
self.git_dir = git_dir
self.git_file = git_file
self.worktree = worktree
self.common_dir = common_dir
def get(self, path):
"""Search for git worktrees and bare repositories"""
if not self.git_dir or not self.worktree:
ceiling_dirs = set()
ceiling = core.getenv('GIT_CEILING_DIRECTORIES')
if ceiling:
ceiling_dirs.update([x for x in ceiling.split(os.pathsep) if x])
if path:
path = core.abspath(path)
self._search_for_git(path, ceiling_dirs)
if self.git_dir:
git_dir_path = read_git_file(self.git_dir)
if git_dir_path:
self.git_file = self.git_dir
self.git_dir = git_dir_path
commondir_file = join(git_dir_path, 'commondir')
if core.exists(commondir_file):
common_path = core.read(commondir_file).strip()
if common_path:
if os.path.isabs(common_path):
common_dir = common_path
else:
common_dir = join(git_dir_path, common_path)
common_dir = os.path.normpath(common_dir)
self.common_dir = common_dir
# usage: Paths().get()
return self
def _search_for_git(self, path, ceiling_dirs):
"""Search for git repositories located at path or above"""
while path:
if path in ceiling_dirs:
break
if is_git_dir(path):
if not self.git_dir:
self.git_dir = path
basename = os.path.basename(path)
if not self.worktree and basename == '.git':
self.worktree = os.path.dirname(path)
# We are either in a bare repository, or someone set GIT_DIR
# but did not set GIT_WORK_TREE.
if self.git_dir:
if not self.worktree:
basename = os.path.basename(self.git_dir)
if basename == '.git':
self.worktree = os.path.dirname(self.git_dir)
elif path and not is_git_dir(path):
self.worktree = path
break
gitpath = join(path, '.git')
if is_git_dir(gitpath):
if not self.git_dir:
self.git_dir = gitpath
if not self.worktree:
self.worktree = path
break
path, dummy = os.path.split(path)
if not dummy:
break
def find_git_directory(path):
"""Perform Git repository discovery"""
return Paths(
git_dir=core.getenv('GIT_DIR'), worktree=core.getenv('GIT_WORK_TREE')
).get(path)
class Git:
"""
The Git class manages communication with the Git binary
"""
def __init__(self, worktree=None):
self.paths = Paths()
self._valid = {} #: Store the result of is_git_dir() for performance
self.set_worktree(worktree or core.getcwd())
def is_git_repository(self, path):
return is_git_repository(path)
def getcwd(self):
"""Return the working directory used by git()"""
return self.paths.worktree or self.paths.git_dir
def set_worktree(self, path):
path = core.decode(path)
self.paths = find_git_directory(path)
return self.paths.worktree
def worktree(self):
if not self.paths.worktree:
path = core.abspath(core.getcwd())
self.paths = find_git_directory(path)
return self.paths.worktree
def is_valid(self):
"""Is this a valid git repository?
Cache the result to avoid hitting the filesystem.
"""
git_dir = self.paths.git_dir
try:
valid = bool(git_dir) and self._valid[git_dir]
except KeyError:
valid = self._valid[git_dir] = is_git_dir(git_dir)
return valid
def git_path(self, *paths):
result = None
if self.paths.git_dir:
result = join(self.paths.git_dir, *paths)
if result and self.paths.common_dir and not core.exists(result):
common_result = join(self.paths.common_dir, *paths)
if core.exists(common_result):
result = common_result
return result
def git_dir(self):
if not self.paths.git_dir:
path = core.abspath(core.getcwd())
self.paths = find_git_directory(path)
return self.paths.git_dir
def __getattr__(self, name):
git_cmd = partial(self.git, name)
setattr(self, name, git_cmd)
return git_cmd
@staticmethod
def execute(
command,
_add_env=None,
_cwd=None,
_decode=True,
_encoding=None,
_raw=False,
_stdin=None,
_stderr=subprocess.PIPE,
_stdout=subprocess.PIPE,
_readonly=False,
_no_win32_startupinfo=False,
):
"""
Execute a command and returns its output
:param command: argument list to execute.
:param _cwd: working directory, defaults to the current directory.
:param _decode: whether to decode output, defaults to True.
:param _encoding: default encoding, defaults to None (utf-8).
:param _readonly: avoid taking the index lock. Assume the command is read-only.
:param _raw: do not strip trailing whitespace.
:param _stdin: optional stdin filehandle.
:returns (status, out, err): exit status, stdout, stderr
"""
# Allow the user to have the command executed in their working dir.
if not _cwd:
_cwd = core.getcwd()
extra = {}
if hasattr(os, 'setsid'):
# SSH uses the SSH_ASKPASS variable only if the process is really
# detached from the TTY (stdin redirection and setting the
# SSH_ASKPASS environment variable is not enough). To detach a
# process from the console it should fork and call os.setsid().
extra['preexec_fn'] = os.setsid
start_time = time.time()
# Start the process
# Guard against thread-unsafe .git/index.lock files
if not _readonly:
_index_lock.acquire()
try:
status, out, err = core.run_command(
command,
add_env=_add_env,
cwd=_cwd,
encoding=_encoding,
stdin=_stdin,
stdout=_stdout,
stderr=_stderr,
no_win32_startupinfo=_no_win32_startupinfo,
**extra,
)
finally:
# Let the next thread in
if not _readonly:
_index_lock.release()
end_time = time.time()
elapsed_time = abs(end_time - start_time)
if not _raw and out is not None:
out = core.UStr(out.rstrip('\n'), out.encoding)
cola_trace = GIT_COLA_TRACE
if cola_trace == 'trace':
msg = f'trace: {elapsed_time:.3f}s: {core.list2cmdline(command)}'
Interaction.log_status(status, msg, '')
elif cola_trace == 'full':
if out or err:
core.print_stderr(
"# %.3fs: %s -> %d: '%s' '%s'"
% (elapsed_time, ' '.join(command), status, out, err)
)
else:
core.print_stderr(
'# %.3fs: %s -> %d' % (elapsed_time, ' '.join(command), status)
)
elif cola_trace:
core.print_stderr('# {:.3f}s: {}'.format(elapsed_time, ' '.join(command)))
# Allow access to the command's status code
return (status, out, err)
def git(self, cmd, *args, **kwargs):
# Handle optional arguments prior to calling transform_kwargs
# otherwise they'll end up in args, which is bad.
_kwargs = {'_cwd': self.getcwd()}
execute_kwargs = (
'_add_env',
'_cwd',
'_decode',
'_encoding',
'_stdin',
'_stdout',
'_stderr',
'_raw',
'_readonly',
'_no_win32_startupinfo',
)
for kwarg in execute_kwargs:
if kwarg in kwargs:
_kwargs[kwarg] = kwargs.pop(kwarg)
# Prepare the argument list
git_args = [
GIT,
'-c',
'diff.suppressBlankEmpty=false',
'-c',
'log.showSignature=false',
dashify(cmd),
]
opt_args = transform_kwargs(**kwargs)
call = git_args + opt_args
call.extend(args)
try:
result = self.execute(call, **_kwargs)
except OSError as exc:
if WIN32 and exc.errno == errno.ENOENT:
# see if git exists at all. On win32 it can fail with ENOENT in
# case of argv overflow. We should be safe from that but use
# defensive coding for the worst-case scenario. On UNIX
# we have ENAMETOOLONG but that doesn't exist on Windows.
if _git_is_installed():
raise exc
_print_win32_git_hint()
result = (1, '', "error: unable to execute '%s'" % GIT)
return result
def _git_is_installed():
"""Return True if git is installed"""
# On win32 Git commands can fail with ENOENT in case of argv overflow. We
# should be safe from that but use defensive coding for the worst-case
# scenario. On UNIX we have ENAMETOOLONG but that doesn't exist on
# Windows.
try:
status, _, _ = Git.execute([GIT, '--version'])
result = status == 0
except OSError:
result = False
return result
def transform_kwargs(**kwargs):
"""Transform kwargs into git command line options
Callers can assume the following behavior:
Passing foo=None ignores foo, so that callers can
use default values of None that are ignored unless
set explicitly.
Passing foo=False ignore foo, for the same reason.
Passing foo={string-or-number} results in ['--foo=<value>']
in the resulting arguments.
"""
args = []
types_to_stringify = (ustr, float, str) + int_types
for k, value in kwargs.items():
if len(k) == 1:
dashes = '-'
equals = ''
else:
dashes = '--'
equals = '='
# isinstance(False, int) is True, so we have to check bool first
if isinstance(value, bool):
if value:
args.append(f'{dashes}{dashify(k)}')
# else: pass # False is ignored; flag=False inhibits --flag
elif isinstance(value, types_to_stringify):
args.append(f'{dashes}{dashify(k)}{equals}{value}')
return args
def win32_git_error_hint():
return (
'\n'
'NOTE: If you have Git installed in a custom location, e.g.\n'
'C:\\Tools\\Git, then you can create a file at\n'
'~/.config/git-cola/git-bindir with following text\n'
'and git-cola will add the specified location to your $PATH\n'
'automatically when starting cola:\n'
'\n'
r'C:\Tools\Git\bin'
)
@memoize
def _print_win32_git_hint():
hint = '\n' + win32_git_error_hint() + '\n'
core.print_stderr("error: unable to execute 'git'" + hint)
def create():
"""Create Git instances
>>> git = create()
>>> status, out, err = git.version()
>>> 'git' == out[:3].lower()
True
"""
return Git()
| 14,698 | Python | .py | 383 | 28.284595 | 87 | 0.56887 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
46 | display.py | git-cola_git-cola/cola/display.py | """Display models and utility functions"""
import collections
try:
import notify2
except ImportError:
notify2 = None
try:
import notifypy
except ImportError:
notifypy = None
from . import interaction
def shorten_paths(source_paths):
"""Shorten a sequence of paths into unique strings for display"""
result = {}
# Start by assuming that all paths are in conflict.
# On each iteration we will collect all the path suffixes, move the newly
# unique entries to the result, and repeat until no conflicts remain.
count = 0
conflicts = list(source_paths)
in_conflict = True
while in_conflict:
count += 1
# Gather the suffixes for the current paths in conflict
suffixes = collections.defaultdict(list)
for path in conflicts:
suffix = path_suffix(path, count)
suffixes[suffix].append(path)
# Loop over the suffixes to gather new conflicts and unique entries.
conflicts = []
in_conflict = False
for suffix, paths in suffixes.items():
# If only a single path exists for the suffix then no conflict
# exists, and the suffix is valid.
if len(paths) == 1:
result[paths[0]] = suffix
# If this loop runs too long then bail out by using the full path.
elif count >= 128:
for path in paths:
result[path] = path
# If multiple paths map to the same suffix then the paths are
# considered in conflict, and will be reprocessed.
else:
conflicts.extend(paths)
in_conflict = True
return result
def path_suffix(path, count):
"""Return `count` number of trailing path components"""
path = normalize_path(path)
components = path.split('/')[-count:]
return '/'.join(components)
def normalize_path(path):
"""Normalize a path so that only "/" is used as a separator"""
return path.replace('\\', '/')
def notify(app_name, title, message, icon):
"""Send a notification using notify2 xor notifypy"""
if notify2:
notify2.init(app_name)
notification = notify2.Notification(title, message, icon)
notification.show()
elif notifypy:
notification = notifypy.Notify()
notification.application_name = app_name
notification.title = title
notification.message = message
notification.icon = icon
notification.send()
else:
interaction.Interaction.log(f'{title}: {message}')
| 2,585 | Python | .py | 68 | 30.294118 | 78 | 0.64377 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
47 | app.py | git-cola_git-cola/cola/app.py | """Provides the main() routine and ColaApplication"""
from functools import partial
import argparse
import os
import random
import signal
import sys
import time
try:
from qtpy import QtCore
except ImportError as error:
sys.stderr.write(
"""
Your Python environment does not have qtpy and PyQt (or PySide).
The following error was encountered when importing "qtpy":
ImportError: {err}
Install qtpy and PyQt (or PySide) into your Python environment.
On a Debian/Ubuntu system you can install these modules using apt:
sudo apt install python3-pyqt5 python3-pyqt5.qtwebengine python3-qtpy
""".format(
err=error
)
)
sys.exit(1)
from qtpy import QtWidgets
from qtpy.QtCore import Qt
try:
# Qt 5.12 / PyQt 5.13 is unable to use QtWebEngineWidgets unless it is
# imported before QApplication is constructed.
from qtpy import QtWebEngineWidgets # noqa
except ImportError:
# QtWebEngineWidgets / QtWebKit is not available -- no big deal.
pass
# Import cola modules
from .i18n import N_
from .interaction import Interaction
from .models import main
from .models import selection
from .widgets import cfgactions
from .widgets import standard
from .widgets import startup
from .settings import Session
from .settings import Settings
from . import cmds
from . import core
from . import compat
from . import fsmonitor
from . import git
from . import gitcfg
from . import guicmds
from . import hidpi
from . import icons
from . import i18n
from . import qtcompat
from . import qtutils
from . import resources
from . import themes
from . import utils
from . import version
def setup_environment():
"""Set environment variables to control git's behavior"""
# Allow Ctrl-C to exit
random.seed(hash(time.time()))
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Session management wants an absolute path when restarting
sys.argv[0] = sys_argv0 = os.path.abspath(sys.argv[0])
# Spoof an X11 display for SSH
os.environ.setdefault('DISPLAY', ':0')
if not core.getenv('SHELL', ''):
for shell in ('/bin/zsh', '/bin/bash', '/bin/sh'):
if os.path.exists(shell):
compat.setenv('SHELL', shell)
break
# Setup the path so that git finds us when we run 'git cola'
path_entries = core.getenv('PATH', '').split(os.pathsep)
bindir = core.decode(os.path.dirname(sys_argv0))
path_entries.append(bindir)
path = os.pathsep.join(path_entries)
compat.setenv('PATH', path)
# We don't ever want a pager
compat.setenv('GIT_PAGER', '')
# Setup *SSH_ASKPASS
git_askpass = core.getenv('GIT_ASKPASS')
ssh_askpass = core.getenv('SSH_ASKPASS')
if git_askpass:
askpass = git_askpass
elif ssh_askpass:
askpass = ssh_askpass
elif sys.platform == 'darwin':
askpass = resources.package_command('ssh-askpass-darwin')
else:
askpass = resources.package_command('ssh-askpass')
compat.setenv('GIT_ASKPASS', askpass)
compat.setenv('SSH_ASKPASS', askpass)
# --- >8 --- >8 ---
# Git v1.7.10 Release Notes
# =========================
#
# Compatibility Notes
# -------------------
#
# * From this release on, the "git merge" command in an interactive
# session will start an editor when it automatically resolves the
# merge for the user to explain the resulting commit, just like the
# "git commit" command does when it wasn't given a commit message.
#
# If you have a script that runs "git merge" and keeps its standard
# input and output attached to the user's terminal, and if you do not
# want the user to explain the resulting merge commits, you can
# export GIT_MERGE_AUTOEDIT environment variable set to "no", like
# this:
#
# #!/bin/sh
# GIT_MERGE_AUTOEDIT=no
# export GIT_MERGE_AUTOEDIT
#
# to disable this behavior (if you want your users to explain their
# merge commits, you do not have to do anything). Alternatively, you
# can give the "--no-edit" option to individual invocations of the
# "git merge" command if you know everybody who uses your script has
# Git v1.7.8 or newer.
# --- >8 --- >8 ---
# Longer-term: Use `git merge --no-commit` so that we always
# have a chance to explain our merges.
compat.setenv('GIT_MERGE_AUTOEDIT', 'no')
def get_icon_themes(context):
"""Return the default icon theme names"""
result = []
icon_themes_env = core.getenv('GIT_COLA_ICON_THEME')
if icon_themes_env:
result.extend([x for x in icon_themes_env.split(':') if x])
icon_themes_cfg = list(reversed(context.cfg.get_all('cola.icontheme')))
if icon_themes_cfg:
result.extend(icon_themes_cfg)
if not result:
result.append('light')
return result
# style note: we use camelCase here since we're masquerading a Qt class
class ColaApplication:
"""The main cola application
ColaApplication handles i18n of user-visible data
"""
def __init__(self, context, argv, locale=None, icon_themes=None, gui_theme=None):
cfgactions.install()
i18n.install(locale)
qtcompat.install()
guicmds.install()
standard.install()
icons.install(icon_themes or get_icon_themes(context))
self.context = context
self.theme = None
self._install_hidpi_config()
self._app = ColaQApplication(context, list(argv))
self._app.setWindowIcon(icons.cola())
self._app.setDesktopFileName('git-cola')
self._install_style(gui_theme)
def _install_style(self, theme_str):
"""Generate and apply a stylesheet to the app"""
if theme_str is None:
theme_str = self.context.cfg.get('cola.theme', default='default')
theme = themes.find_theme(theme_str)
self.theme = theme
self._app.setStyleSheet(theme.build_style_sheet(self._app.palette()))
is_macos_theme = theme_str.startswith('macos-')
if is_macos_theme:
themes.apply_platform_theme(theme_str)
elif theme_str != 'default':
self._app.setPalette(theme.build_palette(self._app.palette()))
def _install_hidpi_config(self):
"""Sets QT HiDPI scaling (requires Qt 5.6)"""
value = self.context.cfg.get('cola.hidpi', default=hidpi.Option.AUTO)
hidpi.apply_choice(value)
def activeWindow(self):
"""QApplication::activeWindow() pass-through"""
return self._app.activeWindow()
def palette(self):
"""QApplication::palette() pass-through"""
return self._app.palette()
def start(self):
"""Wrap exec_() and start the application"""
# Defer connection so that local cola.inotify is honored
context = self.context
monitor = context.fsmonitor
monitor.files_changed.connect(
cmds.run(cmds.Refresh, context), type=Qt.QueuedConnection
)
monitor.config_changed.connect(
cmds.run(cmds.RefreshConfig, context), type=Qt.QueuedConnection
)
# Start the filesystem monitor thread
monitor.start()
return self._app.exec_()
def stop(self):
"""Finalize the application"""
self.context.fsmonitor.stop()
# Workaround QTBUG-52988 by deleting the app manually to prevent a
# crash during app shutdown.
# https://bugreports.qt.io/browse/QTBUG-52988
try:
del self._app
except (AttributeError, RuntimeError):
pass
self._app = None
def exit(self, status):
"""QApplication::exit(status) pass-through"""
return self._app.exit(status)
class ColaQApplication(QtWidgets.QApplication):
"""QApplication implementation for handling custom events"""
def __init__(self, context, argv):
super().__init__(argv)
self.context = context
# Make icons sharp in HiDPI screen
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
self.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
def event(self, e):
"""Respond to focus events for the cola.refreshonfocus feature"""
if e.type() == QtCore.QEvent.ApplicationActivate:
context = self.context
if context:
cfg = context.cfg
if context.git.is_valid() and cfg.get(
'cola.refreshonfocus', default=False
):
cmds.do(cmds.Refresh, context)
return super().event(e)
def commitData(self, session_mgr):
"""Save session data"""
if not self.context or not self.context.view:
return
view = self.context.view
if not hasattr(view, 'save_state'):
return
sid = session_mgr.sessionId()
skey = session_mgr.sessionKey()
session_id = f'{sid}_{skey}'
session = Session(session_id, repo=core.getcwd())
session.update()
view.save_state(settings=session)
def process_args(args):
"""Process and verify command-line arguments"""
if args.version:
# Accept 'git cola --version' or 'git cola version'
version.print_version()
sys.exit(core.EXIT_SUCCESS)
# Handle session management
restore_session(args)
# Bail out if --repo is not a directory
repo = core.decode(args.repo)
if repo.startswith('file:'):
repo = repo[len('file:') :]
repo = core.realpath(repo)
if not core.isdir(repo):
errmsg = (
N_(
'fatal: "%s" is not a directory. '
'Please specify a correct --repo <path>.'
)
% repo
)
core.print_stderr(errmsg)
sys.exit(core.EXIT_USAGE)
def restore_session(args):
"""Load a session based on the window-manager provided arguments"""
# args.settings is provided when restoring from a session.
args.settings = None
if args.session is None:
return
session = Session(args.session)
if session.load():
args.settings = session
args.repo = session.repo
def application_init(args, update=False, app_name='Git Cola'):
"""Parses the command-line arguments and starts git-cola"""
# Ensure that we're working in a valid git repository.
# If not, try to find one. When found, chdir there.
setup_environment()
process_args(args)
context = new_context(args, app_name)
timer = context.timer
timer.start('init')
new_worktree(context, args.repo, args.prompt)
if update:
context.model.update_status()
timer.stop('init')
if args.perf:
timer.display('init')
return context
def new_context(args, app_name):
"""Create top-level ApplicationContext objects"""
context = ApplicationContext(args)
context.settings = args.settings or Settings.read()
context.git = git.create()
context.cfg = gitcfg.create(context)
context.fsmonitor = fsmonitor.create(context)
context.selection = selection.create()
context.model = main.create(context)
context.app_name = app_name
context.app = new_application(context, args)
context.timer = Timer()
return context
def application_run(context, view, start=None, stop=None):
"""Run the application main loop"""
initialize_view(context, view)
# Startup callbacks
if start:
start(context, view)
# Start the event loop
result = context.app.start()
# Finish
if stop:
stop(context, view)
context.app.stop()
return result
def initialize_view(context, view):
"""Register the main widget and display it"""
context.set_view(view)
view.show()
if sys.platform == 'darwin':
view.raise_()
def application_start(context, view):
"""Show the GUI and start the main event loop"""
# Store the view for session management
return application_run(context, view, start=default_start, stop=default_stop)
def default_start(context, _view):
"""Scan for the first time"""
QtCore.QTimer.singleShot(0, startup_message)
QtCore.QTimer.singleShot(0, lambda: async_update(context))
def default_stop(_context, _view):
"""All done, cleanup"""
QtCore.QThreadPool.globalInstance().waitForDone()
def add_common_arguments(parser):
"""Add command arguments to the ArgumentParser"""
# We also accept 'git cola version'
parser.add_argument(
'--version', default=False, action='store_true', help='print version number'
)
# Specifies a git repository to open
parser.add_argument(
'-r',
'--repo',
metavar='<repo>',
default=core.getcwd(),
help='open the specified git repository',
)
# Specifies that we should prompt for a repository at startup
parser.add_argument(
'--prompt', action='store_true', default=False, help='prompt for a repository'
)
# Specify the icon theme
parser.add_argument(
'--icon-theme',
metavar='<theme>',
dest='icon_themes',
action='append',
default=[],
help='specify an icon theme (name or directory)',
)
# Resume an X Session Management session
parser.add_argument(
'-session', metavar='<session>', default=None, help=argparse.SUPPRESS
)
# Enable timing information
parser.add_argument(
'--perf', action='store_true', default=False, help=argparse.SUPPRESS
)
# Specify the GUI theme
parser.add_argument(
'--theme', metavar='<name>', default=None, help='specify an GUI theme name'
)
def new_application(context, args):
"""Create a new ColaApplication"""
return ColaApplication(
context, sys.argv, icon_themes=args.icon_themes, gui_theme=args.theme
)
def new_worktree(context, repo, prompt):
"""Find a Git repository, or prompt for one when not found"""
model = context.model
cfg = context.cfg
parent = qtutils.active_window()
valid = False
if not prompt:
valid = model.set_worktree(repo)
if not valid:
# We are not currently in a git repository so we need to find one.
# Before prompting the user for a repository, check if they've
# configured a default repository and attempt to use it.
default_repo = cfg.get('cola.defaultrepo')
if default_repo:
valid = model.set_worktree(default_repo)
while not valid:
# If we've gotten into this loop then that means that neither the
# current directory nor the default repository were available.
# Prompt the user for a repository.
startup_dlg = startup.StartupDialog(context, parent)
gitdir = startup_dlg.find_git_repo()
if not gitdir:
sys.exit(core.EXIT_NOINPUT)
if not core.exists(os.path.join(gitdir, '.git')):
offer_to_create_repo(context, gitdir)
valid = model.set_worktree(gitdir)
continue
valid = model.set_worktree(gitdir)
if not valid:
err = model.error
standard.critical(
N_('Error Opening Repository'),
message=N_('Could not open %s.' % gitdir),
details=err,
)
def offer_to_create_repo(context, gitdir):
"""Offer to create a new repo"""
title = N_('Repository Not Found')
text = N_('%s is not a Git repository.') % gitdir
informative_text = N_('Create a new repository at that location?')
if standard.confirm(title, text, informative_text, N_('Create')):
status, out, err = context.git.init(gitdir)
title = N_('Error Creating Repository')
if status != 0:
Interaction.command_error(title, 'git init', status, out, err)
def async_update(context):
"""Update the model in the background
git-cola should startup as quickly as possible.
"""
update_status = partial(context.model.update_status, update_index=True)
task = qtutils.SimpleTask(update_status)
context.runtask.start(task)
def startup_message():
"""Print debug startup messages"""
trace = git.GIT_COLA_TRACE
if trace in ('2', 'trace'):
msg1 = 'info: debug level 2: trace mode enabled'
msg2 = 'info: set GIT_COLA_TRACE=1 for less-verbose output'
Interaction.log(msg1)
Interaction.log(msg2)
elif trace:
msg1 = 'info: debug level 1'
msg2 = 'info: set GIT_COLA_TRACE=2 for trace mode'
Interaction.log(msg1)
Interaction.log(msg2)
def initialize():
"""System-level initialization"""
# We support ~/.config/git-cola/git-bindir on Windows for configuring
# a custom location for finding the "git" executable.
git_path = find_git()
if git_path:
prepend_path(git_path)
# The current directory may have been deleted while we are still
# in that directory. We rectify this situation by walking up the
# directory tree and retrying.
#
# This is needed because because Python throws exceptions in lots of
# stdlib functions when in this situation, e.g. os.path.abspath() and
# os.path.realpath(), so it's simpler to mitigate the damage by changing
# the current directory to one that actually exists.
while True:
try:
return core.getcwd()
except OSError:
os.chdir('..')
class Timer:
"""Simple performance timer"""
def __init__(self):
self._data = {}
def start(self, key):
"""Start a timer"""
now = time.time()
self._data[key] = [now, now]
def stop(self, key):
"""Stop a timer and return its elapsed time"""
entry = self._data[key]
entry[1] = time.time()
return self.elapsed(key)
def elapsed(self, key):
"""Return the elapsed time for a timer"""
entry = self._data[key]
return entry[1] - entry[0]
def display(self, key):
"""Display a timer"""
elapsed = self.elapsed(key)
sys.stdout.write(f'{key}: {elapsed:.5f}s\n')
class NullArgs:
"""Stub arguments for interactive API use"""
def __init__(self):
self.icon_themes = []
self.perf = False
self.prompt = False
self.repo = core.getcwd()
self.session = None
self.settings = None
self.theme = None
self.version = False
def null_args():
"""Create a new instance of application arguments"""
return NullArgs()
class ApplicationContext:
"""Context for performing operations on Git and related data models"""
def __init__(self, args):
self.args = args
self.app = None # ColaApplication
self.git = None # git.Git
self.cfg = None # gitcfg.GitConfig
self.model = None # main.MainModel
self.timer = None # Timer
self.runtask = None # qtutils.RunTask
self.settings = None # settings.Settings
self.selection = None # selection.SelectionModel
self.fsmonitor = None # fsmonitor
self.view = None # QWidget
self.browser_windows = [] # list of browse.Browser
def set_view(self, view):
"""Initialize view-specific members"""
self.view = view
self.runtask = qtutils.RunTask(parent=view)
def find_git():
"""Return the path of git.exe, or None if we can't find it."""
if not utils.is_win32():
return None # UNIX systems have git in their $PATH
# If the user wants to use a Git/bin/ directory from a non-standard
# directory then they can write its location into
# ~/.config/git-cola/git-bindir
git_bindir = resources.config_home('git-bindir')
if core.exists(git_bindir):
custom_path = core.read(git_bindir).strip()
if custom_path and core.exists(custom_path):
return custom_path
# Try to find Git's bin/ directory in one of the typical locations
pf = os.environ.get('ProgramFiles', 'C:\\Program Files')
pf32 = os.environ.get('ProgramFiles(x86)', 'C:\\Program Files (x86)')
pf64 = os.environ.get('ProgramW6432', 'C:\\Program Files')
for p in [pf64, pf32, pf, 'C:\\']:
candidate = os.path.join(p, 'Git\\bin')
if os.path.isdir(candidate):
return candidate
return None
def prepend_path(path):
"""Adds git to the PATH. This is needed on Windows."""
path = core.decode(path)
path_entries = core.getenv('PATH', '').split(os.pathsep)
if path not in path_entries:
path_entries.insert(0, path)
compat.setenv('PATH', os.pathsep.join(path_entries))
| 20,714 | Python | .py | 541 | 31.484288 | 86 | 0.648103 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
48 | i18n.py | git-cola_git-cola/cola/i18n.py | """i18n and l10n support for git-cola"""
import locale
import os
try:
import polib
except ImportError:
from . import polib
import sys
from . import core
from . import resources
class NullTranslation:
"""This is a pass-through object that does nothing"""
def gettext(self, value):
return value
class State:
"""The application-wide current translation state"""
translation = NullTranslation()
@classmethod
def reset(cls):
cls.translation = NullTranslation()
@classmethod
def update(cls, lang):
cls.translation = Translation(lang)
@classmethod
def gettext(cls, value):
"""Return a translated value"""
return cls.translation.gettext(value)
class Translation:
def __init__(self, lang):
self.lang = lang
self.messages = {}
self.filename = get_filename_for_locale(lang)
if self.filename:
self.load()
def load(self):
"""Read the .po file content into memory"""
po = polib.pofile(self.filename, encoding='utf-8')
messages = self.messages
for entry in po.translated_entries():
messages[entry.msgid] = entry.msgstr
def gettext(self, value):
return self.messages.get(value, value)
def gettext(value):
"""Translate a string"""
txt = State.gettext(value)
# handle @@verb / @@noun
if txt[-6:-4] == '@@':
txt = txt.replace('@@verb', '').replace('@@noun', '')
return txt
def N_(value):
"""Marker function for translated values
N_("Some string value") is used to mark strings for translation.
"""
return gettext(value)
def get_filename_for_locale(name):
"""Return the .po file for the specified locale"""
# When <name> is "foo_BAR.UTF-8", the name is truncated to "foo_BAR".
# When <name> is "foo_BAR", the <short_name> is "foo"
# Try the following locations:
# cola/i18n/<name>.po
# cola/i18n/<short_name>.po
if not name: # If no locale was specified then try the current locale.
name = locale.getdefaultlocale()[0]
if not name:
return None
name = name.split('.', 1)[0] # foo_BAR.UTF-8 -> foo_BAR
filename = resources.i18n('%s.po' % name)
if os.path.exists(filename):
return filename
short_name = name.split('_', 1)[0]
filename = resources.i18n('%s.po' % short_name)
if os.path.exists(filename):
return filename
return None
def install(lang):
if sys.platform == 'win32' and not lang:
lang = _get_win32_default_locale()
lang = _install_custom_language(lang)
State.update(lang)
def uninstall():
State.reset()
def _install_custom_language(lang):
"""Allow a custom language to be set in ~/.config/git-cola/language"""
lang_file = resources.config_home('language')
if not core.exists(lang_file):
return lang
try:
lang = core.read(lang_file).strip()
except OSError:
return lang
return lang
def _get_win32_default_locale():
"""Get the default locale on Windows"""
for name in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
lang = os.environ.get(name)
if lang:
return lang
try:
import ctypes
except ImportError:
# use only user's default locale
return locale.getdefaultlocale()[0]
# using ctypes to determine all locales
lcid_user = ctypes.windll.kernel32.GetUserDefaultLCID()
lcid_system = ctypes.windll.kernel32.GetSystemDefaultLCID()
lang_user = locale.windows_locale.get(lcid_user)
lang_system = locale.windows_locale.get(lcid_system)
if lang_user:
lang = lang_user
else:
lang = lang_system
return lang
| 3,742 | Python | .py | 112 | 27.464286 | 75 | 0.647942 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
49 | hotkeys.py | git-cola_git-cola/cola/hotkeys.py | import sys
from qtpy.QtGui import QKeySequence
from qtpy.QtCore import Qt
def hotkey(*seq):
return QKeySequence(*seq)
# A-G
STAGE_MODIFIED = hotkey(Qt.ALT | Qt.Key_A)
WORD_LEFT = hotkey(Qt.Key_B)
BLAME = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_B)
BRANCH = hotkey(Qt.CTRL | Qt.Key_B)
CHECKOUT = hotkey(Qt.ALT | Qt.Key_B)
CHERRY_PICK = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_C)
COPY_COMMIT_ID = hotkey(Qt.CTRL | Qt.ALT | Qt.Key_C)
COPY_DIFF = hotkey(Qt.ALT | Qt.SHIFT | Qt.Key_C)
DIFFSTAT = hotkey(Qt.ALT | Qt.Key_D)
DIFF = hotkey(Qt.CTRL | Qt.Key_D)
DIFF_SECONDARY = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_D)
EDIT_SHORT = hotkey(Qt.Key_E)
EDIT = hotkey(Qt.CTRL | Qt.Key_E)
EDIT_SECONDARY = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_E)
EXPORT = hotkey(Qt.ALT | Qt.SHIFT | Qt.Key_E)
FIT = hotkey(Qt.Key_F)
FETCH = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_F)
FILTER = hotkey(Qt.ALT | Qt.SHIFT | Qt.Key_F)
GOTO_END = hotkey(Qt.SHIFT | Qt.Key_G)
GOTO_START = hotkey(Qt.Key_G, Qt.Key_G) # gg
GREP = hotkey(Qt.ALT | Qt.Key_G)
# H-P
MOVE_LEFT = hotkey(Qt.Key_H)
MOVE_LEFT_SHIFT = hotkey(Qt.SHIFT | Qt.Key_H)
HISTORY = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_H)
SIGNOFF = hotkey(Qt.CTRL | Qt.Key_I)
MOVE_DOWN = hotkey(Qt.Key_J)
MOVE_DOWN_SHIFT = hotkey(Qt.SHIFT | Qt.Key_J)
MOVE_DOWN_SECONDARY = hotkey(Qt.ALT | Qt.Key_J)
MOVE_DOWN_TERTIARY = hotkey(Qt.SHIFT | Qt.Key_J)
MOVE_UP = hotkey(Qt.Key_K)
MOVE_UP_SHIFT = hotkey(Qt.SHIFT | Qt.Key_K)
MOVE_UP_SECONDARY = hotkey(Qt.ALT | Qt.Key_K)
MOVE_UP_TERTIARY = hotkey(Qt.SHIFT | Qt.Key_K)
MOVE_RIGHT = hotkey(Qt.Key_L)
MOVE_RIGHT_SHIFT = hotkey(Qt.SHIFT | Qt.Key_L)
FOCUS = hotkey(Qt.CTRL | Qt.Key_L)
FOCUS_DIFF = hotkey(Qt.CTRL | Qt.Key_J)
FOCUS_INPUT = hotkey(Qt.CTRL | Qt.Key_L)
FOCUS_STATUS = hotkey(Qt.CTRL | Qt.Key_K)
FOCUS_TREE = hotkey(Qt.CTRL | Qt.Key_K)
AMEND_DEFAULT = hotkey(Qt.CTRL | Qt.Key_M)
AMEND_MACOS = hotkey(Qt.ALT | Qt.Key_M)
if sys.platform == 'darwin':
AMEND = (AMEND_MACOS,)
else:
AMEND = (AMEND_DEFAULT, AMEND_MACOS)
MACOS_MINIMIZE = hotkey(Qt.CTRL | Qt.Key_M)
MERGE = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_M)
PUSH = hotkey(Qt.CTRL | Qt.Key_P)
PULL = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_P)
OPEN_REPO_SEARCH = hotkey(Qt.ALT | Qt.Key_P)
# Q-Z
QUIT = hotkey(Qt.CTRL | Qt.Key_Q)
REFRESH = hotkey(Qt.CTRL | Qt.Key_R)
REFRESH_SECONDARY = hotkey(Qt.Key_F5)
REFRESH_HOTKEYS = (REFRESH, REFRESH_SECONDARY)
STAGE_DIFF = hotkey(Qt.Key_S)
EDIT_AND_STAGE_DIFF = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_S)
SEARCH = hotkey(Qt.CTRL | Qt.Key_F)
SEARCH_NEXT = hotkey(Qt.CTRL | Qt.Key_G)
SEARCH_PREV = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_G)
STAGE_DIFF_ALT = hotkey(Qt.SHIFT | Qt.Key_S)
STAGE_SELECTION = hotkey(Qt.CTRL | Qt.Key_S)
STAGE_ALL = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_S)
STASH = hotkey(Qt.ALT | Qt.SHIFT | Qt.Key_S)
FINDER = hotkey(Qt.CTRL | Qt.Key_T)
FINDER_SECONDARY = hotkey(Qt.Key_T)
TERMINAL = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_T)
STAGE_UNTRACKED = hotkey(Qt.ALT | Qt.Key_U)
REVERT = hotkey(Qt.CTRL | Qt.Key_U)
REVERT_ALT = hotkey(Qt.ALT | Qt.SHIFT | Qt.Key_R)
EDIT_AND_REVERT = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_U)
WORD_RIGHT = hotkey(Qt.Key_W)
# Numbers
START_OF_LINE = hotkey(Qt.Key_0)
# Special keys
BACKSPACE = hotkey(Qt.Key_Backspace)
TRASH = hotkey(Qt.CTRL | Qt.Key_Backspace)
DELETE_FILE = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_Backspace)
DELETE_FILE_SECONDARY = hotkey(Qt.CTRL | Qt.Key_Backspace)
PREFERENCES = hotkey(Qt.CTRL | Qt.Key_Comma)
END_OF_LINE = hotkey(Qt.Key_Dollar)
DOWN = hotkey(Qt.Key_Down)
ENTER = hotkey(Qt.Key_Enter)
ZOOM_OUT = hotkey(Qt.Key_Minus)
REMOVE_ITEM = hotkey(Qt.Key_Minus)
ADD_ITEM = hotkey(Qt.Key_Plus)
ZOOM_IN = hotkey(Qt.Key_Plus)
ZOOM_IN_SECONDARY = hotkey(Qt.Key_Equal)
QUESTION = hotkey(Qt.Key_Question)
RETURN = hotkey(Qt.Key_Return)
ACCEPT = (ENTER, RETURN)
APPLY = hotkey(Qt.CTRL | Qt.Key_Return)
PREPARE_COMMIT_MESSAGE = hotkey(Qt.CTRL | Qt.SHIFT | Qt.Key_Return)
PRIMARY_ACTION = hotkey(hotkey(Qt.Key_Space))
SECONDARY_ACTION = hotkey(Qt.SHIFT | Qt.Key_Space)
LEAVE = hotkey(Qt.SHIFT | Qt.Key_Tab)
UP = hotkey(Qt.Key_Up)
CTRL_RETURN = hotkey(Qt.CTRL | Qt.Key_Return)
CTRL_ENTER = hotkey(Qt.CTRL | Qt.Key_Enter)
# Rebase
REBASE_START_AND_CONTINUE = hotkey(Qt.ALT | Qt.Key_R)
REBASE_PICK = (hotkey(Qt.Key_1), hotkey(Qt.Key_P))
REBASE_REWORD = (hotkey(Qt.Key_2), hotkey(Qt.Key_R))
REBASE_EDIT = (hotkey(Qt.Key_3), hotkey(Qt.Key_E))
REBASE_FIXUP = (hotkey(Qt.Key_4), hotkey(Qt.Key_F))
REBASE_SQUASH = (hotkey(Qt.Key_5), hotkey(Qt.Key_S))
REBASE_DROP = (hotkey(Qt.Key_6), hotkey(Qt.Key_D))
UNDO = hotkey(Qt.CTRL | Qt.Key_Z)
REDO = hotkey(Qt.SHIFT | Qt.CTRL | Qt.Key_Z)
# Key Sequences
COPY = QKeySequence.Copy
CLOSE = QKeySequence.Close
CUT = QKeySequence.Cut
PASTE = QKeySequence.Paste
DELETE = QKeySequence.Delete
NEW = QKeySequence.New
OPEN = QKeySequence.Open
SELECT_ALL = QKeySequence.SelectAll
# Text navigation
TEXT_DOWN = hotkey(Qt.Key_D)
TEXT_UP = hotkey(Qt.Key_U)
SELECT_FORWARD = hotkey(Qt.SHIFT | Qt.Key_F)
SELECT_BACK = hotkey(Qt.SHIFT | Qt.Key_B)
SELECT_DOWN = hotkey(Qt.SHIFT | Qt.Key_D)
SELECT_UP = hotkey(Qt.SHIFT | Qt.Key_U)
| 5,027 | Python | .py | 133 | 36.609023 | 67 | 0.714403 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
50 | utils.py | git-cola_git-cola/cola/utils.py | """Miscellaneous utility functions"""
import copy
import os
import re
import shlex
import sys
import tempfile
import time
import traceback
from . import core
from . import compat
def asint(obj, default=0):
"""Make any value into an int, even if the cast fails"""
try:
value = int(obj)
except (TypeError, ValueError):
value = default
return value
def clamp(value, low, high):
"""Clamp a value to the specified range"""
return min(high, max(low, value))
def epoch_millis():
return int(time.time() * 1000)
def add_parents(paths):
"""Iterate over each item in the set and add its parent directories."""
all_paths = set()
for path in paths:
while '//' in path:
path = path.replace('//', '/')
all_paths.add(path)
if '/' in path:
parent_dir = dirname(path)
while parent_dir:
all_paths.add(parent_dir)
parent_dir = dirname(parent_dir)
return all_paths
def format_exception(exc):
"""Format an exception object for display"""
exc_type, exc_value, exc_tb = sys.exc_info()
details = traceback.format_exception(exc_type, exc_value, exc_tb)
details = '\n'.join(map(core.decode, details))
if hasattr(exc, 'msg'):
msg = exc.msg
else:
msg = core.decode(repr(exc))
return (msg, details)
def sublist(values, remove):
"""Subtracts list b from list a and returns the resulting list."""
# conceptually, c = a - b
result = []
for item in values:
if item not in remove:
result.append(item)
return result
__grep_cache = {}
def grep(pattern, items, squash=True):
"""Greps a list for items that match a pattern
:param squash: If only one item matches, return just that item
:returns: List of matching items
"""
isdict = isinstance(items, dict)
if pattern in __grep_cache:
regex = __grep_cache[pattern]
else:
regex = __grep_cache[pattern] = re.compile(pattern)
matched = []
matchdict = {}
for item in items:
match = regex.match(item)
if not match:
continue
groups = match.groups()
if not groups:
subitems = match.group(0)
else:
if len(groups) == 1:
subitems = groups[0]
else:
subitems = list(groups)
if isdict:
matchdict[item] = items[item]
else:
matched.append(subitems)
if isdict:
result = matchdict
elif squash and len(matched) == 1:
result = matched[0]
else:
result = matched
return result
def basename(path):
"""
An os.path.basename() implementation that always uses '/'
Avoid os.path.basename because git's output always
uses '/' regardless of platform.
"""
return path.rsplit('/', 1)[-1]
def strip_one(path):
"""Strip one level of directory"""
return path.strip('/').split('/', 1)[-1]
def dirname(path, current_dir=''):
"""
An os.path.dirname() implementation that always uses '/'
Avoid os.path.dirname because git's output always
uses '/' regardless of platform.
"""
while '//' in path:
path = path.replace('//', '/')
path_dirname = path.rsplit('/', 1)[0]
if path_dirname == path:
return current_dir
return path.rsplit('/', 1)[0]
def splitpath(path):
"""Split paths using '/' regardless of platform"""
return path.split('/')
def split(name):
"""Split a path-like name. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. The "head" may be empty.
This is the same as os.path.split() but only uses '/' as the delimiter.
>>> split('a/b/c')
('a/b', 'c')
>>> split('xyz')
('', 'xyz')
"""
return (dirname(name), basename(name))
def join(*paths):
"""Join paths using '/' regardless of platform
>>> join('a', 'b', 'c')
'a/b/c'
"""
return '/'.join(paths)
def normalize_slash(value):
"""Strip and normalize slashes in a string
>>> normalize_slash('///Meow///Cat///')
'Meow/Cat'
"""
value = value.strip('/')
new_value = value.replace('//', '/')
while new_value != value:
value = new_value
new_value = value.replace('//', '/')
return value
def pathjoin(paths):
"""Join a list of paths using '/' regardless of platform
>>> pathjoin(['a', 'b', 'c'])
'a/b/c'
"""
return join(*paths)
def pathset(path):
"""Return all of the path components for the specified path
>>> pathset('foo/bar/baz') == ['foo', 'foo/bar', 'foo/bar/baz']
True
"""
result = []
parts = splitpath(path)
prefix = ''
for part in parts:
result.append(prefix + part)
prefix += part + '/'
return result
def select_directory(paths):
"""Return the first directory in a list of paths"""
if not paths:
return core.getcwd()
for path in paths:
if core.isdir(path):
return path
return os.path.dirname(paths[0]) or core.getcwd()
def strip_prefix(prefix, string):
"""Return string, without the prefix. Blow up if string doesn't
start with prefix."""
assert string.startswith(prefix)
return string[len(prefix) :]
def tablength(word, tabwidth):
"""Return length of a word taking tabs into account
>>> tablength("\\t\\t\\t\\tX", 8)
33
"""
return len(word.replace('\t', '')) + word.count('\t') * tabwidth
def _shell_split_py2(value):
"""Python2 requires bytes inputs to shlex.split(). Returns [unicode]"""
try:
result = shlex.split(core.encode(value))
except ValueError:
result = core.encode(value).strip().split()
# Decode to Unicode strings
return [core.decode(arg) for arg in result]
def _shell_split_py3(value):
"""Python3 requires Unicode inputs to shlex.split(). Convert to Unicode"""
try:
result = shlex.split(value)
except ValueError:
result = core.decode(value).strip().split()
# Already Unicode
return result
def shell_split(value):
if compat.PY2:
# Encode before calling split()
values = _shell_split_py2(value)
else:
# Python3 does not need the encode/decode dance
values = _shell_split_py3(value)
return values
def tmp_filename(label, suffix=''):
label = 'git-cola-' + label.replace('/', '-').replace('\\', '-')
with tempfile.NamedTemporaryFile(
prefix=label + '-', suffix=suffix, delete=False
) as handle:
return handle.name
def is_linux():
"""Is this a Linux machine?"""
return sys.platform.startswith('linux')
def is_debian():
"""Is this a Debian/Linux machine?"""
return os.path.exists('/usr/bin/apt-get')
def is_darwin():
"""Is this a macOS machine?"""
return sys.platform == 'darwin'
def is_win32():
"""Return True on win32"""
return sys.platform in {'win32', 'cygwin'}
def launch_default_app(paths):
"""Execute the default application on the specified paths"""
if is_win32():
for path in paths:
if hasattr(os, 'startfile'):
os.startfile(os.path.abspath(path))
return
if is_darwin():
launcher = 'open'
else:
launcher = 'xdg-open'
core.fork([launcher] + paths)
def expandpath(path):
"""Expand ~user/ and environment $variables"""
path = os.path.expandvars(path)
if path.startswith('~'):
path = os.path.expanduser(path)
return path
class Group:
"""Operate on a collection of objects as a single unit"""
def __init__(self, *members):
self._members = members
def __getattr__(self, name):
"""Return a function that relays calls to the group"""
def relay(*args, **kwargs):
for member in self._members:
method = getattr(member, name)
method(*args, **kwargs)
setattr(self, name, relay)
return relay
class Proxy:
"""Wrap an object and override attributes"""
def __init__(self, obj, **overrides):
self._obj = obj
for k, v in overrides.items():
setattr(self, k, v)
def __getattr__(self, name):
return getattr(self._obj, name)
def slice_func(input_items, map_func):
"""Slice input_items and call `map_func` over every slice
This exists because of "errno: Argument list too long"
"""
# This comment appeared near the top of include/linux/binfmts.h
# in the Linux source tree:
#
# /*
# * MAX_ARG_PAGES defines the number of pages allocated for arguments
# * and envelope for the new program. 32 should suffice, this gives
# * a maximum env+arg of 128kB w/4KB pages!
# */
# #define MAX_ARG_PAGES 32
#
# 'size' is a heuristic to keep things highly performant by minimizing
# the number of slices. If we wanted it to run as few commands as
# possible we could call "getconf ARG_MAX" and make a better guess,
# but it's probably not worth the complexity (and the extra call to
# getconf that we can't do on Windows anyways).
#
# In my testing, getconf ARG_MAX on Mac OS X Mountain Lion reported
# 262144 and Debian/Linux-x86_64 reported 2097152.
#
# The hard-coded max_arg_len value is safely below both of these
# real-world values.
# 4K pages x 32 MAX_ARG_PAGES
max_arg_len = (32 * 4096) // 4 # allow plenty of space for the environment
max_filename_len = 256
size = max_arg_len // max_filename_len
status = 0
outs = []
errs = []
items = copy.copy(input_items)
while items:
stat, out, err = map_func(items[:size])
if stat < 0:
status = min(stat, status)
else:
status = max(stat, status)
outs.append(out)
errs.append(err)
items = items[size:]
return (status, '\n'.join(outs), '\n'.join(errs))
class Sequence:
def __init__(self, sequence):
self.sequence = sequence
def index(self, item, default=-1):
try:
idx = self.sequence.index(item)
except ValueError:
idx = default
return idx
def __getitem__(self, idx):
return self.sequence[idx]
def catch_runtime_error(func, *args, **kwargs):
"""Run the function safely.
Catch RuntimeError to avoid tracebacks during application shutdown.
"""
# Signals and callbacks can sometimes get triggered during application shutdown.
# This can happen when exiting while background tasks are still processing.
# Guard against this by making this operation a no-op.
try:
valid = True
result = func(*args, **kwargs)
except RuntimeError:
valid = False
result = None
return (valid, result)
| 10,897 | Python | .py | 327 | 27.033639 | 84 | 0.619166 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
51 | core.py | git-cola_git-cola/cola/core.py | """This module provides core functions for handling Unicode and Unix quirks
The @interruptable functions retry when system calls are interrupted,
e.g. when python raises an IOError or OSError with errno == EINTR.
"""
import ctypes
import functools
import itertools
import mimetypes
import os
import platform
import subprocess
import sys
from .decorators import interruptable
from .compat import ustr
from .compat import PY2
from .compat import PY3
from .compat import WIN32
# /usr/include/stdlib.h
# #define EXIT_SUCCESS 0 /* Successful exit status. */
# #define EXIT_FAILURE 1 /* Failing exit status. */
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
# /usr/include/sysexits.h
# #define EX_USAGE 64 /* command line usage error */
# #define EX_NOINPUT 66 /* cannot open input */
# #define EX_UNAVAILABLE 69 /* service unavailable */
EXIT_USAGE = 64
EXIT_NOINPUT = 66
EXIT_UNAVAILABLE = 69
# Default encoding
ENCODING = 'utf-8'
# Some files are not in UTF-8; some other aren't in any codification.
# Remember that GIT doesn't care about encodings (saves binary data)
_encoding_tests = [
ENCODING,
'iso-8859-15',
'windows1252',
'ascii',
# <-- add encodings here
]
class UStr(ustr):
"""Unicode string wrapper that remembers its encoding
UStr wraps Unicode strings to provide the `encoding` attribute.
UStr is used when decoding strings of an unknown encoding.
In order to generate patches that contain the original byte sequences,
we must preserve the original encoding when calling decode()
so that it can later be used when reconstructing the original
byte sequences.
"""
def __new__(cls, string, encoding):
if isinstance(string, UStr):
if encoding != string.encoding:
raise ValueError(f'Encoding conflict: {string.encoding} vs. {encoding}')
string = ustr(string)
obj = ustr.__new__(cls, string)
obj.encoding = encoding
return obj
def decode_maybe(value, encoding, errors='strict'):
"""Decode a value when the "decode" method exists"""
if hasattr(value, 'decode'):
result = value.decode(encoding, errors=errors)
else:
result = value
return result
def decode(value, encoding=None, errors='strict'):
"""decode(encoded_string) returns an un-encoded Unicode string"""
if value is None:
result = None
elif isinstance(value, ustr):
result = UStr(value, ENCODING)
elif encoding == 'bytes':
result = value
else:
result = None
if encoding is None:
encoding_tests = _encoding_tests
else:
encoding_tests = itertools.chain([encoding], _encoding_tests)
for enc in encoding_tests:
try:
decoded = value.decode(enc, errors)
result = UStr(decoded, enc)
break
except ValueError:
pass
if result is None:
decoded = value.decode(ENCODING, errors='ignore')
result = UStr(decoded, ENCODING)
return result
def encode(string, encoding=None):
"""encode(string) returns a byte string encoded to UTF-8"""
if not isinstance(string, ustr):
return string
return string.encode(encoding or ENCODING, 'replace')
def mkpath(path, encoding=None):
# The Windows API requires Unicode strings regardless of python version
if WIN32:
return decode(path, encoding=encoding)
# UNIX prefers bytes
return encode(path, encoding=encoding)
def decode_seq(seq, encoding=None):
"""Decode a sequence of values"""
return [decode(x, encoding=encoding) for x in seq]
def list2cmdline(cmd):
return subprocess.list2cmdline([decode(c) for c in cmd])
def read(filename, size=-1, encoding=None, errors='strict'):
"""Read filename and return contents"""
with xopen(filename, 'rb') as fh:
return xread(fh, size=size, encoding=encoding, errors=errors)
def write(path, contents, encoding=None, append=False):
"""Writes a Unicode string to a file"""
if append:
mode = 'ab'
else:
mode = 'wb'
with xopen(path, mode) as fh:
return xwrite(fh, contents, encoding=encoding)
@interruptable
def xread(fh, size=-1, encoding=None, errors='strict'):
"""Read from a file handle and retry when interrupted"""
return decode(fh.read(size), encoding=encoding, errors=errors)
@interruptable
def xwrite(fh, content, encoding=None):
"""Write to a file handle and retry when interrupted"""
return fh.write(encode(content, encoding=encoding))
@interruptable
def wait(proc):
"""Wait on a subprocess and retry when interrupted"""
return proc.wait()
@interruptable
def readline(fh, encoding=None):
return decode(fh.readline(), encoding=encoding)
@interruptable
def start_command(
cmd,
cwd=None,
add_env=None,
universal_newlines=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
no_win32_startupinfo=False,
stderr=subprocess.PIPE,
**extra,
):
"""Start the given command, and return a subprocess object.
This provides a simpler interface to the subprocess module.
"""
env = extra.pop('env', None)
if add_env is not None:
env = os.environ.copy()
env.update(add_env)
# Python3 on windows always goes through list2cmdline() internally inside
# of subprocess.py so we must provide Unicode strings here otherwise
# Python3 breaks when bytes are provided.
#
# Additionally, the preferred usage on Python3 is to pass Unicode
# strings to subprocess. Python will automatically encode into the
# default encoding (UTF-8) when it gets Unicode strings.
shell = extra.get('shell', False)
cmd = prep_for_subprocess(cmd, shell=shell)
if WIN32 and cwd == getcwd():
# Windows cannot deal with passing a cwd that contains Unicode
# but we luckily can pass None when the supplied cwd is the same
# as our current directory and get the same effect.
# Not doing this causes Unicode encoding errors when launching
# the subprocess.
cwd = None
if PY2 and cwd:
cwd = encode(cwd)
if WIN32:
# If git-cola is invoked on Windows using "start pythonw git-cola",
# a console window will briefly flash on the screen each time
# git-cola invokes git, which is very annoying. The code below
# prevents this by ensuring that any window will be hidden.
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
extra['startupinfo'] = startupinfo
if WIN32 and not no_win32_startupinfo:
CREATE_NO_WINDOW = 0x08000000
extra['creationflags'] = CREATE_NO_WINDOW
# Use line buffering when in text/universal_newlines mode,
# otherwise use the system default buffer size.
bufsize = 1 if universal_newlines else -1
return subprocess.Popen(
cmd,
bufsize=bufsize,
stdin=stdin,
stdout=stdout,
stderr=stderr,
cwd=cwd,
env=env,
universal_newlines=universal_newlines,
**extra,
)
def prep_for_subprocess(cmd, shell=False):
"""Decode on Python3, encode on Python2"""
# See the comment in start_command()
if shell:
if PY3:
cmd = decode(cmd)
else:
cmd = encode(cmd)
else:
if PY3:
cmd = [decode(c) for c in cmd]
else:
cmd = [encode(c) for c in cmd]
return cmd
@interruptable
def communicate(proc):
return proc.communicate()
def run_command(cmd, *args, **kwargs):
"""Run the given command to completion, and return its results.
This provides a simpler interface to the subprocess module.
The results are formatted as a 3-tuple: (exit_code, output, errors)
The other arguments are passed on to start_command().
"""
encoding = kwargs.pop('encoding', None)
process = start_command(cmd, *args, **kwargs)
(output, errors) = communicate(process)
output = decode(output, encoding=encoding)
errors = decode(errors, encoding=encoding)
exit_code = process.returncode
return (exit_code, output or UStr('', ENCODING), errors or UStr('', ENCODING))
@interruptable
def _fork_posix(args, cwd=None, shell=False):
"""Launch a process in the background."""
encoded_args = [encode(arg) for arg in args]
return subprocess.Popen(encoded_args, cwd=cwd, shell=shell).pid
def _fork_win32(args, cwd=None, shell=False):
"""Launch a background process using crazy win32 voodoo."""
# This is probably wrong, but it works. Windows.. Wow.
if args[0] == 'git-dag':
# win32 can't exec python scripts
args = [sys.executable] + args
if not shell:
args[0] = _win32_find_exe(args[0])
if PY3:
# see comment in start_command()
argv = [decode(arg) for arg in args]
else:
argv = [encode(arg) for arg in args]
DETACHED_PROCESS = 0x00000008 # Amazing!
return subprocess.Popen(
argv, cwd=cwd, creationflags=DETACHED_PROCESS, shell=shell
).pid
def _win32_find_exe(exe):
"""Find the actual file for a Windows executable.
This function goes through the same process that the Windows shell uses to
locate an executable, taking into account the PATH and PATHEXT environment
variables. This allows us to avoid passing shell=True to subprocess.Popen.
For reference, see:
https://technet.microsoft.com/en-us/library/cc723564.aspx#XSLTsection127121120120
"""
# try the argument itself
candidates = [exe]
# if argument does not have an extension, also try it with each of the
# extensions specified in PATHEXT
if '.' not in exe:
extensions = getenv('PATHEXT', '').split(os.pathsep)
candidates.extend([(exe + ext) for ext in extensions if ext.startswith('.')])
# search the current directory first
for candidate in candidates:
if exists(candidate):
return candidate
# if the argument does not include a path separator, search each of the
# directories on the PATH
if not os.path.dirname(exe):
for path in getenv('PATH').split(os.pathsep):
if path:
for candidate in candidates:
full_path = os.path.join(path, candidate)
if exists(full_path):
return full_path
# not found, punt and return the argument unchanged
return exe
# Portability wrappers
if sys.platform in {'win32', 'cygwin'}:
fork = _fork_win32
else:
fork = _fork_posix
def _decorator_noop(x):
return x
def wrap(action, func, decorator=None):
"""Wrap arguments with `action`, optionally decorate the result"""
if decorator is None:
decorator = _decorator_noop
@functools.wraps(func)
def wrapped(*args, **kwargs):
return decorator(func(action(*args, **kwargs)))
return wrapped
def decorate(decorator, func):
"""Decorate the result of `func` with `action`"""
@functools.wraps(func)
def decorated(*args, **kwargs):
return decorator(func(*args, **kwargs))
return decorated
def getenv(name, default=None):
return decode(os.getenv(name, default))
def guess_mimetype(filename):
"""Robustly guess a filename's mimetype"""
mimetype = None
try:
mimetype = mimetypes.guess_type(filename)[0]
except UnicodeEncodeError:
mimetype = mimetypes.guess_type(encode(filename))[0]
except (TypeError, ValueError):
mimetype = mimetypes.guess_type(decode(filename))[0]
return mimetype
def xopen(path, mode='r', encoding=None):
"""Open a file with the specified mode and encoding
The path is decoded into Unicode on Windows and encoded into bytes on Unix.
"""
return open(mkpath(path, encoding=encoding), mode)
def open_append(path, encoding=None):
"""Open a file for appending in UTF-8 text mode"""
return open(mkpath(path, encoding=encoding), 'a', encoding='utf-8')
def open_read(path, encoding=None):
"""Open a file for reading in UTF-8 text mode"""
return open(mkpath(path, encoding=encoding), encoding='utf-8')
def open_write(path, encoding=None):
"""Open a file for writing in UTF-8 text mode"""
return open(mkpath(path, encoding=encoding), 'w', encoding='utf-8')
def print_stdout(msg, linesep='\n'):
msg = msg + linesep
if PY2:
msg = encode(msg, encoding=ENCODING)
sys.stdout.write(msg)
def print_stderr(msg, linesep='\n'):
msg = msg + linesep
if PY2:
msg = encode(msg, encoding=ENCODING)
sys.stderr.write(msg)
def error(msg, status=EXIT_FAILURE, linesep='\n'):
print_stderr(msg, linesep=linesep)
sys.exit(status)
@interruptable
def node():
return platform.node()
abspath = wrap(mkpath, os.path.abspath, decorator=decode)
chdir = wrap(mkpath, os.chdir)
exists = wrap(mkpath, os.path.exists)
expanduser = wrap(encode, os.path.expanduser, decorator=decode)
if PY2:
if hasattr(os, 'getcwdu'):
getcwd = os.getcwdu
else:
getcwd = decorate(decode, os.getcwd)
else:
getcwd = os.getcwd
# NOTE: find_executable() is originally from the stdlib, but starting with
# python3.7 the stdlib no longer bundles distutils.
def _find_executable(executable, path=None):
"""Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found.
"""
if path is None:
path = os.environ['PATH']
paths = path.split(os.pathsep)
_, ext = os.path.splitext(executable)
if (sys.platform == 'win32') and (ext != '.exe'):
executable = executable + '.exe'
if not os.path.isfile(executable):
for dirname in paths:
filename = os.path.join(dirname, executable)
if os.path.isfile(filename):
# the file exists, we have a shot at spawn working
return filename
return None
return executable
def _fdatasync(fd):
"""fdatasync the file descriptor. Returns True on success"""
try:
os.fdatasync(fd)
except OSError:
pass
def _fsync(fd):
"""fsync the file descriptor. Returns True on success"""
try:
os.fsync(fd)
except OSError:
pass
def fsync(fd):
"""Flush contents to disk using fdatasync() / fsync()"""
has_libc_fdatasync = False
has_libc_fsync = False
has_os_fdatasync = hasattr(os, 'fdatasync')
has_os_fsync = hasattr(os, 'fsync')
if not has_os_fdatasync and not has_os_fsync:
try:
libc = ctypes.CDLL('libc.so.6')
except OSError:
libc = None
has_libc_fdatasync = libc and hasattr(libc, 'fdatasync')
has_libc_fsync = libc and hasattr(libc, 'fsync')
if has_os_fdatasync:
_fdatasync(fd)
elif has_os_fsync:
_fsync(fd)
elif has_libc_fdatasync:
libc.fdatasync(fd)
elif has_libc_fsync:
libc.fsync(fd)
def rename(old, new):
"""Rename a path. Transform arguments to handle non-ASCII file paths"""
os.rename(mkpath(old), mkpath(new))
if PY2:
find_executable = wrap(mkpath, _find_executable, decorator=decode)
else:
find_executable = wrap(decode, _find_executable, decorator=decode)
isdir = wrap(mkpath, os.path.isdir)
isfile = wrap(mkpath, os.path.isfile)
islink = wrap(mkpath, os.path.islink)
listdir = wrap(mkpath, os.listdir, decorator=decode_seq)
makedirs = wrap(mkpath, os.makedirs)
try:
readlink = wrap(mkpath, os.readlink, decorator=decode)
except AttributeError:
def _readlink_noop(p):
return p
readlink = _readlink_noop
realpath = wrap(mkpath, os.path.realpath, decorator=decode)
relpath = wrap(mkpath, os.path.relpath, decorator=decode)
remove = wrap(mkpath, os.remove)
stat = wrap(mkpath, os.stat)
unlink = wrap(mkpath, os.unlink)
if PY2:
walk = wrap(mkpath, os.walk)
else:
walk = os.walk
| 16,154 | Python | .py | 431 | 31.672854 | 88 | 0.677287 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
52 | gitcfg.py | git-cola_git-cola/cola/gitcfg.py | from binascii import unhexlify
import collections
import copy
import fnmatch
import os
import struct
try:
import pwd
_use_pwd = True
except ImportError:
_use_pwd = False
from qtpy import QtCore
from qtpy.QtCore import Signal
from . import core
from . import utils
from . import version
from . import resources
from .compat import int_types
from .compat import ustr
def create(context):
"""Create GitConfig instances"""
return GitConfig(context)
def _cache_key_from_paths(paths):
"""Return a stat cache from the given paths"""
if not paths:
return None
mtimes = []
for path in sorted(paths):
try:
mtimes.append(core.stat(path).st_mtime)
except OSError:
continue
if mtimes:
return mtimes
return None
def _config_to_python(value):
"""Convert a Git config string into a Python value"""
if value in ('true', 'yes'):
value = True
elif value in ('false', 'no'):
value = False
else:
try:
value = int(value)
except ValueError:
pass
return value
def unhex(value):
"""Convert a value (int or hex string) into bytes"""
if isinstance(value, int_types):
# If the value is an integer then it's a value that was converted
# by the config reader. Zero-pad it into a 6-digit hex number.
value = '%06d' % value
return unhexlify(core.encode(value.lstrip('#')))
def _config_key_value(line, splitchar):
"""Split a config line into a (key, value) pair"""
try:
k, v = line.split(splitchar, 1)
except ValueError:
# the user has an empty entry in their git config,
# which Git interprets as meaning "true"
k = line
v = 'true'
return k, _config_to_python(v)
def _append_tab(value):
"""Return a value and the same value with tab appended"""
return (value, value + '\t')
class GitConfig(QtCore.QObject):
"""Encapsulate access to git-config values."""
user_config_changed = Signal(str, object)
repo_config_changed = Signal(str, object)
updated = Signal()
def __init__(self, context):
super().__init__()
self.context = context
self.git = context.git
self._system = {}
self._global = {}
self._global_or_system = {}
self._local = {}
self._all = {}
self._renamed_keys = {}
self._multi_values = collections.defaultdict(list)
self._cache_key = None
self._cache_paths = []
self._attr_cache = {}
self._binary_cache = {}
def reset(self):
self._cache_key = None
self._cache_paths = []
self._attr_cache.clear()
self._binary_cache.clear()
self.reset_values()
def reset_values(self):
self._system.clear()
self._global.clear()
self._global_or_system.clear()
self._local.clear()
self._all.clear()
self._renamed_keys.clear()
self._multi_values.clear()
def user(self):
return copy.deepcopy(self._global)
def repo(self):
return copy.deepcopy(self._local)
def all(self):
return copy.deepcopy(self._all)
def _is_cached(self):
"""
Return True when the cache matches.
Updates the cache and returns False when the cache does not match.
"""
cache_key = _cache_key_from_paths(self._cache_paths)
return self._cache_key and cache_key == self._cache_key
def update(self):
"""Read git config value into the system, user and repo dicts."""
if self._is_cached():
return
self.reset_values()
show_scope = version.check_git(self.context, 'config-show-scope')
show_origin = version.check_git(self.context, 'config-show-origin')
if show_scope:
reader = _read_config_with_scope
elif show_origin:
reader = _read_config_with_origin
else:
reader = _read_config_fallback
unknown_scope = 'unknown'
system_scope = 'system'
global_scope = 'global'
local_scope = 'local'
worktree_scope = 'worktree'
cache_paths = set()
for current_scope, current_key, current_value, continuation in reader(
self.context, cache_paths, self._renamed_keys
):
# Store the values for fast cached lookup.
self._all[current_key] = current_value
# macOS has credential.helper=osxkeychain in the "unknown" scope from
# /Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig.
# Treat "unknown" as equivalent to "system" (lowest priority).
if current_scope in (system_scope, unknown_scope):
self._system[current_key] = current_value
self._global_or_system[current_key] = current_value
elif current_scope == global_scope:
self._global[current_key] = current_value
self._global_or_system[current_key] = current_value
# "worktree" is treated as equivalent to "local".
elif current_scope in (local_scope, worktree_scope):
self._local[current_key] = current_value
# Add this value to the multi-values storage used by get_all().
# This allows us to handle keys that store multiple values.
if continuation:
# If this is a continuation line then we should *not* append to its
# multi-values list. We should update it in-place.
self._multi_values[current_key][-1] = current_value
else:
self._multi_values[current_key].append(current_value)
# Update the cache
self._cache_paths = sorted(cache_paths)
self._cache_key = _cache_key_from_paths(self._cache_paths)
# Send a notification that the configuration has been updated.
self.updated.emit()
def _get(self, src, key, default, func=None, cached=True):
if not cached or not src:
self.update()
try:
value = self._get_value(src, key)
except KeyError:
if func:
value = func()
else:
value = default
return value
def _get_value(self, src, key):
"""Return a value from the map"""
try:
return src[key]
except KeyError:
pass
# Try the original key name.
key = self._renamed_keys.get(key.lower(), key)
try:
return src[key]
except KeyError:
pass
# Allow the final KeyError to bubble up
return src[key.lower()]
def get(self, key, default=None, func=None, cached=True):
"""Return the string value for a config key."""
return self._get(self._all, key, default, func=func, cached=cached)
def get_all(self, key):
"""Return all values for a key sorted in priority order
The purpose of this function is to group the values returned by
`git config --show-origin --list` so that the relative order is
preserved and can be overridden at each level.
One use case is the `cola.icontheme` variable, which is an ordered
list of icon themes to load. This value can be set both in
~/.gitconfig as well as .git/config, and we want to allow a
relative order to be defined in either file.
The problem is that git will read the system /etc/gitconfig,
global ~/.gitconfig, and then the local .git/config settings
and return them in that order, so we must post-process them to
get them in an order which makes sense for use for our values.
Otherwise, we cannot replace the order, or make a specific theme used
first, in our local .git/config since the native order returned by
git will always list the global config before the local one.
get_all() allows for this use case by reading from a defaultdict
that contains all of the per-config values separately so that the
caller can order them according to its preferred precedence.
"""
if not self._multi_values:
self.update()
# Check for this key as-is.
if key in self._multi_values:
return self._multi_values[key]
# Check for a renamed version of this key (x.kittycat -> x.kittyCat)
renamed_key = self._renamed_keys.get(key.lower(), key)
if renamed_key in self._multi_values:
return self._multi_values[renamed_key]
key_lower = key.lower()
if key_lower in self._multi_values:
return self._multi_values[key_lower]
# Nothing found -> empty list.
return []
def get_user(self, key, default=None):
return self._get(self._global, key, default)
def get_repo(self, key, default=None):
return self._get(self._local, key, default)
def get_user_or_system(self, key, default=None):
return self._get(self._global_or_system, key, default)
def set_user(self, key, value):
if value in (None, ''):
self.git.config('--global', key, unset=True, _readonly=True)
else:
self.git.config('--global', key, python_to_git(value), _readonly=True)
self.update()
self.user_config_changed.emit(key, value)
def set_repo(self, key, value):
if value in (None, ''):
self.git.config(key, unset=True, _readonly=True)
self._local.pop(key, None)
else:
self.git.config(key, python_to_git(value), _readonly=True)
self._local[key] = value
self.updated.emit()
self.repo_config_changed.emit(key, value)
def find(self, pat):
"""Return a dict of values for all keys matching the specified pattern"""
pat = pat.lower()
match = fnmatch.fnmatch
result = {}
if not self._all:
self.update()
for key, val in self._all.items():
if match(key.lower(), pat):
result[key] = val
return result
def is_annex(self):
"""Return True when git-annex is enabled"""
return bool(self.get('annex.uuid', default=False))
def gui_encoding(self):
return self.get('gui.encoding', default=None)
def is_per_file_attrs_enabled(self):
return self.get(
'cola.fileattributes', func=lambda: os.path.exists('.gitattributes')
)
def is_binary(self, path):
"""Return True if the file has the binary attribute set"""
if not self.is_per_file_attrs_enabled():
return None
cache = self._binary_cache
try:
value = cache[path]
except KeyError:
value = cache[path] = self._is_binary(path)
return value
def _is_binary(self, path):
"""Return the file encoding for a path"""
value = self.check_attr('binary', path)
return value == 'set'
def file_encoding(self, path):
if not self.is_per_file_attrs_enabled():
return self.gui_encoding()
cache = self._attr_cache
try:
value = cache[path]
except KeyError:
value = cache[path] = self._file_encoding(path) or self.gui_encoding()
return value
def _file_encoding(self, path):
"""Return the file encoding for a path"""
encoding = self.check_attr('encoding', path)
if encoding in ('unspecified', 'unset', 'set'):
result = None
else:
result = encoding
return result
def check_attr(self, attr, path):
"""Check file attributes for a path"""
value = None
status, out, _ = self.git.check_attr(attr, '--', path, _readonly=True)
if status == 0:
header = f'{path}: {attr}: '
if out.startswith(header):
value = out[len(header) :].strip()
return value
def get_author(self):
"""Return (name, email) for authoring commits"""
if _use_pwd:
user = pwd.getpwuid(os.getuid()).pw_name
else:
user = os.getenv('USER', 'unknown')
name = self.get('user.name', user)
email = self.get('user.email', f'{user}@{core.node()}')
return (name, email)
def get_guitool_opts(self, name):
"""Return the guitool.<name> namespace as a dict
The dict keys are simplified so that "guitool.$name.cmd" is accessible
as `opts[cmd]`.
"""
prefix = len('guitool.%s.' % name)
guitools = self.find('guitool.%s.*' % name)
return {key[prefix:]: value for (key, value) in guitools.items()}
def get_guitool_names(self):
guitools = self.find('guitool.*.cmd')
prefix = len('guitool.')
suffix = len('.cmd')
return sorted([name[prefix:-suffix] for (name, _) in guitools.items()])
def get_guitool_names_and_shortcuts(self):
"""Return guitool names and their configured shortcut"""
names = self.get_guitool_names()
return [(name, self.get('guitool.%s.shortcut' % name)) for name in names]
def terminal(self):
"""Return a suitable terminal command for running a shell"""
term = self.get('cola.terminal', default=None)
if term:
return term
# find a suitable default terminal
if utils.is_win32():
# Try to find Git's sh.exe directory in
# one of the typical locations
pf = os.environ.get('ProgramFiles', r'C:\Program Files')
pf32 = os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)')
pf64 = os.environ.get('ProgramW6432', r'C:\Program Files')
for p in [pf64, pf32, pf, 'C:\\']:
candidate = os.path.join(p, r'Git\bin\sh.exe')
if os.path.isfile(candidate):
return candidate
return None
# If no terminal has been configured then we'll look for the following programs
# and use the first one we find.
terminals = (
# (<executable>, <command> for running arbitrary commands)
('kitty', 'kitty'),
('alacritty', 'alacritty -e'),
('uxterm', 'uxterm -e'),
('konsole', 'konsole -e'),
('gnome-terminal', 'gnome-terminal --'),
('mate-terminal', 'mate-terminal --'),
('xterm', 'xterm -e'),
)
for executable, command in terminals:
if core.find_executable(executable):
return command
return None
def color(self, key, default):
value = self.get('cola.color.%s' % key, default=default)
struct_layout = core.encode('BBB')
try:
red, green, blue = struct.unpack(struct_layout, unhex(value))
except (struct.error, TypeError):
red, green, blue = struct.unpack(struct_layout, unhex(default))
return (red, green, blue)
def hooks(self):
"""Return the path to the git hooks directory"""
gitdir_hooks = self.git.git_path('hooks')
return self.get('core.hookspath', default=gitdir_hooks)
def hooks_path(self, *paths):
"""Return a path from within the git hooks directory"""
return os.path.join(self.hooks(), *paths)
def _read_config_with_scope(context, cache_paths, renamed_keys):
"""Read the output from "git config --show-scope --show-origin --list
``--show-scope`` was introduced in Git v2.26.0.
"""
unknown_key = 'unknown\t'
system_key = 'system\t'
global_key = 'global\t'
local_key = 'local\t'
worktree_key = 'worktree\t'
command_scope, command_key = _append_tab('command')
command_line = 'command line:'
file_scheme = 'file:'
current_value = ''
current_key = ''
current_scope = ''
current_path = ''
status, config_output, _ = context.git.config(
show_origin=True, show_scope=True, list=True, includes=True
)
if status != 0:
return
for line in config_output.splitlines():
if not line:
continue
if (
line.startswith(system_key)
or line.startswith(global_key)
or line.startswith(local_key)
or line.startswith(command_key)
or line.startswith(worktree_key) # worktree and unknown are uncommon.
or line.startswith(unknown_key)
):
continuation = False
current_scope, current_path, rest = line.split('\t', 2)
if current_scope == command_scope:
continue
current_key, current_value = _config_key_value(rest, '=')
if current_path.startswith(file_scheme):
cache_paths.add(current_path[len(file_scheme) :])
elif current_path == command_line:
continue
renamed_keys[current_key.lower()] = current_key
else:
# Values are allowed to span multiple lines when \n is embedded
# in the value. Detect this and append to the previous value.
continuation = True
if current_value and isinstance(current_value, str):
current_value += '\n'
current_value += line
else:
current_value = line
yield current_scope, current_key, current_value, continuation
def _read_config_with_origin(context, cache_paths, renamed_keys):
"""Read the output from "git config --show-origin --list
``--show-origin`` was introduced in Git v2.8.0.
"""
command_line = 'command line:\t'
system_scope = 'system'
global_scope = 'global'
local_scope = 'local'
file_scheme = 'file:'
system_scope_id = 0
global_scope_id = 1
local_scope_id = 2
current_value = ''
current_key = ''
current_path = ''
current_scope = system_scope
current_scope_id = system_scope_id
status, config_output, _ = context.git.config(
show_origin=True, list=True, includes=True
)
if status != 0:
return
for line in config_output.splitlines():
if not line or line.startswith(command_line):
continue
try:
tab_index = line.index('\t')
except ValueError:
tab_index = 0
if line.startswith(file_scheme) and tab_index > 5:
continuation = False
current_path = line[:tab_index]
rest = line[tab_index + 1 :]
cache_paths.add(current_path)
current_key, current_value = _config_key_value(rest, '=')
renamed_keys[current_key.lower()] = current_key
# The valid state machine transitions are system -> global,
# system -> local and global -> local. We start from the system state.
basename = os.path.basename(current_path)
if current_scope_id == system_scope_id and basename == '.gitconfig':
# system -> global
current_scope_id = global_scope_id
current_scope = global_scope
elif current_scope_id < local_scope_id and basename == 'config':
# system -> local, global -> local
current_scope_id = local_scope_id
current_scope = local_scope
else:
# Values are allowed to span multiple lines when \n is embedded
# in the value. Detect this and append to the previous value.
continuation = True
if current_value and isinstance(current_value, str):
current_value += '\n'
current_value += line
else:
current_value = line
yield current_scope, current_key, current_value, continuation
def _read_config_fallback(context, cache_paths, renamed_keys):
"""Fallback config reader for Git < 2.8.0"""
system_scope = 'system'
global_scope = 'global'
local_scope = 'local'
includes = version.check_git(context, 'config-includes')
current_path = '/etc/gitconfig'
if os.path.exists(current_path):
cache_paths.add(current_path)
status, config_output, _ = context.git.config(
z=True,
list=True,
includes=includes,
system=True,
)
if status == 0:
for key, value in _read_config_from_null_list(config_output):
renamed_keys[key.lower()] = key
yield system_scope, key, value, False
gitconfig_home = core.expanduser(os.path.join('~', '.gitconfig'))
gitconfig_xdg = resources.xdg_config_home('git', 'config')
if os.path.exists(gitconfig_home):
gitconfig = gitconfig_home
elif os.path.exists(gitconfig_xdg):
gitconfig = gitconfig_xdg
else:
gitconfig = None
if gitconfig:
cache_paths.add(gitconfig)
status, config_output, _ = context.git.config(
z=True, list=True, includes=includes, **{'global': True}
)
if status == 0:
for key, value in _read_config_from_null_list(config_output):
renamed_keys[key.lower()] = key
yield global_scope, key, value, False
local_config = context.git.git_path('config')
if local_config and os.path.exists(local_config):
cache_paths.add(gitconfig)
status, config_output, _ = context.git.config(
z=True,
list=True,
includes=includes,
local=True,
)
if status == 0:
for key, value in _read_config_from_null_list(config_output):
renamed_keys[key.lower()] = key
yield local_scope, key, value, False
def _read_config_from_null_list(config_output):
"""Parse the "git config --list -z" records"""
for record in config_output.rstrip('\0').split('\0'):
try:
name, value = record.split('\n', 1)
except ValueError:
name = record
value = 'true'
yield (name, _config_to_python(value))
def python_to_git(value):
if isinstance(value, bool):
return 'true' if value else 'false'
if isinstance(value, int_types):
return ustr(value)
return value
def get_remotes(cfg):
"""Get all of the configured git remotes"""
# Gather all of the remote.*.url entries.
prefix = len('remote.')
suffix = len('.url')
return sorted(key[prefix:-suffix] for key in cfg.find('remote.*.url'))
| 22,649 | Python | .py | 560 | 31.119643 | 87 | 0.595915 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
53 | themes.py | git-cola_git-cola/cola/themes.py | """Themes generators"""
import os
try:
import AppKit
except ImportError:
AppKit = None
from qtpy import QtGui
from .i18n import N_
from .widgets import defs
from . import core
from . import icons
from . import qtutils
from . import resources
from . import utils
class EStylesheet:
DEFAULT = 1
FLAT = 2
CUSTOM = 3 # Files located in ~/.config/git-cola/themes/*.qss
class Theme:
def __init__(
self,
name,
title,
is_dark,
style_sheet=EStylesheet.DEFAULT,
main_color=None,
macos_appearance=None,
):
self.name = name
self.title = title
self.is_dark = is_dark
self.is_palette_dark = None
self.style_sheet = style_sheet
self.main_color = main_color
self.macos_appearance = macos_appearance
self.disabled_text_color = None
self.text_color = None
self.highlight_color = None
self.background_color = None
self.palette = None
def build_style_sheet(self, app_palette):
if self.style_sheet == EStylesheet.CUSTOM:
return self.style_sheet_custom(app_palette)
if self.style_sheet == EStylesheet.FLAT:
return self.style_sheet_flat()
window = app_palette.color(QtGui.QPalette.Window)
self.is_palette_dark = window.lightnessF() < 0.5
return style_sheet_default(app_palette)
def build_palette(self, app_palette):
QPalette = QtGui.QPalette
palette_dark = app_palette.color(QPalette.Base).lightnessF() < 0.5
if self.is_palette_dark is None:
self.is_palette_dark = palette_dark
if palette_dark and self.is_dark:
self.palette = app_palette
return app_palette
if not palette_dark and not self.is_dark:
self.palette = app_palette
return app_palette
if self.is_dark:
background = '#202025'
else:
background = '#edeef3'
bg_color = qtutils.css_color(background)
txt_color = qtutils.css_color('#777777')
palette = QPalette(bg_color)
palette.setColor(QPalette.Base, bg_color)
palette.setColor(QPalette.Disabled, QPalette.Text, txt_color)
self.background_color = background
self.palette = palette
return palette
def style_sheet_flat(self):
main_color = self.main_color
color = qtutils.css_color(main_color)
color_rgb = qtutils.rgb_css(color)
self.is_palette_dark = self.is_dark
if self.is_dark:
background = '#2e2f30'
field = '#383a3c'
grayed = '#06080a'
button_text = '#000000'
field_text = '#d0d0d0'
darker = qtutils.hsl_css(
color.hslHueF(), color.hslSaturationF() * 0.3, color.lightnessF() * 1.3
)
lighter = qtutils.hsl_css(
color.hslHueF(), color.hslSaturationF() * 0.7, color.lightnessF() * 0.6
)
focus = qtutils.hsl_css(
color.hslHueF(), color.hslSaturationF() * 0.7, color.lightnessF() * 0.7
)
else:
background = '#edeef3'
field = '#ffffff'
grayed = '#a2a2b0'
button_text = '#ffffff'
field_text = '#000000'
darker = qtutils.hsl_css(
color.hslHueF(), color.hslSaturationF(), color.lightnessF() * 0.4
)
lighter = qtutils.hsl_css(color.hslHueF(), color.hslSaturationF(), 0.92)
focus = color_rgb
self.disabled_text_color = grayed
self.text_color = field_text
self.highlight_color = lighter
self.background_color = background
return """
/* regular widgets */
* {{
background-color: {background};
color: {field_text};
selection-background-color: {lighter};
alternate-background-color: {field};
selection-color: {field_text};
show-decoration-selected: 1;
spacing: 2px;
}}
/* Focused widths get a thin border */
QTreeView:focus, QListView:focus,
QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus {{
border-width: 1px;
border-style: solid;
border-color: {focus};
}}
QWidget:disabled {{
border-color: {grayed};
color: {grayed};
}}
QDockWidget > QFrame {{
margin: 0px 0px 0px 0px;
}}
QPlainTextEdit, QLineEdit, QTextEdit, QAbstractItemView,
QAbstractSpinBox {{
background-color: {field};
border-color: {grayed};
border-style: solid;
border-width: 1px;
}}
QAbstractItemView::item:selected {{
background-color: {lighter};
}}
QAbstractItemView::item:hover {{
background-color: {lighter};
}}
QLabel {{
color: {darker};
background-color: transparent;
}}
DockTitleBarWidget {{
padding-bottom: 4px;
}}
/* buttons */
QPushButton[flat="false"] {{
background-color: {button};
color: {button_text};
border-radius: 2px;
border-width: 0;
margin-bottom: 1px;
min-width: 55px;
padding: 4px 5px;
}}
QPushButton[flat="true"], QToolButton {{
background-color: transparent;
border-radius: 0px;
}}
QPushButton[flat="true"] {{
margin-bottom: 10px;
}}
QPushButton:hover, QToolButton:hover {{
background-color: {darker};
}}
QPushButton[flat="false"]:pressed, QToolButton:pressed {{
background-color: {darker};
margin: 1px 1px 2px 1px;
}}
QPushButton:disabled {{
background-color: {grayed};
color: {field};
padding-left: 5px;
padding-top: 5px;
}}
QPushButton[flat="true"]:disabled {{
background-color: transparent;
}}
/*menus*/
QMenuBar {{
background-color: {background};
color: {field_text};
border-width: 0;
padding: 1px;
}}
QMenuBar::item {{
background: transparent;
}}
QMenuBar::item:selected {{
background: {button};
}}
QMenuBar::item:pressed {{
background: {button};
}}
QMenu {{
background-color: {field};
}}
QMenu::separator {{
background: {background};
height: 1px;
}}
/* combo box */
QComboBox {{
background-color: {field};
border-color: {grayed};
border-style: solid;
color: {field_text};
border-radius: 0px;
border-width: 1px;
margin-bottom: 1px;
padding: 0 5px;
}}
QComboBox::drop-down {{
border-color: {field_text} {field} {field} {field};
border-style: solid;
subcontrol-position: right;
border-width: 4px 3px 0 3px;
height: 0;
margin-right: 5px;
width: 0;
}}
QComboBox::drop-down:hover {{
border-color: {button} {field} {field} {field};
}}
QComboBox:item {{
background-color: {button};
color: {button_text};
border-width: 0;
height: 22px;
}}
QComboBox:item:selected {{
background-color: {darker};
color: {button_text};
}}
QComboBox:item:checked {{
background-color: {darker};
color: {button_text};
}}
/* MainWindow separator */
QMainWindow::separator {{
width: {separator}px;
height: {separator}px;
}}
QMainWindow::separator:hover {{
background: {focus};
}}
/* scroll bar */
QScrollBar {{
background-color: {field};
border: 0;
}}
QScrollBar::handle {{
background: {background}
}}
QScrollBar::handle:hover {{
background: {button}
}}
QScrollBar:horizontal {{
margin: 0 11px 0 11px;
height: 10px;
}}
QScrollBar:vertical {{
margin: 11px 0 11px 0;
width: 10px;
}}
QScrollBar::add-line, QScrollBar::sub-line {{
background: {background};
subcontrol-origin: margin;
}}
QScrollBar::sub-line:horizontal {{ /*required by a buggy Qt version*/
subcontrol-position: left;
}}
QScrollBar::add-line:hover, QScrollBar::sub-line:hover {{
background: {button};
}}
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {{
width: 10px;
}}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
height: 10px;
}}
QScrollBar:left-arrow, QScrollBar::right-arrow,
QScrollBar::up-arrow, QScrollBar::down-arrow {{
border-style: solid;
height: 0;
width: 0;
}}
QScrollBar:right-arrow {{
border-color: {background} {background}
{background} {darker};
border-width: 3px 0 3px 4px;
}}
QScrollBar:left-arrow {{
border-color: {background} {darker}
{background} {background};
border-width: 3px 4px 3px 0;
}}
QScrollBar:up-arrow {{
border-color: {background} {background}
{darker} {background};
border-width: 0 3px 4px 3px;
}}
QScrollBar:down-arrow {{
border-color: {darker} {background}
{background} {background};
border-width: 4px 3px 0 3px;
}}
QScrollBar:right-arrow:hover {{
border-color: {button} {button}
{button} {darker};
}}
QScrollBar:left-arrow:hover {{
border-color: {button} {darker}
{button} {button};
}}
QScrollBar:up-arrow:hover {{
border-color: {button} {button}
{darker} {button};
}}
QScrollBar:down-arrow:hover {{
border-color: {darker} {button}
{button} {button};
}}
/* tab bar (stacked & docked widgets) */
QTabBar::tab {{
background: transparent;
border-color: {darker};
border-width: 1px;
margin: 1px;
padding: 3px 5px;
}}
QTabBar::tab:selected {{
background: {grayed};
}}
/* check box */
QCheckBox {{
spacing: 8px;
margin: 4px;
background-color: transparent;
}}
QCheckBox::indicator {{
background-color: {field};
border-color: {darker};
border-style: solid;
subcontrol-position: left;
border-width: 1px;
height: 13px;
width: 13px;
}}
QCheckBox::indicator:unchecked:hover {{
background-color: {button};
}}
QCheckBox::indicator:unchecked:pressed {{
background-color: {darker};
}}
QCheckBox::indicator:checked {{
background-color: {darker};
}}
QCheckBox::indicator:checked:hover {{
background-color: {button};
}}
QCheckBox::indicator:checked:pressed {{
background-color: {field};
}}
/* radio checkbox */
QRadioButton {{
spacing: 8px;
margin: 4px;
}}
QRadioButton::indicator {{
height: 0.75em;
width: 0.75em;
}}
/* progress bar */
QProgressBar {{
background-color: {field};
border: 1px solid {darker};
}}
QProgressBar::chunk {{
background-color: {button};
width: 1px;
}}
/* spin box */
QAbstractSpinBox::up-button, QAbstractSpinBox::down-button {{
background-color: transparent;
}}
QAbstractSpinBox::up-arrow, QAbstractSpinBox::down-arrow {{
border-style: solid;
height: 0;
width: 0;
}}
QAbstractSpinBox::up-arrow {{
border-color: {field} {field} {darker} {field};
border-width: 0 3px 4px 3px;
}}
QAbstractSpinBox::up-arrow:hover {{
border-color: {field} {field} {button} {field};
border-width: 0 3px 4px 3px;
}}
QAbstractSpinBox::down-arrow {{
border-color: {darker} {field} {field} {field};
border-width: 4px 3px 0 3px;
}}
QAbstractSpinBox::down-arrow:hover {{
border-color: {button} {field} {field} {field};
border-width: 4px 3px 0 3px;
}}
/* dialogs */
QDialog > QFrame {{
margin: 2px 2px 2px 2px;
}}
/* headers */
QHeaderView {{
color: {field_text};
border-style: solid;
border-width: 0 0 1px 0;
border-color: {grayed};
}}
QHeaderView::section {{
border-style: solid;
border-right: 1px solid {grayed};
background-color: {background};
color: {field_text};
padding-left: 4px;
}}
/* headers */
QHeaderView {{
color: {field_text};
border-style: solid;
border-width: 0 0 1px 0;
border-color: {grayed};
}}
QHeaderView::section {{
border-style: solid;
border-right: 1px solid {grayed};
background-color: {background};
color: {field_text};
padding-left: 4px;
}}
""".format(
background=background,
field=field,
button=color_rgb,
darker=darker,
lighter=lighter,
grayed=grayed,
button_text=button_text,
field_text=field_text,
separator=defs.separator,
focus=focus,
)
def style_sheet_custom(self, app_palette):
"""Get custom style sheet.
File name is saved in variable self.name.
If user has deleted file, use default style"""
# check if path exists
filename = resources.config_home('themes', self.name + '.qss')
if not core.exists(filename):
return style_sheet_default(app_palette)
try:
return core.read(filename)
except OSError as err:
core.print_stderr(f'warning: unable to read custom theme {filename}: {err}')
return style_sheet_default(app_palette)
def get_palette(self):
"""Get a QPalette for the current theme"""
if self.palette is None:
palette = qtutils.current_palette()
else:
palette = self.palette
return palette
def highlight_color_rgb(self):
"""Return an rgb(r,g,b) CSS color value for the selection highlight"""
if self.highlight_color:
highlight_rgb = self.highlight_color
elif self.main_color:
highlight_rgb = qtutils.rgb_css(
qtutils.css_color(self.main_color).lighter()
)
else:
palette = self.get_palette()
color = palette.color(QtGui.QPalette.Highlight)
highlight_rgb = qtutils.rgb_css(color)
return highlight_rgb
def selection_color(self):
"""Return a color suitable for selections"""
highlight = qtutils.css_color(self.highlight_color_rgb())
if highlight.lightnessF() > 0.7: # Avoid clamping light colors to white.
color = highlight
else:
color = highlight.lighter()
return color
def text_colors_rgb(self):
"""Return a pair of rgb(r,g,b) CSS color values for text and selected text"""
if self.text_color:
text_rgb = self.text_color
highlight_text_rgb = self.text_color
else:
palette = self.get_palette()
color = palette.text().color()
text_rgb = qtutils.rgb_css(color)
color = palette.highlightedText().color()
highlight_text_rgb = qtutils.rgb_css(color)
return text_rgb, highlight_text_rgb
def disabled_text_color_rgb(self):
"""Return an rgb(r,g,b) CSS color value for the disabled text"""
if self.disabled_text_color:
disabled_text_rgb = self.disabled_text_color
else:
palette = self.get_palette()
color = palette.color(QtGui.QPalette.Disabled, QtGui.QPalette.Text)
disabled_text_rgb = qtutils.rgb_css(color)
return disabled_text_rgb
def background_color_rgb(self):
"""Return an rgb(r,g,b) CSS color value for the window background"""
if self.background_color:
background_color = self.background_color
else:
palette = self.get_palette()
window = palette.color(QtGui.QPalette.Base)
background_color = qtutils.rgb_css(window)
return background_color
def style_sheet_default(palette):
highlight = palette.color(QtGui.QPalette.Highlight)
shadow = palette.color(QtGui.QPalette.Shadow)
base = palette.color(QtGui.QPalette.Base)
highlight_rgb = qtutils.rgb_css(highlight)
shadow_rgb = qtutils.rgb_css(shadow)
base_rgb = qtutils.rgb_css(base)
return """
QCheckBox::indicator {{
width: {checkbox_size}px;
height: {checkbox_size}px;
}}
QCheckBox::indicator::unchecked {{
border: {checkbox_border}px solid {shadow_rgb};
background: {base_rgb};
}}
QCheckBox::indicator::checked {{
image: url({checkbox_icon});
border: {checkbox_border}px solid {shadow_rgb};
background: {base_rgb};
}}
QRadioButton::indicator {{
width: {radio_size}px;
height: {radio_size}px;
}}
QRadioButton::indicator::unchecked {{
border: {radio_border}px solid {shadow_rgb};
border-radius: {radio_radius}px;
background: {base_rgb};
}}
QRadioButton::indicator::checked {{
image: url({radio_icon});
border: {radio_border}px solid {shadow_rgb};
border-radius: {radio_radius}px;
background: {base_rgb};
}}
QSplitter::handle:hover {{
background: {highlight_rgb};
}}
QMainWindow::separator {{
background: none;
width: {separator}px;
height: {separator}px;
}}
QMainWindow::separator:hover {{
background: {highlight_rgb};
}}
""".format(
separator=defs.separator,
highlight_rgb=highlight_rgb,
shadow_rgb=shadow_rgb,
base_rgb=base_rgb,
checkbox_border=defs.border,
checkbox_icon=icons.check_name(),
checkbox_size=defs.checkbox,
radio_border=defs.radio_border,
radio_icon=icons.dot_name(),
radio_radius=defs.radio // 2,
radio_size=defs.radio,
)
def get_all_themes():
themes = [
Theme(
'default',
N_('Default'),
False,
style_sheet=EStylesheet.DEFAULT,
main_color=None,
),
]
if utils.is_darwin():
themes.extend(get_macos_themes().values())
themes.extend([
Theme(
'flat-light-blue',
N_('Flat light blue'),
False,
style_sheet=EStylesheet.FLAT,
main_color='#5271cc',
),
Theme(
'flat-light-red',
N_('Flat light red'),
False,
style_sheet=EStylesheet.FLAT,
main_color='#cc5452',
),
Theme(
'flat-light-grey',
N_('Flat light grey'),
False,
style_sheet=EStylesheet.FLAT,
main_color='#707478',
),
Theme(
'flat-light-green',
N_('Flat light green'),
False,
style_sheet=EStylesheet.FLAT,
main_color='#42a65c',
),
Theme(
'flat-dark-blue',
N_('Flat dark blue'),
True,
style_sheet=EStylesheet.FLAT,
main_color='#5271cc',
),
Theme(
'flat-dark-red',
N_('Flat dark red'),
True,
style_sheet=EStylesheet.FLAT,
main_color='#cc5452',
),
Theme(
'flat-dark-grey',
N_('Flat dark grey'),
True,
style_sheet=EStylesheet.FLAT,
main_color='#aaaaaa',
),
Theme(
'flat-dark-green',
N_('Flat dark green'),
True,
style_sheet=EStylesheet.FLAT,
main_color='#42a65c',
),
])
# check if themes path exists in user folder
path = resources.config_home('themes')
if not os.path.isdir(path):
return themes
# Gather Qt .qss stylesheet themes
try:
filenames = core.listdir(path)
except OSError:
return themes
for filename in filenames:
name, ext = os.path.splitext(filename)
if ext == '.qss':
themes.append(Theme(name, N_(name), False, EStylesheet.CUSTOM, None))
return themes
def apply_platform_theme(theme):
"""Apply platform-specific themes (e.g. dark mode on macOS)"""
# https://developer.apple.com/documentation/appkit/nsappearancecustomization/choosing_a_specific_appearance_for_your_macos_app
# https://github.com/git-cola/git-cola/issues/905#issuecomment-461118465
if utils.is_darwin():
if AppKit is None:
return
app = AppKit.NSApplication.sharedApplication()
macos_themes = get_macos_themes()
try:
macos_appearance = macos_themes[theme].macos_appearance
except KeyError:
return
if macos_appearance is None:
return
appearance = AppKit.NSAppearance.appearanceNamed_(macos_appearance)
app.setAppearance_(appearance)
def get_macos_themes():
"""Get a mapping from theme names to macOS NSAppearanceName values"""
themes = {}
if AppKit is None:
return themes
def add_macos_theme(name, description, is_dark, attr):
"""Add an AppKit theme if it exists"""
if hasattr(AppKit, attr):
themes[name] = Theme(
name, description, is_dark, macos_appearance=getattr(AppKit, attr)
)
add_macos_theme(
'macos-aqua-light', N_('MacOS Aqua light'), False, 'NSAppearanceNameAqua'
)
add_macos_theme(
'macos-aqua-dark',
N_('MacOS Aqua dark'),
True,
'NSAppearanceNameDarkAqua',
)
add_macos_theme(
'macos-vibrant-light',
N_('MacOS Vibrant light'),
False,
'NSAppearanceNameVibrantLight',
)
add_macos_theme(
'macos-vibrant-dark',
N_('MacOS Vibrant dark'),
True,
'NSAppearanceNameVibrantDark',
)
return themes
def options(themes=None):
"""Return a dictionary mapping display names to theme names"""
if themes is None:
themes = get_all_themes()
return [(theme.title, theme.name) for theme in themes]
def find_theme(name):
themes = get_all_themes()
for item in themes:
if item.name == name:
return item
return themes[0]
| 25,581 | Python | .py | 733 | 22.566166 | 130 | 0.510572 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
54 | diffparse.py | git-cola_git-cola/cola/diffparse.py | import math
import re
from collections import Counter
from itertools import groupby
from . import compat
DIFF_CONTEXT = ' '
DIFF_ADDITION = '+'
DIFF_DELETION = '-'
DIFF_NO_NEWLINE = '\\'
def parse_range_str(range_str):
if ',' in range_str:
begin, end = range_str.split(',', 1)
return int(begin), int(end)
return int(range_str), 1
def _format_range(start, count):
if count == 1:
return str(start)
return '%d,%d' % (start, count)
def _format_hunk_header(old_start, old_count, new_start, new_count, heading=''):
return '@@ -{} +{} @@{}\n'.format(
_format_range(old_start, old_count),
_format_range(new_start, new_count),
heading,
)
def digits(number):
"""Return the number of digits needed to display a number"""
if number >= 0:
result = int(math.log10(number)) + 1
else:
result = 1
return result
class LineCounter:
"""Keep track of a diff range's values"""
def __init__(self, value=0, max_value=-1):
self.value = value
self.max_value = max_value
self._initial_max_value = max_value
def reset(self):
"""Reset the max counter and return self for convenience"""
self.max_value = self._initial_max_value
return self
def parse(self, range_str):
"""Parse a diff range and setup internal state"""
start, count = parse_range_str(range_str)
self.value = start
self.max_value = max(start + count - 1, self.max_value)
def tick(self, amount=1):
"""Return the current value and increment to the next"""
value = self.value
self.value += amount
return value
class DiffLines:
"""Parse diffs and gather line numbers"""
EMPTY = -1
DASH = -2
def __init__(self):
self.merge = False
# diff <old> <new>
# merge <ours> <theirs> <new>
self.old = LineCounter()
self.new = LineCounter()
self.ours = LineCounter()
self.theirs = LineCounter()
def digits(self):
return digits(
max(
self.old.max_value,
self.new.max_value,
self.ours.max_value,
self.theirs.max_value,
)
)
def parse(self, diff_text):
lines = []
diff_state = 1
state = initial_state = 0
merge = self.merge = False
no_newline = r'\ No newline at end of file'
old = self.old.reset()
new = self.new.reset()
ours = self.ours.reset()
theirs = self.theirs.reset()
for text in diff_text.split('\n'):
if text.startswith('@@ -'):
parts = text.split(' ', 4)
if parts[0] == '@@' and parts[3] == '@@':
state = diff_state
old.parse(parts[1][1:])
new.parse(parts[2][1:])
lines.append((self.DASH, self.DASH))
continue
if text.startswith('@@@ -'):
self.merge = merge = True
parts = text.split(' ', 5)
if parts[0] == '@@@' and parts[4] == '@@@':
state = diff_state
ours.parse(parts[1][1:])
theirs.parse(parts[2][1:])
new.parse(parts[3][1:])
lines.append((self.DASH, self.DASH, self.DASH))
continue
if state == initial_state or text.rstrip() == no_newline:
if merge:
lines.append((self.EMPTY, self.EMPTY, self.EMPTY))
else:
lines.append((self.EMPTY, self.EMPTY))
elif not merge and text.startswith('-'):
lines.append((old.tick(), self.EMPTY))
elif merge and text.startswith('- '):
lines.append((ours.tick(), self.EMPTY, self.EMPTY))
elif merge and text.startswith(' -'):
lines.append((self.EMPTY, theirs.tick(), self.EMPTY))
elif merge and text.startswith('--'):
lines.append((ours.tick(), theirs.tick(), self.EMPTY))
elif not merge and text.startswith('+'):
lines.append((self.EMPTY, new.tick()))
elif merge and text.startswith('++'):
lines.append((self.EMPTY, self.EMPTY, new.tick()))
elif merge and text.startswith('+ '):
lines.append((self.EMPTY, theirs.tick(), new.tick()))
elif merge and text.startswith(' +'):
lines.append((ours.tick(), self.EMPTY, new.tick()))
elif not merge and text.startswith(' '):
lines.append((old.tick(), new.tick()))
elif merge and text.startswith(' '):
lines.append((ours.tick(), theirs.tick(), new.tick()))
elif not text:
new.tick()
old.tick()
ours.tick()
theirs.tick()
else:
state = initial_state
if merge:
lines.append((self.EMPTY, self.EMPTY, self.EMPTY))
else:
lines.append((self.EMPTY, self.EMPTY))
return lines
class FormatDigits:
"""Format numbers for use in diff line numbers"""
DASH = DiffLines.DASH
EMPTY = DiffLines.EMPTY
def __init__(self, dash='', empty=''):
self.fmt = ''
self.empty = ''
self.dash = ''
self._dash = dash or compat.uchr(0xB7)
self._empty = empty or ' '
def set_digits(self, value):
self.fmt = '%%0%dd' % value
self.empty = self._empty * value
self.dash = self._dash * value
def value(self, old, new):
old_str = self._format(old)
new_str = self._format(new)
return f'{old_str} {new_str}'
def merge_value(self, old, base, new):
old_str = self._format(old)
base_str = self._format(base)
new_str = self._format(new)
return f'{old_str} {base_str} {new_str}'
def number(self, value):
return self.fmt % value
def _format(self, value):
if value == self.DASH:
result = self.dash
elif value == self.EMPTY:
result = self.empty
else:
result = self.number(value)
return result
class _HunkGrouper:
_HUNK_HEADER_RE = re.compile(r'^@@ -([0-9,]+) \+([0-9,]+) @@(.*)')
def __init__(self):
self.match = None
def __call__(self, line):
match = self._HUNK_HEADER_RE.match(line)
if match is not None:
self.match = match
return self.match
class _DiffHunk:
def __init__(self, old_start, start_offset, heading, content_lines):
type_counts = Counter(line[:1] for line in content_lines)
self.old_count = type_counts[DIFF_CONTEXT] + type_counts[DIFF_DELETION]
self.new_count = type_counts[DIFF_CONTEXT] + type_counts[DIFF_ADDITION]
if self.old_count == 0:
self.old_start = 0
else:
self.old_start = old_start
if self.new_count == 0:
self.new_start = 0
elif self.old_start == 0:
self.new_start = 1
else:
self.new_start = self.old_start + start_offset
self.heading = heading
self.lines = [
_format_hunk_header(
self.old_start,
self.old_count,
self.new_start,
self.new_count,
heading,
),
*content_lines,
]
self.content_lines = content_lines
self.changes = type_counts[DIFF_DELETION] + type_counts[DIFF_ADDITION]
def has_changes(self):
return bool(self.changes)
def line_delta(self):
return self.new_count - self.old_count
class Patch:
"""Parse and rewrite diffs to produce edited patches
This parser is used for modifying the worktree and index by constructing
temporary patches that are applied using "git apply".
"""
def __init__(self, filename, hunks, header_line_count=0):
self.filename = filename
self.hunks = hunks
self.header_line_count = header_line_count
@classmethod
def parse(cls, filename, diff_text):
header_line_count = 0
hunks = []
start_offset = 0
for match, hunk_lines in groupby(diff_text.split('\n'), _HunkGrouper()):
if match is not None:
# Skip the hunk range header line as it will be regenerated by the
# _DiffHunk.
next(hunk_lines)
hunk = _DiffHunk(
old_start=parse_range_str(match.group(1))[0],
start_offset=start_offset,
heading=match.group(3),
content_lines=[line + '\n' for line in hunk_lines if line],
)
if hunk.has_changes():
hunks.append(hunk)
start_offset += hunk.line_delta()
else:
header_line_count = len(list(hunk_lines))
return cls(filename, hunks, header_line_count)
def has_changes(self):
return bool(self.hunks)
def as_text(self, *, file_headers=True):
lines = []
if self.hunks:
if file_headers:
lines.append('--- a/%s\n' % self.filename)
lines.append('+++ b/%s\n' % self.filename)
for hunk in self.hunks:
lines.extend(hunk.lines)
return ''.join(lines)
def _hunk_iter(self):
hunk_last_line_idx = self.header_line_count - 1
for hunk in self.hunks:
hunk_first_line_idx = hunk_last_line_idx + 1
hunk_last_line_idx += len(hunk.lines)
yield hunk_first_line_idx, hunk_last_line_idx, hunk
@staticmethod
def _reverse_content_lines(content_lines):
# Normally in a diff, deletions come before additions. In order to preserve
# this property in reverse patches, when this function encounters a deletion
# line and switches it to addition, it appends the line to the pending_additions
# list, while additions that get switched to deletions are appended directly to
# the content_lines list. Each time a context line is encountered, any pending
# additions are then appended to the content_lines list immediately before the
# context line and the pending_additions list is cleared.
new_content_lines = []
pending_additions = []
line_type = None
for line in content_lines:
prev_line_type = line_type
line_type = line[:1]
if line_type == DIFF_ADDITION:
new_content_lines.append(DIFF_DELETION + line[1:])
elif line_type == DIFF_DELETION:
pending_additions.append(DIFF_ADDITION + line[1:])
elif line_type == DIFF_NO_NEWLINE:
if prev_line_type == DIFF_DELETION:
# Previous line was a deletion that was switched to an
# addition, so the "No newline" line goes with it.
pending_additions.append(line)
else:
new_content_lines.append(line)
else:
new_content_lines.extend(pending_additions)
new_content_lines.append(line)
pending_additions = []
new_content_lines.extend(pending_additions)
return new_content_lines
def extract_subset(self, first_line_idx, last_line_idx, *, reverse=False):
new_hunks = []
start_offset = 0
for hunk_first_line_idx, hunk_last_line_idx, hunk in self._hunk_iter():
# Skip hunks until reaching the one that contains the first selected line.
if hunk_last_line_idx < first_line_idx:
continue
# Stop once the hunk that contains the last selected line has been
# processed.
if hunk_first_line_idx > last_line_idx:
break
content_lines = []
prev_skipped = False
for hunk_line_idx, line in enumerate(
hunk.content_lines, start=hunk_first_line_idx + 1
):
line_type = line[:1]
if not first_line_idx <= hunk_line_idx <= last_line_idx:
if line_type == DIFF_ADDITION:
if reverse:
# Change unselected additions to context for reverse diffs.
line = DIFF_CONTEXT + line[1:]
else:
# Skip unselected additions for normal diffs.
prev_skipped = True
continue
elif line_type == DIFF_DELETION:
if not reverse:
# Change unselected deletions to context for normal diffs.
line = DIFF_CONTEXT + line[1:]
else:
# Skip unselected deletions for reverse diffs.
prev_skipped = True
continue
if line_type == DIFF_NO_NEWLINE and prev_skipped:
# If the line immediately before a "No newline" line was skipped
# (e.g. because it was an unselected addition) skip the "No
# newline" line as well
continue
content_lines.append(line)
if reverse:
old_start = hunk.new_start
content_lines = self._reverse_content_lines(content_lines)
else:
old_start = hunk.old_start
new_hunk = _DiffHunk(
old_start=old_start,
start_offset=start_offset,
heading=hunk.heading,
content_lines=content_lines,
)
if new_hunk.has_changes():
new_hunks.append(new_hunk)
start_offset += new_hunk.line_delta()
return Patch(self.filename, new_hunks)
def extract_hunk(self, line_idx, *, reverse=False):
"""Return a new patch containing only the hunk containing the specified line"""
new_hunks = []
for _, hunk_last_line_idx, hunk in self._hunk_iter():
if line_idx <= hunk_last_line_idx:
if reverse:
old_start = hunk.new_start
content_lines = self._reverse_content_lines(hunk.content_lines)
else:
old_start = hunk.old_start
content_lines = hunk.content_lines
new_hunks = [
_DiffHunk(
old_start=old_start,
start_offset=0,
heading=hunk.heading,
content_lines=content_lines,
)
]
break
return Patch(self.filename, new_hunks)
| 15,170 | Python | .py | 368 | 28.733696 | 88 | 0.532917 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
55 | compat.py | git-cola_git-cola/cola/compat.py | import os
import sys
try:
import urllib2 as parse # noqa
except ImportError:
# Python 3
from urllib import parse # noqa
PY_VERSION = sys.version_info[:2] # (2, 7)
PY_VERSION_MAJOR = PY_VERSION[0]
PY2 = PY_VERSION_MAJOR == 2
PY3 = PY_VERSION_MAJOR >= 3
PY26_PLUS = PY2 and sys.version_info[1] >= 6
WIN32 = sys.platform in {'win32', 'cygwin'}
ENCODING = 'utf-8'
if PY3:
def bstr(value, encoding=ENCODING):
return bytes(value, encoding=encoding)
elif PY26_PLUS:
bstr = bytes
else:
# Python <= 2.5
bstr = str
if PY3:
def bchr(i):
return bytes([i])
int_types = (int,)
maxsize = sys.maxsize
ustr = str
uchr = chr
else:
bchr = chr
maxsize = 2**31
ustr = unicode # noqa
uchr = unichr # noqa
int_types = (int, long) # noqa
# The max 32-bit signed integer range for Qt is (-2147483648 to 2147483647)
maxint = (2**31) - 1
def setenv(key, value):
"""Compatibility wrapper for setting environment variables
Windows requires putenv(). Unix only requires os.environ.
"""
if not PY3 and isinstance(value, ustr):
value = value.encode(ENCODING, 'replace')
os.environ[key] = value
os.putenv(key, value)
def unsetenv(key):
"""Compatibility wrapper for clearing environment variables"""
os.environ.pop(key, None)
if hasattr(os, 'unsetenv'):
os.unsetenv(key)
def no_op(value):
"""Return the value as-is"""
return value
def byte_offset_to_int_converter():
"""Return a function to convert byte string offsets into integers
Indexing into python3 bytes returns integers. Python2 returns str.
Thus, on Python2 we need to use `ord()` to convert the byte into
an integer. It's already an int on Python3, so we use no_op there.
"""
if PY2:
result = ord
else:
result = no_op
return result
| 1,879 | Python | .py | 64 | 25.015625 | 75 | 0.666481 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
56 | inotify.py | git-cola_git-cola/cola/inotify.py | import ctypes
import ctypes.util
import errno
import os
# constant from Linux include/uapi/linux/limits.h
NAME_MAX = 255
# constants from Linux include/uapi/linux/inotify.h
IN_MODIFY = 0x00000002
IN_ATTRIB = 0x00000004
IN_CLOSE_WRITE = 0x00000008
IN_MOVED_FROM = 0x00000040
IN_MOVED_TO = 0x00000080
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
IN_Q_OVERFLOW = 0x00004000
IN_ONLYDIR = 0x01000000
IN_EXCL_UNLINK = 0x04000000
IN_ISDIR = 0x80000000
class inotify_event(ctypes.Structure):
_fields_ = [
('wd', ctypes.c_int),
('mask', ctypes.c_uint32),
('cookie', ctypes.c_uint32),
('len', ctypes.c_uint32),
]
MAX_EVENT_SIZE = ctypes.sizeof(inotify_event) + NAME_MAX + 1
def _errcheck(result, func, arguments):
if result >= 0:
return result
err = ctypes.get_errno()
if err == errno.EINTR:
return func(*arguments)
raise OSError(err, os.strerror(err))
try:
_libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
_read = _libc.read
init = _libc.inotify_init
add_watch = _libc.inotify_add_watch
rm_watch = _libc.inotify_rm_watch
except AttributeError:
raise ImportError('Could not load inotify functions from libc')
_read.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t]
_read.errcheck = _errcheck
init.argtypes = []
init.errcheck = _errcheck
add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
add_watch.errcheck = _errcheck
rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
rm_watch.errcheck = _errcheck
def read_events(inotify_fd, count=64):
buf = ctypes.create_string_buffer(MAX_EVENT_SIZE * count)
num = _read(inotify_fd, buf, ctypes.sizeof(buf))
addr = ctypes.addressof(buf)
while num:
assert num >= ctypes.sizeof(inotify_event)
event = inotify_event.from_address(addr)
addr += ctypes.sizeof(inotify_event)
num -= ctypes.sizeof(inotify_event)
if event.len:
assert num >= event.len
name = ctypes.string_at(addr)
addr += event.len
num -= event.len
else:
name = None
yield event.wd, event.mask, event.cookie, name
| 2,195 | Python | .py | 66 | 28.5 | 70 | 0.683736 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
57 | editpatch.py | git-cola_git-cola/cola/editpatch.py | import textwrap
from . import core
from . import diffparse
from . import utils
from .i18n import N_
from .interaction import Interaction
from .models import prefs
def wrap_comment(context, text):
indent = prefs.comment_char(context) + ' '
return (
textwrap.fill(
text,
width=80,
initial_indent=indent,
subsequent_indent=indent,
)
+ '\n'
)
def strip_comments(context, text):
comment_char = prefs.comment_char(context)
return '\n'.join(
line for line in text.split('\n') if not line.startswith(comment_char)
)
def patch_edit_header(context, *, reverse, apply_to_worktree):
if apply_to_worktree:
header = N_(
'Edit the following patch, which will then be applied to the worktree to'
' revert the changes:'
)
else:
if reverse:
header = N_(
'Edit the following patch, which will then be applied to the staging'
' area to unstage the changes:'
)
else:
header = N_(
'Edit the following patch, which will then be applied to the staging'
' area to stage the changes:'
)
return wrap_comment(context, header)
def patch_edit_footer(context):
parts = [
'---',
N_(
"To avoid applying removal lines ('-'), change them to context lines (' ')."
),
N_("To avoid applying addition lines ('+'), delete them."),
N_('To abort applying this patch, remove all lines.'),
N_("Lines starting with '%s' will be ignored.") % prefs.comment_char(context),
N_(
'It is not necessary to update the hunk header lines as they will be'
' regenerated automatically.'
),
]
return ''.join(wrap_comment(context, part) for part in parts)
def edit_patch(patch, encoding, context, *, reverse, apply_to_worktree):
patch_file_path = utils.tmp_filename('edit', '.patch')
try:
content_parts = [
patch_edit_header(
context, reverse=reverse, apply_to_worktree=apply_to_worktree
),
patch.as_text(file_headers=False),
patch_edit_footer(context),
]
core.write(patch_file_path, ''.join(content_parts), encoding=encoding)
status, _, _ = core.run_command(
[*utils.shell_split(prefs.editor(context)), patch_file_path]
)
if status == 0:
patch_text = strip_comments(
context, core.read(patch_file_path, encoding=encoding)
)
else:
Interaction.log(
N_('Editor returned %s exit code. Not applying patch.') % status
)
patch_text = ''
return diffparse.Patch.parse(patch.filename, patch_text)
finally:
core.unlink(patch_file_path)
| 2,926 | Python | .py | 82 | 26.646341 | 88 | 0.581363 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
58 | textwrap.py | git-cola_git-cola/cola/textwrap.py | """Text wrapping and filling"""
import re
from .compat import ustr
# Copyright (C) 1999-2001 Gregory P. Ward.
# Copyright (C) 2002, 2003 Python Software Foundation.
# Copyright (C) 2013-2024 David Aguilar
# Written by Greg Ward <[email protected]>
# Simplified for git-cola by David Aguilar <[email protected]>
class TextWrapper:
"""
Object for wrapping/filling text. The public interface consists of
the wrap() and fill() methods; the other methods are just there for
subclasses to override in order to tweak the default behaviour.
If you want to completely replace the main wrapping algorithm,
you'll probably have to override _wrap_chunks().
Several instance attributes control various aspects of wrapping:
width (default: 70)
The preferred width of wrapped lines.
tabwidth (default: 8)
The width of a tab used when calculating line length.
break_on_hyphens (default: false)
Allow breaking hyphenated words. If true, wrapping will occur
preferably on whitespace and right after the hyphenated part of
compound words.
drop_whitespace (default: true)
Drop leading and trailing whitespace from lines.
"""
# This funky little regex is just the trick for splitting
# text up into word-wrappable chunks. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
# (after stripping out empty strings).
wordsep_re = re.compile(
r'(\s+|' # any whitespace
r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words
r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))'
) # em-dash
# This less funky little regex just split on recognized spaces. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
wordsep_simple_re = re.compile(r'(\s+)')
def __init__(
self, width=70, tabwidth=8, break_on_hyphens=False, drop_whitespace=True
):
self.width = width
self.tabwidth = tabwidth
self.break_on_hyphens = break_on_hyphens
self.drop_whitespace = drop_whitespace
# recompile the regexes for Unicode mode -- done in this clumsy way for
# backwards compatibility because it's rather common to monkey-patch
# the TextWrapper class' wordsep_re attribute.
self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U)
self.wordsep_simple_re_uni = re.compile(self.wordsep_simple_re.pattern, re.U)
def _split(self, text):
"""_split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the following chunks:
'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', 'option!'
if break_on_hyphens is True, or in:
'Look,', ' ', 'goof-ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', option!'
otherwise.
"""
if isinstance(text, ustr):
if self.break_on_hyphens:
pat = self.wordsep_re_uni
else:
pat = self.wordsep_simple_re_uni
else:
if self.break_on_hyphens:
pat = self.wordsep_re
else:
pat = self.wordsep_simple_re
chunks = pat.split(text)
chunks = list(filter(None, chunks)) # remove empty chunks
return chunks
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of length
'self.width' or less. Some lines may be longer than this. Chunks
correspond roughly to words and the whitespace between them: each
chunk is indivisible, but a line break can come between any two
chunks. Chunks should not have internal whitespace; i.e. a chunk is
either all whitespace or a "word". Whitespace chunks will be removed
from the beginning and end of lines, but apart from that whitespace is
preserved.
"""
lines = []
# Arrange in reverse order so items can be efficiently popped
# from a stack of chucks.
chunks = list(reversed(chunks))
while chunks:
# Start the list of chunks that will make up the current line.
# cur_len is just the length of all the chunks in cur_line.
cur_line = []
cur_len = 0
# Maximum width for this line.
width = self.width
# First chunk on line is a space -- drop it, unless this
# is the very beginning of the text (i.e. no lines started yet).
if self.drop_whitespace and is_blank(chunks[-1]) and lines:
chunks.pop()
linebreak = False
while chunks:
length = self.chunklen(chunks[-1])
# Can at least squeeze this chunk onto the current line.
if cur_len + length <= width:
cur_line.append(chunks.pop())
cur_len += length
# Nope, this line is full.
else:
linebreak = True
break
# The current line is full, and the next chunk is too big to
# fit on *any* line (not just this one).
if chunks and self.chunklen(chunks[-1]) > width:
if not cur_line:
cur_line.append(chunks.pop())
# Avoid whitespace at the beginning of split lines
if (
linebreak
and self.drop_whitespace
and cur_line
and is_blank(cur_line[0])
):
cur_line.pop(0)
# If the last chunk on this line is all a space, drop it.
if self.drop_whitespace and cur_line and is_blank(cur_line[-1]):
cur_line.pop()
# Convert current line back to a string and store it in list
# of all lines (return value).
if cur_line:
lines.append(''.join(cur_line))
return lines
def chunklen(self, word):
"""Return length of a word taking tabs into account
>>> w = TextWrapper(tabwidth=8)
>>> w.chunklen("\\t\\t\\t\\tX")
33
"""
return len(word.replace('\t', '')) + word.count('\t') * self.tabwidth
# -- Public interface ----------------------------------------------
def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
converted to space.
"""
chunks = self._split(text)
return self._wrap_chunks(chunks)
def fill(self, text):
"""fill(text : string) -> string
Reformat the single paragraph in 'text' to fit in lines of no
more than 'self.width' columns, and return a new string
containing the entire wrapped paragraph.
"""
return '\n'.join(self.wrap(text))
def word_wrap(text, tabwidth, limit, break_on_hyphens=False):
"""Wrap long lines to the specified limit"""
lines = []
# Acked-by:, Signed-off-by:, Helped-by:, etc.
special_tag_rgx = re.compile(
r'^('
r'(('
r'Acked-by|'
r"Ack'd-by|"
r'Based-on-patch-by|'
r'Cheered-on-by|'
r'Co-authored-by|'
r'Comments-by|'
r'Confirmed-by|'
r'Contributions-by|'
r'Debugged-by|'
r'Discovered-by|'
r'Explained-by|'
r'Backtraced-by|'
r'Helped-by|'
r'Liked-by|'
r'Link|'
r'Improved-by|'
r'Inspired-by|'
r'Initial-patch-by|'
r'Noticed-by|'
r'Original-patch-by|'
r'Originally-by|'
r'Mentored-by|'
r'Patch-by|'
r'Proposed-by|'
r'References|'
r'Related-to|'
r'Reported-by|'
r'Requested-by|'
r'Reviewed-by|'
r'See-also|'
r'Signed-off-by|'
r'Signed-Off-by|'
r'Spotted-by|'
r'Suggested-by|'
r'Tested-by|'
r'Tested-on-([a-zA-Z-_]+)-by|'
r'With-suggestions-by'
r'):)'
r'|([Cc]\.\s*[Ff]\.\s+)'
r')'
)
wrapper = TextWrapper(
width=limit,
tabwidth=tabwidth,
break_on_hyphens=break_on_hyphens,
drop_whitespace=True,
)
for line in text.split('\n'):
if special_tag_rgx.match(line):
lines.append(line)
else:
lines.append(wrapper.fill(line))
return '\n'.join(lines)
def is_blank(string):
return string and not string.strip(' ')
| 9,212 | Python | .py | 227 | 31.07489 | 85 | 0.572451 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
59 | gravatar.py | git-cola_git-cola/cola/gravatar.py | import time
import hashlib
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy import QtNetwork
from . import core
from . import icons
from . import qtutils
from .compat import parse
from .models import prefs
from .widgets import defs
class Gravatar:
@staticmethod
def url_for_email(email, imgsize):
email_hash = md5_hexdigest(email)
# Python2.6 requires byte strings for urllib2.quote() so we have
# to force
default_url = 'https://git-cola.github.io/images/git-64x64.jpg'
encoded_url = parse.quote(core.encode(default_url), core.encode(''))
query = '?s=%d&d=%s' % (imgsize, core.decode(encoded_url))
url = 'https://gravatar.com/avatar/' + email_hash + query
return url
def md5_hexdigest(value):
"""Return the md5 hexdigest for a value.
Used for implementing the gravatar API. Not used for security purposes.
"""
# https://github.com/git-cola/git-cola/issues/1157
# ValueError: error:060800A3:
# digital envelope routines: EVP_DigestInit_ex: disabled for fips
#
# Newer versions of Python, including Centos8's patched Python3.6 and
# mainline Python 3.9+ have a "usedoforsecurity" parameter which allows us
# to continue using hashlib.md5().
encoded_value = core.encode(value)
result = ''
try:
# This could raise ValueError in theory but we always use encoded bytes
# so that does not happen in practice.
result = hashlib.md5(encoded_value, usedforsecurity=False).hexdigest()
except TypeError:
# Fallback to trying hashlib.md5 directly.
result = hashlib.md5(encoded_value).hexdigest()
return core.decode(result)
class GravatarLabel(QtWidgets.QLabel):
def __init__(self, context, parent=None):
QtWidgets.QLabel.__init__(self, parent)
self.context = context
self.email = None
self.response = None
self.timeout = 0
self.imgsize = defs.medium_icon
self.pixmaps = {}
self._default_pixmap_bytes = None
self.network = QtNetwork.QNetworkAccessManager()
self.network.finished.connect(self.network_finished)
def set_email(self, email):
"""Update the author icon based on the specified email"""
pixmap = self.pixmaps.get(email, None)
if pixmap is not None:
self.setPixmap(pixmap)
return
if self.timeout > 0 and (int(time.time()) - self.timeout) < (5 * 60):
self.set_pixmap_from_response()
return
if email == self.email and self.response is not None:
self.set_pixmap_from_response()
return
self.email = email
self.request(email)
def request(self, email):
if prefs.enable_gravatar(self.context):
url = Gravatar.url_for_email(email, self.imgsize)
self.network.get(QtNetwork.QNetworkRequest(QtCore.QUrl(url)))
else:
self.pixmaps[email] = self.set_pixmap_from_response()
def default_pixmap_as_bytes(self):
if self._default_pixmap_bytes is None:
xres = self.imgsize
pixmap = icons.cola().pixmap(xres)
byte_array = QtCore.QByteArray()
buf = QtCore.QBuffer(byte_array)
buf.open(QtCore.QIODevice.WriteOnly)
pixmap.save(buf, 'PNG')
buf.close()
self._default_pixmap_bytes = byte_array
else:
byte_array = self._default_pixmap_bytes
return byte_array
def network_finished(self, reply):
email = self.email
header = QtCore.QByteArray(b'Location')
location = core.decode(bytes(reply.rawHeader(header))).strip()
if location:
request_location = Gravatar.url_for_email(self.email, self.imgsize)
relocated = location != request_location
else:
relocated = False
no_error = qtutils.enum_value(QtNetwork.QNetworkReply.NetworkError.NoError)
reply_error = qtutils.enum_value(reply.error())
if reply_error == no_error:
if relocated:
# We could do get_url(parse.unquote(location)) to
# download the default image.
# Save bandwidth by using a pixmap.
self.response = self.default_pixmap_as_bytes()
else:
self.response = reply.readAll()
self.timeout = 0
else:
self.response = self.default_pixmap_as_bytes()
self.timeout = int(time.time())
pixmap = self.set_pixmap_from_response()
# If the email has not changed (e.g. no other requests)
# then we know that this pixmap corresponds to this specific
# email address. We can't blindly trust self.email else
# we may add cache entries for thee wrong email address.
url = Gravatar.url_for_email(email, self.imgsize)
if url == reply.url().toString():
self.pixmaps[email] = pixmap
def set_pixmap_from_response(self):
if self.response is None:
self.response = self.default_pixmap_as_bytes()
pixmap = QtGui.QPixmap()
pixmap.loadFromData(self.response)
self.setPixmap(pixmap)
return pixmap
| 5,301 | Python | .py | 127 | 33.062992 | 83 | 0.639379 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
60 | hidpi.py | git-cola_git-cola/cola/hidpi.py | """Provides High DPI support by wrapping Qt options"""
from qtpy import QtCore
from .i18n import N_
from . import core
from . import compat
from . import version
class Option:
AUTO = '0'
DISABLE = 'disable'
TIMES_1 = '1'
TIMES_1_25 = '1.25'
TIMES_1_5 = '1.5'
TIMES_2 = '2'
def is_supported():
return version.check('qt-hidpi-scale', QtCore.__version__)
def apply_choice(value):
value = compat.ustr(value)
if value == Option.AUTO:
# Do not override the configuration when either of these
# two environment variables are defined.
if not core.getenv('QT_AUTO_SCREEN_SCALE_FACTOR') and not core.getenv(
'QT_SCALE_FACTOR'
):
compat.setenv('QT_AUTO_SCREEN_SCALE_FACTOR', '1')
compat.unsetenv('QT_SCALE_FACTOR')
elif value and value != Option.DISABLE:
compat.unsetenv('QT_AUTO_SCREEN_SCALE_FACTOR')
compat.setenv('QT_SCALE_FACTOR', value)
def options():
return (
(N_('Auto'), Option.AUTO),
(N_('Disable'), Option.DISABLE),
(N_('x 1'), Option.TIMES_1),
(N_('x 1.25'), Option.TIMES_1_25),
(N_('x 1.5'), Option.TIMES_1_5),
(N_('x 2'), Option.TIMES_2),
)
| 1,233 | Python | .py | 37 | 27.189189 | 78 | 0.610455 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
61 | version.py | git-cola_git-cola/cola/version.py | """Provide git-cola's version number"""
import sys
try:
if sys.version_info < (3, 8):
import importlib_metadata as metadata
else:
from importlib import metadata
except (ImportError, OSError):
metadata = None
from .git import STDOUT
from .decorators import memoize
from ._version import VERSION
try:
from ._scm_version import __version__ as SCM_VERSION
except ImportError:
SCM_VERSION = None
# minimum version requirements
_versions = {
# git diff learned --patience in 1.6.2
# git mergetool learned --no-prompt in 1.6.2
# git difftool moved out of contrib in git 1.6.3
'git': '1.6.3',
'python': '2.6',
# new: git cat-file --filters --path=<path> SHA1
# old: git cat-file --filters blob SHA1:<path>
'cat-file-filters-path': '2.11.0',
# git diff --submodule was introduced in 1.6.6
'diff-submodule': '1.6.6',
# git check-ignore was introduced in 1.8.2, but did not follow the same
# rules as git add and git status until 1.8.5
'check-ignore': '1.8.5',
# git push --force-with-lease
'force-with-lease': '1.8.5',
# git submodule update --recursive was introduced in 1.6.5
'submodule-update-recursive': '1.6.5',
# git include.path pseudo-variable was introduced in 1.7.10.
'config-includes': '1.7.10',
# git config --show-scope was introduced in 2.26.0
'config-show-scope': '2.26.0',
# git config --show-origin was introduced in 2.8.0
'config-show-origin': '2.8.0',
# git for-each-ref --sort=version:refname
'version-sort': '2.7.0',
# Qt support for QT_AUTO_SCREEN_SCALE_FACTOR and QT_SCALE_FACTOR
'qt-hidpi-scale': '5.6.0',
# git rebase --rebase-merges was added in 2.18.0
'rebase-merges': '2.18.0',
# git rebase --update-refs was added in 2.38.0
'rebase-update-refs': '2.38.0',
# git rev-parse --show-superproject-working-tree was added in 2.13.0
'show-superproject-working-tree': '2.13.0',
}
def get(key):
"""Returns an entry from the known versions table"""
return _versions.get(key)
def version():
"""Returns the current version"""
if SCM_VERSION:
return SCM_VERSION
pkg_version = VERSION
if metadata is None:
return pkg_version
try:
metadata_version = metadata.version('git-cola')
except (ImportError, OSError):
return pkg_version
# Building from a tarball can end up reporting "0.0.0" or "0.1.dev*".
# Use the fallback version in these scenarios.
if not metadata_version.startswith('0.'):
return metadata_version
return pkg_version
def builtin_version():
"""Returns the version recorded in cola/_version.py"""
return VERSION
@memoize
def check_version(min_ver, ver):
"""Check whether ver is greater or equal to min_ver"""
min_ver_list = version_to_list(min_ver)
ver_list = version_to_list(ver)
return min_ver_list <= ver_list
@memoize
def check(key, ver):
"""Checks if a version is greater than the known version for <what>"""
return check_version(get(key), ver)
def check_git(context, key):
"""Checks if Git has a specific feature"""
return check(key, git_version(context))
def version_to_list(value):
"""Convert a version string to a list of numbers or strings"""
ver_list = []
for part in value.split('.'):
try:
number = int(part)
except ValueError:
number = part
ver_list.append(number)
return ver_list
@memoize
def git_version_str(context):
"""Returns the current GIT version"""
git = context.git
return git.version(_readonly=True)[STDOUT].strip()
@memoize
def git_version(context):
"""Returns the current GIT version"""
parts = git_version_str(context).split()
if parts and len(parts) >= 3:
result = parts[2]
else:
# minimum supported version
result = get('git')
return result
def cola_version(builtin=False):
"""A version string for consumption by humans"""
if builtin:
suffix = builtin_version()
else:
suffix = version()
return 'cola version %s' % suffix
def print_version(builtin=False, brief=False):
if builtin and brief:
msg = builtin_version()
elif brief:
msg = version()
else:
msg = cola_version(builtin=builtin)
print(msg)
| 4,357 | Python | .py | 127 | 29.228346 | 75 | 0.66119 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
62 | main.py | git-cola_git-cola/cola/main.py | """Launcher and command line interface to git-cola"""
import argparse
import sys
from . import app
from . import cmds
from . import compat
from . import core
from . import version
def main(argv=None):
app.initialize()
if argv is None:
argv = sys.argv[1:]
# we're using argparse with subparsers, but argparse
# does not allow us to assign a default subparser
# when none has been specified. We fake it by injecting
# 'cola' into the command-line so that parse_args()
# routes them to the 'cola' parser by default.
help_commands = core.encode('--help-commands')
args = [core.encode(arg) for arg in argv]
if not argv or argv[0].startswith('-') and help_commands not in args:
argv.insert(0, 'cola')
elif help_commands in argv:
argv.append('--help')
args = parse_args(argv)
return args.func(args)
def parse_args(argv):
parser = argparse.ArgumentParser()
# Newer versions of argparse (Python 3.6+) emit an error message for
# "--help-commands" unless we register the flag on the main parser.
if compat.PY_VERSION >= (3, 6):
add_help_options(parser)
parser.set_defaults(func=lambda _: parser.print_help())
subparser = parser.add_subparsers(title='valid commands')
add_cola_command(subparser)
add_about_command(subparser)
add_am_command(subparser)
add_archive_command(subparser)
add_branch_command(subparser)
add_browse_command(subparser)
add_clone_command(subparser)
add_config_command(subparser)
add_dag_command(subparser)
add_diff_command(subparser)
add_fetch_command(subparser)
add_find_command(subparser)
add_grep_command(subparser)
add_merge_command(subparser)
add_pull_command(subparser)
add_push_command(subparser)
add_rebase_command(subparser)
add_recent_command(subparser)
add_remote_command(subparser)
add_search_command(subparser)
add_stash_command(subparser)
add_tag_command(subparser)
add_version_command(subparser)
return parser.parse_args(argv)
def add_help_options(parser):
"""Add the --help-commands flag to the parser"""
parser.add_argument(
'--help-commands',
default=False,
action='store_true',
help='show available commands',
)
def add_command(parent, name, description, func):
"""Add a "git cola" command with common arguments"""
parser = parent.add_parser(str(name), help=description)
parser.set_defaults(func=func)
app.add_common_arguments(parser)
return parser
def add_cola_command(subparser):
"""Add the main "git cola" command. "git cola cola" is valid"""
parser = add_command(subparser, 'cola', 'launch git-cola', cmd_cola)
parser.add_argument(
'--amend', default=False, action='store_true', help='start in amend mode'
)
add_help_options(parser)
parser.add_argument(
'--status-filter', '-s', metavar='<path>', default='', help='status path filter'
)
def add_about_command(parent):
"""Add the "git cola about" documentation command"""
add_command(parent, 'about', 'about git-cola', cmd_about)
def add_am_command(parent):
"""Add the "git cola am" command for applying patches"""
parser = add_command(parent, 'am', 'apply patches using "git am"', cmd_am)
parser.add_argument(
'patches', metavar='<patches>', nargs='*', help='patches to apply'
)
def add_archive_command(parent):
"""Add the "git cola archive" tarball export command"""
parser = add_command(parent, 'archive', 'save an archive', cmd_archive)
parser.add_argument(
'ref', metavar='<ref>', nargs='?', default=None, help='commit to archive'
)
def add_branch_command(subparser):
"""Add the "git cola branch" branch creation command"""
add_command(subparser, 'branch', 'create a branch', cmd_branch)
def add_browse_command(subparser):
"""Add the "git cola browse" repository browser command"""
add_command(subparser, 'browse', 'browse repository', cmd_browse)
def add_clone_command(subparser):
"""Add the "git cola clone" command for cloning repositories"""
add_command(subparser, 'clone', 'clone repository', cmd_clone)
def add_config_command(subparser):
"""Add the "git cola config" command for editing preferences"""
add_command(subparser, 'config', 'edit configuration', cmd_config)
def add_dag_command(subparser):
"""Add the "git cola dag" command for visualizing history"""
parser = add_command(subparser, 'dag', 'start git-dag', cmd_dag)
parser.add_argument(
'-c',
'--count',
metavar='<count>',
type=int,
default=1000,
help='number of commits to display',
)
parser.add_argument(
'--all',
action='store_true',
dest='show_all',
help='visualize all branches',
default=False,
)
parser.add_argument(
'args', nargs=argparse.REMAINDER, metavar='<args>', help='git log arguments'
)
def add_diff_command(subparser):
"""Add the "git cola diff" command for diffing changes"""
parser = add_command(subparser, 'diff', 'view diffs', cmd_diff)
parser.add_argument(
'args', nargs=argparse.REMAINDER, metavar='<args>', help='git diff arguments'
)
def add_fetch_command(subparser):
"""Add the "git cola fetch" command for fetching repositories"""
add_command(subparser, 'fetch', 'fetch remotes', cmd_fetch)
def add_find_command(subparser):
"""Add the "git cola find" command for finding files"""
parser = add_command(subparser, 'find', 'find files', cmd_find)
parser.add_argument('paths', nargs='*', metavar='<path>', help='filter by path')
def add_grep_command(subparser):
"""Add the "git cola grep" command for searching files"""
parser = add_command(subparser, 'grep', 'grep source', cmd_grep)
parser.add_argument('args', nargs='*', metavar='<args>', help='git grep arguments')
def add_merge_command(subparser):
"""Add the "git cola merge" command for merging branches"""
parser = add_command(subparser, 'merge', 'merge branches', cmd_merge)
parser.add_argument(
'ref', nargs='?', metavar='<ref>', help='branch, tag, or commit to merge'
)
def add_pull_command(subparser):
"""Add the "git cola pull" command for pulling changes from remotes"""
parser = add_command(subparser, 'pull', 'pull remote branches', cmd_pull)
parser.add_argument(
'--rebase',
default=False,
action='store_true',
help='rebase local branch when pulling',
)
def add_push_command(subparser):
"""Add the "git cola push" command for pushing branches to remotes"""
add_command(subparser, 'push', 'push remote branches', cmd_push)
def add_rebase_command(subparser):
"""Add the "git cola rebase" command for rebasing the current branch"""
parser = add_command(subparser, 'rebase', 'interactive rebase', cmd_rebase)
parser.add_argument(
'-v',
'--verbose',
default=False,
action='store_true',
help='display a diffstat of what changed upstream',
)
parser.add_argument(
'-q',
'--quiet',
default=False,
action='store_true',
help='be quiet. implies --no-stat',
)
parser.add_argument(
'-i', '--interactive', default=True, action='store_true', help=argparse.SUPPRESS
)
parser.add_argument(
'--autostash',
default=False,
action='store_true',
help='automatically stash/stash pop before and after',
)
parser.add_argument(
'--fork-point',
default=False,
action='store_true',
help="use 'merge-base --fork-point' to refine upstream",
)
parser.add_argument(
'--onto',
default=None,
metavar='<newbase>',
help='rebase onto given branch instead of upstream',
)
parser.add_argument(
'-p',
'--preserve-merges',
default=False,
action='store_true',
help=argparse.SUPPRESS,
)
parser.add_argument(
'--rebase-merges',
default=False,
action='store_true',
help='preserve branching structure when rebasing',
)
parser.add_argument(
'-s',
'--strategy',
default=None,
metavar='<strategy>',
help='use the given merge strategy',
)
parser.add_argument(
'--no-ff',
default=False,
action='store_true',
help='cherry-pick all commits, even if unchanged',
)
parser.add_argument(
'-m',
'--merge',
default=False,
action='store_true',
help='use merging strategies to rebase',
)
parser.add_argument(
'-x',
'--exec',
default=None,
help='add exec lines after each commit of ' 'the editable list',
)
parser.add_argument(
'-k',
'--keep-empty',
default=False,
action='store_true',
help='preserve empty commits during rebase',
)
parser.add_argument(
'-f',
'--force-rebase',
default=False,
action='store_true',
help='force rebase even if branch is up to date',
)
parser.add_argument(
'-X',
'--strategy-option',
default=None,
metavar='<arg>',
help='pass the argument through to the merge strategy',
)
parser.add_argument(
'--stat',
default=False,
action='store_true',
help='display a diffstat of what changed upstream',
)
parser.add_argument(
'-n',
'--no-stat',
default=False,
action='store_true',
help='do not show diffstat of what changed upstream',
)
parser.add_argument(
'--verify',
default=False,
action='store_true',
help='allow pre-rebase hook to run',
)
parser.add_argument(
'--rerere-autoupdate',
default=False,
action='store_true',
help='allow rerere to update index with ' 'resolved conflicts',
)
parser.add_argument(
'--root',
default=False,
action='store_true',
help='rebase all reachable commits up to the root(s)',
)
parser.add_argument(
'--autosquash',
default=True,
action='store_true',
help='move commits that begin with ' 'squash!/fixup! under -i',
)
parser.add_argument(
'--no-autosquash',
default=True,
action='store_false',
dest='autosquash',
help='do not move commits that begin with ' 'squash!/fixup! under -i',
)
parser.add_argument(
'--committer-date-is-author-date',
default=False,
action='store_true',
help="passed to 'git am' by 'git rebase'",
)
parser.add_argument(
'--ignore-date',
default=False,
action='store_true',
help="passed to 'git am' by 'git rebase'",
)
parser.add_argument(
'--whitespace',
default=False,
action='store_true',
help="passed to 'git apply' by 'git rebase'",
)
parser.add_argument(
'--ignore-whitespace',
default=False,
action='store_true',
help="passed to 'git apply' by 'git rebase'",
)
parser.add_argument(
'--update-refs',
default=False,
action='store_true',
help='update branches that point to commits that are being rebased',
)
parser.add_argument(
'-C',
dest='context_lines',
default=None,
metavar='<n>',
help="passed to 'git apply' by 'git rebase'",
)
actions = parser.add_argument_group('actions')
actions.add_argument(
'--continue', default=False, action='store_true', help='continue'
)
actions.add_argument(
'--abort',
default=False,
action='store_true',
help='abort and check out the original branch',
)
actions.add_argument(
'--skip',
default=False,
action='store_true',
help='skip current patch and continue',
)
actions.add_argument(
'--edit-todo',
default=False,
action='store_true',
help='edit the todo list during an interactive rebase',
)
parser.add_argument(
'upstream',
nargs='?',
default=None,
metavar='<upstream>',
help='the upstream configured in branch.<name>.remote '
'and branch.<name>.merge options will be used '
'when <upstream> is omitted; see git-rebase(1) '
'for details. If you are currently not on any '
'branch or if the current branch does not have '
'a configured upstream, the rebase will abort',
)
parser.add_argument(
'branch',
nargs='?',
default=None,
metavar='<branch>',
help='git rebase will perform an automatic '
'"git checkout <branch>" before doing anything '
'else when <branch> is specified',
)
def add_recent_command(subparser):
"""Add the "git cola recent" command for opening recently edited files"""
add_command(subparser, 'recent', 'edit recent files', cmd_recent)
def add_remote_command(subparser):
"""Add the "git cola remote" command for editing remotes"""
add_command(subparser, 'remote', 'edit remotes', cmd_remote)
def add_search_command(subparser):
"""Add the "git cola search" command for searching over commits"""
add_command(subparser, 'search', 'search commits', cmd_search)
def add_stash_command(subparser):
"""Add the "git cola stash" command for creating and applying stashes"""
add_command(subparser, 'stash', 'stash and unstash changes', cmd_stash)
def add_tag_command(subparser):
"""Add the "git cola tag" command for creating tags"""
parser = add_command(subparser, 'tag', 'create tags', cmd_tag)
parser.add_argument(
'name', metavar='<name>', nargs='?', default=None, help='tag name'
)
parser.add_argument(
'ref', metavar='<ref>', nargs='?', default=None, help='commit to tag'
)
parser.add_argument(
'-s',
'--sign',
default=False,
action='store_true',
help='annotated and GPG-signed tag',
)
def add_version_command(subparser):
"""Add the "git cola version" command for displaying Git Cola's version"""
parser = add_command(subparser, 'version', 'print the version', cmd_version)
parser.add_argument(
'--builtin',
action='store_true',
default=False,
help='print the builtin fallback version',
)
parser.add_argument(
'--brief',
action='store_true',
default=False,
help='print the version number only',
)
# entry points
def cmd_cola(args):
"""The "git cola" entry point"""
from .widgets.main import MainView
status_filter = args.status_filter
if status_filter:
status_filter = core.abspath(status_filter)
context = app.application_init(args)
context.timer.start('view')
view = MainView(context)
if args.amend:
cmds.do(cmds.AmendMode, context, amend=True)
if status_filter:
view.set_filter(core.relpath(status_filter))
context.timer.stop('view')
if args.perf:
context.timer.display('view')
return app.application_run(context, view, start=start_cola, stop=app.default_stop)
def start_cola(context, view):
app.default_start(context, view)
view.start(context)
def cmd_about(args):
from .widgets import about
context = app.application_init(args)
view = about.about_dialog(context)
return app.application_start(context, view)
def cmd_am(args):
from .widgets.patch import new_apply_patches
context = app.application_init(args)
view = new_apply_patches(context, patches=args.patches)
return app.application_start(context, view)
def cmd_archive(args):
from .widgets import archive
context = app.application_init(args, update=True)
if args.ref is None:
args.ref = context.model.currentbranch
view = archive.Archive(context, args.ref)
return app.application_start(context, view)
def cmd_branch(args):
from .widgets.createbranch import create_new_branch
context = app.application_init(args, update=True)
view = create_new_branch(context)
return app.application_start(context, view)
def cmd_browse(args):
from .widgets.browse import worktree_browser
context = app.application_init(args)
view = worktree_browser(context, show=False, update=False)
return app.application_start(context, view)
def cmd_clone(args):
from .widgets import clone
context = app.application_init(args)
view = clone.clone(context)
context.set_view(view)
result = 0 if view.exec_() == view.Accepted else 1
app.default_stop(context, view)
return result
def cmd_config(args):
from .widgets.prefs import preferences
context = app.application_init(args)
view = preferences(context)
return app.application_start(context, view)
def cmd_dag(args):
from .widgets import dag
context = app.application_init(args, app_name='Git DAG')
# cola.main() uses parse_args(), unlike dag.main() which uses
# parse_known_args(), thus we aren't able to automatically forward
# all unknown arguments. Special-case support for "--all" since it's
# used by the history viewer command on Windows.
if args.show_all:
args.args.insert(0, '--all')
view = dag.git_dag(context, args=args, show=False)
return app.application_start(context, view)
def cmd_diff(args):
from .difftool import diff_expression
context = app.application_init(args)
expr = core.list2cmdline(args.args)
view = diff_expression(context, None, expr, create_widget=True)
return app.application_start(context, view)
def cmd_fetch(args):
# TODO: the calls to update_status() can be done asynchronously
# by hooking into the message_updated notification.
from .widgets import remote
context = app.application_init(args)
context.model.update_status()
view = remote.fetch(context)
return app.application_start(context, view)
def cmd_find(args):
from .widgets import finder
context = app.application_init(args)
paths = core.list2cmdline(args.paths)
view = finder.finder(context, paths=paths)
return app.application_start(context, view)
def cmd_grep(args):
from .widgets import grep
context = app.application_init(args)
text = core.list2cmdline(args.args)
view = grep.new_grep(context, text=text, parent=None)
return app.application_start(context, view)
def cmd_merge(args):
from .widgets.merge import Merge
context = app.application_init(args, update=True)
view = Merge(context, parent=None, ref=args.ref)
return app.application_start(context, view)
def cmd_version(args):
from . import version
version.print_version(builtin=args.builtin, brief=args.brief)
return 0
def cmd_pull(args):
from .widgets import remote
context = app.application_init(args, update=True)
view = remote.pull(context)
if args.rebase:
view.set_rebase(True)
return app.application_start(context, view)
def cmd_push(args):
from .widgets import remote
context = app.application_init(args, update=True)
view = remote.push(context)
return app.application_start(context, view)
def cmd_rebase(args):
context = app.application_init(args)
context.model.update_refs()
kwargs = {
'verbose': args.verbose,
'quiet': args.quiet,
'autostash': args.autostash,
'fork_point': args.fork_point,
'onto': args.onto,
'strategy': args.strategy,
'no_ff': args.no_ff,
'merge': args.merge,
'exec': getattr(args, 'exec', None), # python keyword
'keep_empty': args.keep_empty,
'force_rebase': args.force_rebase,
'strategy_option': args.strategy_option,
'stat': args.stat,
'no_stat': args.no_stat,
'verify': args.verify,
'rerere_autoupdate': args.rerere_autoupdate,
'root': args.root,
'autosquash': args.autosquash,
'committer_date_is_author_date': args.committer_date_is_author_date,
'ignore_date': args.ignore_date,
'whitespace': args.whitespace,
'ignore_whitespace': args.ignore_whitespace,
'C': args.context_lines,
'continue': getattr(args, 'continue', False), # python keyword
'abort': args.abort,
'skip': args.skip,
'edit_todo': args.edit_todo,
'update_refs': args.update_refs,
'upstream': args.upstream,
'branch': args.branch,
}
# Backwards compatibility: --preserve-merges was replaced by --rebase-merges.
rebase_merges = args.rebase_merges or args.preserve_merges
if version.check_git(context, 'rebase-merges'):
kwargs['rebase_merges'] = rebase_merges
else:
kwargs['preserve_merges'] = rebase_merges
status, _, _ = cmds.do(cmds.Rebase, context, **kwargs)
return status
def cmd_recent(args):
from .widgets import recent
context = app.application_init(args)
view = recent.browse_recent_files(context)
return app.application_start(context, view)
def cmd_remote(args):
from .widgets import editremotes
context = app.application_init(args)
view = editremotes.editor(context, run=False)
return app.application_start(context, view)
def cmd_search(args):
from .widgets.search import search
context = app.application_init(args)
view = search(context)
return app.application_start(context, view)
def cmd_stash(args):
from .widgets import stash
context = app.application_init(args)
view = stash.view(context, show=False)
return app.application_start(context, view)
def cmd_tag(args):
from .widgets.createtag import new_create_tag
context = app.application_init(args)
context.model.update_status()
view = new_create_tag(context, name=args.name, ref=args.ref, sign=args.sign)
return app.application_start(context, view)
# Windows shortcut launch features:
def shortcut_launch():
"""Launch from a shortcut
Prompt for the repository by default.
"""
argv = sys.argv[1:]
if not argv:
argv = ['cola', '--prompt']
return main(argv=argv)
| 22,506 | Python | .py | 626 | 29.619808 | 88 | 0.654264 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
63 | qtcompat.py | git-cola_git-cola/cola/qtcompat.py | from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
try:
from qtpy import PYQT4
except ImportError:
PYQT4 = False
from . import hotkeys
def patch(obj, attr, value):
if not hasattr(obj, attr):
setattr(obj, attr, value)
def install():
patch(QtWidgets.QGraphicsItem, 'mapRectToScene', _map_rect_to_scene)
patch(QtGui.QKeySequence, 'Preferences', hotkeys.PREFERENCES)
def add_search_path(prefix, path):
if hasattr(QtCore.QDir, 'addSearchPath'):
QtCore.QDir.addSearchPath(prefix, path)
def set_common_dock_options(window):
if not hasattr(window, 'setDockOptions'):
return
nested = QtWidgets.QMainWindow.AllowNestedDocks
tabbed = QtWidgets.QMainWindow.AllowTabbedDocks
animated = QtWidgets.QMainWindow.AnimatedDocks
window.setDockOptions(nested | tabbed | animated)
def _map_rect_to_scene(self, rect):
"""Only available in newer PyQt4 versions"""
return self.sceneTransform().mapRect(rect)
def wheel_translation(event):
"""Return the (Tx, Ty) translation delta for a pan"""
if PYQT4:
tx = event.delta()
ty = 0.0
if event.orientation() == Qt.Vertical:
(tx, ty) = (ty, tx)
else:
angle = event.angleDelta()
tx = angle.x()
ty = angle.y()
return (tx, ty)
def wheel_delta(event):
"""Return a single wheel delta"""
if PYQT4:
delta = event.delta()
else:
angle = event.angleDelta()
x = angle.x()
y = angle.y()
if abs(x) > abs(y):
delta = x
else:
delta = y
return delta
| 1,659 | Python | .py | 53 | 25.471698 | 72 | 0.658491 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
64 | decorators.py | git-cola_git-cola/cola/decorators.py | import errno
import functools
__all__ = ('decorator', 'memoize', 'interruptable')
def decorator(caller, func=None):
"""
Create a new decorator
decorator(caller) converts a caller function into a decorator;
decorator(caller, func) decorates a function using a caller.
"""
if func is None:
# return a decorator
@functools.wraps(caller)
def _decorator(func, *dummy_args, **dummy_opts):
@functools.wraps(func)
def _caller(*args, **opts):
return caller(func, *args, **opts)
return _caller
_decorator.func = caller
return _decorator
# return a decorated function
@functools.wraps(func)
def _decorated(*args, **opts):
return caller(func, *args, **opts)
_decorated.func = func
return _decorated
def memoize(func):
"""
A decorator for memoizing function calls
https://en.wikipedia.org/wiki/Memoization
"""
func.cache = {}
return decorator(_memoize, func)
def _memoize(func, *args, **opts):
"""Implements memoized cache lookups"""
if opts: # frozenset is used to ensure hashability
key = (args, frozenset(list(opts.items())))
else:
key = args
cache = func.cache # attribute added by memoize
try:
result = cache[key]
except KeyError:
result = cache[key] = func(*args, **opts)
return result
@decorator
def interruptable(func, *args, **opts):
"""Handle interruptible system calls
macOS and others are known to interrupt system calls
https://en.wikipedia.org/wiki/PCLSRing
http://en.wikipedia.org/wiki/Unix_philosophy#Worse_is_better
The @interruptable decorator handles this situation
"""
while True:
try:
result = func(*args, **opts)
except OSError as e:
if e.errno in (errno.EINTR, errno.EINVAL):
continue
raise e
break
return result
| 1,991 | Python | .py | 61 | 25.639344 | 68 | 0.633648 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
65 | cmd.py | git-cola_git-cola/cola/cmd.py | """Base Command class"""
class Command:
"""Mixin interface for commands"""
UNDOABLE = False
@staticmethod
def name():
"""Return the command's name"""
return '(undefined)'
@classmethod
def is_undoable(cls):
"""Can this be undone?"""
return cls.UNDOABLE
def do(self):
"""Execute the command"""
return
def undo(self):
"""Undo the command"""
return
class ContextCommand(Command):
"""Base class for commands that operate on a context"""
def __init__(self, context):
self.context = context
self.model = context.model
self.cfg = context.cfg
self.git = context.git
self.selection = context.selection
self.fsmonitor = context.fsmonitor
| 789 | Python | .py | 27 | 22.222222 | 59 | 0.610372 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
66 | actions.py | git-cola_git-cola/cola/actions.py | """QAction creator functions"""
from . import cmds
from . import difftool
from . import hotkeys
from . import icons
from . import qtutils
from .i18n import N_
def cmd_action(widget, cmd, context, icon, *shortcuts):
"""Wrap a generic ContextCommand in a QAction"""
action = qtutils.add_action(widget, cmd.name(), cmds.run(cmd, context), *shortcuts)
action.setIcon(icon)
return action
def launch_editor(context, widget, *shortcuts):
"""Create a QAction to launch an editor"""
icon = icons.edit()
return cmd_action(
widget, cmds.LaunchEditor, context, icon, hotkeys.EDIT, *shortcuts
)
def launch_editor_at_line(context, widget, *shortcuts):
"""Create a QAction to launch an editor at the current line"""
icon = icons.edit()
return cmd_action(
widget, cmds.LaunchEditorAtLine, context, icon, hotkeys.EDIT, *shortcuts
)
def launch_difftool(context, widget):
"""Create a QAction to launch git-difftool(1)"""
icon = icons.diff()
cmd = difftool.LaunchDifftool
action = qtutils.add_action(
widget, cmd.name(), cmds.run(cmd, context), hotkeys.DIFF
)
action.setIcon(icon)
return action
def stage_or_unstage(context, widget):
"""Create a QAction to stage or unstage the selection"""
icon = icons.add()
return cmd_action(
widget, cmds.StageOrUnstage, context, icon, hotkeys.STAGE_SELECTION
)
def move_down(widget):
"""Create a QAction to select the next item"""
action = qtutils.add_action(
widget, N_('Next File'), widget.down.emit, hotkeys.MOVE_DOWN_SECONDARY
)
action.setIcon(icons.move_down())
return action
def move_up(widget):
"""Create a QAction to select the previous/above item"""
action = qtutils.add_action(
widget, N_('Previous File'), widget.up.emit, hotkeys.MOVE_UP_SECONDARY
)
action.setIcon(icons.move_up())
return action
| 1,920 | Python | .py | 53 | 31.54717 | 87 | 0.696544 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
67 | fsmonitor.py | git-cola_git-cola/cola/fsmonitor.py | # Copyright (C) 2008-2024 David Aguilar
# Copyright (C) 2015 Daniel Harding
"""Filesystem monitor for Linux and Windows
Linux monitoring uses using inotify.
Windows monitoring uses pywin32 and the ReadDirectoryChanges function.
"""
import errno
import os
import os.path
import select
from threading import Lock
from qtpy import QtCore
from qtpy.QtCore import Signal
from . import utils
from . import core
from . import gitcmds
from . import version
from .compat import bchr
from .i18n import N_
from .interaction import Interaction
AVAILABLE = None
pywintypes = None
win32file = None
win32con = None
win32event = None
if utils.is_win32():
try:
import pywintypes
import win32con
import win32event
import win32file
AVAILABLE = 'pywin32'
except ImportError:
pass
elif utils.is_linux():
try:
from . import inotify
except ImportError:
pass
else:
AVAILABLE = 'inotify'
class _Monitor(QtCore.QObject):
files_changed = Signal()
config_changed = Signal()
def __init__(self, context, thread_class):
QtCore.QObject.__init__(self)
self.context = context
self._thread_class = thread_class
self._thread = None
def start(self):
if self._thread_class is not None:
assert self._thread is None
self._thread = self._thread_class(self.context, self)
self._thread.start()
def stop(self):
if self._thread_class is not None:
assert self._thread is not None
self._thread.stop()
self._thread.wait()
self._thread = None
def refresh(self):
if self._thread is not None:
self._thread.refresh()
class _BaseThread(QtCore.QThread):
#: The delay, in milliseconds, between detecting file system modification
#: and triggering the 'files_changed' signal, to coalesce multiple
#: modifications into a single signal.
_NOTIFICATION_DELAY = 888
def __init__(self, context, monitor):
QtCore.QThread.__init__(self)
self.context = context
self._monitor = monitor
self._running = True
self._use_check_ignore = version.check_git(context, 'check-ignore')
self._force_notify = False
self._force_config = False
self._file_paths = set()
@property
def _pending(self):
return self._force_notify or self._file_paths or self._force_config
def refresh(self):
"""Do any housekeeping necessary in response to repository changes."""
return
def notify(self):
"""Notifies all observers"""
do_notify = False
do_config = False
if self._force_config:
do_config = True
if self._force_notify:
do_notify = True
elif self._file_paths:
proc = core.start_command(
['git', 'check-ignore', '--verbose', '--non-matching', '-z', '--stdin']
)
path_list = bchr(0).join(core.encode(path) for path in self._file_paths)
out, _ = proc.communicate(path_list)
if proc.returncode:
do_notify = True
else:
# Each output record is four fields separated by NULL
# characters (records are also separated by NULL characters):
# <source> <NULL> <linenum> <NULL> <pattern> <NULL> <pathname>
# For paths which are not ignored, all fields will be empty
# except for <pathname>. So to see if we have any non-ignored
# files, we simply check every fourth field to see if any of
# them are empty.
source_fields = out.split(bchr(0))[0:-1:4]
do_notify = not all(source_fields)
self._force_notify = False
self._force_config = False
self._file_paths = set()
# "files changed" is a bigger hammer than "config changed".
# and is a superset relative to what is done in response to the
# signal. Thus, the "elif" below avoids repeated work that
# would be done if it were a simple "if" check instead.
if do_notify:
self._monitor.files_changed.emit()
elif do_config:
self._monitor.config_changed.emit()
@staticmethod
def _log_enabled_message():
msg = N_('File system change monitoring: enabled.\n')
Interaction.log(msg)
if AVAILABLE == 'inotify':
class _InotifyThread(_BaseThread):
_TRIGGER_MASK = (
inotify.IN_ATTRIB
| inotify.IN_CLOSE_WRITE
| inotify.IN_CREATE
| inotify.IN_DELETE
| inotify.IN_MODIFY
| inotify.IN_MOVED_FROM
| inotify.IN_MOVED_TO
)
_ADD_MASK = _TRIGGER_MASK | inotify.IN_EXCL_UNLINK | inotify.IN_ONLYDIR
def __init__(self, context, monitor):
_BaseThread.__init__(self, context, monitor)
git = context.git
worktree = git.worktree()
if worktree is not None:
worktree = core.abspath(worktree)
self._worktree = worktree
self._git_dir = git.git_path()
self._lock = Lock()
self._inotify_fd = None
self._pipe_r = None
self._pipe_w = None
self._worktree_wd_to_path_map = {}
self._worktree_path_to_wd_map = {}
self._git_dir_wd_to_path_map = {}
self._git_dir_path_to_wd_map = {}
self._git_dir_wd = None
@staticmethod
def _log_out_of_wds_message():
msg = N_(
'File system change monitoring: disabled because the'
' limit on the total number of inotify watches was'
' reached. You may be able to increase the limit on'
' the number of watches by running:\n'
'\n'
' echo fs.inotify.max_user_watches=100000 |'
' sudo tee -a /etc/sysctl.conf &&'
' sudo sysctl -p\n'
)
Interaction.log(msg)
def run(self):
try:
with self._lock:
try:
self._inotify_fd = inotify.init()
except OSError as e:
self._inotify_fd = None
self._running = False
if e.errno == errno.EMFILE:
self._log_out_of_wds_message()
return
self._pipe_r, self._pipe_w = os.pipe()
poll_obj = select.poll()
poll_obj.register(self._inotify_fd, select.POLLIN)
poll_obj.register(self._pipe_r, select.POLLIN)
self.refresh()
if self._running:
self._log_enabled_message()
self._process_events(poll_obj)
finally:
self._close_fds()
def _process_events(self, poll_obj):
while self._running:
if self._pending:
timeout = self._NOTIFICATION_DELAY
else:
timeout = None
try:
events = poll_obj.poll(timeout)
except OSError:
continue
else:
if not self._running:
break
if not events:
self.notify()
else:
for fd, _ in events:
if fd == self._inotify_fd:
self._handle_events()
def _close_fds(self):
with self._lock:
if self._inotify_fd is not None:
os.close(self._inotify_fd)
self._inotify_fd = None
if self._pipe_r is not None:
os.close(self._pipe_r)
self._pipe_r = None
os.close(self._pipe_w)
self._pipe_w = None
def refresh(self):
with self._lock:
self._refresh()
def _refresh(self):
if self._inotify_fd is None:
return
context = self.context
try:
if self._worktree is not None:
tracked_dirs = {
os.path.dirname(os.path.join(self._worktree, path))
for path in gitcmds.tracked_files(context)
}
self._refresh_watches(
tracked_dirs,
self._worktree_wd_to_path_map,
self._worktree_path_to_wd_map,
)
git_dirs = set()
git_dirs.add(self._git_dir)
for dirpath, _, _ in core.walk(os.path.join(self._git_dir, 'refs')):
git_dirs.add(dirpath)
self._refresh_watches(
git_dirs, self._git_dir_wd_to_path_map, self._git_dir_path_to_wd_map
)
self._git_dir_wd = self._git_dir_path_to_wd_map.get(self._git_dir)
except OSError as e:
if e.errno in (errno.ENOSPC, errno.EMFILE):
self._log_out_of_wds_message()
self._running = False
else:
raise
def _refresh_watches(self, paths_to_watch, wd_to_path_map, path_to_wd_map):
watched_paths = set(path_to_wd_map)
for path in watched_paths - paths_to_watch:
wd = path_to_wd_map.pop(path)
wd_to_path_map.pop(wd)
try:
inotify.rm_watch(self._inotify_fd, wd)
except OSError as e:
if e.errno == errno.EINVAL:
# This error can occur if the target of the watch was
# removed on the filesystem before we call
# inotify.rm_watch() so ignore it.
continue
raise e
for path in paths_to_watch - watched_paths:
try:
wd = inotify.add_watch(
self._inotify_fd, core.encode(path), self._ADD_MASK
)
except PermissionError:
continue
except OSError as e:
if e.errno in (errno.ENOENT, errno.ENOTDIR):
# These two errors should only occur as a result of
# race conditions: the first if the directory
# referenced by path was removed or renamed before the
# call to inotify.add_watch(); the second if the
# directory referenced by path was replaced with a file
# before the call to inotify.add_watch(). Therefore we
# simply ignore them.
continue
raise e
wd_to_path_map[wd] = path
path_to_wd_map[path] = wd
def _check_event(self, wd, mask, name):
if mask & inotify.IN_Q_OVERFLOW:
self._force_notify = True
elif not mask & self._TRIGGER_MASK:
pass
elif mask & inotify.IN_ISDIR:
pass
elif wd in self._worktree_wd_to_path_map:
if self._use_check_ignore and name:
path = os.path.join(
self._worktree_wd_to_path_map[wd], core.decode(name)
)
self._file_paths.add(path)
else:
self._force_notify = True
elif wd == self._git_dir_wd:
name = core.decode(name)
if name in ('HEAD', 'index'):
self._force_notify = True
elif name == 'config':
self._force_config = True
elif wd in self._git_dir_wd_to_path_map and not core.decode(name).endswith(
'.lock'
):
self._force_notify = True
def _handle_events(self):
for wd, mask, _, name in inotify.read_events(self._inotify_fd):
if not self._force_notify:
self._check_event(wd, mask, name)
def stop(self):
self._running = False
with self._lock:
if self._pipe_w is not None:
os.write(self._pipe_w, bchr(0))
self.wait()
if AVAILABLE == 'pywin32':
class _Win32Watch:
def __init__(self, path, flags):
self.flags = flags
self.handle = None
self.event = None
try:
self.handle = win32file.CreateFileW(
path,
0x0001, # FILE_LIST_DIRECTORY
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED,
None,
)
self.buffer = win32file.AllocateReadBuffer(8192)
self.event = win32event.CreateEvent(None, True, False, None)
self.overlapped = pywintypes.OVERLAPPED()
self.overlapped.hEvent = self.event
self._start()
except Exception:
self.close()
def append(self, events):
"""Append our event to the events list when valid"""
if self.event is not None:
events.append(self.event)
def _start(self):
if self.handle is None:
return
win32file.ReadDirectoryChangesW(
self.handle, self.buffer, True, self.flags, self.overlapped
)
def read(self):
if self.handle is None or self.event is None:
return []
if win32event.WaitForSingleObject(self.event, 0) == win32event.WAIT_TIMEOUT:
result = []
else:
nbytes = win32file.GetOverlappedResult(
self.handle, self.overlapped, False
)
result = win32file.FILE_NOTIFY_INFORMATION(self.buffer, nbytes)
self._start()
return result
def close(self):
if self.handle is not None:
win32file.CancelIo(self.handle)
win32file.CloseHandle(self.handle)
if self.event is not None:
win32file.CloseHandle(self.event)
class _Win32Thread(_BaseThread):
_FLAGS = (
win32con.FILE_NOTIFY_CHANGE_FILE_NAME
| win32con.FILE_NOTIFY_CHANGE_DIR_NAME
| win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES
| win32con.FILE_NOTIFY_CHANGE_SIZE
| win32con.FILE_NOTIFY_CHANGE_LAST_WRITE
| win32con.FILE_NOTIFY_CHANGE_SECURITY
)
def __init__(self, context, monitor):
_BaseThread.__init__(self, context, monitor)
git = context.git
worktree = git.worktree()
if worktree is not None:
worktree = self._transform_path(core.abspath(worktree))
self._worktree = worktree
self._worktree_watch = None
self._git_dir = self._transform_path(core.abspath(git.git_path()))
self._git_dir_watch = None
self._stop_event_lock = Lock()
self._stop_event = None
@staticmethod
def _transform_path(path):
return path.replace('\\', '/').lower()
def run(self):
try:
with self._stop_event_lock:
self._stop_event = win32event.CreateEvent(None, True, False, None)
events = [self._stop_event]
if self._worktree is not None:
self._worktree_watch = _Win32Watch(self._worktree, self._FLAGS)
self._worktree_watch.append(events)
self._git_dir_watch = _Win32Watch(self._git_dir, self._FLAGS)
self._git_dir_watch.append(events)
self._log_enabled_message()
while self._running:
if self._pending:
timeout = self._NOTIFICATION_DELAY
else:
timeout = win32event.INFINITE
status = win32event.WaitForMultipleObjects(events, False, timeout)
if not self._running:
break
if status == win32event.WAIT_TIMEOUT:
self.notify()
else:
self._handle_results()
finally:
with self._stop_event_lock:
if self._stop_event is not None:
win32file.CloseHandle(self._stop_event)
self._stop_event = None
if self._worktree_watch is not None:
self._worktree_watch.close()
if self._git_dir_watch is not None:
self._git_dir_watch.close()
def _handle_results(self):
if self._worktree_watch is not None:
for _, path in self._worktree_watch.read():
if not self._running:
break
if self._force_notify:
continue
path = self._worktree + '/' + self._transform_path(path)
if (
path != self._git_dir
and not path.startswith(self._git_dir + '/')
and not os.path.isdir(path)
):
if self._use_check_ignore:
self._file_paths.add(path)
else:
self._force_notify = True
for _, path in self._git_dir_watch.read():
if not self._running:
break
if self._force_notify:
continue
path = self._transform_path(path)
if path.endswith('.lock'):
continue
if path == 'config':
self._force_config = True
continue
if path == 'head' or path == 'index' or path.startswith('refs/'):
self._force_notify = True
def stop(self):
self._running = False
with self._stop_event_lock:
if self._stop_event is not None:
win32event.SetEvent(self._stop_event)
self.wait()
def create(context):
thread_class = None
cfg = context.cfg
if not cfg.get('cola.inotify', default=True):
msg = N_(
'File system change monitoring: disabled because'
' "cola.inotify" is false.\n'
)
Interaction.log(msg)
elif AVAILABLE == 'inotify':
thread_class = _InotifyThread
elif AVAILABLE == 'pywin32':
thread_class = _Win32Thread
else:
if utils.is_win32():
msg = N_(
'File system change monitoring: disabled because pywin32'
' is not installed.\n'
)
Interaction.log(msg)
elif utils.is_linux():
msg = N_(
'File system change monitoring: disabled because libc'
' does not support the inotify system calls.\n'
)
Interaction.log(msg)
return _Monitor(context, thread_class)
| 19,921 | Python | .py | 487 | 26.431211 | 88 | 0.507382 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
68 | icons.py | git-cola_git-cola/cola/icons.py | """The only file where icon filenames are mentioned"""
import os
from qtpy import QtGui
from qtpy import QtWidgets
from . import core
from . import decorators
from . import qtcompat
from . import resources
from .compat import ustr
from .i18n import N_
KNOWN_FILE_MIME_TYPES = [
('text', 'file-code.svg'),
('image', 'file-media.svg'),
('octet', 'file-binary.svg'),
]
KNOWN_FILE_EXTENSIONS = {
'.bash': 'file-code.svg',
'.c': 'file-code.svg',
'.cpp': 'file-code.svg',
'.css': 'file-code.svg',
'.cxx': 'file-code.svg',
'.h': 'file-code.svg',
'.hpp': 'file-code.svg',
'.hs': 'file-code.svg',
'.html': 'file-code.svg',
'.java': 'file-code.svg',
'.js': 'file-code.svg',
'.ksh': 'file-code.svg',
'.lisp': 'file-code.svg',
'.perl': 'file-code.svg',
'.pl': 'file-code.svg',
'.py': 'file-code.svg',
'.rb': 'file-code.svg',
'.rs': 'file-code.svg',
'.sh': 'file-code.svg',
'.zsh': 'file-code.svg',
}
def install(themes):
for theme in themes:
icon_dir = resources.icon_dir(theme)
qtcompat.add_search_path('icons', icon_dir)
def icon_themes():
return (
(N_('Default'), 'default'),
(N_('Dark Theme'), 'dark'),
(N_('Light Theme'), 'light'),
)
def name_from_basename(basename):
"""Prefix the basename with "icons:" so that git-cola's icons are found
"icons" is registered with the Qt resource system during install().
"""
return 'icons:' + basename
@decorators.memoize
def from_name(name):
"""Return a QIcon from an absolute filename or "icons:basename.svg" name"""
return QtGui.QIcon(name)
def icon(basename):
"""Given a basename returns a QIcon from the corresponding cola icon"""
return from_name(name_from_basename(basename))
def from_theme(name, fallback=None):
"""Grab an icon from the current theme with a fallback
Support older versions of Qt checking for fromTheme's availability.
"""
if hasattr(QtGui.QIcon, 'fromTheme'):
base, _ = os.path.splitext(name)
if fallback:
qicon = QtGui.QIcon.fromTheme(base, icon(fallback))
else:
qicon = QtGui.QIcon.fromTheme(base)
if not qicon.isNull():
return qicon
return icon(fallback or name)
def basename_from_filename(filename):
"""Returns an icon name based on the filename"""
mimetype = core.guess_mimetype(filename)
if mimetype is not None:
mimetype = mimetype.lower()
for filetype, icon_name in KNOWN_FILE_MIME_TYPES:
if filetype in mimetype:
return icon_name
extension = os.path.splitext(filename)[1]
return KNOWN_FILE_EXTENSIONS.get(extension.lower(), 'file-text.svg')
def from_filename(filename):
"""Return a QIcon from a filename"""
basename = basename_from_filename(filename)
return from_name(name_from_basename(basename))
def mkicon(value, default=None):
"""Create an icon from a string value"""
if value is None and default is not None:
value = default()
elif value and isinstance(value, (str, ustr)):
value = QtGui.QIcon(value)
return value
def from_style(key):
"""Maintain a cache of standard icons and return cache entries."""
style = QtWidgets.QApplication.instance().style()
return style.standardIcon(key)
def status(filename, deleted, is_staged, untracked):
"""Status icon for a file"""
if deleted:
icon_name = 'circle-slash-red.svg'
elif is_staged:
icon_name = 'staged.svg'
elif untracked:
icon_name = 'question-plain.svg'
else:
icon_name = basename_from_filename(filename)
return icon_name
# Icons creators and SVG file references
def three_bars():
"""Three-bars icon"""
return icon('three-bars.svg')
def add():
"""Add icon"""
return from_theme('list-add', fallback='plus.svg')
def alphabetical():
"""Alphabetical icon"""
return from_theme('view-sort', fallback='a-z-order.svg')
def branch():
"""Branch icon"""
return icon('git-branch.svg')
def check_name():
"""Check mark icon name"""
return name_from_basename('check.svg')
def cherry_pick():
"""Cherry-pick icon"""
return icon('git-commit.svg')
def circle_slash_red():
"""A circle with a slash through it"""
return icon('circle-slash-red.svg')
def close():
"""Close icon"""
return icon('x.svg')
def cola():
"""Git Cola icon"""
return icon('git-cola.svg')
def commit():
"""Commit icon"""
return icon('document-save-symbolic.svg')
def compare():
"""Compare icon"""
return icon('git-compare.svg')
def configure():
"""Configure icon"""
return icon('gear.svg')
def cut():
"""Cut icon"""
return from_theme('edit-cut', fallback='edit-cut.svg')
def copy():
"""Copy icon"""
return from_theme('edit-copy', fallback='edit-copy.svg')
def paste():
"""Paste icon"""
return from_theme('edit-paste', fallback='edit-paste.svg')
def play():
"""Play icon"""
return icon('play.svg')
def delete():
"""Delete icon"""
return from_theme('edit-delete', fallback='trashcan.svg')
def default_app():
"""Default app icon"""
return icon('telescope.svg')
def dot_name():
"""Dot icon name"""
return name_from_basename('primitive-dot.svg')
def download():
"""Download icon"""
return icon('file-download.svg')
def discard():
"""Discard icon"""
return from_theme('delete', fallback='trashcan.svg')
# folder vs directory: directory is opaque, folder is just an outline
# directory is used for the File Browser, where more contrast with the file
# icons are needed.
def folder():
"""Folder icon"""
return from_theme('folder', fallback='folder.svg')
def directory():
"""Directory icon"""
return from_theme('folder', fallback='file-directory.svg')
def diff():
"""Diff icon"""
return icon('diff.svg')
def edit():
"""Edit icon"""
return from_theme('document-edit', fallback='pencil.svg')
def ellipsis():
"""Ellipsis icon"""
return icon('ellipsis.svg')
def external():
"""External link icon"""
return icon('link-external.svg')
def file_code():
"""Code file icon"""
return icon('file-code.svg')
def file_text():
"""Text file icon"""
return icon('file-text.svg')
def file_zip():
"""Zip file / tarball icon"""
return icon('file-zip.svg')
def fold():
"""Fold icon"""
return icon('fold.svg')
def merge():
"""Merge icon"""
return icon('git-merge.svg')
def modified():
"""Modified icon"""
return icon('modified.svg')
def modified_name():
"""Modified icon name"""
return name_from_basename('modified.svg')
def move_down():
"""Move down icon"""
return from_theme('go-next', fallback='arrow-down.svg')
def move_up():
"""Move up icon"""
return from_theme('go-previous', fallback='arrow-up.svg')
def new():
"""Add new/add-to-list icon"""
return from_theme('list-add', fallback='folder-new.svg')
def ok():
"""Ok/accept icon"""
return from_theme('checkmark', fallback='check.svg')
def open_directory():
"""Open directory icon"""
return from_theme('folder', fallback='folder.svg')
def up():
"""Previous icon"""
return icon('arrow-up.svg')
def down():
"""Go to next item icon"""
return icon('arrow-down.svg')
def partial_name():
"""Partial icon name"""
return name_from_basename('partial.svg')
def pull():
"""Pull icon"""
return icon('repo-pull.svg')
def push():
"""Push icon"""
return icon('repo-push.svg')
def question():
"""Question icon"""
return icon('question.svg')
def remove():
"""Remove icon"""
return from_theme('list-remove', fallback='circle-slash.svg')
def repo():
"""Repository icon"""
return icon('repo.svg')
def reverse_chronological():
"""Reverse chronological icon"""
return icon('last-first-order.svg')
def save():
"""Save icon"""
return from_theme('document-save', fallback='desktop-download.svg')
def search():
"""Search icon"""
return from_theme('search', fallback='search.svg')
def select_all():
"""Select all icon"""
return from_theme('edit-select-all', fallback='edit-select-all')
def staged():
"""Staged icon"""
return icon('staged.svg')
def staged_name():
"""Staged icon name"""
return name_from_basename('staged.svg')
def star():
"""Star icon"""
return icon('star.svg')
def sync():
"""Sync/update icon"""
return icon('sync.svg')
def tag():
"""Tag icon"""
return icon('tag.svg')
def terminal():
"""Terminal icon"""
return icon('terminal.svg')
def undo():
"""Undo icon"""
return from_theme('edit-undo', fallback='edit-undo.svg')
def redo():
"""Redo icon"""
return from_theme('edit-redo', fallback='edit-redo.svg')
def style_dialog_apply():
"""Apply icon from the current style"""
return from_style(QtWidgets.QStyle.SP_DialogApplyButton)
def style_dialog_discard():
"""Discard icon for the current style"""
return from_style(QtWidgets.QStyle.SP_DialogDiscardButton)
def style_dialog_reset():
"""Reset icon for the current style"""
return from_style(QtWidgets.QStyle.SP_DialogResetButton)
def unfold():
"""Expand/unfold icon"""
return icon('unfold.svg')
def visualize():
"""An eye icon to represent visualization"""
return icon('eye.svg')
def upstream_name():
"""Upstream branch icon name"""
return name_from_basename('upstream.svg')
def zoom_fit_best():
"""Zoom-to-fit icon"""
return from_theme('zoom-fit-best', fallback='zoom-fit-best.svg')
def zoom_in():
"""Zoom-in icon"""
return from_theme('zoom-in', fallback='zoom-in.svg')
def zoom_out():
"""Zoom-out icon"""
return from_theme('zoom-out', fallback='zoom-out.svg')
| 9,943 | Python | .py | 316 | 26.810127 | 79 | 0.650804 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
69 | gitcmds.py | git-cola_git-cola/cola/gitcmds.py | """Git commands and queries for Git"""
import json
import os
import re
from io import StringIO
from . import core
from . import utils
from . import version
from .git import STDOUT
from .git import EMPTY_TREE_OID
from .git import OID_LENGTH
from .i18n import N_
from .interaction import Interaction
from .models import prefs
def add(context, items, u=False):
"""Run "git add" while preventing argument overflow"""
git_add = context.git.add
return utils.slice_func(
items, lambda paths: git_add('--', force=True, verbose=True, u=u, *paths)
)
def apply_diff(context, filename):
"""Use "git apply" to apply the patch in `filename` to the staging area"""
git = context.git
return git.apply(filename, index=True, cached=True)
def apply_diff_to_worktree(context, filename):
"""Use "git apply" to apply the patch in `filename` to the worktree"""
git = context.git
return git.apply(filename)
def get_branch(context, branch):
"""Get the current branch"""
if branch is None:
branch = current_branch(context)
return branch
def upstream_remote(context, branch=None):
"""Return the remote associated with the specified branch"""
config = context.cfg
branch = get_branch(context, branch)
return config.get('branch.%s.remote' % branch)
def remote_url(context, remote, push=False):
"""Return the URL for the specified remote"""
config = context.cfg
url = config.get('remote.%s.url' % remote, '')
if push:
url = config.get('remote.%s.pushurl' % remote, url)
return url
def diff_index_filenames(context, ref):
"""
Return a diff of filenames that have been modified relative to the index
"""
git = context.git
out = git.diff_index(ref, name_only=True, z=True, _readonly=True)[STDOUT]
return _parse_diff_filenames(out)
def diff_filenames(context, *args):
"""Return a list of filenames that have been modified"""
out = diff_tree(context, *args)[STDOUT]
return _parse_diff_filenames(out)
def changed_files(context, oid):
"""Return the list of filenames that changed in a given commit oid"""
status, out, _ = diff_tree(context, oid + '~', oid)
if status != 0:
# git init
status, out, _ = diff_tree(context, EMPTY_TREE_OID, oid)
if status == 0:
result = _parse_diff_filenames(out)
else:
result = []
return result
def diff_tree(context, *args):
"""Return a list of filenames that have been modified"""
git = context.git
return git_diff_tree(git, *args)
def git_diff_tree(git, *args):
return git.diff_tree(
name_only=True, no_commit_id=True, r=True, z=True, _readonly=True, *args
)
def listdir(context, dirname, ref='HEAD'):
"""Get the contents of a directory according to Git
Query Git for the content of a directory, taking ignored
files into account.
"""
dirs = []
files = []
# first, parse git ls-tree to get the tracked files
# in a list of (type, path) tuples
entries = ls_tree(context, dirname, ref=ref)
for entry in entries:
if entry[0][0] == 't': # tree
dirs.append(entry[1])
else:
files.append(entry[1])
# gather untracked files
untracked = untracked_files(context, paths=[dirname], directory=True)
for path in untracked:
if path.endswith('/'):
dirs.append(path[:-1])
else:
files.append(path)
dirs.sort()
files.sort()
return (dirs, files)
def diff(context, args):
"""Return a list of filenames for the given diff arguments
:param args: list of arguments to pass to "git diff --name-only"
"""
git = context.git
out = git.diff(name_only=True, z=True, _readonly=True, *args)[STDOUT]
return _parse_diff_filenames(out)
def _parse_diff_filenames(out):
if out:
return out[:-1].split('\0')
return []
def tracked_files(context, *args):
"""Return the names of all files in the repository"""
git = context.git
out = git.ls_files('--', *args, z=True, _readonly=True)[STDOUT]
if out:
return sorted(out[:-1].split('\0'))
return []
def all_files(context, *args):
"""Returns a sorted list of all files, including untracked files."""
git = context.git
ls_files = git.ls_files(
'--',
*args,
z=True,
cached=True,
others=True,
exclude_standard=True,
_readonly=True,
)[STDOUT]
return sorted([f for f in ls_files.split('\0') if f])
class CurrentBranchCache:
"""Cache for current_branch()"""
key = None
value = None
def reset():
"""Reset cached value in this module (e.g. the cached current branch)"""
CurrentBranchCache.key = None
def current_branch(context):
"""Return the current branch"""
git = context.git
head = git.git_path('HEAD')
try:
key = core.stat(head).st_mtime
if CurrentBranchCache.key == key:
return CurrentBranchCache.value
except OSError:
# OSError means we can't use the stat cache
key = 0
status, data, _ = git.rev_parse('HEAD', symbolic_full_name=True, _readonly=True)
if status != 0:
# git init -- read .git/HEAD. We could do this unconditionally...
data = _read_git_head(context, head)
for refs_prefix in ('refs/heads/', 'refs/remotes/', 'refs/tags/'):
if data.startswith(refs_prefix):
value = data[len(refs_prefix) :]
CurrentBranchCache.key = key
CurrentBranchCache.value = value
return value
# Detached head
return data
def _read_git_head(context, head, default='main'):
"""Pure-python .git/HEAD reader"""
# Common .git/HEAD "ref: refs/heads/main" files
git = context.git
islink = core.islink(head)
if core.isfile(head) and not islink:
data = core.read(head).rstrip()
ref_prefix = 'ref: '
if data.startswith(ref_prefix):
return data[len(ref_prefix) :]
# Detached head
return data
# Legacy .git/HEAD symlinks
if islink:
refs_heads = core.realpath(git.git_path('refs', 'heads'))
path = core.abspath(head).replace('\\', '/')
if path.startswith(refs_heads + '/'):
return path[len(refs_heads) + 1 :]
return default
def branch_list(context, remote=False):
"""
Return a list of local or remote branches
This explicitly removes HEAD from the list of remote branches.
"""
if remote:
return for_each_ref_basename(context, 'refs/remotes')
return for_each_ref_basename(context, 'refs/heads')
def _version_sort(context, key='version:refname'):
if version.check_git(context, 'version-sort'):
sort = key
else:
sort = False
return sort
def for_each_ref_basename(context, refs):
"""Return refs starting with 'refs'."""
git = context.git
sort = _version_sort(context)
_, out, _ = git.for_each_ref(refs, format='%(refname)', sort=sort, _readonly=True)
output = out.splitlines()
non_heads = [x for x in output if not x.endswith('/HEAD')]
offset = len(refs) + 1
return [x[offset:] for x in non_heads]
def _prefix_and_size(prefix, values):
"""Return a tuple of (prefix, len(prefix) + 1, y) for <prefix>/ stripping"""
return (prefix, len(prefix) + 1, values)
def all_refs(context, split=False, sort_key='version:refname'):
"""Return a tuple of (local branches, remote branches, tags)."""
git = context.git
local_branches = []
remote_branches = []
tags = []
query = (
_prefix_and_size('refs/tags', tags),
_prefix_and_size('refs/heads', local_branches),
_prefix_and_size('refs/remotes', remote_branches),
)
sort = _version_sort(context, key=sort_key)
_, out, _ = git.for_each_ref(format='%(refname)', sort=sort, _readonly=True)
for ref in out.splitlines():
for prefix, prefix_len, dst in query:
if ref.startswith(prefix) and not ref.endswith('/HEAD'):
dst.append(ref[prefix_len:])
continue
tags.reverse()
if split:
return local_branches, remote_branches, tags
return local_branches + remote_branches + tags
def tracked_branch(context, branch=None):
"""Return the remote branch associated with 'branch'."""
if branch is None:
branch = current_branch(context)
if branch is None:
return None
config = context.cfg
remote = config.get('branch.%s.remote' % branch)
if not remote:
return None
merge_ref = config.get('branch.%s.merge' % branch)
if not merge_ref:
return None
refs_heads = 'refs/heads/'
if merge_ref.startswith(refs_heads):
return remote + '/' + merge_ref[len(refs_heads) :]
return None
def parse_remote_branch(branch):
"""Split a remote branch apart into (remote, name) components"""
rgx = re.compile(r'^(?P<remote>[^/]+)/(?P<branch>.+)$')
match = rgx.match(branch)
remote = ''
branch = ''
if match:
remote = match.group('remote')
branch = match.group('branch')
return (remote, branch)
def untracked_files(context, paths=None, **kwargs):
"""Returns a sorted list of untracked files."""
git = context.git
if paths is None:
paths = []
args = ['--'] + paths
out = git.ls_files(
z=True, others=True, exclude_standard=True, _readonly=True, *args, **kwargs
)[STDOUT]
if out:
return out[:-1].split('\0')
return []
def tag_list(context):
"""Return a list of tags."""
result = for_each_ref_basename(context, 'refs/tags')
result.reverse()
return result
def log(git, *args, **kwargs):
return git.log(
no_color=True,
no_abbrev_commit=True,
no_ext_diff=True,
_readonly=True,
*args,
**kwargs,
)[STDOUT]
def commit_diff(context, oid):
git = context.git
return log(git, '-1', oid, '--') + '\n\n' + oid_diff(context, oid)
_diff_overrides = {}
def update_diff_overrides(space_at_eol, space_change, all_space, function_context):
_diff_overrides['ignore_space_at_eol'] = space_at_eol
_diff_overrides['ignore_space_change'] = space_change
_diff_overrides['ignore_all_space'] = all_space
_diff_overrides['function_context'] = function_context
def common_diff_opts(context):
config = context.cfg
# Default to --patience when diff.algorithm is unset
patience = not config.get('diff.algorithm', default='')
submodule = version.check_git(context, 'diff-submodule')
opts = {
'patience': patience,
'submodule': submodule,
'no_color': True,
'no_ext_diff': True,
'unified': config.get('gui.diffcontext', default=3),
'_raw': True,
'_readonly': True,
}
opts.update(_diff_overrides)
return opts
def _add_filename(args, filename):
if filename:
args.extend(['--', filename])
def oid_diff(context, oid, filename=None):
"""Return the diff for an oid"""
# Naively "$oid^!" is what we'd like to use but that doesn't
# give the correct result for merges--the diff is reversed.
# Be explicit and compare oid against its first parent.
return oid_diff_range(context, oid + '~', oid, filename=filename)
def oid_diff_range(context, start, end, filename=None):
"""Return the diff for a commit range"""
args = [start, end]
git = context.git
opts = common_diff_opts(context)
_add_filename(args, filename)
status, out, _ = git.diff(*args, **opts)
if status != 0:
# We probably don't have "$oid~" because this is the root commit.
# "git show" is clever enough to handle the root commit.
args = [end + '^!']
_add_filename(args, filename)
_, out, _ = git.show(pretty='format:', *args, **opts)
out = out.lstrip()
return out
def diff_info(context, oid, filename=None):
"""Return the diff for the specified oid"""
return diff_range(context, oid + '~', oid, filename=filename)
def diff_range(context, start, end, filename=None):
"""Return the diff for the specified commit range"""
git = context.git
decoded = log(git, '-1', end, '--', pretty='format:%b').strip()
if decoded:
decoded += '\n\n'
return decoded + oid_diff_range(context, start, end, filename=filename)
def diff_helper(
context,
commit=None,
ref=None,
endref=None,
filename=None,
cached=True,
deleted=False,
head=None,
amending=False,
with_diff_header=False,
suppress_header=True,
reverse=False,
untracked=False,
):
"""Invoke git diff on a path"""
git = context.git
cfg = context.cfg
if commit:
ref, endref = commit + '^', commit
argv = []
if ref and endref:
argv.append(f'{ref}..{endref}')
elif ref:
argv.extend(utils.shell_split(ref.strip()))
elif head and amending and cached:
argv.append(head)
encoding = None
if untracked:
argv.append('--no-index')
argv.append(os.devnull)
argv.append(filename)
elif filename:
argv.append('--')
if isinstance(filename, (list, tuple)):
argv.extend(filename)
else:
argv.append(filename)
encoding = cfg.file_encoding(filename)
status, out, _ = git.diff(
R=reverse,
M=True,
cached=cached,
_encoding=encoding,
*argv,
**common_diff_opts(context),
)
success = status == 0
# Diff will return 1 when comparing untracked file and it has change,
# therefore we will check for diff header from output to differentiate
# from actual error such as file not found.
if untracked and status == 1:
try:
_, second, _ = out.split('\n', 2)
except ValueError:
second = ''
success = second.startswith('new file mode ')
if not success:
# git init
if with_diff_header:
return ('', '')
return ''
result = extract_diff_header(deleted, with_diff_header, suppress_header, out)
return core.UStr(result, out.encoding)
def extract_diff_header(deleted, with_diff_header, suppress_header, diffoutput):
"""Split a diff into a header section and payload section"""
if diffoutput.startswith('Submodule'):
if with_diff_header:
return ('', diffoutput)
return diffoutput
start = False
del_tag = 'deleted file mode '
output = StringIO()
headers = StringIO()
for line in diffoutput.split('\n'):
if not start and line[:2] == '@@' and '@@' in line[2:]:
start = True
if start or (deleted and del_tag in line):
output.write(line + '\n')
else:
if with_diff_header:
headers.write(line + '\n')
elif not suppress_header:
output.write(line + '\n')
output_text = output.getvalue()
output.close()
headers_text = headers.getvalue()
headers.close()
if with_diff_header:
return (headers_text, output_text)
return output_text
def format_patchsets(context, to_export, revs, output='patches'):
"""
Group contiguous revision selection into patch sets
Exists to handle multi-selection.
Multiple disparate ranges in the revision selection
are grouped into continuous lists.
"""
outs = []
errs = []
cur_rev = to_export[0]
cur_rev_idx = revs.index(cur_rev)
patches_to_export = [[cur_rev]]
patchset_idx = 0
# Group the patches into continuous sets
for rev in to_export[1:]:
# Limit the search to the current neighborhood for efficiency
try:
rev_idx = revs[cur_rev_idx:].index(rev)
rev_idx += cur_rev_idx
except ValueError:
rev_idx = revs.index(rev)
if rev_idx == cur_rev_idx + 1:
patches_to_export[patchset_idx].append(rev)
cur_rev_idx += 1
else:
patches_to_export.append([rev])
cur_rev_idx = rev_idx
patchset_idx += 1
# Export each patch set
status = 0
for patchset in patches_to_export:
stat, out, err = export_patchset(
context,
patchset[0],
patchset[-1],
output=output,
n=len(patchset) > 1,
thread=True,
patch_with_stat=True,
)
outs.append(out)
if err:
errs.append(err)
status = max(stat, status)
return (status, '\n'.join(outs), '\n'.join(errs))
def export_patchset(context, start, end, output='patches', **kwargs):
"""Export patches from start^ to end."""
git = context.git
return git.format_patch('-o', output, start + '^..' + end, **kwargs)
def reset_paths(context, head, items):
"""Run "git reset" while preventing argument overflow"""
items = list(set(items))
func = context.git.reset
status, out, err = utils.slice_func(items, lambda paths: func(head, '--', *paths))
return (status, out, err)
def unstage_paths(context, args, head='HEAD'):
"""Unstage paths while accounting for git init"""
status, out, err = reset_paths(context, head, args)
if status == 128:
# handle git init: we have to use 'git rm --cached'
# detect this condition by checking if the file is still staged
return untrack_paths(context, args)
return (status, out, err)
def untrack_paths(context, args):
if not args:
return (-1, N_('Nothing to do'), '')
git = context.git
return git.update_index('--', force_remove=True, *set(args))
def worktree_state(
context, head='HEAD', update_index=False, display_untracked=True, paths=None
):
"""Return a dict of files in various states of being
:rtype: dict, keys are staged, unstaged, untracked, unmerged,
changed_upstream, and submodule.
"""
git = context.git
if update_index:
git.update_index(refresh=True)
staged, unmerged, staged_deleted, staged_submods = diff_index(
context, head, paths=paths
)
modified, unstaged_deleted, modified_submods = diff_worktree(context, paths)
if display_untracked:
untracked = untracked_files(context, paths=paths)
else:
untracked = []
# Remove unmerged paths from the modified list
if unmerged:
unmerged_set = set(unmerged)
modified = [path for path in modified if path not in unmerged_set]
# Look for upstream modified files if this is a tracking branch
upstream_changed = diff_upstream(context, head)
# Keep stuff sorted
staged.sort()
modified.sort()
unmerged.sort()
untracked.sort()
upstream_changed.sort()
return {
'staged': staged,
'modified': modified,
'unmerged': unmerged,
'untracked': untracked,
'upstream_changed': upstream_changed,
'staged_deleted': staged_deleted,
'unstaged_deleted': unstaged_deleted,
'submodules': staged_submods | modified_submods,
}
def _parse_raw_diff(out):
while out:
info, path, out = out.split('\0', 2)
status = info[-1]
is_submodule = '160000' in info[1:14]
yield (path, status, is_submodule)
def diff_index(context, head, cached=True, paths=None):
git = context.git
staged = []
unmerged = []
deleted = set()
submodules = set()
if paths is None:
paths = []
args = [head, '--'] + paths
status, out, _ = git.diff_index(cached=cached, z=True, _readonly=True, *args)
if status != 0:
# handle git init
args[0] = EMPTY_TREE_OID
status, out, _ = git.diff_index(cached=cached, z=True, _readonly=True, *args)
for path, status, is_submodule in _parse_raw_diff(out):
if is_submodule:
submodules.add(path)
if status in 'DAMT':
staged.append(path)
if status == 'D':
deleted.add(path)
elif status == 'U':
unmerged.append(path)
return staged, unmerged, deleted, submodules
def diff_worktree(context, paths=None):
git = context.git
ignore_submodules_value = context.cfg.get('diff.ignoresubmodules', 'none')
ignore_submodules = ignore_submodules_value in {'all', 'dirty', 'untracked'}
modified = []
deleted = set()
submodules = set()
if paths is None:
paths = []
args = ['--'] + paths
status, out, _ = git.diff_files(z=True, _readonly=True, *args)
for path, status, is_submodule in _parse_raw_diff(out):
if is_submodule:
submodules.add(path)
if ignore_submodules:
continue
if status in 'DAMT':
modified.append(path)
if status == 'D':
deleted.add(path)
return modified, deleted, submodules
def diff_upstream(context, head):
"""Given `ref`, return $(git merge-base ref HEAD)..ref."""
tracked = tracked_branch(context)
if not tracked:
return []
base = merge_base(context, head, tracked)
return diff_filenames(context, base, tracked)
def list_submodule(context):
"""Return submodules in the format(state, sha_1, path, describe)"""
git = context.git
status, data, _ = git.submodule('status')
ret = []
if status == 0 and data:
data = data.splitlines()
# see git submodule status
for line in data:
state = line[0].strip()
sha1 = line[1 : OID_LENGTH + 1]
left_bracket = line.find('(', OID_LENGTH + 3)
if left_bracket == -1:
left_bracket = len(line) + 1
path = line[OID_LENGTH + 2 : left_bracket - 1]
describe = line[left_bracket + 1 : -1]
ret.append((state, sha1, path, describe))
return ret
def merge_base(context, head, ref):
"""Return the merge-base of head and ref"""
git = context.git
return git.merge_base(head, ref, _readonly=True)[STDOUT]
def merge_base_parent(context, branch):
tracked = tracked_branch(context, branch=branch)
if tracked:
return tracked
return 'HEAD'
def ls_tree(context, path, ref='HEAD'):
"""Return a parsed git ls-tree result for a single directory"""
git = context.git
result = []
status, out, _ = git.ls_tree(
ref, '--', path, z=True, full_tree=True, _readonly=True
)
if status == 0 and out:
path_offset = 6 + 1 + 4 + 1 + OID_LENGTH + 1
for line in out[:-1].split('\0'):
# 1 1 1
# .....6 ...4 ......................................40
# 040000 tree c127cde9a0c644a3a8fef449a244f47d5272dfa6 relative
# 100644 blob 139e42bf4acaa4927ec9be1ec55a252b97d3f1e2 relative/path
# 0..... 7... 12...................................... 53
# path_offset = 6 + 1 + 4 + 1 + OID_LENGTH(40) + 1
objtype = line[7:11]
relpath = line[path_offset:]
result.append((objtype, relpath))
return result
# A regex for matching the output of git(log|rev-list) --pretty=oneline
REV_LIST_REGEX = re.compile(r'^([0-9a-f]{40}) (.*)$')
def parse_rev_list(raw_revs):
"""Parse `git log --pretty=online` output into (oid, summary) pairs."""
revs = []
for line in raw_revs.splitlines():
match = REV_LIST_REGEX.match(line)
if match:
rev_id = match.group(1)
summary = match.group(2)
revs.append((
rev_id,
summary,
))
return revs
def log_helper(context, all=False, extra_args=None):
"""Return parallel arrays containing oids and summaries."""
revs = []
summaries = []
args = []
if extra_args:
args = extra_args
git = context.git
output = log(git, pretty='oneline', all=all, *args)
for line in output.splitlines():
match = REV_LIST_REGEX.match(line)
if match:
revs.append(match.group(1))
summaries.append(match.group(2))
return (revs, summaries)
def rev_list_range(context, start, end):
"""Return (oid, summary) pairs between start and end."""
git = context.git
revrange = f'{start}..{end}'
out = git.rev_list(revrange, pretty='oneline', _readonly=True)[STDOUT]
return parse_rev_list(out)
def commit_message_path(context):
"""Return the path to .git/GIT_COLA_MSG"""
git = context.git
path = git.git_path('GIT_COLA_MSG')
if core.exists(path):
return path
return None
def merge_message_path(context):
"""Return the path to .git/MERGE_MSG or .git/SQUASH_MSG."""
git = context.git
for basename in ('MERGE_MSG', 'SQUASH_MSG'):
path = git.git_path(basename)
if core.exists(path):
return path
return None
def read_merge_commit_message(context, path):
"""Read a merge commit message from disk while stripping commentary"""
content = core.read(path)
cleanup_mode = prefs.commit_cleanup(context)
if cleanup_mode in ('verbatim', 'scissors', 'whitespace'):
return content
comment_char = prefs.comment_char(context)
return '\n'.join(
line for line in content.splitlines() if not line.startswith(comment_char)
)
def prepare_commit_message_hook(context):
"""Run the cola.preparecommitmessagehook to prepare the commit message"""
config = context.cfg
default_hook = config.hooks_path('cola-prepare-commit-msg')
return config.get('cola.preparecommitmessagehook', default=default_hook)
def cherry_pick(context, revs):
"""Cherry-picks each revision into the current branch.
Returns (0, out, err) where stdout and stderr across all "git cherry-pick"
invocations are combined into single values when all cherry-picks succeed.
Returns a combined (status, out, err) of the first failing "git cherry-pick"
in the event of a non-zero exit status.
"""
if not revs:
return []
outs = []
errs = []
status = 0
for rev in revs:
status, out, err = context.git.cherry_pick(rev)
if status != 0:
details = N_(
'Hint: The "Actions > Abort Cherry-Pick" menu action can be used to '
'cancel the current cherry-pick.'
)
output = f'# git cherry-pick {rev}\n# {details}\n\n{out}'
return (status, output, err)
outs.append(out)
errs.append(err)
return (0, '\n'.join(outs), '\n'.join(errs))
def abort_apply_patch(context):
"""Abort a "git am" session."""
# Reset the worktree
git = context.git
status, out, err = git.am(abort=True)
return status, out, err
def abort_cherry_pick(context):
"""Abort a cherry-pick."""
# Reset the worktree
git = context.git
status, out, err = git.cherry_pick(abort=True)
return status, out, err
def abort_merge(context):
"""Abort a merge"""
# Reset the worktree
git = context.git
status, out, err = git.merge(abort=True)
return status, out, err
def strip_remote(remotes, remote_branch):
"""Get branch names with the "<remote>/" prefix removed"""
for remote in remotes:
prefix = remote + '/'
if remote_branch.startswith(prefix):
return remote_branch[len(prefix) :]
return remote_branch.split('/', 1)[-1]
def parse_refs(context, argv):
"""Parse command-line arguments into object IDs"""
git = context.git
status, out, _ = git.rev_parse(_readonly=True, *argv)
if status == 0:
oids = [oid for oid in out.splitlines() if oid]
else:
oids = argv
return oids
def prev_commitmsg(context, *args):
"""Queries git for the latest commit message."""
git = context.git
return git.log(
'-1', no_color=True, pretty='format:%s%n%n%b', _readonly=True, *args
)[STDOUT]
def rev_parse(context, name):
"""Call git rev-parse and return the output"""
git = context.git
status, out, _ = git.rev_parse(name, _readonly=True)
if status == 0:
result = out.strip()
else:
result = name
return result
def write_blob(context, oid, filename):
"""Write a blob to a temporary file and return the path
Modern versions of Git allow invoking filters. Older versions
get the object content as-is.
"""
if version.check_git(context, 'cat-file-filters-path'):
return cat_file_to_path(context, filename, oid)
return cat_file_blob(context, filename, oid)
def cat_file_blob(context, filename, oid):
"""Write a blob from git to the specified filename"""
return cat_file(context, filename, 'blob', oid)
def cat_file_to_path(context, filename, oid):
"""Extract a file from an commit ref and a write it to the specified filename"""
return cat_file(context, filename, oid, path=filename, filters=True)
def cat_file(context, filename, *args, **kwargs):
"""Redirect git cat-file output to a path"""
result = None
git = context.git
# Use the original filename in the suffix so that the generated filename
# has the correct extension, and so that it resembles the original name.
basename = os.path.basename(filename)
suffix = '-' + basename # ensures the correct filename extension
path = utils.tmp_filename('blob', suffix=suffix)
with open(path, 'wb') as tmp_file:
status, out, err = git.cat_file(
_raw=True, _readonly=True, _stdout=tmp_file, *args, **kwargs
)
Interaction.command(N_('Error'), 'git cat-file', status, out, err)
if status == 0:
result = path
if not result:
core.unlink(path)
return result
def write_blob_path(context, head, oid, filename):
"""Use write_blob() when modern git is available"""
if version.check_git(context, 'cat-file-filters-path'):
return write_blob(context, oid, filename)
return cat_file_blob(context, filename, head + ':' + filename)
def annex_path(context, head, filename):
"""Return the git-annex path for a filename at the specified commit"""
git = context.git
path = None
annex_info = {}
# unfortunately there's no way to filter this down to a single path
# so we just have to scan all reported paths
status, out, _ = git.annex('findref', '--json', head, _readonly=True)
if status == 0:
for line in out.splitlines():
info = json.loads(line)
try:
annex_file = info['file']
except (ValueError, KeyError):
continue
# we only care about this file so we can skip the rest
if annex_file == filename:
annex_info = info
break
key = annex_info.get('key', '')
if key:
status, out, _ = git.annex('contentlocation', key, _readonly=True)
if status == 0 and os.path.exists(out):
path = out
return path
def is_binary(context, filename):
"""A heuristic to determine whether `filename` contains (non-text) binary content"""
cfg_is_binary = context.cfg.is_binary(filename)
if cfg_is_binary is not None:
return cfg_is_binary
# This is the same heuristic as xdiff-interface.c:buffer_is_binary().
size = 8000
try:
result = core.read(filename, size=size, encoding='bytes')
except OSError:
result = b''
return b'\0' in result
def is_valid_ref(context, ref):
"""Is the provided Git ref a valid refname?"""
status, _, _ = context.git.rev_parse(ref, quiet=True, verify=True, _readonly=True)
return status == 0
| 31,804 | Python | .py | 862 | 30.219258 | 88 | 0.624947 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
70 | edit-copy.svg | git-cola_git-cola/cola/icons/edit-copy.svg | <svg width="22" height="22" version="1.1" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg"><path d="m14.682 2h-9.8182c-.9 0-1.6364.73636-1.6364 1.6364v11.455h1.6364v-11.455h9.8182zm2.4545 3.2727h-9c-.9 0-1.6364.73636-1.6364 1.6364v11.455c0 .9.73636 1.6364 1.6364 1.6364h9c.9 0 1.6364-.73636 1.6364-1.6364v-11.455c0-.9-.73636-1.6364-1.6364-1.6364zm0 13.091h-9v-11.455h9z" style="stroke-width:.81818"/></svg>
| 413 | Python | .py | 1 | 412 | 412 | 0.708738 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
71 | edit-copy.svg | git-cola_git-cola/cola/icons/dark/edit-copy.svg | <svg width="22" height="22" version="1.1" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg"><path d="m14.682 2h-9.8182c-.9 0-1.6364.73636-1.6364 1.6364v11.455h1.6364v-11.455h9.8182zm2.4545 3.2727h-9c-.9 0-1.6364.73636-1.6364 1.6364v11.455c0 .9.73636 1.6364 1.6364 1.6364h9c.9 0 1.6364-.73636 1.6364-1.6364v-11.455c0-.9-.73636-1.6364-1.6364-1.6364zm0 13.091h-9v-11.455h9z" style="stroke-width:.81818;fill:#ffffff"/></svg>
| 426 | Python | .py | 1 | 425 | 425 | 0.710588 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
72 | about.py | git-cola_git-cola/cola/widgets/about.py | import platform
import webbrowser
import os
import sys
import qtpy
from qtpy import QtCore
from qtpy.QtCore import Qt
from qtpy import QtGui
from qtpy import QtWidgets
from ..i18n import N_
from .. import resources
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import utils
from .. import version
from . import defs
def about_dialog(context):
"""Launches the Help -> About dialog"""
view = AboutView(context, qtutils.active_window())
view.show()
return view
class ExpandingTabBar(QtWidgets.QTabBar):
"""A TabBar with tabs that expand to fill the empty space
The setExpanding(True) method does not work in practice because
it respects the OS style. We override the style by implementing
tabSizeHint() so that we can specify the size explicitly.
"""
def tabSizeHint(self, tab_index):
width = self.parent().width() // max(2, self.count()) - 1
size = super().tabSizeHint(tab_index)
size.setWidth(width)
return size
class ExpandingTabWidget(QtWidgets.QTabWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setTabBar(ExpandingTabBar(self))
def resizeEvent(self, event):
"""Forward resize events to the ExpandingTabBar"""
# Qt does not resize the tab bar when the dialog is resized
# so manually forward resize events to the tab bar.
width = event.size().width()
height = self.tabBar().height()
self.tabBar().resize(width, height)
return super().resizeEvent(event)
class AboutView(QtWidgets.QDialog):
"""Provides the git-cola 'About' dialog"""
def __init__(self, context, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.context = context
self.setWindowTitle(N_('About git-cola'))
self.setWindowModality(Qt.WindowModal)
# Top-most large icon
logo_pixmap = icons.cola().pixmap(defs.huge_icon, defs.large_icon)
self.logo_label = QtWidgets.QLabel()
self.logo_label.setPixmap(logo_pixmap)
self.logo_label.setAlignment(Qt.AlignCenter)
self.logo_text_label = QtWidgets.QLabel()
self.logo_text_label.setText('Git Cola')
self.logo_text_label.setAlignment(Qt.AlignLeft | Qt.AlignCenter)
font = self.logo_text_label.font()
font.setPointSize(defs.logo_text)
self.logo_text_label.setFont(font)
self.text = qtutils.textbrowser(text=copyright_text())
self.version = qtutils.textbrowser(text=version_text(context))
self.authors = qtutils.textbrowser(text=authors_text())
self.translators = qtutils.textbrowser(text=translators_text())
self.tabs = ExpandingTabWidget()
self.tabs.addTab(self.text, N_('About'))
self.tabs.addTab(self.version, N_('Version'))
self.tabs.addTab(self.authors, N_('Authors'))
self.tabs.addTab(self.translators, N_('Translators'))
self.close_button = qtutils.close_button()
self.close_button.setDefault(True)
self.logo_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.logo_label,
self.logo_text_label,
qtutils.STRETCH,
)
self.button_layout = qtutils.hbox(
defs.spacing, defs.margin, qtutils.STRETCH, self.close_button
)
self.main_layout = qtutils.vbox(
defs.no_margin,
defs.spacing,
self.logo_layout,
self.tabs,
self.button_layout,
)
self.setLayout(self.main_layout)
qtutils.connect_button(self.close_button, self.accept)
self.resize(defs.scale(600), defs.scale(720))
def copyright_text():
return """
Git Cola: The highly caffeinated Git GUI
Copyright (C) 2007-2024 David Aguilar and contributors
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the
GNU General Public License along with this program.
If not, see http://www.gnu.org/licenses/.
"""
def version_text(context):
git_version = version.git_version(context)
cola_version = version.version()
python_path = sys.executable
python_version = sys.version
qt_version = qtpy.QT_VERSION
qtpy_version = qtpy.__version__
pyqt_api_name = qtpy.API_NAME
if (
getattr(qtpy, 'PYQT6', False)
or getattr(qtpy, 'PYQT5', False)
or getattr(qtpy, 'PYQT4', False)
):
pyqt_api_version = qtpy.PYQT_VERSION
elif qtpy.PYSIDE:
pyqt_api_version = qtpy.PYSIDE_VERSION
else:
pyqt_api_version = 'unknown'
platform_version = platform.platform()
scope = dict(
cola_version=cola_version,
git_version=git_version,
platform_version=platform_version,
pyqt_api_name=pyqt_api_name,
pyqt_api_version=pyqt_api_version,
python_path=python_path,
python_version=python_version,
qt_version=qt_version,
qtpy_version=qtpy_version,
)
return (
N_(
"""
<br>
Git Cola version %(cola_version)s
<ul>
<li> %(platform_version)s
<li> Python (%(python_path)s) %(python_version)s
<li> Git %(git_version)s
<li> Qt %(qt_version)s
<li> QtPy %(qtpy_version)s
<li> %(pyqt_api_name)s %(pyqt_api_version)s
</ul>
"""
)
% scope
)
def mailto(email, text, palette):
return qtutils.link('mailto:%s' % email, text, palette) + '<br>'
def render_authors(authors):
"""Render a list of author details into rich text html"""
for x in authors:
x.setdefault('email', '')
entries = [
(
"""
<p>
<strong>%(name)s</strong><br>
<em>%(title)s</em><br>
%(email)s
</p>
"""
% author
)
for author in authors
]
return ''.join(entries)
def contributors_text(authors, prelude='', epilogue=''):
author_text = render_authors(authors)
scope = dict(author_text=author_text, epilogue=epilogue, prelude=prelude)
return (
"""
%(prelude)s
%(author_text)s
%(epilogue)s
"""
% scope
)
def authors_text():
palette = QtGui.QPalette()
contact = N_('Email contributor')
authors = (
# The names listed here are listed in the same order as
# `git shortlog --summary --numbered --no-merges`
# Please submit a pull request if you would like to include your
# email address in the about screen.
# See the `generate-about` script in the "todo" branch.
# vim :read! ./todo/generate-about
dict(
name='David Aguilar',
title=N_('Maintainer (since 2007) and developer'),
email=mailto('[email protected]', contact, palette),
),
dict(name='Daniel Harding', title=N_('Developer')),
dict(name='Efimov Vasily', title=N_('Developer')),
dict(
name='V字龍(Vdragon)',
title=N_('Developer'),
email=mailto('[email protected]', contact, palette),
),
dict(name='Kurt McKee', title=N_('Developer')),
dict(name='Guillaume de Bure', title=N_('Developer')),
dict(name='Javier Rodriguez Cuevas', title=N_('Developer')),
dict(name='Uri Okrent', title=N_('Developer')),
dict(name='Alex Chernetz', title=N_('Developer')),
dict(name='xhl', title=N_('Developer')),
dict(name='Ville Skyttä', title=N_('Developer')),
dict(name='Thomas Kluyver', title=N_('Developer')),
dict(name='Andreas Sommer', title=N_('Developer')),
dict(name='nakanoi', title=N_('Developer')),
dict(name='Szymon Judasz', title=N_('Developer')),
dict(name='Minarto Margoliono', title=N_('Developer')),
dict(name='Stanislaw Halik', title=N_('Developer')),
dict(name='jm4R', title=N_('Developer')),
dict(name='Igor Galarraga', title=N_('Developer')),
dict(name='Luke Horwell', title=N_('Developer')),
dict(name='Virgil Dupras', title=N_('Developer')),
dict(name='Barry Roberts', title=N_('Developer')),
dict(name='wsdfhjxc', title=N_('Developer')),
dict(name='Guo Yunhe', title=N_('Developer')),
dict(name='malpas', title=N_('Developer')),
dict(name='林博仁(Buo-ren Lin)', title=N_('Developer')),
dict(name='Matthias Mailänder', title=N_('Developer')),
dict(name='cclauss', title=N_('Developer')),
dict(name='Benjamin Somers', title=N_('Developer')),
dict(name='Max Harmathy', title=N_('Developer')),
dict(name='Stefan Naewe', title=N_('Developer')),
dict(name='Victor Nepveu', title=N_('Developer')),
dict(name='Benedict Lee', title=N_('Developer')),
dict(name='Filip Danilović', title=N_('Developer')),
dict(name='Nanda Lopes', title=N_('Developer')),
dict(name='NotSqrt', title=N_('Developer')),
dict(name='Pavel Rehak', title=N_('Developer')),
dict(name='Steffen Prohaska', title=N_('Developer')),
dict(name='Thomas Kiley', title=N_('Developer')),
dict(name='Tim Brown', title=N_('Developer')),
dict(name='Chris Stefano', title=N_('Developer')),
dict(name='Floris Lambrechts', title=N_('Developer')),
dict(name='Martin Gysel', title=N_('Developer')),
dict(name='Michael Geddes', title=N_('Developer')),
dict(name='Rustam Safin', title=N_('Developer')),
dict(name='abid1998', title=N_('Developer')),
dict(name='Alex Gulyás', title=N_('Developer')),
dict(name='David Martínez Martí', title=N_('Developer')),
dict(name='Hualiang Xie', title=N_('Developer')),
dict(name='Justin Lecher', title=N_('Developer')),
dict(name='Kai Krakow', title=N_('Developer')),
dict(name='Karl Bielefeldt', title=N_('Developer')),
dict(name='Marco Costalba', title=N_('Developer')),
dict(name='Michael Baumgartner', title=N_('Developer')),
dict(name='Michael Homer', title=N_('Developer')),
dict(name='Mithil Poojary', title=N_('Developer')),
dict(name='Sven Claussner', title=N_('Developer')),
dict(name='Victor Gambier', title=N_('Developer')),
dict(name='bsomers', title=N_('Developer')),
dict(name='mmargoliono', title=N_('Developer')),
dict(name='v.paritskiy', title=N_('Developer')),
dict(name='vanderkoort', title=N_('Developer')),
dict(name='wm4', title=N_('Developer')),
dict(name='0xflotus', title=N_('Developer')),
dict(name='AJ Bagwell', title=N_('Developer')),
dict(name='Adrien be', title=N_('Developer')),
dict(name='Alexander Preißner', title=N_('Developer')),
dict(name='Andrej', title=N_('Developer')),
dict(name='Arthur Coelho', title=N_('Developer')),
dict(name='Audrius Karabanovas', title=N_('Developer')),
dict(name='Axel Heider', title=N_('Developer')),
dict(name='Barrett Lowe', title=N_('Developer')),
dict(name='Ben Boeckel', title=N_('Developer')),
dict(name='Bob van der Linden', title=N_('Developer')),
dict(name='Boerje Sewing', title=N_('Developer')),
dict(name='Boris W', title=N_('Developer')),
dict(name='Bruno Cabral', title=N_('Developer')),
dict(name='Charles', title=N_('Developer')),
dict(name='Christoph Erhardt', title=N_('Developer')),
dict(name='Clément Pit--Claudel', title=N_('Developer')),
dict(name='Daniel Haskin', title=N_('Developer')),
dict(name='Daniel King', title=N_('Developer')),
dict(name='Daniel Pavel', title=N_('Developer')),
dict(name='DasaniT', title=N_('Developer')),
dict(name='Dave Cottlehuber', title=N_('Developer')),
dict(name='David Schwörer', title=N_('Developer')),
dict(name='David Zumbrunnen', title=N_('Developer')),
dict(name='George Vasilakos', title=N_('Developer')),
dict(name='Ilya Tumaykin', title=N_('Developer')),
dict(name='Iulian Udrea', title=N_('Developer')),
dict(name='Jake Biesinger', title=N_('Developer')),
dict(name='Jakub Szymański', title=N_('Developer')),
dict(name='Jamie Pate', title=N_('Developer')),
dict(name='Jean-Francois Dagenais', title=N_('Developer')),
dict(name='Joachim Lusiardi', title=N_('Developer')),
dict(name='Karthik Manamcheri', title=N_('Developer')),
dict(name='Kelvie Wong', title=N_('Developer')),
dict(name='Klaas Neirinck', title=N_('Developer')),
dict(name='Kyle', title=N_('Developer')),
dict(name='Laszlo Boszormenyi (GCS)', title=N_('Developer')),
dict(name='Maciej Filipiak', title=N_('Developer')),
dict(name='Maicon D. Filippsen', title=N_('Developer')),
dict(name='Markus Heidelberg', title=N_('Developer')),
dict(name='Matthew E. Levine', title=N_('Developer')),
dict(name='Md. Mahbub Alam', title=N_('Developer')),
dict(name='Mikhail Terekhov', title=N_('Developer')),
dict(name='Niel Buys', title=N_('Developer')),
dict(name='Ori shalhon', title=N_('Developer')),
dict(name='Paul Hildebrandt', title=N_('Developer')),
dict(name='Paul Weingardt', title=N_('Developer')),
dict(name='Paulo Fidalgo', title=N_('Developer')),
dict(name='Petr Gladkikh', title=N_('Developer')),
dict(name='Philip Stark', title=N_('Developer')),
dict(name='Radek Postołowicz', title=N_('Developer')),
dict(name='Rainer Müller', title=N_('Developer')),
dict(name='Ricardo J. Barberis', title=N_('Developer')),
dict(name='Rolando Espinoza', title=N_('Developer')),
dict(name="Samsul Ma'arif", title=N_('Developer')),
dict(name='Sebastian Brass', title=N_('Developer')),
dict(name='Sergei Dyshel', title=N_('Developer')),
dict(name='Simon Peeters', title=N_('Developer')),
dict(name='Stephen', title=N_('Developer')),
dict(name='Tim Gates', title=N_('Developer')),
dict(name='Vaibhav Sagar', title=N_('Developer')),
dict(name='Ved Vyas', title=N_('Developer')),
dict(name='VishnuSanal', title=N_('Developer')),
dict(name='Voicu Hodrea', title=N_('Developer')),
dict(name='WNguyen14', title=N_('Developer')),
dict(name='Wesley Wong', title=N_('Developer')),
dict(name='Wolfgang Ocker', title=N_('Developer')),
dict(name='Zhang Han', title=N_('Developer')),
dict(name='beauxq', title=N_('Developer')),
dict(name='bensmrs', title=N_('Developer')),
dict(name='lcjh', title=N_('Developer')),
dict(name='lefairy', title=N_('Developer')),
dict(name='melkecelioglu', title=N_('Developer')),
dict(name='ochristi', title=N_('Developer')),
dict(name='yael levi', title=N_('Developer')),
dict(name='Łukasz Wojniłowicz', title=N_('Developer')),
)
bug_url = 'https://github.com/git-cola/git-cola/issues'
bug_link = qtutils.link(bug_url, bug_url)
scope = dict(bug_link=bug_link)
prelude = (
N_(
"""
<br>
Please use %(bug_link)s to report issues.
<br>
"""
)
% scope
)
return contributors_text(authors, prelude=prelude)
def translators_text():
palette = QtGui.QPalette()
contact = N_('Email contributor')
translators = (
# See the `generate-about` script in the "todo" branch.
# vim :read! ./todo/generate-about --translators
dict(
name='V字龍(Vdragon)',
title=N_('Traditional Chinese (Taiwan) translation'),
email=mailto('[email protected]', contact, palette),
),
dict(name='Pavel Rehak', title=N_('Czech translation')),
dict(name='Victorhck', title=N_('Spanish translation')),
dict(name='Vitor Lobo', title=N_('Brazilian translation')),
dict(name='Zhang Han', title=N_('Simplified Chinese translation')),
dict(name='Łukasz Wojniłowicz', title=N_('Polish translation')),
dict(name='Igor Kopach', title=N_('Ukranian translation')),
dict(name='Gyuris Gellért', title=N_('Hungarian translation')),
dict(name='fu7mu4', title=N_('Japanese translation')),
dict(name='Barış ÇELİK', title=N_('Turkish translation')),
dict(name='Guo Yunhe', title=N_('Simplified Chinese translation')),
dict(name='Luke Horwell', title=N_('Translation')),
dict(name='Minarto Margoliono', title=N_('Indonesian translation')),
dict(name='Rafael Nascimento', title=N_('Brazilian translation')),
dict(name='Rafael Reuber', title=N_('Brazilian translation')),
dict(name='Shun Sakai', title=N_('Japanese translation')),
dict(name='Sven Claussner', title=N_('German translation')),
dict(name='Vaiz', title=N_('Russian translation')),
dict(name='adlgrbz', title=N_('Turkish translation')),
dict(name='Balázs Meskó', title=N_('Translation')),
dict(name='Joachim Lusiardi', title=N_('German translation')),
dict(name='Kai Krakow', title=N_('German translation')),
dict(name='Louis Rousseau', title=N_('French translation')),
dict(name='Mickael Albertus', title=N_('French translation')),
dict(
name='Peter Dave Hello',
title=N_('Traditional Chinese (Taiwan) translation'),
),
dict(name='Pilar Molina Lopez', title=N_('Spanish translation')),
dict(name='Sabri Ünal', title=N_('Turkish translation')),
dict(name="Samsul Ma'arif", title=N_('Indonesian translation')),
dict(name='YAMAMOTO Kenyu', title=N_('Translation')),
dict(name='Zeioth', title=N_('Spanish translation')),
dict(name='balping', title=N_('Hungarian translation')),
dict(name='p-bo', title=N_('Czech translation')),
dict(
name='林博仁(Buo-ren Lin)',
title=N_('Traditional Chinese (Taiwan) translation'),
),
)
bug_url = 'https://github.com/git-cola/git-cola/issues'
bug_link = qtutils.link(bug_url, bug_url)
scope = dict(bug_link=bug_link)
prelude = (
N_(
"""
<br>
Git Cola has been translated into different languages thanks
to the help of the individuals listed below.
<br>
<p>
Translation is approximate. If you find a mistake,
please let us know by opening an issue on Github:
</p>
<p>
%(bug_link)s
</p>
<br>
<p>
We invite you to participate in translation by adding or updating
a translation and opening a pull request.
</p>
<br>
"""
)
% scope
)
return contributors_text(translators, prelude=prelude)
def show_shortcuts():
hotkeys_html = resources.data_path(N_('hotkeys.html'))
if utils.is_win32():
hotkeys_url = 'file:///' + hotkeys_html.replace('\\', '/')
else:
hotkeys_url = 'file://' + hotkeys_html
if not os.path.isfile(hotkeys_html):
hotkeys_url = 'https://git-cola.gitlab.io/share/doc/git-cola/hotkeys.html'
try:
from qtpy import QtWebEngineWidgets
except (ImportError, qtpy.PythonQtError):
# Redhat disabled QtWebKit in their Qt build but don't punish the users
webbrowser.open_new_tab(hotkeys_url)
return
parent = qtutils.active_window()
widget = QtWidgets.QDialog(parent)
widget.setWindowModality(Qt.WindowModal)
widget.setWindowTitle(N_('Shortcuts'))
web = QtWebEngineWidgets.QWebEngineView()
web.setUrl(QtCore.QUrl(hotkeys_url))
layout = qtutils.hbox(defs.no_margin, defs.spacing, web)
widget.setLayout(layout)
widget.resize(800, min(parent.height(), 600))
qtutils.add_action(
widget, N_('Close'), widget.accept, hotkeys.QUESTION, *hotkeys.ACCEPT
)
widget.show()
widget.exec_()
| 20,603 | Python | .py | 466 | 36.038627 | 82 | 0.61787 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
73 | bookmarks.py | git-cola_git-cola/cola/widgets/bookmarks.py | """Provides widgets related to bookmarks"""
import os
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from .. import cmds
from .. import core
from .. import git
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import utils
from ..i18n import N_
from ..interaction import Interaction
from ..models import prefs
from ..widgets import defs
from ..widgets import standard
from ..widgets import switcher
BOOKMARKS = 0
RECENT_REPOS = 1
def bookmark(context, parent):
return BookmarksWidget(context, BOOKMARKS, parent=parent)
def recent(context, parent):
return BookmarksWidget(context, RECENT_REPOS, parent=parent)
class BookmarksWidget(QtWidgets.QFrame):
def __init__(self, context, style=BOOKMARKS, parent=None):
QtWidgets.QFrame.__init__(self, parent)
self.context = context
self.style = style
self.items = items = []
self.model = model = QtGui.QStandardItemModel()
settings = context.settings
builder = BuildItem(context)
# bookmarks
if self.style == BOOKMARKS:
entries = settings.bookmarks
# recent items
elif self.style == RECENT_REPOS:
entries = settings.recent
for entry in entries:
item = builder.get(entry['path'], entry['name'])
items.append(item)
model.appendRow(item)
place_holder = N_('Search repositories by name...')
self.quick_switcher = switcher.switcher_outer_view(
context, model, place_holder=place_holder
)
self.tree = BookmarksTreeView(
context, style, self.set_items_to_models, parent=self
)
self.add_button = qtutils.create_action_button(
tooltip=N_('Add'), icon=icons.add()
)
self.delete_button = qtutils.create_action_button(
tooltip=N_('Delete'), icon=icons.remove()
)
self.open_button = qtutils.create_action_button(
tooltip=N_('Open'), icon=icons.repo()
)
self.search_button = qtutils.create_action_button(
tooltip=N_('Search'), icon=icons.search()
)
self.button_group = utils.Group(self.delete_button, self.open_button)
self.button_group.setEnabled(False)
self.setFocusProxy(self.tree)
if style == BOOKMARKS:
self.setToolTip(N_('Favorite repositories'))
elif style == RECENT_REPOS:
self.setToolTip(N_('Recent repositories'))
self.add_button.hide()
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.search_button,
self.open_button,
self.add_button,
self.delete_button,
)
self.main_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.quick_switcher, self.tree
)
self.setLayout(self.main_layout)
self.corner_widget = QtWidgets.QWidget(self)
self.corner_widget.setLayout(self.button_layout)
titlebar = parent.titleBarWidget()
titlebar.add_corner_widget(self.corner_widget)
qtutils.connect_button(self.add_button, self.tree.add_bookmark)
qtutils.connect_button(self.delete_button, self.tree.delete_bookmark)
qtutils.connect_button(self.open_button, self.tree.open_repo)
qtutils.connect_button(self.search_button, self.toggle_switcher_input_field)
QtCore.QTimer.singleShot(0, self.reload_bookmarks)
self.tree.toggle_switcher.connect(self.enable_switcher_input_field)
# moving key has pressed while focusing on input field
self.quick_switcher.filter_input.switcher_selection_move.connect(
self.tree.keyPressEvent
)
# escape key has pressed while focusing on input field
self.quick_switcher.filter_input.switcher_escape.connect(
self.close_switcher_input_field
)
# some key except moving key has pressed while focusing on list view
self.tree.switcher_text.connect(self.switcher_text_inputted)
def reload_bookmarks(self):
# Called once after the GUI is initialized
tree = self.tree
tree.refresh()
model = tree.model()
model.dataChanged.connect(tree.item_changed)
selection = tree.selectionModel()
selection.selectionChanged.connect(tree.item_selection_changed)
tree.doubleClicked.connect(tree.tree_double_clicked)
def tree_item_selection_changed(self):
enabled = bool(self.tree.selected_item())
self.button_group.setEnabled(enabled)
def connect_to(self, other):
self.tree.default_changed.connect(other.tree.refresh)
other.tree.default_changed.connect(self.tree.refresh)
def set_items_to_models(self, items):
model = self.model
self.items.clear()
model.clear()
for item in items:
self.items.append(item)
model.appendRow(item)
self.quick_switcher.proxy_model.setSourceModel(model)
self.tree.setModel(self.quick_switcher.proxy_model)
def toggle_switcher_input_field(self):
visible = self.quick_switcher.filter_input.isVisible()
self.enable_switcher_input_field(not visible)
def close_switcher_input_field(self):
self.enable_switcher_input_field(False)
def enable_switcher_input_field(self, visible):
filter_input = self.quick_switcher.filter_input
filter_input.setVisible(visible)
if not visible:
filter_input.clear()
def switcher_text_inputted(self, event):
# default selection for first index
first_proxy_idx = self.quick_switcher.proxy_model.index(0, 0)
self.tree.setCurrentIndex(first_proxy_idx)
self.quick_switcher.filter_input.keyPressEvent(event)
def disable_rename(_path, _name, _new_name):
return False
class BookmarksTreeView(standard.TreeView):
default_changed = Signal()
toggle_switcher = Signal(bool)
# this signal will be emitted when some key pressed while focusing on tree view
switcher_text = Signal(QtGui.QKeyEvent)
def __init__(self, context, style, set_model, parent=None):
standard.TreeView.__init__(self, parent=parent)
self.context = context
self.style = style
self.set_model = set_model
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setHeaderHidden(True)
# We make the items editable, but we don't want the double-click
# behavior to trigger editing. Make it behave like Mac OS X's Finder.
self.setEditTriggers(self.__class__.SelectedClicked)
self.open_action = qtutils.add_action(
self, N_('Open'), self.open_repo, hotkeys.OPEN
)
self.accept_action = qtutils.add_action(
self, N_('Accept'), self.accept_repo, *hotkeys.ACCEPT
)
self.open_new_action = qtutils.add_action(
self, N_('Open in New Window'), self.open_new_repo, hotkeys.NEW
)
self.set_default_repo_action = qtutils.add_action(
self, N_('Set Default Repository'), self.set_default_repo
)
self.clear_default_repo_action = qtutils.add_action(
self, N_('Clear Default Repository'), self.clear_default_repo
)
self.rename_repo_action = qtutils.add_action(
self, N_('Rename Repository'), self.rename_repo
)
self.open_default_action = qtutils.add_action(
self, cmds.OpenDefaultApp.name(), self.open_default, hotkeys.PRIMARY_ACTION
)
self.launch_editor_action = qtutils.add_action(
self, cmds.Edit.name(), self.launch_editor, hotkeys.EDIT
)
self.launch_terminal_action = qtutils.add_action(
self, cmds.LaunchTerminal.name(), self.launch_terminal, hotkeys.TERMINAL
)
self.copy_action = qtutils.add_action(self, N_('Copy'), self.copy, hotkeys.COPY)
self.delete_action = qtutils.add_action(
self, N_('Delete'), self.delete_bookmark
)
self.remove_missing_action = qtutils.add_action(
self, N_('Prune Missing Entries'), self.remove_missing
)
self.remove_missing_action.setToolTip(
N_('Remove stale entries for repositories that no longer exist')
)
self.action_group = utils.Group(
self.open_action,
self.open_new_action,
self.copy_action,
self.launch_editor_action,
self.launch_terminal_action,
self.open_default_action,
self.rename_repo_action,
self.delete_action,
)
self.action_group.setEnabled(False)
self.set_default_repo_action.setEnabled(False)
self.clear_default_repo_action.setEnabled(False)
# Connections
if style == RECENT_REPOS:
context.model.worktree_changed.connect(
self.refresh, type=Qt.QueuedConnection
)
def keyPressEvent(self, event):
"""
This will be hooked while focusing on this list view.
Set input field invisible when escape key pressed.
Move selection when move key like tab, UP etc pressed.
Or open input field and simply act like text input to it. This is when
some character key pressed while focusing on tree view, NOT input field.
"""
selection_moving_keys = switcher.moving_keys()
pressed_key = event.key()
if pressed_key == Qt.Key_Escape:
self.toggle_switcher.emit(False)
elif pressed_key in hotkeys.ACCEPT:
self.accept_repo()
elif pressed_key in selection_moving_keys:
super().keyPressEvent(event)
else:
self.toggle_switcher.emit(True)
self.switcher_text.emit(event)
def refresh(self):
context = self.context
settings = context.settings
builder = BuildItem(context)
# bookmarks
if self.style == BOOKMARKS:
entries = settings.bookmarks
# recent items
elif self.style == RECENT_REPOS:
entries = settings.recent
items = [builder.get(entry['path'], entry['name']) for entry in entries]
if self.style == BOOKMARKS and prefs.sort_bookmarks(context):
items.sort(key=lambda x: x.name.lower())
self.set_model(items)
def contextMenuEvent(self, event):
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.open_action)
menu.addAction(self.open_new_action)
menu.addAction(self.open_default_action)
menu.addSeparator()
menu.addAction(self.copy_action)
menu.addAction(self.launch_editor_action)
menu.addAction(self.launch_terminal_action)
menu.addSeparator()
item = self.selected_item()
is_default = bool(item and item.is_default)
if is_default:
menu.addAction(self.clear_default_repo_action)
else:
menu.addAction(self.set_default_repo_action)
menu.addAction(self.rename_repo_action)
menu.addSeparator()
menu.addAction(self.delete_action)
menu.addAction(self.remove_missing_action)
menu.exec_(self.mapToGlobal(event.pos()))
def item_selection_changed(self, selected, _deselected):
item_idx = selected.indexes()
if item_idx:
item = self.model().itemFromIndex(item_idx[0])
enabled = bool(item)
self.action_group.setEnabled(enabled)
is_default = bool(item and item.is_default)
self.set_default_repo_action.setEnabled(not is_default)
self.clear_default_repo_action.setEnabled(is_default)
def tree_double_clicked(self, _index):
context = self.context
item = self.selected_item()
cmds.do(cmds.OpenRepo, context, item.path)
self.toggle_switcher.emit(False)
def selected_item(self):
index = self.currentIndex()
return self.model().itemFromIndex(index)
def item_changed(self, _top_left, _bottom_right, _roles):
item = self.selected_item()
self.rename_entry(item, item.text())
def rename_entry(self, item, new_name):
settings = self.context.settings
if self.style == BOOKMARKS:
rename = settings.rename_bookmark
elif self.style == RECENT_REPOS:
rename = settings.rename_recent
else:
rename = disable_rename
if rename(item.path, item.name, new_name):
settings.save()
item.name = new_name
else:
item.setText(item.name)
self.toggle_switcher.emit(False)
def apply_func(self, func, *args, **kwargs):
item = self.selected_item()
if item:
func(item, *args, **kwargs)
def copy(self):
self.apply_func(lambda item: qtutils.set_clipboard(item.path))
self.toggle_switcher.emit(False)
def open_default(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.OpenDefaultApp, context, [item.path]))
self.toggle_switcher.emit(False)
def set_default_repo(self):
self.apply_func(self.set_default_item)
self.toggle_switcher.emit(False)
def set_default_item(self, item):
context = self.context
cmds.do(cmds.SetDefaultRepo, context, item.path)
self.refresh()
self.default_changed.emit()
self.toggle_switcher.emit(False)
def clear_default_repo(self):
self.apply_func(self.clear_default_item)
self.default_changed.emit()
self.toggle_switcher.emit(False)
def clear_default_item(self, _item):
context = self.context
cmds.do(cmds.SetDefaultRepo, context, None)
self.refresh()
self.toggle_switcher.emit(False)
def rename_repo(self):
index = self.currentIndex()
self.edit(index)
self.toggle_switcher.emit(False)
def accept_repo(self):
self.apply_func(self.accept_item)
self.toggle_switcher.emit(False)
def accept_item(self, _item):
if self.state() & self.EditingState:
current_index = self.currentIndex()
widget = self.indexWidget(current_index)
if widget:
self.commitData(widget)
self.closePersistentEditor(current_index)
self.refresh()
else:
self.open_selected_repo()
def open_repo(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.OpenRepo, context, item.path))
def open_selected_repo(self):
item = self.selected_item()
context = self.context
cmds.do(cmds.OpenRepo, context, item.path)
self.toggle_switcher.emit(False)
def open_new_repo(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.OpenNewRepo, context, item.path))
self.toggle_switcher.emit(False)
def launch_editor(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.Edit, context, [item.path]))
self.toggle_switcher.emit(False)
def launch_terminal(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.LaunchTerminal, context, item.path))
self.toggle_switcher.emit(False)
def add_bookmark(self):
normpath = utils.expandpath(core.getcwd())
name = os.path.basename(normpath)
prompt = (
(N_('Name'), name),
(N_('Path'), core.getcwd()),
)
ok, values = qtutils.prompt_n(N_('Add Favorite'), prompt)
if not ok:
return
name, path = values
normpath = utils.expandpath(path)
if git.is_git_worktree(normpath):
settings = self.context.settings
settings.load()
settings.add_bookmark(normpath, name)
settings.save()
self.refresh()
else:
Interaction.critical(N_('Error'), N_('%s is not a Git repository.') % path)
def delete_bookmark(self):
"""Removes a bookmark from the bookmarks list"""
item = self.selected_item()
context = self.context
if not item:
return
if self.style == BOOKMARKS:
cmd = cmds.RemoveBookmark
elif self.style == RECENT_REPOS:
cmd = cmds.RemoveRecent
else:
return
ok, _, _, _ = cmds.do(cmd, context, item.path, item.name, icon=icons.discard())
if ok:
self.refresh()
self.toggle_switcher.emit(False)
def remove_missing(self):
"""Remove missing entries from the favorites/recent file list"""
settings = self.context.settings
if self.style == BOOKMARKS:
settings.remove_missing_bookmarks()
elif self.style == RECENT_REPOS:
settings.remove_missing_recent()
self.refresh()
class BuildItem:
def __init__(self, context):
self.star_icon = icons.star()
self.folder_icon = icons.folder()
cfg = context.cfg
self.default_repo = cfg.get('cola.defaultrepo')
def get(self, path, name):
is_default = self.default_repo == path
if is_default:
icon = self.star_icon
else:
icon = self.folder_icon
return BookmarksTreeItem(path, name, icon, is_default)
class BookmarksTreeItem(switcher.SwitcherListItem):
def __init__(self, path, name, icon, is_default):
switcher.SwitcherListItem.__init__(self, name, icon=icon, name=name)
self.path = path
self.name = name
self.is_default = is_default
self.setIcon(icon)
self.setText(name)
self.setToolTip(path)
self.setFlags(self.flags() | Qt.ItemIsEditable)
| 18,050 | Python | .py | 436 | 32.215596 | 88 | 0.638518 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
74 | browse.py | git-cola_git-cola/cola/widgets/browse.py | import shlex
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from ..models.browse import GitRepoModel
from ..models.browse import GitRepoNameItem
from ..models.selection import State
from ..i18n import N_
from ..interaction import Interaction
from .. import cmds
from .. import core
from .. import difftool
from .. import gitcmds
from .. import hotkeys
from .. import icons
from .. import utils
from .. import qtutils
from .selectcommits import select_commits
from . import common
from . import defs
from . import standard
def worktree_browser(context, parent=None, update=True, show=True):
"""Create a new worktree browser"""
view = Browser(context, parent, update=update)
if parent is None:
context.browser_windows.append(view)
view.closed.connect(context.browser_windows.remove)
model = GitRepoModel(context, view.tree)
view.set_model(model)
if update:
view.refresh()
if show:
view.show()
return view
def save_path(context, path, model):
"""Choose an output filename based on the selected path"""
filename = qtutils.save_as(path)
if filename:
model.filename = filename
cmds.do(SaveBlob, context, model)
result = True
else:
result = False
return result
class Browser(standard.Widget):
"""A repository branch file browser. Browses files provided by GitRepoModel"""
# Read-only mode property
mode = property(lambda self: self.model.mode)
def __init__(self, context, parent, update=True):
standard.Widget.__init__(self, parent)
self.tree = RepoTreeView(context, self)
self.mainlayout = qtutils.hbox(defs.no_margin, defs.spacing, self.tree)
self.setLayout(self.mainlayout)
self.model = context.model
self.model.updated.connect(self._updated_callback, type=Qt.QueuedConnection)
if parent is None:
qtutils.add_close_action(self)
if update:
self._updated_callback()
self.init_state(context.settings, self.resize, 720, 420)
def set_model(self, model):
"""Set the model"""
self.tree.set_model(model)
def refresh(self):
"""Refresh the model triggering view updates"""
self.tree.refresh()
def _updated_callback(self):
branch = self.model.currentbranch
curdir = core.getcwd()
msg = N_('Repository: %s') % curdir
msg += '\n'
msg += N_('Branch: %s') % branch
self.setToolTip(msg)
scope = {
'project': self.model.project,
'branch': branch,
}
title = N_('%(project)s: %(branch)s - Browse') % scope
if self.mode == self.model.mode_amend:
title += ' %s' % N_('(Amending)')
self.setWindowTitle(title)
class RepoTreeView(standard.TreeView):
"""Provides a filesystem-like view of a git repository."""
def __init__(self, context, parent):
standard.TreeView.__init__(self, parent)
self.context = context
self.selection = context.selection
self.saved_selection = []
self.saved_current_path = None
self.saved_open_folders = set()
self.restoring_selection = False
self._columns_sized = False
self.setDragEnabled(True)
self.setRootIsDecorated(False)
self.setSortingEnabled(False)
self.setSelectionMode(self.ExtendedSelection)
# Observe model updates
model = context.model
model.about_to_update.connect(self.save_selection, type=Qt.QueuedConnection)
model.updated.connect(self.update_actions, type=Qt.QueuedConnection)
self.expanded.connect(self.index_expanded)
self.collapsed.connect(lambda idx: self.size_columns())
self.collapsed.connect(self.index_collapsed)
# Sync selection before the key press event changes the model index
queued = Qt.QueuedConnection
self.index_about_to_change.connect(self.sync_selection, type=queued)
self.action_history = qtutils.add_action_with_tooltip(
self,
N_('View History...'),
N_('View history for selected paths'),
self.view_history,
hotkeys.HISTORY,
)
self.action_stage = qtutils.add_action_with_tooltip(
self,
cmds.StageOrUnstage.name(),
N_('Stage/unstage selected paths for commit'),
cmds.run(cmds.StageOrUnstage, context),
hotkeys.STAGE_SELECTION,
)
self.action_untrack = qtutils.add_action_with_tooltip(
self,
N_('Untrack Selected'),
N_('Stop tracking paths'),
self.untrack_selected,
)
self.action_rename = qtutils.add_action_with_tooltip(
self, N_('Rename'), N_('Rename selected paths'), self.rename_selected
)
self.action_difftool = qtutils.add_action_with_tooltip(
self,
difftool.LaunchDifftool.name(),
N_('Launch git-difftool on the current path'),
cmds.run(difftool.LaunchDifftool, context),
hotkeys.DIFF,
)
self.action_difftool_predecessor = qtutils.add_action_with_tooltip(
self,
N_('Diff Against Predecessor...'),
N_('Launch git-difftool against previous versions'),
self.diff_predecessor,
hotkeys.DIFF_SECONDARY,
)
self.action_revert_unstaged = qtutils.add_action_with_tooltip(
self,
cmds.RevertUnstagedEdits.name(),
N_('Revert unstaged changes to selected paths'),
cmds.run(cmds.RevertUnstagedEdits, context),
hotkeys.REVERT,
hotkeys.REVERT_ALT,
)
self.action_revert_uncommitted = qtutils.add_action_with_tooltip(
self,
cmds.RevertUncommittedEdits.name(),
N_('Revert uncommitted changes to selected paths'),
cmds.run(cmds.RevertUncommittedEdits, context),
hotkeys.UNDO,
)
self.action_editor = qtutils.add_action_with_tooltip(
self,
cmds.LaunchEditor.name(),
N_('Edit selected paths'),
cmds.run(cmds.LaunchEditor, context),
hotkeys.EDIT,
)
self.action_blame = qtutils.add_action_with_tooltip(
self,
cmds.BlamePaths.name(),
N_('Blame selected paths'),
cmds.run(cmds.BlamePaths, context),
)
self.action_refresh = common.refresh_action(context, self)
self.action_default_app = common.default_app_action(
context, self, self.selected_paths
)
self.action_parent_dir = common.parent_dir_action(
context, self, self.selected_paths
)
self.action_terminal = common.terminal_action(
context, self, func=self.selected_paths
)
self.x_width = qtutils.text_width(self.font(), 'x')
self.size_columns(force=True)
def index_expanded(self, index):
"""Update information about a directory as it is expanded."""
# Remember open folders so that we can restore them when refreshing
item = self.name_item_from_index(index)
self.saved_open_folders.add(item.path)
self.size_columns()
# update information about a directory as it is expanded
if item.cached:
return
path = item.path
model = self.model()
model.populate(item)
model.update_entry(path)
for row in range(item.rowCount()):
path = item.child(row, 0).path
model.update_entry(path)
item.cached = True
def index_collapsed(self, index):
item = self.name_item_from_index(index)
self.saved_open_folders.remove(item.path)
def refresh(self):
self.model().refresh()
def size_columns(self, force=False):
"""Set the column widths."""
cfg = self.context.cfg
should_resize = cfg.get('cola.resizebrowsercolumns', default=False)
if not force and not should_resize:
return
self.resizeColumnToContents(0)
self.resizeColumnToContents(1)
self.resizeColumnToContents(2)
self.resizeColumnToContents(3)
self.resizeColumnToContents(4)
def sizeHintForColumn(self, column):
x_width = self.x_width
if column == 1:
# Status
size = x_width * 11
elif column == 2:
# Summary
size = x_width * 64
elif column == 3:
# Author
size = x_width * 18
elif column == 4:
# Age
size = x_width * 16
else:
# Filename and others use the actual content
size = super().sizeHintForColumn(column)
return size
def save_selection(self):
selection = self.selected_paths()
if selection:
self.saved_selection = selection
current = self.current_item()
if current:
self.saved_current_path = current.path
def restore(self):
selection = self.selectionModel()
flags = selection.Select | selection.Rows
self.restoring_selection = True
# Restore opened folders
model = self.model()
for path in sorted(self.saved_open_folders):
row = model.get(path)
if not row:
continue
index = row[0].index()
if index.isValid():
self.setExpanded(index, True)
# Restore the current item. We do this first, otherwise
# setCurrentIndex() can mess with the selection we set below
current_index = None
current_path = self.saved_current_path
if current_path:
row = model.get(current_path)
if row:
current_index = row[0].index()
if current_index and current_index.isValid():
self.setCurrentIndex(current_index)
# Restore selected items
for path in self.saved_selection:
row = model.get(path)
if not row:
continue
index = row[0].index()
if index.isValid():
self.scrollTo(index)
selection.select(index, flags)
self.restoring_selection = False
# Resize the columns once when cola.resizebrowsercolumns is False.
# This provides a good initial size since we will not be resizing
# the columns during expand/collapse.
if not self._columns_sized:
self._columns_sized = True
self.size_columns(force=True)
self.update_diff()
def update_actions(self):
"""Enable/disable actions."""
selection = self.selected_paths()
selected = bool(selection)
staged = bool(self.selected_staged_paths(selection=selection))
modified = bool(self.selected_modified_paths(selection=selection))
unstaged = bool(self.selected_unstaged_paths(selection=selection))
tracked = bool(self.selected_tracked_paths(selection=selection))
revertable = staged or modified
self.action_editor.setEnabled(selected)
self.action_history.setEnabled(selected)
self.action_default_app.setEnabled(selected)
self.action_parent_dir.setEnabled(selected)
if self.action_terminal is not None:
self.action_terminal.setEnabled(selected)
self.action_stage.setEnabled(staged or unstaged)
self.action_untrack.setEnabled(tracked)
self.action_rename.setEnabled(tracked)
self.action_difftool.setEnabled(staged or modified)
self.action_difftool_predecessor.setEnabled(tracked)
self.action_revert_unstaged.setEnabled(revertable)
self.action_revert_uncommitted.setEnabled(revertable)
def contextMenuEvent(self, event):
"""Create a context menu."""
self.update_actions()
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.action_editor)
menu.addAction(self.action_stage)
menu.addSeparator()
menu.addAction(self.action_history)
menu.addAction(self.action_difftool)
menu.addAction(self.action_difftool_predecessor)
menu.addAction(self.action_blame)
menu.addSeparator()
menu.addAction(self.action_revert_unstaged)
menu.addAction(self.action_revert_uncommitted)
menu.addAction(self.action_untrack)
menu.addAction(self.action_rename)
menu.addSeparator()
menu.addAction(self.action_default_app)
menu.addAction(self.action_parent_dir)
if self.action_terminal is not None:
menu.addAction(self.action_terminal)
menu.exec_(self.mapToGlobal(event.pos()))
def mousePressEvent(self, event):
"""Synchronize the selection on mouse-press."""
result = QtWidgets.QTreeView.mousePressEvent(self, event)
self.sync_selection()
return result
def sync_selection(self):
"""Push selection into the selection model."""
staged = []
unmerged = []
modified = []
untracked = []
state = State(staged, unmerged, modified, untracked)
paths = self.selected_paths()
model = self.context.model
model_staged = utils.add_parents(model.staged)
model_modified = utils.add_parents(model.modified)
model_unmerged = utils.add_parents(model.unmerged)
model_untracked = utils.add_parents(model.untracked)
for path in paths:
if path in model_unmerged:
unmerged.append(path)
elif path in model_untracked:
untracked.append(path)
elif path in model_staged:
staged.append(path)
elif path in model_modified:
modified.append(path)
else:
staged.append(path)
# Push the new selection into the model.
self.selection.set_selection(state)
return paths
def selectionChanged(self, old, new):
"""Override selectionChanged to update available actions."""
result = QtWidgets.QTreeView.selectionChanged(self, old, new)
if not self.restoring_selection:
self.update_actions()
self.update_diff()
return result
def update_diff(self):
context = self.context
model = context.model
paths = self.sync_selection()
if paths and self.model().path_is_interesting(paths[0]):
cached = paths[0] in model.staged
cmds.do(cmds.Diff, context, paths[0], cached)
def set_model(self, model):
"""Set the concrete QAbstractItemModel instance."""
self.setModel(model)
model.restore.connect(self.restore, type=Qt.QueuedConnection)
def name_item_from_index(self, model_index):
"""Return the name item corresponding to the model index."""
index = model_index.sibling(model_index.row(), 0)
return self.model().itemFromIndex(index)
def paths_from_indexes(self, indexes):
return qtutils.paths_from_indexes(
self.model(), indexes, item_type=GitRepoNameItem.TYPE
)
def selected_paths(self):
"""Return the selected paths."""
return self.paths_from_indexes(self.selectedIndexes())
def selected_staged_paths(self, selection=None):
"""Return selected staged paths."""
if selection is None:
selection = self.selected_paths()
model = self.context.model
staged = utils.add_parents(model.staged)
return [p for p in selection if p in staged]
def selected_modified_paths(self, selection=None):
"""Return selected modified paths."""
if selection is None:
selection = self.selected_paths()
model = self.context.model
modified = utils.add_parents(model.modified)
return [p for p in selection if p in modified]
def selected_unstaged_paths(self, selection=None):
"""Return selected unstaged paths."""
if selection is None:
selection = self.selected_paths()
model = self.context.model
modified = utils.add_parents(model.modified)
untracked = utils.add_parents(model.untracked)
unstaged = modified.union(untracked)
return [p for p in selection if p in unstaged]
def selected_tracked_paths(self, selection=None):
"""Return selected tracked paths."""
if selection is None:
selection = self.selected_paths()
model = self.context.model
staged = set(self.selected_staged_paths(selection=selection))
modified = set(self.selected_modified_paths(selection=selection))
untracked = utils.add_parents(model.untracked)
tracked = staged.union(modified)
return [p for p in selection if p not in untracked or p in tracked]
def view_history(self):
"""Launch the configured history browser path-limited to entries."""
paths = self.selected_paths()
cmds.do(cmds.VisualizePaths, self.context, paths)
def untrack_selected(self):
"""Untrack selected paths."""
context = self.context
cmds.do(cmds.Untrack, context, self.selected_tracked_paths())
def rename_selected(self):
"""Untrack selected paths."""
context = self.context
cmds.do(cmds.Rename, context, self.selected_tracked_paths())
def diff_predecessor(self):
"""Diff paths against previous versions."""
context = self.context
paths = self.selected_tracked_paths()
args = ['--'] + paths
revs, summaries = gitcmds.log_helper(context, all=False, extra_args=args)
commits = select_commits(
context, N_('Select Previous Version'), revs, summaries, multiselect=False
)
if not commits:
return
commit = commits[0]
difftool.difftool_launch(context, left=commit, paths=paths)
def current_path(self):
"""Return the path for the current item."""
index = self.currentIndex()
if not index.isValid():
return None
return self.name_item_from_index(index).path
class BrowseModel:
"""Context data used for browsing branches via git-ls-tree"""
def __init__(self, ref, filename=None):
self.ref = ref
self.relpath = filename
self.filename = filename
class SaveBlob(cmds.ContextCommand):
def __init__(self, context, model):
super().__init__(context)
self.browse_model = model
def do(self):
git = self.context.git
model = self.browse_model
ref = f'{model.ref}:{model.relpath}'
with core.xopen(model.filename, 'wb') as fp:
status, output, err = git.show(ref, _stdout=fp)
out = '# git show {} >{}\n{}'.format(
shlex.quote(ref),
shlex.quote(model.filename),
output,
)
Interaction.command(N_('Error Saving File'), 'git show', status, out, err)
if status != 0:
return
msg = N_('Saved "%(filename)s" from "%(ref)s" to "%(destination)s"') % {
'filename': model.relpath,
'ref': model.ref,
'destination': model.filename,
}
Interaction.log_status(status, msg, '')
Interaction.information(
N_('File Saved'), N_('File saved to "%s"') % model.filename
)
class BrowseBranch(standard.Dialog):
@classmethod
def browse(cls, context, ref):
model = BrowseModel(ref)
dlg = cls(context, model, parent=qtutils.active_window())
dlg_model = GitTreeModel(context, ref, dlg)
dlg.setModel(dlg_model)
dlg.setWindowTitle(N_('Browsing %s') % model.ref)
dlg.show()
dlg.raise_()
if dlg.exec_() != dlg.Accepted:
return None
return dlg
def __init__(self, context, model, parent=None):
standard.Dialog.__init__(self, parent=parent)
if parent is not None:
self.setWindowModality(Qt.WindowModal)
# updated for use by commands
self.context = context
self.model = model
# widgets
self.tree = GitTreeWidget(parent=self)
self.close_button = qtutils.close_button()
text = N_('Save')
self.save = qtutils.create_button(text=text, enabled=False, default=True)
# layouts
self.btnlayt = qtutils.hbox(
defs.margin, defs.spacing, self.close_button, qtutils.STRETCH, self.save
)
self.layt = qtutils.vbox(defs.margin, defs.spacing, self.tree, self.btnlayt)
self.setLayout(self.layt)
# connections
self.tree.path_chosen.connect(self.save_path)
self.tree.selection_changed.connect(
self.selection_changed, type=Qt.QueuedConnection
)
qtutils.connect_button(self.close_button, self.close)
qtutils.connect_button(self.save, self.save_blob)
self.init_size(parent=parent)
def expandAll(self):
self.tree.expandAll()
def setModel(self, model):
self.tree.setModel(model)
def path_chosen(self, path, close=True):
"""Update the model from the view"""
model = self.model
model.relpath = path
model.filename = path
if close:
self.accept()
def save_path(self, path):
"""Choose an output filename based on the selected path"""
self.path_chosen(path, close=False)
if save_path(self.context, path, self.model):
self.accept()
def save_blob(self):
"""Save the currently selected file"""
filenames = self.tree.selected_files()
if not filenames:
return
self.save_path(filenames[0])
def selection_changed(self):
"""Update actions based on the current selection"""
filenames = self.tree.selected_files()
self.save.setEnabled(bool(filenames))
class GitTreeWidget(standard.TreeView):
selection_changed = Signal()
path_chosen = Signal(object)
def __init__(self, parent=None):
standard.TreeView.__init__(self, parent)
self.setHeaderHidden(True)
self.doubleClicked.connect(self.double_clicked)
def double_clicked(self, index):
item = self.model().itemFromIndex(index)
if item is None:
return
if item.is_dir:
return
self.path_chosen.emit(item.path)
def selected_files(self):
items = self.selected_items()
return [i.path for i in items if not i.is_dir]
def selectionChanged(self, old_selection, new_selection):
QtWidgets.QTreeView.selectionChanged(self, old_selection, new_selection)
self.selection_changed.emit()
def select_first_file(self):
"""Select the first filename in the tree"""
model = self.model()
idx = self.indexAt(QtCore.QPoint(0, 0))
item = model.itemFromIndex(idx)
while idx and idx.isValid() and item and item.is_dir:
idx = self.indexBelow(idx)
item = model.itemFromIndex(idx)
if idx and idx.isValid() and item:
self.setCurrentIndex(idx)
class GitFileTreeModel(QtGui.QStandardItemModel):
"""Presents a list of file paths as a hierarchical tree."""
def __init__(self, parent):
QtGui.QStandardItemModel.__init__(self, parent)
self.dir_entries = {'': self.invisibleRootItem()}
self.dir_rows = {}
def clear(self):
QtGui.QStandardItemModel.clear(self)
self.dir_rows = {}
self.dir_entries = {'': self.invisibleRootItem()}
def add_files(self, files):
"""Add a list of files"""
add_file = self.add_file
for f in files:
add_file(f)
def add_file(self, path):
"""Add a file to the model."""
dirname = utils.dirname(path)
dir_entries = self.dir_entries
try:
parent = dir_entries[dirname]
except KeyError:
parent = dir_entries[dirname] = self.create_dir_entry(dirname)
row_items = create_row(path, False)
parent.appendRow(row_items)
def add_directory(self, parent, path):
"""Add a directory entry to the model."""
# Create model items
row_items = create_row(path, True)
try:
parent_path = parent.path
except AttributeError: # root QStandardItem
parent_path = ''
# Insert directories before file paths
try:
row = self.dir_rows[parent_path]
except KeyError:
row = self.dir_rows[parent_path] = 0
parent.insertRow(row, row_items)
self.dir_rows[parent_path] += 1
self.dir_entries[path] = row_items[0]
return row_items[0]
def create_dir_entry(self, dirname):
"""
Create a directory entry for the model.
This ensures that directories are always listed before files.
"""
entries = dirname.split('/')
curdir = []
parent = self.invisibleRootItem()
curdir_append = curdir.append
self_add_directory = self.add_directory
dir_entries = self.dir_entries
for entry in entries:
curdir_append(entry)
path = '/'.join(curdir)
try:
parent = dir_entries[path]
except KeyError:
grandparent = parent
parent = self_add_directory(grandparent, path)
dir_entries[path] = parent
return parent
def create_row(path, is_dir):
"""Return a list of items representing a row."""
return [GitTreeItem(path, is_dir)]
class GitTreeModel(GitFileTreeModel):
def __init__(self, context, ref, parent):
GitFileTreeModel.__init__(self, parent)
self.context = context
self.ref = ref
self._initialize()
def _initialize(self):
"""Iterate over git-ls-tree and create GitTreeItems."""
git = self.context.git
status, out, err = git.ls_tree('--full-tree', '-r', '-t', '-z', self.ref)
if status != 0:
Interaction.log_status(status, out, err)
return
if not out:
return
for line in out[:-1].split('\0'):
# .....6 ...4 ......................................40
# 040000 tree c127cde9a0c644a3a8fef449a244f47d5272dfa6 relative
# 100644 blob 139e42bf4acaa4927ec9be1ec55a252b97d3f1e2 relative/path
objtype = line[7]
relpath = line[6 + 1 + 4 + 1 + 40 + 1 :]
if objtype == 't':
parent = self.dir_entries[utils.dirname(relpath)]
self.add_directory(parent, relpath)
elif objtype == 'b':
self.add_file(relpath)
class GitTreeItem(QtGui.QStandardItem):
"""
Represents a cell in a tree view.
Many GitRepoItems could map to a single repository path,
but this tree only has a single column.
Each GitRepoItem manages a different cell in the tree view.
"""
def __init__(self, path, is_dir):
QtGui.QStandardItem.__init__(self)
self.is_dir = is_dir
self.path = path
self.setEditable(False)
self.setDragEnabled(False)
self.setText(utils.basename(path))
if is_dir:
icon = icons.directory()
else:
icon = icons.file_text()
self.setIcon(icon)
| 27,762 | Python | .py | 691 | 30.82055 | 86 | 0.620613 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
75 | recent.py | git-cola_git-cola/cola/widgets/recent.py | from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..i18n import N_
from ..qtutils import get
from .. import cmds
from .. import gitcmds
from .. import hotkeys
from .. import icons
from .. import qtutils
from .browse import GitTreeWidget
from .browse import GitFileTreeModel
from . import defs
from . import standard
def browse_recent_files(context):
dialog = RecentFiles(context, parent=qtutils.active_window())
dialog.show()
return dialog
class UpdateFileListThread(QtCore.QThread):
result = Signal(object)
def __init__(self, context, count):
QtCore.QThread.__init__(self)
self.context = context
self.count = count
def run(self):
context = self.context
ref = 'HEAD~%d' % self.count
filenames = gitcmds.diff_index_filenames(context, ref)
self.result.emit(filenames)
class RecentFiles(standard.Dialog):
def __init__(self, context, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.setWindowTitle(N_('Recently Modified Files'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
count = 8
self.update_thread = UpdateFileListThread(context, count)
self.count = standard.SpinBox(
value=count, maxi=10000, suffix=N_(' commits ago')
)
self.count_label = QtWidgets.QLabel()
self.count_label.setText(N_('Showing changes since'))
self.refresh_button = qtutils.refresh_button(enabled=False)
self.tree = GitTreeWidget(parent=self)
self.tree_model = GitFileTreeModel(self)
self.tree.setModel(self.tree_model)
self.expand_button = qtutils.create_button(
text=N_('Expand all'), icon=icons.unfold()
)
self.collapse_button = qtutils.create_button(
text=N_('Collapse all'), icon=icons.fold()
)
self.edit_button = qtutils.edit_button(enabled=False, default=True)
self.close_button = qtutils.close_button()
self.top_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.count_label,
self.count,
qtutils.STRETCH,
self.refresh_button,
)
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.expand_button,
self.collapse_button,
qtutils.STRETCH,
self.close_button,
self.edit_button,
)
self.main_layout = qtutils.vbox(
defs.margin, defs.spacing, self.top_layout, self.tree, self.button_layout
)
self.setLayout(self.main_layout)
self.tree.selection_changed.connect(self.tree_selection_changed)
self.tree.path_chosen.connect(self.edit_file)
self.count.valueChanged.connect(self.count_changed)
self.count.editingFinished.connect(self.refresh)
thread = self.update_thread
thread.result.connect(self.set_filenames, type=Qt.QueuedConnection)
qtutils.connect_button(self.refresh_button, self.refresh)
qtutils.connect_button(self.expand_button, self.tree.expandAll)
qtutils.connect_button(self.collapse_button, self.tree.collapseAll)
qtutils.connect_button(self.close_button, self.accept)
qtutils.connect_button(self.edit_button, self.edit_selected)
qtutils.add_action(self, N_('Refresh'), self.refresh, hotkeys.REFRESH)
self.update_thread.start()
self.init_size(parent=parent)
def edit_selected(self):
filenames = self.tree.selected_files()
if not filenames:
return
self.edit_files(filenames)
def edit_files(self, filenames):
cmds.do(cmds.Edit, self.context, filenames)
def edit_file(self, filename):
self.edit_files([filename])
def refresh(self):
self.refresh_button.setEnabled(False)
self.count.setEnabled(False)
self.tree_model.clear()
self.tree.setEnabled(False)
self.update_thread.count = get(self.count)
self.update_thread.start()
def count_changed(self, _value):
self.refresh_button.setEnabled(True)
def tree_selection_changed(self):
"""Update actions based on the current selection"""
filenames = self.tree.selected_files()
self.edit_button.setEnabled(bool(filenames))
def set_filenames(self, filenames):
self.count.setEnabled(True)
self.tree.setEnabled(True)
self.tree_model.clear()
self.tree_model.add_files(filenames)
self.tree.expandAll()
self.tree.select_first_file()
self.tree.setFocus()
| 4,782 | Python | .py | 121 | 31.272727 | 85 | 0.660112 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
76 | stash.py | git-cola_git-cola/cola/widgets/stash.py | """Widgets for manipulating git stashes"""
from qtpy.QtCore import Qt
from ..i18n import N_
from ..interaction import Interaction
from ..models import stash
from ..qtutils import get
from .. import cmds
from .. import hotkeys
from .. import icons
from .. import qtutils
from . import defs
from . import diff
from . import standard
def view(context, show=True):
"""Launches a stash dialog using the provided model + view"""
model = stash.StashModel(context)
stash_view = StashView(context, model, parent=qtutils.active_window())
if show:
stash_view.show()
stash_view.raise_()
return stash_view
class StashView(standard.Dialog):
def __init__(self, context, model, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.model = model
self.stashes = []
self.revids = []
self.names = []
self.setWindowTitle(N_('Stash'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.stash_list = standard.ListWidget(parent=self)
self.stash_text = diff.DiffTextEdit(context, self)
self.button_rename = qtutils.create_button(
text=N_('Rename'),
tooltip=N_('Rename the selected stash'),
icon=icons.edit(),
)
self.button_apply = qtutils.create_button(
text=N_('Apply'), tooltip=N_('Apply the selected stash'), icon=icons.ok()
)
self.button_save = qtutils.create_button(
text=N_('Save'),
tooltip=N_('Save modified state to new stash'),
icon=icons.save(),
default=True,
)
self.button_drop = qtutils.create_button(
text=N_('Drop'), tooltip=N_('Drop the selected stash'), icon=icons.discard()
)
self.button_pop = qtutils.create_button(
text=N_('Pop'),
tooltip=N_('Apply and drop the selected stash (git stash pop)'),
icon=icons.discard(),
)
self.button_close = qtutils.close_button()
self.keep_index = qtutils.checkbox(
text=N_('Keep Index'),
checked=True,
tooltip=N_('Stash unstaged changes only, keeping staged changes'),
)
self.stash_index = qtutils.checkbox(
text=N_('Stash Index'), tooltip=N_('Stash staged changes only')
)
# Arrange layouts
self.splitter = qtutils.splitter(
Qt.Horizontal, self.stash_list, self.stash_text
)
self.splitter.setChildrenCollapsible(False)
self.btn_layt = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.stash_index,
self.keep_index,
qtutils.STRETCH,
self.button_close,
self.button_save,
self.button_rename,
self.button_apply,
self.button_pop,
self.button_drop,
)
self.main_layt = qtutils.vbox(
defs.margin, defs.spacing, self.splitter, self.btn_layt
)
self.setLayout(self.main_layt)
self.splitter.setSizes([self.width() // 3, self.width() * 2 // 3])
# Apply stash with Ctrl+Enter
self.apply_action = qtutils.add_action(
self, N_('Apply'), self.stash_apply, hotkeys.APPLY
)
# Pop stash with Ctrl+Backspace
self.pop_action = qtutils.add_action(
self, N_('Pop'), self.stash_pop, hotkeys.DELETE_FILE_SECONDARY
)
# Drop stash with Ctrl+Shift+Backspace
self.drop_action = qtutils.add_action(
self, N_('Pop'), self.stash_drop, hotkeys.DELETE_FILE
)
self.stash_list.itemSelectionChanged.connect(self.item_selected)
qtutils.connect_button(self.button_save, self.stash_save)
qtutils.connect_button(self.button_rename, self.stash_rename)
qtutils.connect_button(self.button_apply, self.stash_apply)
qtutils.connect_button(self.button_pop, self.stash_pop)
qtutils.connect_button(self.button_drop, self.stash_drop)
qtutils.connect_button(self.button_close, self.close_and_rescan)
qtutils.connect_checkbox(self.stash_index, self.stash_index_clicked)
qtutils.connect_checkbox(self.keep_index, self.keep_index_clicked)
self.init_size(parent=parent)
self.update_from_model()
self.update_actions()
def close_and_rescan(self):
cmds.do(cmds.Rescan, self.context)
self.reject()
# "stash" and "keep" index are mutually disable, but we don't
# want a radio button because we'd have to add a 3rd "default" option.
def stash_index_clicked(self, clicked):
if clicked:
self.keep_index.setChecked(False)
def keep_index_clicked(self, clicked):
if clicked:
self.stash_index.setChecked(False)
def selected_stash(self):
"""Returns the stash name of the currently selected stash"""
list_widget = self.stash_list
stash_list = self.revids
return qtutils.selected_item(list_widget, stash_list)
def selected_name(self):
list_widget = self.stash_list
stash_list = self.names
return qtutils.selected_item(list_widget, stash_list)
def item_selected(self):
"""Shows the current stash in the main view."""
self.update_actions()
selection = self.selected_stash()
if not selection:
return
diff_text = self.model.stash_diff(selection)
self.stash_text.setPlainText(diff_text)
def update_actions(self):
is_staged = self.model.is_staged()
self.stash_index.setEnabled(is_staged)
is_changed = self.model.is_changed()
self.keep_index.setEnabled(is_changed)
self.button_save.setEnabled(is_changed)
is_selected = bool(self.selected_stash())
self.apply_action.setEnabled(is_selected)
self.drop_action.setEnabled(is_selected)
self.pop_action.setEnabled(is_selected)
self.button_rename.setEnabled(is_selected)
self.button_apply.setEnabled(is_selected)
self.button_drop.setEnabled(is_selected)
self.button_pop.setEnabled(is_selected)
def update_from_model(self):
"""Initiates git queries on the model and updates the view"""
stashes, revids, author_dates, names = self.model.stash_info()
self.stashes = stashes
self.revids = revids
self.names = names
self.stash_list.clear()
self.stash_list.addItems(self.stashes)
if self.stash_list.count() > 0:
for i in range(self.stash_list.count()):
self.stash_list.item(i).setToolTip(author_dates[i])
item = self.stash_list.item(0)
self.stash_list.setCurrentItem(item)
# "Stash Index" depends on staged changes, so disable this option
# if there are no staged changes.
is_staged = self.model.is_staged()
if get(self.stash_index) and not is_staged:
self.stash_index.setChecked(False)
def stash_rename(self):
"""Renames the currently selected stash"""
selection = self.selected_stash()
name = self.selected_name()
new_name, ok = qtutils.prompt(
N_('Enter a new name for the stash'),
text=name,
title=N_('Rename Stash'),
parent=self,
)
if not ok or not new_name:
return
if new_name == name:
Interaction.information(
N_('No change made'), N_('The stash has not been renamed')
)
return
context = self.context
cmds.do(stash.RenameStash, context, selection, new_name)
self.update_from_model()
def stash_pop(self):
self.stash_apply(pop=True)
def stash_apply(self, pop=False):
"""Applies the currently selected stash"""
selection = self.selected_stash()
if not selection:
return
context = self.context
index = get(self.keep_index)
cmds.do(stash.ApplyStash, context, selection, index, pop)
self.update_from_model()
def stash_save(self):
"""Saves the worktree in a stash
This prompts the user for a stash name and creates
a git stash named accordingly.
"""
stash_name, ok = qtutils.prompt(
N_('Enter a name for the stash'), title=N_('Save Stash'), parent=self
)
if not ok or not stash_name:
return
context = self.context
keep_index = get(self.keep_index)
stash_index = get(self.stash_index)
if stash_index:
cmds.do(stash.StashIndex, context, stash_name)
else:
cmds.do(stash.SaveStash, context, stash_name, keep_index)
self.update_from_model()
def stash_drop(self):
"""Drops the currently selected stash"""
selection = self.selected_stash()
name = self.selected_name()
if not selection:
return
if not Interaction.confirm(
N_('Drop Stash?'),
N_('Recovering a dropped stash is not possible.'),
N_('Drop the "%s" stash?') % name,
N_('Drop Stash'),
default=True,
icon=icons.discard(),
):
return
cmds.do(stash.DropStash, self.context, selection)
self.update_from_model()
self.stash_text.setPlainText('')
def export_state(self):
"""Export persistent settings"""
state = super().export_state()
state['keep_index'] = get(self.keep_index)
state['stash_index'] = get(self.stash_index)
state['sizes'] = get(self.splitter)
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = super().apply_state(state)
keep_index = bool(state.get('keep_index', True))
stash_index = bool(state.get('stash_index', False))
self.keep_index.setChecked(keep_index)
self.stash_index.setChecked(stash_index)
try:
self.splitter.setSizes(state['sizes'])
except (KeyError, ValueError, AttributeError):
pass
return result
| 10,311 | Python | .py | 258 | 30.585271 | 88 | 0.613725 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
77 | finder.py | git-cola_git-cola/cola/widgets/finder.py | """File finder widgets"""
import os
from functools import partial
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..i18n import N_
from ..qtutils import get
from ..utils import Group
from .. import cmds
from .. import core
from .. import gitcmds
from .. import hotkeys
from .. import icons
from .. import utils
from .. import qtutils
from . import completion
from . import defs
from . import filetree
from . import standard
from . import text
def finder(context, paths=None):
"""Prompt and use 'git grep' to find the content."""
parent = qtutils.active_window()
widget = new_finder(context, paths=paths, parent=parent)
widget.show()
widget.raise_()
return widget
def new_finder(context, paths=None, parent=None):
"""Create a finder widget"""
widget = Finder(context, parent=parent)
widget.search_for(paths or '')
return widget
def add_wildcards(arg):
"""Add "*" around user input to generate ls-files pathspec matches
>>> '*x*' == \
add_wildcards('x') == \
add_wildcards('*x') == \
add_wildcards('x*') == \
add_wildcards('*x*')
True
"""
if not arg.startswith('*'):
arg = '*' + arg
if not arg.endswith('*'):
arg = arg + '*'
return arg
def show_help(context):
"""Show the help page"""
help_text = N_(
"""
Keyboard Shortcuts
------------------
J, Down = Move Down
K, Up = Move Up
Enter = Edit Selected Files
Spacebar = Open File Using Default Application
Ctrl + L = Focus Text Entry Field
? = Show Help
The up and down arrows change focus between the text entry field
and the results.
"""
)
title = N_('Help - Find Files')
return text.text_dialog(context, help_text, title)
class FindFilesThread(QtCore.QThread):
"""Finds files asynchronously"""
result = Signal(object)
def __init__(self, context, parent):
QtCore.QThread.__init__(self, parent)
self.context = context
self.query = None
def run(self):
context = self.context
query = self.query
if query is None:
args = []
else:
args = [add_wildcards(arg) for arg in utils.shell_split(query)]
filenames = gitcmds.tracked_files(context, *args)
if query == self.query:
self.result.emit(filenames)
else:
self.run()
class Finder(standard.Dialog):
"""File Finder dialog"""
def __init__(self, context, parent=None):
standard.Dialog.__init__(self, parent)
self.context = context
self.setWindowTitle(N_('Find Files'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
label = os.path.basename(core.getcwd()) + '/'
self.input_label = QtWidgets.QLabel(label)
self.input_txt = completion.GitTrackedLineEdit(context, hint=N_('<path> ...'))
self.tree = filetree.FileTree(parent=self)
self.edit_button = qtutils.edit_button(default=True)
self.edit_button.setShortcut(hotkeys.EDIT)
name = cmds.OpenDefaultApp.name()
icon = icons.default_app()
self.open_default_button = qtutils.create_button(text=name, icon=icon)
self.open_default_button.setShortcut(hotkeys.PRIMARY_ACTION)
self.button_group = Group(self.edit_button, self.open_default_button)
self.button_group.setEnabled(False)
self.refresh_button = qtutils.refresh_button()
self.refresh_button.setShortcut(hotkeys.REFRESH)
self.help_button = qtutils.create_button(
text=N_('Help'), tooltip=N_('Show help\nShortcut: ?'), icon=icons.question()
)
self.close_button = qtutils.close_button()
self.input_layout = qtutils.hbox(
defs.no_margin, defs.button_spacing, self.input_label, self.input_txt
)
self.bottom_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.help_button,
self.refresh_button,
qtutils.STRETCH,
self.close_button,
self.open_default_button,
self.edit_button,
)
self.main_layout = qtutils.vbox(
defs.margin,
defs.no_spacing,
self.input_layout,
self.tree,
self.bottom_layout,
)
self.setLayout(self.main_layout)
self.setFocusProxy(self.input_txt)
thread = self.worker_thread = FindFilesThread(context, self)
thread.result.connect(self.process_result, type=Qt.QueuedConnection)
self.input_txt.textChanged.connect(lambda s: self.search())
self.input_txt.activated.connect(self.focus_tree)
self.input_txt.down.connect(self.focus_tree)
self.input_txt.enter.connect(self.focus_tree)
item_selection_changed = self.tree_item_selection_changed
self.tree.itemSelectionChanged.connect(item_selection_changed)
self.tree.up.connect(self.focus_input)
self.tree.space.connect(self.open_default)
qtutils.add_action(
self, 'Focus Input', self.focus_input, hotkeys.FOCUS, hotkeys.FINDER
)
self.show_help_action = qtutils.add_action(
self, N_('Show Help'), partial(show_help, context), hotkeys.QUESTION
)
qtutils.connect_button(self.edit_button, self.edit)
qtutils.connect_button(self.open_default_button, self.open_default)
qtutils.connect_button(self.refresh_button, self.search)
qtutils.connect_button(self.help_button, partial(show_help, context))
qtutils.connect_button(self.close_button, self.close)
qtutils.add_close_action(self)
self.init_size(parent=parent)
def focus_tree(self):
self.tree.setFocus()
def focus_input(self):
self.input_txt.setFocus()
def search(self):
self.button_group.setEnabled(False)
self.refresh_button.setEnabled(False)
query = get(self.input_txt)
self.worker_thread.query = query
self.worker_thread.start()
def search_for(self, txt):
self.input_txt.set_value(txt)
self.focus_input()
def process_result(self, filenames):
self.tree.set_filenames(filenames, select=True)
self.refresh_button.setEnabled(True)
def edit(self):
context = self.context
paths = self.tree.selected_filenames()
cmds.do(cmds.Edit, context, paths, background_editor=True)
def open_default(self):
context = self.context
paths = self.tree.selected_filenames()
cmds.do(cmds.OpenDefaultApp, context, paths)
def tree_item_selection_changed(self):
enabled = bool(self.tree.selected_item())
self.button_group.setEnabled(enabled)
| 6,865 | Python | .py | 183 | 30.26776 | 88 | 0.647023 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
78 | switcher.py | git-cola_git-cola/cola/widgets/switcher.py | """Provides quick switcher"""
import re
from qtpy import QtCore
from qtpy import QtGui
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from .. import qtutils
from ..widgets import defs
from ..widgets import standard
from ..widgets import text
def switcher_inner_view(
context, entries, title=None, place_holder=None, enter_action=None, parent=None
):
dialog = SwitcherInnerView(
context, entries, title, place_holder, enter_action, parent
)
dialog.show()
return dialog
def switcher_outer_view(context, entries, place_holder=None, parent=None):
dialog = SwitcherOuterView(context, entries, place_holder, parent)
dialog.show()
return dialog
def switcher_item(key, icon=None, name=None):
return SwitcherListItem(key, icon, name)
def moving_keys():
selection_move_keys = [
Qt.Key_Enter,
Qt.Key_Return,
Qt.Key_Up,
Qt.Key_Down,
Qt.Key_Home,
Qt.Key_End,
Qt.Key_PageUp,
Qt.Key_PageDown,
]
return selection_move_keys
class Switcher(standard.Dialog):
"""
Quick switcher base class. This contains input field, filter proxy model.
This will be inherited by outer-view class(SwitcherOuterView) or inner-view class
(SwitcherInnerView).
The inner-view class is a quick-switcher widget including view. In this case, this
switcher will have switcher_list field, and show the items list in itself.
The outer-view class is a quick-switcher widget without view(only input field),
which shares model with other view class.
The switcher_selection_move signal is the event that the selection move actions
emit while the input field is focused.
"""
def __init__(
self,
context,
entries_model,
place_holder=None,
parent=None,
):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.entries_model = entries_model
self.filter_input = SwitcherLineEdit(place_holder=place_holder, parent=self)
self.proxy_model = SwitcherSortFilterProxyModel(entries_model, parent=self)
self.switcher_list = None
self.filter_input.textChanged.connect(self.filter_input_changed)
def filter_input_changed(self):
input_text = self.filter_input.text()
pattern = '.*'.join(re.escape(c) for c in input_text)
self.proxy_model.setFilterRegExp(pattern)
class SwitcherInnerView(Switcher):
def __init__(
self,
context,
entries_model,
title,
place_holder=None,
enter_action=None,
parent=None,
):
Switcher.__init__(
self,
context,
entries_model,
place_holder=place_holder,
parent=parent,
)
self.setWindowTitle(title)
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.enter_action = enter_action
self.switcher_list = SwitcherTreeView(
self.proxy_model, self.enter_selected_item, parent=self
)
self.main_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.filter_input, self.switcher_list
)
self.setLayout(self.main_layout)
# moving key has pressed while focusing on input field
self.filter_input.switcher_selection_move.connect(
self.switcher_list.keyPressEvent
)
# escape key pressed while focusing on input field
self.filter_input.switcher_escape.connect(self.close)
self.filter_input.switcher_accept.connect(self.accept_selected_item)
# some key except moving key has pressed while focusing on list view
self.switcher_list.switcher_inner_text.connect(self.filter_input.keyPressEvent)
# default selection for first index
first_proxy_idx = self.proxy_model.index(0, 0)
self.switcher_list.setCurrentIndex(first_proxy_idx)
self.set_initial_geometry(parent)
def accept_selected_item(self):
item = self.switcher_list.selected_item()
if item:
self.enter_action(item)
self.accept()
def set_initial_geometry(self, parent):
"""Set the initial size and position"""
if parent is None:
return
# Size
width = parent.width()
height = parent.height()
self.resize(max(width * 2 // 3, 320), max(height * 2 // 3, 240))
def enter_selected_item(self, index):
item = self.switcher_list.model().itemFromIndex(index)
if item:
self.enter_action(item)
self.accept()
class SwitcherOuterView(Switcher):
def __init__(self, context, entries_model, place_holder=None, parent=None):
Switcher.__init__(
self,
context,
entries_model,
place_holder=place_holder,
parent=parent,
)
self.filter_input.hide()
self.main_layout = qtutils.vbox(defs.no_margin, defs.spacing, self.filter_input)
self.setLayout(self.main_layout)
def filter_input_changed(self):
super().filter_input_changed()
# Hide the input when it becomes empty.
input_text = self.filter_input.text()
if not input_text:
self.filter_input.hide()
class SwitcherLineEdit(text.LineEdit):
"""Quick switcher input line class"""
# signal is for the event that selection move key like UP, DOWN has pressed
# while focusing on this line edit widget
switcher_selection_move = Signal(QtGui.QKeyEvent)
switcher_visible = Signal(bool)
switcher_accept = Signal()
switcher_escape = Signal()
def __init__(self, place_holder=None, parent=None):
text.LineEdit.__init__(self, parent=parent)
if place_holder:
self.setPlaceholderText(place_holder)
def keyPressEvent(self, event):
"""
To be able to move the selection while focus on the input field, input text
field should be able to filter pressed key.
If pressed key is moving selection key like UP or DOWN, the
switcher_selection_move signal will be emitted and the view selection
will be moved regardless whether Switcher is inner-view or outer-view.
Or else, simply act like text input to the field.
"""
selection_moving_keys = moving_keys()
pressed_key = event.key()
if pressed_key == Qt.Key_Escape:
self.switcher_escape.emit()
elif pressed_key in (Qt.Key_Enter, Qt.Key_Return):
self.switcher_accept.emit()
elif pressed_key in selection_moving_keys:
self.switcher_selection_move.emit(event)
else:
super().keyPressEvent(event)
class SwitcherSortFilterProxyModel(QtCore.QSortFilterProxyModel):
"""Filtering class for candidate items."""
def __init__(self, entries, parent=None):
QtCore.QSortFilterProxyModel.__init__(self, parent)
self.entries = entries
self.setDynamicSortFilter(True)
self.setSourceModel(entries)
self.setFilterCaseSensitivity(Qt.CaseInsensitive)
def itemFromIndex(self, index):
return self.entries.itemFromIndex(self.mapToSource(index))
class SwitcherTreeView(standard.TreeView):
"""Tree view class for showing proxy items in SwitcherSortFilterProxyModel"""
# signal is for the event that some key except moving key has pressed
# while focusing this view
switcher_inner_text = Signal(QtGui.QKeyEvent)
def __init__(self, entries_proxy_model, enter_action, parent=None):
standard.TreeView.__init__(self, parent)
self.setHeaderHidden(True)
self.setModel(entries_proxy_model)
self.doubleClicked.connect(enter_action)
def keyPressEvent(self, event):
"""hooks when a key has pressed while focusing on list view"""
selection_moving_keys = moving_keys()
pressed_key = event.key()
if pressed_key in selection_moving_keys or pressed_key == Qt.Key_Escape:
super().keyPressEvent(event)
else:
self.switcher_inner_text.emit(event)
class SwitcherListItem(QtGui.QStandardItem):
"""Item class for SwitcherTreeView and SwitcherSortFilterProxyModel"""
def __init__(self, key, icon=None, name=None):
QtGui.QStandardItem.__init__(self)
self.key = key
if not name:
name = key
self.setText(name)
if icon:
self.setIcon(icon)
| 8,555 | Python | .py | 212 | 32.358491 | 88 | 0.665258 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
79 | createtag.py | git-cola_git-cola/cola/widgets/createtag.py | from qtpy import QtWidgets
from qtpy.QtCore import Qt
from .. import cmds
from .. import icons
from .. import qtutils
from ..i18n import N_
from ..qtutils import get
from . import defs
from . import completion
from . import standard
from . import text
def new_create_tag(context, name='', ref='', sign=False, parent=None):
"""Entry point for external callers."""
opts = TagOptions(name, ref, sign)
view = CreateTag(context, opts, parent=parent)
return view
def create_tag(context, name='', ref='', sign=False):
"""Entry point for external callers."""
view = new_create_tag(
context,
name=name,
ref=ref,
sign=sign,
parent=qtutils.active_window(),
)
view.show()
view.raise_()
return view
class TagOptions:
"""Simple data container for the CreateTag dialog."""
def __init__(self, name, ref, sign):
self.name = name or ''
self.ref = ref or 'HEAD'
self.sign = sign
class CreateTag(standard.Dialog):
def __init__(self, context, opts, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.model = model = context.model
self.opts = opts
self.setWindowTitle(N_('Create Tag'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
# Tag label
self.tag_name_label = QtWidgets.QLabel(self)
self.tag_name_label.setText(N_('Name'))
self.tag_name = text.HintedLineEdit(context, N_('vX.Y.Z'), parent=self)
self.tag_name.set_value(opts.name)
self.tag_name.setToolTip(N_('Specifies the tag name'))
qtutils.add_completer(self.tag_name, model.tags)
# Sign Tag
self.sign_label = QtWidgets.QLabel(self)
self.sign_label.setText(N_('Sign Tag'))
tooltip = N_('Whether to sign the tag (git tag -s)')
self.sign_tag = qtutils.checkbox(checked=True, tooltip=tooltip)
# Tag message
self.tag_msg_label = QtWidgets.QLabel(self)
self.tag_msg_label.setText(N_('Message'))
self.tag_msg = text.HintedPlainTextEdit(context, N_('Tag message...'), self)
self.tag_msg.setToolTip(N_('Specifies the tag message'))
# Revision
self.rev_label = QtWidgets.QLabel(self)
self.rev_label.setText(N_('Revision'))
self.revision = completion.GitRefLineEdit(context)
self.revision.setText(self.opts.ref)
self.revision.setToolTip(N_('Specifies the commit to tag'))
# Buttons
self.create_button = qtutils.create_button(
text=N_('Create Tag'), icon=icons.tag(), default=True
)
self.close_button = qtutils.close_button()
# Form layout for inputs
self.input_layout = qtutils.form(
defs.margin,
defs.spacing,
(self.tag_name_label, self.tag_name),
(self.tag_msg_label, self.tag_msg),
(self.rev_label, self.revision),
(self.sign_label, self.sign_tag),
)
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
qtutils.STRETCH,
self.close_button,
self.create_button,
)
self.main_layt = qtutils.vbox(
defs.margin, defs.spacing, self.input_layout, self.button_layout
)
self.setLayout(self.main_layt)
qtutils.connect_button(self.close_button, self.close)
qtutils.connect_button(self.create_button, self.create_tag)
settings = context.settings
self.init_state(settings, self.resize, defs.scale(720), defs.scale(210))
def create_tag(self):
"""Verifies inputs and emits a notifier tag message."""
context = self.context
revision = get(self.revision)
tag_name = get(self.tag_name)
tag_msg = get(self.tag_msg)
sign_tag = get(self.sign_tag)
ok = cmds.do(
cmds.Tag, context, tag_name, revision, sign=sign_tag, message=tag_msg
)
if ok:
self.close()
| 4,105 | Python | .py | 107 | 30.149533 | 84 | 0.621914 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
80 | spellcheck.py | git-cola_git-cola/cola/widgets/spellcheck.py | import re
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from .. import qtutils
from .. import spellcheck
from ..i18n import N_
from .text import HintedTextEdit
class SpellCheckTextEdit(HintedTextEdit):
def __init__(self, context, hint, check=None, parent=None):
HintedTextEdit.__init__(self, context, hint, parent)
# Default dictionary based on the current locale.
self.spellcheck = check or spellcheck.NorvigSpellCheck()
self.highlighter = Highlighter(self.document(), self.spellcheck)
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
# Rewrite the mouse event to a left button event so the cursor is
# moved to the location of the pointer.
if hasattr(event, 'position'): # Qt6
position = event.position()
else:
position = event.pos()
event = QtGui.QMouseEvent(
QtCore.QEvent.MouseButtonPress,
position,
Qt.LeftButton,
Qt.LeftButton,
Qt.NoModifier,
)
HintedTextEdit.mousePressEvent(self, event)
def create_context_menu(self, event_pos):
popup_menu = super().create_context_menu(event_pos)
# Check if the selected word is misspelled and offer spelling
# suggestions if it is.
spell_menu = None
if self.textCursor().hasSelection():
text = self.textCursor().selectedText()
if not self.spellcheck.check(text):
title = N_('Spelling Suggestions')
spell_menu = qtutils.create_menu(title, self)
for word in self.spellcheck.suggest(text):
action = SpellAction(word, spell_menu)
action.result.connect(self.correct)
spell_menu.addAction(action)
# Only add the spelling suggests to the menu if there are
# suggestions.
if spell_menu.actions():
popup_menu.addSeparator()
popup_menu.addMenu(spell_menu)
return popup_menu
def contextMenuEvent(self, event):
"""Select the current word and then show a context menu"""
# Select the word under the cursor before calling the default contextMenuEvent.
cursor = self.textCursor()
cursor.select(QtGui.QTextCursor.WordUnderCursor)
self.setTextCursor(cursor)
super().contextMenuEvent(event)
def correct(self, word):
"""Replaces the selected text with word."""
cursor = self.textCursor()
cursor.beginEditBlock()
cursor.removeSelectedText()
cursor.insertText(word)
cursor.endEditBlock()
class SpellCheckLineEdit(SpellCheckTextEdit):
"""A fake QLineEdit that provides spellcheck capabilities
This class emulates QLineEdit using our QPlainTextEdit base class
so that we can leverage the existing spellcheck feature.
"""
down_pressed = QtCore.Signal()
# This widget is a single-line QTextEdit as described in
# http://blog.ssokolow.com/archives/2022/07/22/a-qlineedit-replacement-with-spell-checking/
def __init__(self, context, hint, check=None, parent=None):
super().__init__(context, hint, check=check, parent=parent)
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
self.setLineWrapMode(QtWidgets.QTextEdit.NoWrap)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setWordWrapMode(QtGui.QTextOption.NoWrap)
self.setTabChangesFocus(True)
self.textChanged.connect(self._trim_changed_text_lines)
def focusInEvent(self, event):
"""Select text when entering with a tab to mimic QLineEdit"""
super().focusInEvent(event)
if event.reason() in (
Qt.BacktabFocusReason,
Qt.ShortcutFocusReason,
Qt.TabFocusReason,
):
self.selectAll()
def focusOutEvent(self, event):
"""De-select text when exiting with tab to mimic QLineEdit"""
super().focusOutEvent(event)
if event.reason() in (
Qt.BacktabFocusReason,
Qt.MouseFocusReason,
Qt.ShortcutFocusReason,
Qt.TabFocusReason,
):
cur = self.textCursor()
cur.movePosition(QtGui.QTextCursor.End)
self.setTextCursor(cur)
def keyPressEvent(self, event):
"""Handle the up/down arrow keys"""
event_key = event.key()
if event_key == Qt.Key_Up:
cursor = self.textCursor()
if cursor.position() == 0:
cursor.clearSelection()
else:
if event.modifiers() & Qt.ShiftModifier:
mode = QtGui.QTextCursor.KeepAnchor
else:
mode = QtGui.QTextCursor.MoveAnchor
cursor.setPosition(0, mode)
self.setTextCursor(cursor)
return
if event_key == Qt.Key_Down:
cursor = self.textCursor()
cur_position = cursor.position()
end_position = len(self.value())
if cur_position == end_position:
cursor.clearSelection()
self.setTextCursor(cursor)
self.down_pressed.emit()
else:
if event.modifiers() & Qt.ShiftModifier:
mode = QtGui.QTextCursor.KeepAnchor
else:
mode = QtGui.QTextCursor.MoveAnchor
cursor.setPosition(end_position, mode)
self.setTextCursor(cursor)
return
super().keyPressEvent(event)
def minimumSizeHint(self):
"""Match QLineEdit's size behavior"""
block_fmt = self.document().firstBlock().blockFormat()
width = super().minimumSizeHint().width()
height = int(
QtGui.QFontMetricsF(self.font()).lineSpacing()
+ block_fmt.topMargin()
+ block_fmt.bottomMargin()
+ self.document().documentMargin()
+ 2 * self.frameWidth()
)
style_opts = QtWidgets.QStyleOptionFrame()
style_opts.initFrom(self)
style_opts.lineWidth = self.frameWidth()
return self.style().sizeFromContents(
QtWidgets.QStyle.CT_LineEdit, style_opts, QtCore.QSize(width, height), self
)
def sizeHint(self):
"""Use the minimum size as the sizeHint()"""
return self.minimumSizeHint()
def _trim_changed_text_lines(self):
"""Trim the document to a single line to enforce a maximum of one line"""
# self.setMaximumBlockCount(1) Undo/Redo.
if self.document().blockCount() > 1:
self.document().setPlainText(self.document().firstBlock().text())
class Highlighter(QtGui.QSyntaxHighlighter):
WORDS = r"(?iu)[\w']+"
def __init__(self, doc, spellcheck_widget):
QtGui.QSyntaxHighlighter.__init__(self, doc)
self.spellcheck = spellcheck_widget
self.enabled = False
def enable(self, enabled):
self.enabled = enabled
self.rehighlight()
def highlightBlock(self, text):
if not self.enabled:
return
fmt = QtGui.QTextCharFormat()
fmt.setUnderlineColor(Qt.red)
fmt.setUnderlineStyle(QtGui.QTextCharFormat.SpellCheckUnderline)
for word_object in re.finditer(self.WORDS, text):
if not self.spellcheck.check(word_object.group()):
self.setFormat(
word_object.start(), word_object.end() - word_object.start(), fmt
)
class SpellAction(QtWidgets.QAction):
"""QAction that returns the text in a signal."""
result = QtCore.Signal(object)
def __init__(self, *args):
QtWidgets.QAction.__init__(self, *args)
self.triggered.connect(self.correct)
def correct(self):
self.result.emit(self.text())
| 8,143 | Python | .py | 188 | 32.648936 | 95 | 0.621051 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
81 | highlighter.py | git-cola_git-cola/cola/widgets/highlighter.py | from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
have_pygments = True
try:
from pygments.styles import get_style_by_name
from pygments import lex
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_for_filename
except ImportError:
have_pygments = False
def highlight_document(edit, filename):
if not have_pygments:
return
doc = edit.document()
try:
lexer = get_lexer_for_filename(filename, stripnl=False)
except ClassNotFound:
return
style = get_style_by_name('default')
font = doc.defaultFont()
base_format = QtGui.QTextCharFormat()
base_format.setFont(font)
token_formats = {}
window = edit.window()
if hasattr(window, 'processEvents'):
processEvents = window.processEvents
else:
processEvents = QtCore.QCoreApplication.processEvents
def get_token_format(token):
if token in token_formats:
return token_formats[token]
if token.parent:
parent_format = get_token_format(token.parent)
else:
parent_format = base_format
fmt = QtGui.QTextCharFormat(parent_format)
font = fmt.font()
if style.styles_token(token):
tstyle = style.style_for_token(token)
if tstyle['color']:
fmt.setForeground(QtGui.QColor('#' + tstyle['color']))
if tstyle['bold']:
font.setWeight(QtGui.QFont.Bold)
if tstyle['italic']:
font.setItalic(True)
if tstyle['underline']:
fmt.setFontUnderline(True)
if tstyle['bgcolor']:
fmt.setBackground(QtGui.QColor('#' + tstyle['bgcolor']))
token_formats[token] = fmt
return fmt
text = doc.toPlainText()
block_count = 0
block = doc.firstBlock()
assert isinstance(block, QtGui.QTextBlock)
block_pos = 0
block_len = block.length()
block_formats = []
for token, ttext in lex(text, lexer):
format_len = len(ttext)
fmt = get_token_format(token)
while format_len > 0:
format_range = QtGui.QTextLayout.FormatRange()
format_range.start = block_pos
format_range.length = min(format_len, block_len)
format_range.format = fmt
block_formats.append(format_range)
block_len -= format_range.length
format_len -= format_range.length
block_pos += format_range.length
if block_len == 0:
block.layout().setAdditionalFormats(block_formats)
doc.markContentsDirty(block.position(), block.length())
block = block.next()
block_pos = 0
block_len = block.length()
block_formats = []
block_count += 1
if block_count % 100 == 0:
processEvents()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
python = QtWidgets.QPlainTextEdit()
with open(__file__, encoding='utf-8') as f:
python.setPlainText(f.read())
python.setWindowTitle('python')
python.show()
highlight_document(python, __file__)
app.exec_()
| 3,268 | Python | .py | 90 | 27.2 | 72 | 0.606646 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
82 | submodules.py | git-cola_git-cola/cola/widgets/submodules.py | """Provides widgets related to submodules"""
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from .. import cmds
from .. import compat
from .. import core
from .. import qtutils
from .. import icons
from ..i18n import N_
from ..widgets import defs
from ..widgets import standard
from ..widgets import text
def add_submodule(context, parent):
"""Add a new submodule"""
dlg = AddSubmodule(parent)
dlg.show()
if dlg.exec_() == standard.Dialog.Accepted:
cmd = dlg.get(context)
cmd.do()
class SubmodulesWidget(QtWidgets.QFrame):
def __init__(self, context, parent):
super().__init__(parent)
self.context = context
self.tree = SubmodulesTreeWidget(context, parent=self)
self.setFocusProxy(self.tree)
self.main_layout = qtutils.vbox(defs.no_margin, defs.spacing, self.tree)
self.setLayout(self.main_layout)
# Titlebar buttons
self.add_button = qtutils.create_action_button(
tooltip=N_('Add Submodule'), icon=icons.add()
)
self.refresh_button = qtutils.create_action_button(
tooltip=N_('Refresh'), icon=icons.sync()
)
self.open_parent_button = qtutils.create_action_button(
tooltip=N_('Open Parent'), icon=icons.repo()
)
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.add_button,
self.open_parent_button,
self.refresh_button,
)
self.corner_widget = QtWidgets.QWidget(self)
self.corner_widget.setLayout(self.button_layout)
titlebar = parent.titleBarWidget()
titlebar.add_corner_widget(self.corner_widget)
# Connections
qtutils.connect_button(self.add_button, self.add_submodule)
qtutils.connect_button(self.refresh_button, self.tree.update_model.emit)
qtutils.connect_button(
self.open_parent_button, cmds.run(cmds.OpenParentRepo, context)
)
def add_submodule(self):
add_submodule(self.context, self)
class AddSubmodule(standard.Dialog):
"""Add a new submodule"""
def __init__(self, parent):
super().__init__(parent=parent)
self.setWindowTitle(N_('Submodules'))
hint = N_('git://git.example.com/repo.git')
tooltip = N_('Submodule URL (can be relative, ex: ../repo.git)')
self.url_text = text.HintedDefaultLineEdit(hint, tooltip=tooltip, parent=self)
hint = N_('path/to/submodule')
tooltip = N_('Submodule path within the current repository (optional)')
self.path_text = text.HintedDefaultLineEdit(hint, tooltip=tooltip, parent=self)
hint = N_('Branch name')
tooltip = N_('Submodule branch to track (optional)')
self.branch_text = text.HintedDefaultLineEdit(
hint, tooltip=tooltip, parent=self
)
self.depth_spinbox = standard.SpinBox(
mini=0, maxi=compat.maxint, value=0, parent=self
)
self.depth_spinbox.setToolTip(
N_(
'Create a shallow clone with history truncated to the '
'specified number of revisions. 0 performs a full clone.'
)
)
hint = N_('Reference URL')
tooltip = N_('Reference repository to use when cloning (optional)')
self.reference_text = text.HintedDefaultLineEdit(
hint, tooltip=tooltip, parent=self
)
self.add_button = qtutils.ok_button(N_('Add Submodule'), enabled=False)
self.close_button = qtutils.close_button()
self.form_layout = qtutils.form(
defs.no_margin,
defs.button_spacing,
(N_('URL'), self.url_text),
(N_('Path'), self.path_text),
(N_('Branch'), self.branch_text),
(N_('Depth'), self.depth_spinbox),
(N_('Reference Repository'), self.reference_text),
)
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
qtutils.STRETCH,
self.close_button,
self.add_button,
)
self.main_layout = qtutils.vbox(
defs.large_margin, defs.spacing, self.form_layout, self.button_layout
)
self.setLayout(self.main_layout)
self.init_size(parent=qtutils.active_window())
self.url_text.textChanged.connect(lambda x: self._update_widgets())
qtutils.connect_button(self.add_button, self.accept)
qtutils.connect_button(self.close_button, self.close)
def _update_widgets(self):
value = self.url_text.value()
self.add_button.setEnabled(bool(value))
def get(self, context):
return cmds.SubmoduleAdd(
context,
self.url_text.value(),
self.path_text.value(),
self.branch_text.value(),
self.depth_spinbox.value(),
self.reference_text.value(),
)
class SubmodulesTreeWidget(standard.TreeWidget):
update_model = Signal()
def __init__(self, context, parent=None):
standard.TreeWidget.__init__(self, parent=parent)
model = context.model
self.context = context
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setHeaderHidden(True)
# UI
self._active = False
self.list_helper = BuildItem()
# Connections
self.itemDoubleClicked.connect(self.tree_double_clicked)
model.submodules_changed.connect(self.refresh, type=Qt.QueuedConnection)
self.update_model.connect(
model.update_submodules_list, type=Qt.QueuedConnection
)
def refresh(self):
if not self._active:
return
submodules = self.context.model.submodules_list
items = [self.list_helper.get(entry) for entry in submodules]
self.clear()
if items:
self.addTopLevelItems(items)
def showEvent(self, event):
"""Defer updating widgets until the widget is visible"""
if not self._active:
self._active = True
self.update_model.emit()
return super().showEvent(event)
def tree_double_clicked(self, item, _column):
path = core.abspath(item.path)
cmds.do(cmds.OpenRepo, self.context, path)
class BuildItem:
def __init__(self):
self.state_folder_map = {}
self.state_folder_map[''] = icons.folder()
self.state_folder_map['+'] = icons.staged()
self.state_folder_map['-'] = icons.modified()
self.state_folder_map['U'] = icons.merge()
def get(self, entry):
"""entry: same as returned from list_submodule"""
name = entry[2]
path = entry[2]
tip = path + '\n' + entry[1]
if entry[3]:
tip += f'\n({entry[3]})'
icon = self.state_folder_map[entry[0]]
return SubmodulesTreeWidgetItem(name, path, tip, icon)
class SubmodulesTreeWidgetItem(QtWidgets.QTreeWidgetItem):
def __init__(self, name, path, tip, icon):
QtWidgets.QTreeWidgetItem.__init__(self)
self.path = path
self.setIcon(0, icon)
self.setText(0, name)
self.setToolTip(0, tip)
| 7,291 | Python | .py | 182 | 31.120879 | 87 | 0.622807 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
83 | merge.py | git-cola_git-cola/cola/widgets/merge.py | from qtpy import QtWidgets
from qtpy.QtCore import Qt
from ..i18n import N_
from ..interaction import Interaction
from ..qtutils import get
from .. import cmds
from .. import icons
from .. import qtutils
from . import completion
from . import standard
from . import defs
def local_merge(context):
"""Provides a dialog for merging branches"""
view = Merge(context, qtutils.active_window())
view.show()
view.raise_()
return view
class Merge(standard.Dialog):
"""Provides a dialog for merging branches."""
def __init__(self, context, parent=None, ref=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.cfg = cfg = context.cfg
self.model = context.model
if parent is not None:
self.setWindowModality(Qt.WindowModal)
# Widgets
self.title_label = QtWidgets.QLabel()
self.revision_label = QtWidgets.QLabel()
self.revision_label.setText(N_('Revision to Merge'))
self.revision = completion.GitRefLineEdit(context)
self.revision.setToolTip(N_('Revision to Merge'))
if ref:
self.revision.set_value(ref)
self.radio_local = qtutils.radio(text=N_('Local Branch'), checked=True)
self.radio_remote = qtutils.radio(text=N_('Tracking Branch'))
self.radio_tag = qtutils.radio(text=N_('Tag'))
self.revisions = QtWidgets.QListWidget()
self.revisions.setAlternatingRowColors(True)
self.button_viz = qtutils.create_button(
text=N_('Visualize'), icon=icons.visualize()
)
tooltip = N_('Squash the merged commits into a single commit')
self.checkbox_squash = qtutils.checkbox(text=N_('Squash'), tooltip=tooltip)
tooltip = N_(
'Always create a merge commit when enabled, '
'even when the merge is a fast-forward update'
)
self.checkbox_noff = qtutils.checkbox(
text=N_('No fast forward'), tooltip=tooltip, checked=False
)
self.checkbox_noff_state = False
tooltip = N_(
'Commit the merge if there are no conflicts. '
'Uncheck to leave the merge uncommitted'
)
self.checkbox_commit = qtutils.checkbox(
text=N_('Commit'), tooltip=tooltip, checked=True
)
self.checkbox_commit_state = True
text = N_('Create Signed Commit')
checked = cfg.get('cola.signcommits', False)
tooltip = N_('GPG-sign the merge commit')
self.checkbox_sign = qtutils.checkbox(
text=text, checked=checked, tooltip=tooltip
)
self.button_close = qtutils.close_button()
icon = icons.merge()
self.button_merge = qtutils.create_button(
text=N_('Merge'), icon=icon, default=True
)
# Layouts
self.revlayt = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.revision_label,
self.revision,
qtutils.STRETCH,
self.title_label,
)
self.radiolayt = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.radio_local,
self.radio_remote,
self.radio_tag,
)
self.buttonlayt = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.button_viz,
self.checkbox_squash,
self.checkbox_noff,
self.checkbox_commit,
self.checkbox_sign,
qtutils.STRETCH,
self.button_close,
self.button_merge,
)
self.mainlayt = qtutils.vbox(
defs.margin,
defs.spacing,
self.radiolayt,
self.revisions,
self.revlayt,
self.buttonlayt,
)
self.setLayout(self.mainlayt)
# Signal/slot connections
self.revision.textChanged.connect(self.update_title)
self.revision.enter.connect(self.merge_revision)
self.revisions.itemSelectionChanged.connect(self.revision_selected)
qtutils.connect_released(self.radio_local, self.update_revisions)
qtutils.connect_released(self.radio_remote, self.update_revisions)
qtutils.connect_released(self.radio_tag, self.update_revisions)
qtutils.connect_button(self.button_merge, self.merge_revision)
qtutils.connect_button(self.checkbox_squash, self.toggle_squash)
qtutils.connect_button(self.button_viz, self.viz_revision)
qtutils.connect_button(self.button_close, self.reject)
# Observer messages
self.model.updated.connect(self.update_all)
self.update_all()
self.init_size(parent=parent)
self.revision.setFocus()
def update_all(self):
"""Set the branch name for the window title and label."""
self.update_title()
self.update_revisions()
def update_title(self, _txt=None):
branch = self.model.currentbranch
revision = self.revision.text()
if revision:
txt = N_('Merge "%(revision)s" into "%(branch)s"') % {
'revision': revision,
'branch': branch,
}
else:
txt = N_('Merge into "%s"') % branch
self.button_merge.setEnabled(bool(revision))
self.title_label.setText(txt)
self.setWindowTitle(txt)
def toggle_squash(self):
"""Toggles the commit checkbox based on the squash checkbox."""
if get(self.checkbox_squash):
self.checkbox_commit_state = self.checkbox_commit.checkState()
self.checkbox_commit.setCheckState(Qt.Unchecked)
self.checkbox_commit.setDisabled(True)
self.checkbox_noff_state = self.checkbox_noff.checkState()
self.checkbox_noff.setCheckState(Qt.Unchecked)
self.checkbox_noff.setDisabled(True)
else:
self.checkbox_noff.setDisabled(False)
oldstateff = self.checkbox_noff_state
self.checkbox_noff.setCheckState(oldstateff)
self.checkbox_commit.setDisabled(False)
oldstate = self.checkbox_commit_state
self.checkbox_commit.setCheckState(oldstate)
def update_revisions(self):
"""Update the revision list whenever a radio button is clicked"""
self.revisions.clear()
self.revisions.addItems(self.current_revisions())
def revision_selected(self):
"""Update the revision field when a list item is selected"""
revlist = self.current_revisions()
widget = self.revisions
revision = qtutils.selected_item(widget, revlist)
if revision is not None:
self.revision.setText(revision)
def current_revisions(self):
"""Retrieve candidate items to merge"""
if get(self.radio_local):
return self.model.local_branches
if get(self.radio_remote):
return self.model.remote_branches
if get(self.radio_tag):
return self.model.tags
return []
def viz_revision(self):
"""Launch a gitk-like viewer on the selection revision"""
revision = self.revision.text()
if not revision:
Interaction.information(
N_('No Revision Specified'), N_('You must specify a revision to view.')
)
return
cmds.do(cmds.VisualizeRevision, self.context, revision)
def merge_revision(self):
"""Merge the selected revision/branch"""
revision = self.revision.text()
if not revision:
Interaction.information(
N_('No Revision Specified'), N_('You must specify a revision to merge.')
)
return
noff = get(self.checkbox_noff)
no_commit = not get(self.checkbox_commit)
squash = get(self.checkbox_squash)
sign = get(self.checkbox_sign)
context = self.context
cmds.do(cmds.Merge, context, revision, no_commit, squash, noff, sign)
self.accept()
def export_state(self):
"""Export persistent settings"""
state = super().export_state()
state['no-ff'] = get(self.checkbox_noff)
state['sign'] = get(self.checkbox_sign)
state['commit'] = get(self.checkbox_commit)
return state
def apply_state(self, state):
"""Apply persistent settings"""
result = super().apply_state(state)
self.checkbox_noff.setChecked(state.get('no-ff', False))
self.checkbox_sign.setChecked(state.get('sign', False))
self.checkbox_commit.setChecked(state.get('commit', True))
return result
| 8,704 | Python | .py | 215 | 30.8 | 88 | 0.621718 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
84 | archive.py | git-cola_git-cola/cola/widgets/archive.py | """Git Archive dialog"""
import os
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..git import STDOUT
from ..i18n import N_
from ..interaction import Interaction
from .. import cmds
from .. import core
from .. import icons
from .. import qtutils
from .text import LineEdit
from .standard import Dialog
from . import defs
class ExpandableGroupBox(QtWidgets.QGroupBox):
expanded = Signal(bool)
def __init__(self, parent=None):
QtWidgets.QGroupBox.__init__(self, parent)
self.setFlat(True)
self.is_expanded = True
self.click_pos = None
self.arrow_icon_size = defs.small_icon
def set_expanded(self, expanded):
if expanded == self.is_expanded:
self.expanded.emit(expanded)
return
self.is_expanded = expanded
for widget in self.findChildren(QtWidgets.QWidget):
widget.setHidden(not expanded)
self.expanded.emit(expanded)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
option = QtWidgets.QStyleOptionGroupBox()
self.initStyleOption(option)
icon_size = defs.small_icon
button_area = QtCore.QRect(0, 0, icon_size, icon_size)
offset = icon_size + defs.spacing
adjusted = option.rect.adjusted(0, 0, -offset, 0)
top_left = adjusted.topLeft()
button_area.moveTopLeft(QtCore.QPoint(top_left))
self.click_pos = event.pos()
QtWidgets.QGroupBox.mousePressEvent(self, event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.click_pos == event.pos():
self.set_expanded(not self.is_expanded)
QtWidgets.QGroupBox.mouseReleaseEvent(self, event)
def paintEvent(self, _event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOptionGroupBox()
self.initStyleOption(option)
painter.save()
painter.translate(self.arrow_icon_size + defs.spacing, 0)
painter.drawText(option.rect, Qt.AlignLeft, self.title())
painter.restore()
style = QtWidgets.QStyle
point = option.rect.adjusted(0, -4, 0, 0).topLeft()
icon_size = self.arrow_icon_size
option.rect = QtCore.QRect(point.x(), point.y(), icon_size, icon_size)
if self.is_expanded:
painter.drawPrimitive(style.PE_IndicatorArrowDown, option)
else:
painter.drawPrimitive(style.PE_IndicatorArrowRight, option)
def save_archive(context):
oid = context.git.rev_parse('HEAD')[STDOUT]
show_save_dialog(context, oid, parent=qtutils.active_window())
def show_save_dialog(context, oid, parent=None):
shortoid = oid[:7]
dlg = Archive(context, oid, shortoid, parent=parent)
dlg.show()
if dlg.exec_() != dlg.Accepted:
return None
return dlg
class Archive(Dialog):
def __init__(self, context, ref, shortref=None, parent=None):
Dialog.__init__(self, parent=parent)
self.context = context
if parent is not None:
self.setWindowModality(Qt.WindowModal)
# input
self.ref = ref
if shortref is None:
shortref = ref
# outputs
self.fmt = None
filename = f'{os.path.basename(core.getcwd())}-{shortref}'
self.prefix = filename + '/'
self.filename = filename
# widgets
self.setWindowTitle(N_('Save Archive'))
self.filetext = LineEdit()
self.filetext.set_value(self.filename)
self.browse = qtutils.create_toolbutton(icon=icons.file_zip())
stdout = context.git.archive('--list')[STDOUT]
self.format_strings = stdout.rstrip().splitlines()
self.format_combo = qtutils.combo(self.format_strings)
self.close_button = qtutils.close_button()
self.save_button = qtutils.create_button(
text=N_('Save'), icon=icons.save(), default=True
)
self.prefix_label = QtWidgets.QLabel()
self.prefix_label.setText(N_('Prefix'))
self.prefix_text = LineEdit()
self.prefix_text.set_value(self.prefix)
self.prefix_group = ExpandableGroupBox()
self.prefix_group.setTitle(N_('Advanced'))
# layouts
self.filelayt = qtutils.hbox(
defs.no_margin, defs.spacing, self.browse, self.filetext, self.format_combo
)
self.prefixlayt = qtutils.hbox(
defs.margin, defs.spacing, self.prefix_label, self.prefix_text
)
self.prefix_group.setLayout(self.prefixlayt)
self.prefix_group.set_expanded(False)
self.btnlayt = qtutils.hbox(
defs.no_margin,
defs.spacing,
qtutils.STRETCH,
self.close_button,
self.save_button,
)
self.mainlayt = qtutils.vbox(
defs.margin,
defs.no_spacing,
self.filelayt,
self.prefix_group,
qtutils.STRETCH,
self.btnlayt,
)
self.setLayout(self.mainlayt)
# initial setup; done before connecting to avoid
# signal/slot side-effects
if 'tar.gz' in self.format_strings:
idx = self.format_strings.index('tar.gz')
elif 'zip' in self.format_strings:
idx = self.format_strings.index('zip')
else:
idx = 0
self.format_combo.setCurrentIndex(idx)
self.update_format(idx)
# connections
self.filetext.textChanged.connect(self.filetext_changed)
self.prefix_text.textChanged.connect(self.prefix_text_changed)
self.format_combo.currentIndexChanged.connect(self.update_format)
self.prefix_group.expanded.connect(self.prefix_group_expanded)
self.accepted.connect(self.archive_saved)
qtutils.connect_button(self.browse, self.choose_filename)
qtutils.connect_button(self.close_button, self.reject)
qtutils.connect_button(self.save_button, self.save_archive)
self.init_size(parent=parent)
def archive_saved(self):
context = self.context
ref = self.ref
fmt = self.fmt
prefix = self.prefix
filename = self.filename
cmds.do(cmds.Archive, context, ref, fmt, prefix, filename)
Interaction.information(
N_('File Saved'), N_('File saved to "%s"') % self.filename
)
def save_archive(self):
filename = self.filename
if not filename:
return
if core.exists(filename):
title = N_('Overwrite File?')
msg = N_('The file "%s" exists and will be overwritten.') % filename
info_txt = N_('Overwrite "%s"?') % filename
ok_txt = N_('Overwrite')
if not Interaction.confirm(
title, msg, info_txt, ok_txt, default=False, icon=icons.save()
):
return
self.accept()
def choose_filename(self):
filename = qtutils.save_as(self.filename)
if not filename:
return
self.filetext.setText(filename)
self.update_format(self.format_combo.currentIndex())
def filetext_changed(self, filename):
self.filename = filename
self.save_button.setEnabled(bool(self.filename))
prefix = self.strip_exts(os.path.basename(self.filename)) + '/'
self.prefix_text.setText(prefix)
def prefix_text_changed(self, prefix):
self.prefix = prefix
def strip_exts(self, text):
for format_string in self.format_strings:
ext = '.' + format_string
if text.endswith(ext):
return text[: -len(ext)]
return text
def update_format(self, idx):
self.fmt = self.format_strings[idx]
text = self.strip_exts(self.filetext.text())
self.filename = f'{text}.{self.fmt}'
self.filetext.setText(self.filename)
self.filetext.setFocus()
if '/' in text:
start = text.rindex('/') + 1
else:
start = 0
self.filetext.setSelection(start, len(text) - start)
def prefix_group_expanded(self, expanded):
if expanded:
self.prefix_text.setFocus()
else:
self.filetext.setFocus()
| 8,366 | Python | .py | 211 | 30.582938 | 87 | 0.626649 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
85 | startup.py | git-cola_git-cola/cola/widgets/startup.py | """The startup dialog is presented when no repositories can be found at startup"""
from qtpy.QtCore import Qt
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from ..i18n import N_
from ..models import prefs
from .. import cmds
from .. import core
from .. import display
from .. import guicmds
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import utils
from .. import version
from . import clone
from . import defs
from . import standard
ICON_MODE = 0
LIST_MODE = 1
class StartupDialog(standard.Dialog):
"""Provides a GUI to Open or Clone a git repository."""
def __init__(self, context, parent=None):
standard.Dialog.__init__(self, parent)
self.context = context
self.setWindowTitle(N_('git-cola'))
# Top-most large icon
logo_pixmap = icons.cola().pixmap(defs.huge_icon, defs.huge_icon)
self.logo_label = QtWidgets.QLabel()
self.logo_label.setPixmap(logo_pixmap)
self.logo_label.setAlignment(Qt.AlignCenter)
self.logo_text_label = qtutils.label(text=version.cola_version())
self.logo_text_label.setAlignment(Qt.AlignCenter)
self.repodir = None
if context.runtask:
self.runtask = context.runtask
else:
self.runtask = context.runtask = qtutils.RunTask(parent=self)
self.new_button = qtutils.create_button(text=N_('New...'), icon=icons.new())
self.open_button = qtutils.create_button(
text=N_('Open Git Repository'), icon=icons.folder()
)
self.clone_button = qtutils.create_button(
text=N_('Clone...'), icon=icons.cola()
)
self.close_button = qtutils.close_button()
self.bookmarks_model = bookmarks_model = QtGui.QStandardItemModel()
self.items = items = []
item = QtGui.QStandardItem(N_('Browse...'))
item.setEditable(False)
item.setIcon(icons.open_directory())
bookmarks_model.appendRow(item)
# The tab bar allows choosing between Folder and List mode
self.tab_bar = QtWidgets.QTabBar()
self.tab_bar.setMovable(False)
self.tab_bar.addTab(icons.directory(), N_('Folder'))
self.tab_bar.addTab(icons.three_bars(), N_('List'))
# Bookmarks/"Favorites" and Recent are lists of {name,path: str}
normalize = display.normalize_path
settings = context.settings
all_repos = get_all_repos(self.context, settings)
added = set()
builder = BuildItem(self.context)
default_view_mode = ICON_MODE
for repo, is_bookmark in all_repos:
path = normalize(repo['path'])
name = normalize(repo['name'])
if path in added:
continue
added.add(path)
item = builder.get(path, name, default_view_mode, is_bookmark)
bookmarks_model.appendRow(item)
items.append(item)
self.bookmarks = BookmarksListView(
context,
bookmarks_model,
self.open_selected_bookmark,
self.set_model,
)
self.tab_layout = qtutils.vbox(
defs.no_margin, defs.no_spacing, self.tab_bar, self.bookmarks
)
self.logo_layout = qtutils.vbox(
defs.no_margin,
defs.spacing,
self.logo_label,
self.logo_text_label,
defs.button_spacing,
qtutils.STRETCH,
)
self.button_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.open_button,
self.clone_button,
self.new_button,
qtutils.STRETCH,
self.close_button,
)
self.main_layout = qtutils.grid(defs.margin, defs.spacing)
self.main_layout.addItem(self.logo_layout, 1, 1)
self.main_layout.addItem(self.tab_layout, 1, 2)
self.main_layout.addItem(self.button_layout, 2, 1, columnSpan=2)
self.setLayout(self.main_layout)
qtutils.connect_button(self.open_button, self.open_repo)
qtutils.connect_button(self.clone_button, self.clone_repo)
qtutils.connect_button(self.new_button, self.new_repo)
qtutils.connect_button(self.close_button, self.reject)
self.tab_bar.currentChanged.connect(self.tab_changed)
self.init_state(settings, self.resize_widget)
self.setFocusProxy(self.bookmarks)
self.bookmarks.setFocus()
# Update the list mode
list_mode = context.cfg.get('cola.startupmode', default='folder')
self.list_mode = list_mode
if list_mode == 'list':
self.tab_bar.setCurrentIndex(1)
def tab_changed(self, idx):
bookmarks = self.bookmarks
if idx == ICON_MODE:
mode = QtWidgets.QListView.IconMode
icon_size = make_size(defs.medium_icon)
grid_size = make_size(defs.large_icon)
list_mode = 'folder'
view_mode = ICON_MODE
rename_enabled = True
else:
mode = QtWidgets.QListView.ListMode
icon_size = make_size(defs.default_icon)
grid_size = QtCore.QSize()
list_mode = 'list'
view_mode = LIST_MODE
rename_enabled = False
self.bookmarks.set_rename_enabled(rename_enabled)
self.bookmarks.set_view_mode(view_mode)
bookmarks.setViewMode(mode)
bookmarks.setIconSize(icon_size)
bookmarks.setGridSize(grid_size)
new_items = []
builder = BuildItem(self.context)
for item in self.items:
if isinstance(item, PromptWidgetItem):
item = builder.get(item.path, item.name, view_mode, item.is_bookmark)
new_items.append(item)
self.set_model(new_items)
if list_mode != self.list_mode:
self.list_mode = list_mode
self.context.cfg.set_user('cola.startupmode', list_mode)
def resize_widget(self):
width, height = qtutils.desktop_size()
self.setGeometry(
width // 4,
height // 4,
width // 2,
height // 2,
)
def find_git_repo(self):
"""
Return a path to a git repository
This is the entry point for external callers.
This method finds a git repository by allowing the
user to browse to one on the filesystem or by creating
a new one with git-clone.
"""
self.show()
self.raise_()
if self.exec_() == QtWidgets.QDialog.Accepted:
return self.repodir
return None
def open_repo(self):
self.repodir = self.get_selected_bookmark()
if not self.repodir:
self.repodir = qtutils.opendir_dialog(
N_('Open Git Repository'), core.getcwd()
)
if self.repodir:
self.accept()
def clone_repo(self):
context = self.context
progress = standard.progress('', '', self)
clone.clone_repo(context, True, progress, self.clone_repo_done, False)
def clone_repo_done(self, task):
if task.cmd and task.cmd.status == 0:
self.repodir = task.destdir
self.accept()
else:
clone.task_finished(task)
def new_repo(self):
context = self.context
repodir = guicmds.new_repo(context)
if repodir:
self.repodir = repodir
self.accept()
def open_selected_bookmark(self):
selected = self.bookmarks.selectedIndexes()
if selected:
self.open_bookmark(selected[0])
def open_bookmark(self, index):
if index.row() == 0:
self.open_repo()
else:
self.repodir = self.bookmarks_model.data(index, Qt.UserRole)
if not self.repodir:
return
if not core.exists(self.repodir):
self.handle_broken_repo(index)
return
self.accept()
def handle_broken_repo(self, index):
settings = self.context.settings
all_repos = get_all_repos(self.context, settings)
repodir = self.bookmarks_model.data(index, Qt.UserRole)
repo = next(repo for repo, is_bookmark in all_repos if repo['path'] == repodir)
title = N_('Repository Not Found')
text = N_('%s could not be opened. Remove from bookmarks?') % repo['path']
logo = icons.from_style(QtWidgets.QStyle.SP_MessageBoxWarning)
if standard.question(title, text, N_('Remove'), logo=logo):
self.context.settings.remove_bookmark(repo['path'], repo['name'])
self.context.settings.remove_recent(repo['path'])
self.context.settings.save()
item = self.bookmarks_model.item(index.row())
self.items.remove(item)
self.bookmarks_model.removeRow(index.row())
def get_selected_bookmark(self):
selected = self.bookmarks.selectedIndexes()
if selected and selected[0].row() != 0:
return self.bookmarks_model.data(selected[0], Qt.UserRole)
return None
def set_model(self, items):
bookmarks_model = self.bookmarks_model
self.items = new_items = []
bookmarks_model.clear()
item = QtGui.QStandardItem(N_('Browse...'))
item.setEditable(False)
item.setIcon(icons.open_directory())
bookmarks_model.appendRow(item)
for item in items:
bookmarks_model.appendRow(item)
new_items.append(item)
def get_all_repos(context, settings):
"""Return a sorted list of bookmarks and recent repositories"""
bookmarks = settings.bookmarks
recent = settings.recent
all_repos = [(repo, True) for repo in bookmarks] + [
(repo, False) for repo in recent
]
if prefs.sort_bookmarks(context):
all_repos.sort(key=lambda details: details[0]['path'].lower())
return all_repos
class BookmarksListView(QtWidgets.QListView):
"""
List view class implementation of QWidgets.QListView for bookmarks and recent repos.
Almost methods is comes from `cola/widgets/bookmarks.py`.
"""
def __init__(self, context, model, open_selected_repo, set_model, parent=None):
super().__init__(parent)
self.current_mode = ICON_MODE
self.context = context
self.open_selected_repo = open_selected_repo
self.set_model = set_model
self.setEditTriggers(self.__class__.SelectedClicked)
self.activated.connect(self.open_selected_repo)
self.setModel(model)
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setViewMode(QtWidgets.QListView.IconMode)
self.setResizeMode(QtWidgets.QListView.Adjust)
self.setGridSize(make_size(defs.large_icon))
self.setIconSize(make_size(defs.medium_icon))
self.setDragEnabled(False)
self.setWordWrap(True)
# Context Menu
self.open_action = qtutils.add_action(
self, N_('Open'), self.open_selected_repo, hotkeys.OPEN
)
self.accept_action = qtutils.add_action(
self, N_('Accept'), self.accept_repo, *hotkeys.ACCEPT
)
self.open_new_action = qtutils.add_action(
self, N_('Open in New Window'), self.open_new_repo, hotkeys.NEW
)
self.set_default_repo_action = qtutils.add_action(
self, N_('Set Default Repository'), self.set_default_repo
)
self.clear_default_repo_action = qtutils.add_action(
self, N_('Clear Default Repository'), self.clear_default_repo
)
self.rename_repo_action = qtutils.add_action(
self, N_('Rename Repository'), self.rename_repo
)
self.open_default_action = qtutils.add_action(
self, cmds.OpenDefaultApp.name(), self.open_default, hotkeys.PRIMARY_ACTION
)
self.launch_editor_action = qtutils.add_action(
self, cmds.Edit.name(), self.launch_editor, hotkeys.EDIT
)
self.launch_terminal_action = qtutils.add_action(
self, cmds.LaunchTerminal.name(), self.launch_terminal, hotkeys.TERMINAL
)
self.copy_action = qtutils.add_action(self, N_('Copy'), self.copy, hotkeys.COPY)
self.delete_action = qtutils.add_action(self, N_('Delete'), self.delete_item)
self.remove_missing_action = qtutils.add_action(
self, N_('Prune Missing Entries'), self.remove_missing
)
self.remove_missing_action.setToolTip(
N_('Remove stale entries for repositories that no longer exist')
)
self.model().itemChanged.connect(self.item_changed)
self.action_group = utils.Group(
self.open_action,
self.open_new_action,
self.copy_action,
self.launch_editor_action,
self.launch_terminal_action,
self.open_default_action,
self.rename_repo_action,
self.delete_action,
)
self.action_group.setEnabled(True)
self.set_default_repo_action.setEnabled(True)
self.clear_default_repo_action.setEnabled(True)
def set_rename_enabled(self, is_enabled):
self.rename_repo_action.setEnabled(is_enabled)
def set_view_mode(self, view_mode):
self.current_mode = view_mode
def selected_item(self):
index = self.currentIndex()
return self.model().itemFromIndex(index)
def refresh(self):
self.model().layoutChanged.emit()
context = self.context
settings = context.settings
builder = BuildItem(context)
normalize = display.normalize_path
items = []
added = set()
all_repos = get_all_repos(self.context, settings)
for repo, is_bookmark in all_repos:
path = normalize(repo['path'])
name = normalize(repo['name'])
if path in added:
continue
added.add(path)
item = builder.get(path, name, self.current_mode, is_bookmark)
items.append(item)
self.set_model(items)
def contextMenuEvent(self, event):
"""Configures prompt's context menu."""
item = self.selected_item()
if isinstance(item, PromptWidgetItem):
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.open_action)
menu.addAction(self.open_new_action)
menu.addAction(self.open_default_action)
menu.addSeparator()
menu.addAction(self.copy_action)
menu.addAction(self.launch_editor_action)
menu.addAction(self.launch_terminal_action)
menu.addSeparator()
if item and item.is_default:
menu.addAction(self.clear_default_repo_action)
else:
menu.addAction(self.set_default_repo_action)
menu.addAction(self.rename_repo_action)
menu.addSeparator()
menu.addAction(self.delete_action)
menu.addAction(self.remove_missing_action)
menu.exec_(self.mapToGlobal(event.pos()))
def item_changed(self, item):
self.rename_entry(item, item.text())
def rename_entry(self, item, new_name):
settings = self.context.settings
if item.is_bookmark:
rename = settings.rename_bookmark
else:
rename = settings.rename_recent
if rename(item.path, item.name, new_name):
settings.save()
item.name = new_name
else:
item.setText(item.name)
def apply_func(self, func, *args, **kwargs):
item = self.selected_item()
if item:
func(item, *args, **kwargs)
def copy(self):
self.apply_func(lambda item: qtutils.set_clipboard(item.path))
def open_default(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.OpenDefaultApp, context, [item.path]))
def set_default_repo(self):
self.apply_func(self.set_default_item)
def set_default_item(self, item):
context = self.context
cmds.do(cmds.SetDefaultRepo, context, item.path)
self.refresh()
def clear_default_repo(self):
self.apply_func(self.clear_default_item)
def clear_default_item(self, _item):
context = self.context
cmds.do(cmds.SetDefaultRepo, context, None)
self.refresh()
def rename_repo(self):
index = self.currentIndex()
self.edit(index)
def accept_repo(self):
self.apply_func(self.accept_item)
def accept_item(self, _item):
if qtutils.enum_value(self.state()) & qtutils.enum_value(self.EditingState):
current_index = self.currentIndex()
widget = self.indexWidget(current_index)
if widget:
self.commitData(widget)
self.closePersistentEditor(current_index)
self.refresh()
else:
self.open_selected_repo()
def open_new_repo(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.OpenNewRepo, context, item.path))
def launch_editor(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.Edit, context, [item.path]))
def launch_terminal(self):
context = self.context
self.apply_func(lambda item: cmds.do(cmds.LaunchTerminal, context, item.path))
def delete_item(self):
"""Remove the selected repo item
If the item comes from bookmarks (item.is_bookmark) then delete the item
from the Bookmarks list, otherwise delete it from the Recents list.
"""
item = self.selected_item()
if not item:
return
if item.is_bookmark:
cmd = cmds.RemoveBookmark
else:
cmd = cmds.RemoveRecent
context = self.context
ok, _, _, _ = cmds.do(cmd, context, item.path, item.name, icon=icons.discard())
if ok:
self.refresh()
def remove_missing(self):
"""Remove missing entries from the favorites/recent file list"""
settings = self.context.settings
settings.remove_missing_bookmarks()
settings.remove_missing_recent()
self.refresh()
class BuildItem:
def __init__(self, context):
self.star_icon = icons.star()
self.folder_icon = icons.folder()
cfg = context.cfg
self.default_repo = cfg.get('cola.defaultrepo')
def get(self, path, name, mode, is_bookmark):
is_default = self.default_repo == path
if is_default:
icon = self.star_icon
else:
icon = self.folder_icon
return PromptWidgetItem(path, name, mode, icon, is_default, is_bookmark)
class PromptWidgetItem(QtGui.QStandardItem):
def __init__(self, path, name, mode, icon, is_default, is_bookmark):
QtGui.QStandardItem.__init__(self, icon, name)
self.path = path
self.name = name
self.mode = mode
self.is_default = is_default
self.is_bookmark = is_bookmark
editable = mode == ICON_MODE
if self.mode == ICON_MODE:
item_text = self.name
else:
item_text = self.path
user_role = Qt.UserRole
self.setEditable(editable)
self.setData(path, user_role)
self.setIcon(icon)
self.setText(item_text)
self.setToolTip(path)
def make_size(size):
"""Construct a QSize from a single value"""
return QtCore.QSize(size, size)
| 19,701 | Python | .py | 483 | 31.15528 | 88 | 0.61906 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
86 | dag.py | git-cola_git-cola/cola/widgets/dag.py | import collections
import itertools
import math
from functools import partial
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from ..compat import maxsize
from ..i18n import N_
from ..models import dag
from ..models import main
from ..models import prefs
from ..qtutils import get
from .. import core
from .. import cmds
from .. import difftool
from .. import gitcmds
from .. import guicmds
from .. import hotkeys
from .. import icons
from .. import qtcompat
from .. import qtutils
from .. import utils
from . import archive
from . import browse
from . import completion
from . import createbranch
from . import createtag
from . import defs
from . import diff
from . import filelist
from . import standard
def git_dag(context, args=None, existing_view=None, show=True):
"""Return a pre-populated git DAG widget."""
model = context.model
branch = model.currentbranch
# disambiguate between branch names and filenames by using '--'
branch_doubledash = (branch + ' --') if branch else ''
params = dag.DAG(branch_doubledash, 1000)
params.set_arguments(args)
if existing_view is None:
view = GitDAG(context, params)
else:
view = existing_view
view.set_params(params)
if params.ref:
view.display()
if show:
view.show()
return view
class FocusRedirectProxy:
"""Redirect actions from the main widget to child widgets"""
def __init__(self, *widgets):
"""Provide proxied widgets; the default widget must be first"""
self.widgets = widgets
self.default = widgets[0]
def __getattr__(self, name):
return lambda *args, **kwargs: self._forward_action(name, *args, **kwargs)
def _forward_action(self, name, *args, **kwargs):
"""Forward the captured action to the focused or default widget"""
widget = QtWidgets.QApplication.focusWidget()
if widget in self.widgets and hasattr(widget, name):
func = getattr(widget, name)
else:
func = getattr(self.default, name)
return func(*args, **kwargs)
class ViewerMixin:
"""Implementations must provide selected_items()"""
def __init__(self):
self.context = None # provided by implementation
self.selected = None
self.clicked = None
self.menu_actions = None # provided by implementation
def selected_item(self):
"""Return the currently selected item"""
selected_items = self.selected_items()
if not selected_items:
return None
return selected_items[0]
def selected_oid(self):
"""Return the currently selected commit object ID"""
item = self.selected_item()
if item is None:
result = None
else:
result = item.commit.oid
return result
def selected_oids(self):
"""Return the currently selected commit object IDs"""
return [i.commit for i in self.selected_items()]
def clicked_oid(self):
"""Return the clicked or selected commit object ID"""
if self.clicked:
return self.clicked.oid
return self.selected_oid()
def with_oid(self, func):
"""Run an operation with a commit object ID"""
oid = self.clicked_oid()
if oid:
result = func(oid)
else:
result = None
return result
def with_oid_short(self, func):
"""Run an operation with a short commit object ID"""
oid = self.clicked_oid()
if oid:
abbrev = prefs.abbrev(self.context)
result = func(oid[:abbrev])
else:
result = None
return result
def with_selected_oid(self, func):
"""Run an operation with a commit object ID"""
oid = self.selected_oid()
if oid:
result = func(oid)
else:
result = None
return result
def diff_selected_this(self):
"""Diff the selected commit against the clicked commit"""
clicked_oid = self.clicked.oid
selected_oid = self.selected.oid
self.diff_commits.emit(selected_oid, clicked_oid)
def diff_this_selected(self):
"""Diff the clicked commit against the selected commit"""
clicked_oid = self.clicked.oid
selected_oid = self.selected.oid
self.diff_commits.emit(clicked_oid, selected_oid)
def cherry_pick(self):
"""Cherry-pick a commit using git cherry-pick"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.CherryPick, context, [oid]))
def revert(self):
"""Revert a commit using git revert"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.Revert, context, oid))
def copy_to_clipboard(self):
"""Copy the current commit object ID to the clipboard"""
self.with_oid(qtutils.set_clipboard)
def copy_to_clipboard_short(self):
"""Copy the current commit object ID to the clipboard"""
self.with_oid_short(qtutils.set_clipboard)
def checkout_branch(self):
"""Checkout the clicked/selected branch"""
branches = []
clicked = self.clicked
selected = self.selected_item()
if clicked:
branches.extend(clicked.branches)
if selected:
branches.extend(selected.commit.branches)
if not branches:
return
guicmds.checkout_branch(self.context, default=branches[0])
def create_branch(self):
"""Create a branch at the selected commit"""
context = self.context
create_new_branch = partial(createbranch.create_new_branch, context)
self.with_oid(lambda oid: create_new_branch(revision=oid))
def create_tag(self):
"""Create a tag at the selected commit"""
context = self.context
self.with_oid(lambda oid: createtag.create_tag(context, ref=oid))
def create_tarball(self):
"""Create a tarball from the selected commit"""
context = self.context
self.with_oid(lambda oid: archive.show_save_dialog(context, oid, parent=self))
def show_diff(self):
"""Show the diff for the selected commit"""
context = self.context
self.with_oid(
lambda oid: difftool.diff_expression(
context, self, oid + '^!', hide_expr=False, focus_tree=True
)
)
def show_dir_diff(self):
"""Show a full directory diff for the selected commit"""
context = self.context
self.with_oid(
lambda oid: difftool.difftool_launch(
context, left=oid, left_take_magic=True, dir_diff=True
)
)
def rebase_to_commit(self):
"""Rebase the current branch to the selected commit"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.Rebase, context, upstream=oid))
def reset_mixed(self):
"""Reset the repository using git reset --mixed"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.ResetMixed, context, ref=oid))
def reset_keep(self):
"""Reset the repository using git reset --keep"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.ResetKeep, context, ref=oid))
def reset_merge(self):
"""Reset the repository using git reset --merge"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.ResetMerge, context, ref=oid))
def reset_soft(self):
"""Reset the repository using git reset --soft"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.ResetSoft, context, ref=oid))
def reset_hard(self):
"""Reset the repository using git reset --hard"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.ResetHard, context, ref=oid))
def restore_worktree(self):
"""Reset the worktree contents from the selected commit"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.RestoreWorktree, context, ref=oid))
def checkout_detached(self):
"""Checkout a commit using an anonymous detached HEAD"""
context = self.context
self.with_oid(lambda oid: cmds.do(cmds.Checkout, context, [oid]))
def save_blob_dialog(self):
"""Save a file blob from the selected commit"""
context = self.context
self.with_oid(lambda oid: browse.BrowseBranch.browse(context, oid))
def save_blob_from_parent_dialog(self):
"""Save a file blob from the parent of the selected commit"""
context = self.context
self.with_oid(lambda oid: browse.BrowseBranch.browse(context, oid + '^'))
def update_menu_actions(self, event):
"""Update menu actions to reflect the selection state"""
selected_items = self.selected_items()
selected_item = self.selected_item()
item = self.itemAt(event.pos())
if item is None:
self.clicked = commit = None
else:
self.clicked = commit = item.commit
has_single_selection = len(selected_items) == 1
has_single_selection_or_clicked = bool(has_single_selection or commit)
has_selection = bool(selected_items)
can_diff = bool(
commit
and has_single_selection
and selected_items
and commit is not selected_items[0].commit
)
has_branches = (
has_single_selection
and selected_item
and bool(selected_item.commit.branches)
) or (self.clicked and bool(self.clicked.branches))
if can_diff:
self.selected = selected_items[0].commit
else:
self.selected = None
self.menu_actions['diff_this_selected'].setEnabled(can_diff)
self.menu_actions['diff_selected_this'].setEnabled(can_diff)
self.menu_actions['diff_commit'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['diff_commit_all'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['checkout_branch'].setEnabled(has_branches)
self.menu_actions['checkout_detached'].setEnabled(
has_single_selection_or_clicked
)
self.menu_actions['cherry_pick'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['copy'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['copy_short'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['create_branch'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['create_patch'].setEnabled(has_selection)
self.menu_actions['create_tag'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['create_tarball'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['rebase_to_commit'].setEnabled(
has_single_selection_or_clicked
)
self.menu_actions['reset_mixed'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['reset_keep'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['reset_merge'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['reset_soft'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['reset_hard'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['restore_worktree'].setEnabled(
has_single_selection_or_clicked
)
self.menu_actions['revert'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['save_blob'].setEnabled(has_single_selection_or_clicked)
self.menu_actions['save_blob_from_parent'].setEnabled(
has_single_selection_or_clicked
)
def context_menu_event(self, event):
"""Build a context menu and execute it"""
self.update_menu_actions(event)
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.menu_actions['diff_this_selected'])
menu.addAction(self.menu_actions['diff_selected_this'])
menu.addAction(self.menu_actions['diff_commit'])
menu.addAction(self.menu_actions['diff_commit_all'])
menu.addSeparator()
menu.addAction(self.menu_actions['checkout_branch'])
menu.addAction(self.menu_actions['create_branch'])
menu.addAction(self.menu_actions['create_tag'])
menu.addAction(self.menu_actions['rebase_to_commit'])
menu.addSeparator()
menu.addAction(self.menu_actions['cherry_pick'])
menu.addAction(self.menu_actions['revert'])
menu.addAction(self.menu_actions['create_patch'])
menu.addAction(self.menu_actions['create_tarball'])
menu.addSeparator()
reset_menu = menu.addMenu(N_('Reset'))
reset_menu.addAction(self.menu_actions['reset_soft'])
reset_menu.addAction(self.menu_actions['reset_mixed'])
reset_menu.addAction(self.menu_actions['restore_worktree'])
reset_menu.addSeparator()
reset_menu.addAction(self.menu_actions['reset_keep'])
reset_menu.addAction(self.menu_actions['reset_merge'])
reset_menu.addAction(self.menu_actions['reset_hard'])
menu.addAction(self.menu_actions['checkout_detached'])
menu.addSeparator()
menu.addAction(self.menu_actions['save_blob'])
menu.addAction(self.menu_actions['save_blob_from_parent'])
menu.addAction(self.menu_actions['copy_short'])
menu.addAction(self.menu_actions['copy'])
menu.exec_(self.mapToGlobal(event.pos()))
def set_icon(icon, action):
""" "Set the icon for an action and return the action"""
action.setIcon(icon)
return action
def viewer_actions(widget, proxy):
"""Return common actions across the tree and graph widgets"""
return {
'diff_this_selected': set_icon(
icons.compare(),
qtutils.add_action(
widget, N_('Diff this -> selected'), proxy.diff_this_selected
),
),
'diff_selected_this': set_icon(
icons.compare(),
qtutils.add_action(
widget, N_('Diff selected -> this'), proxy.diff_selected_this
),
),
'create_branch': set_icon(
icons.branch(),
qtutils.add_action(widget, N_('Create Branch'), proxy.create_branch),
),
'create_patch': set_icon(
icons.save(),
qtutils.add_action(widget, N_('Create Patch'), proxy.create_patch),
),
'create_tag': set_icon(
icons.tag(),
qtutils.add_action(widget, N_('Create Tag'), proxy.create_tag),
),
'create_tarball': set_icon(
icons.file_zip(),
qtutils.add_action(
widget, N_('Save As Tarball/Zip...'), proxy.create_tarball
),
),
'cherry_pick': set_icon(
icons.cherry_pick(),
qtutils.add_action(widget, N_('Cherry Pick'), proxy.cherry_pick),
),
'revert': set_icon(
icons.undo(), qtutils.add_action(widget, N_('Revert'), proxy.revert)
),
'diff_commit': set_icon(
icons.diff(),
qtutils.add_action(
widget, N_('Launch Diff Tool'), proxy.show_diff, hotkeys.DIFF
),
),
'diff_commit_all': set_icon(
icons.diff(),
qtutils.add_action(
widget,
N_('Launch Directory Diff Tool'),
proxy.show_dir_diff,
hotkeys.DIFF_SECONDARY,
),
),
'checkout_branch': set_icon(
icons.branch(),
qtutils.add_action(widget, N_('Checkout Branch'), proxy.checkout_branch),
),
'checkout_detached': qtutils.add_action(
widget, N_('Checkout Detached HEAD'), proxy.checkout_detached
),
'rebase_to_commit': set_icon(
icons.play(),
qtutils.add_action(
widget, N_('Rebase to this commit'), proxy.rebase_to_commit
),
),
'reset_soft': set_icon(
icons.style_dialog_reset(),
qtutils.add_action(widget, N_('Reset Branch (Soft)'), proxy.reset_soft),
),
'reset_mixed': set_icon(
icons.style_dialog_reset(),
qtutils.add_action(
widget, N_('Reset Branch and Stage (Mixed)'), proxy.reset_mixed
),
),
'reset_keep': set_icon(
icons.style_dialog_reset(),
qtutils.add_action(
widget,
N_('Restore Worktree and Reset All (Keep Unstaged Edits)'),
proxy.reset_keep,
),
),
'reset_merge': set_icon(
icons.style_dialog_reset(),
qtutils.add_action(
widget,
N_('Restore Worktree and Reset All (Merge)'),
proxy.reset_merge,
),
),
'reset_hard': set_icon(
icons.style_dialog_reset(),
qtutils.add_action(
widget,
N_('Restore Worktree and Reset All (Hard)'),
proxy.reset_hard,
),
),
'restore_worktree': set_icon(
icons.edit(),
qtutils.add_action(widget, N_('Restore Worktree'), proxy.restore_worktree),
),
'save_blob': set_icon(
icons.save(),
qtutils.add_action(widget, N_('Grab File...'), proxy.save_blob_dialog),
),
'save_blob_from_parent': set_icon(
icons.save(),
qtutils.add_action(
widget,
N_('Grab File from Parent Commit...'),
proxy.save_blob_from_parent_dialog,
),
),
'copy': set_icon(
icons.copy(),
qtutils.add_action(
widget,
N_('Copy Commit'),
proxy.copy_to_clipboard,
hotkeys.COPY_COMMIT_ID,
),
),
'copy_short': set_icon(
icons.copy(),
qtutils.add_action(
widget,
N_('Copy Commit (Short)'),
proxy.copy_to_clipboard_short,
hotkeys.COPY,
),
),
}
class GitDagLineEdit(completion.GitLogLineEdit):
"""The text input field for specifying "git log" options"""
def __init__(self, context):
super().__init__(context)
self._action_filter_to_current_author = qtutils.add_action(
self, N_('Commits authored by me'), self._filter_to_current_author
)
self._action_pickaxe_search = qtutils.add_action(
self, N_('Pickaxe search for changes containing text'), self._pickaxe_search
)
self._action_grep_search = qtutils.add_action(
self,
N_('Search commit messages'),
self._grep_search,
)
self._action_no_merges = qtutils.add_action(
self, N_('Ignore merge commits'), self._no_merges
)
def contextMenuEvent(self, event):
"""Adds custom actions to the default context menu"""
event_pos = event.pos()
menu = self.createStandardContextMenu()
menu.addSeparator()
actions = menu.actions()
first_action = actions[0]
menu.insertAction(first_action, self._action_pickaxe_search)
menu.insertAction(first_action, self._action_filter_to_current_author)
menu.insertAction(first_action, self._action_grep_search)
menu.insertAction(first_action, self._action_no_merges)
menu.insertSeparator(first_action)
menu.exec_(self.mapToGlobal(event_pos))
def insert(self, text):
"""Insert text at the beginning of the current text"""
value = self.value()
if value:
text = f'{text} {value}'
self.setText(text)
self.close_popup()
def _filter_to_current_author(self):
"""Filter to commits by the current author/user"""
_, email = self.context.cfg.get_author()
author_filter = '--author=' + email
self.insert(author_filter)
def _pickaxe_search(self):
"""Pickaxe search for changes containing text"""
self.insert('-G"search"')
start = len('-G"')
length = len('search')
self.setSelection(start, length)
def _grep_search(self):
"""Pickaxe search for changes containing text"""
self.insert('--grep="search"')
start = len('--grep="')
length = len('search')
self.setSelection(start, length)
def _no_merges(self):
"""Ignore merge commits"""
self.insert('--no-merges')
class CommitTreeWidgetItem(QtWidgets.QTreeWidgetItem):
"""Custom TreeWidgetItem used in to build the commit tree widget"""
def __init__(self, commit, parent=None):
QtWidgets.QTreeWidgetItem.__init__(self, parent)
self.commit = commit
self.setText(0, commit.summary)
self.setText(1, commit.author)
self.setText(2, commit.authdate)
class CommitTreeWidget(standard.TreeWidget, ViewerMixin):
"""Display commits using a flat treewidget in "list" mode"""
commits_selected = Signal(object)
diff_commits = Signal(object, object)
zoom_to_fit = Signal()
def __init__(self, context, parent):
standard.TreeWidget.__init__(self, parent)
ViewerMixin.__init__(self)
self.setSelectionMode(self.ExtendedSelection)
self.setHeaderLabels([N_('Summary'), N_('Author'), N_('Date, Time')])
self.context = context
self.oidmap = {}
self.menu_actions = None
self.selecting = False
self.commits = []
self._adjust_columns = False
self.action_up = qtutils.add_action(
self, N_('Go Up'), self.go_up, hotkeys.MOVE_UP
)
self.action_down = qtutils.add_action(
self, N_('Go Down'), self.go_down, hotkeys.MOVE_DOWN
)
self.zoom_to_fit_action = qtutils.add_action(
self, N_('Zoom to Fit'), self.zoom_to_fit.emit, hotkeys.FIT
)
self.itemSelectionChanged.connect(self.selection_changed)
def export_state(self):
"""Export the widget's state"""
# The base class method is intentionally overridden because we only
# care about the details below for this sub-widget.
state = {}
state['column_widths'] = self.column_widths()
return state
def apply_state(self, state):
"""Apply the exported widget state"""
try:
column_widths = state['column_widths']
except (KeyError, ValueError):
column_widths = None
if column_widths:
self.set_column_widths(column_widths)
else:
# Defer showing the columns until we are shown, and our true width
# is known. Calling adjust_columns() here ends up with the wrong
# answer because we have not yet been parented to the layout.
# We set this flag that we process once during our initial
# showEvent().
self._adjust_columns = True
return True
# Qt overrides
def showEvent(self, event):
"""Override QWidget::showEvent() to size columns when we are shown"""
if self._adjust_columns:
self._adjust_columns = False
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)
return standard.TreeWidget.showEvent(self, event)
# ViewerMixin
def go_up(self):
"""Select the item above the current item"""
self.goto(self.itemAbove)
def go_down(self):
"""Select the item below the current item"""
self.goto(self.itemBelow)
def goto(self, finder):
"""Move the selection using a finder strategy"""
items = self.selected_items()
item = items[0] if items else None
if item is None:
return
found = finder(item)
if found:
self.select([found.commit.oid])
def selected_commit_range(self):
"""Return a range of selected commits"""
selected_items = self.selected_items()
if not selected_items:
return None, None
return selected_items[-1].commit.oid, selected_items[0].commit.oid
def set_selecting(self, selecting):
"""Record the "are we selecting?" status"""
self.selecting = selecting
def selection_changed(self):
"""Respond to itemSelectionChanged notifications"""
items = self.selected_items()
if not items:
self.set_selecting(True)
self.commits_selected.emit([])
self.set_selecting(False)
return
self.set_selecting(True)
self.commits_selected.emit(sort_by_generation([i.commit for i in items]))
self.set_selecting(False)
def select_commits(self, commits):
"""Select commits that were selected by the sibling tree/graph widget"""
if self.selecting:
return
with qtutils.BlockSignals(self):
self.select([commit.oid for commit in commits])
def select(self, oids):
"""Mark items as selected"""
self.clearSelection()
if not oids:
return
for oid in oids:
try:
item = self.oidmap[oid]
except KeyError:
continue
self.scrollToItem(item)
item.setSelected(True)
def clear(self):
"""Clear the tree"""
QtWidgets.QTreeWidget.clear(self)
self.oidmap.clear()
self.commits = []
def add_commits(self, commits):
"""Add commits to the tree"""
self.commits.extend(commits)
items = []
for c in reversed(commits):
item = CommitTreeWidgetItem(c)
items.append(item)
self.oidmap[c.oid] = item
for tag in c.tags:
self.oidmap[tag] = item
self.insertTopLevelItems(0, items)
def create_patch(self):
"""Export a patch from the selected items"""
items = self.selectedItems()
if not items:
return
context = self.context
oids = [item.commit.oid for item in reversed(items)]
all_oids = [c.oid for c in self.commits]
cmds.do(cmds.FormatPatch, context, oids, all_oids)
# Qt overrides
def contextMenuEvent(self, event):
"""Create a custom context menu and execute it"""
self.context_menu_event(event)
def mousePressEvent(self, event):
"""Intercept the right-click event to retain selection state"""
item = self.itemAt(event.pos())
if item is None:
self.clicked = None
else:
self.clicked = item.commit
if event.button() == Qt.RightButton:
event.accept()
return
QtWidgets.QTreeWidget.mousePressEvent(self, event)
class GitDAG(standard.MainWindow):
"""The git-dag widget."""
commits_selected = Signal(object)
def __init__(self, context, params, parent=None):
super().__init__(parent)
self.setMinimumSize(420, 420)
# change when widgets are added/removed
self.widget_version = 2
self.context = context
self.params = params
self.model = context.model
self.commits = {}
self.commit_list = []
self.selection = []
self.old_refs = set()
self.old_oids = None
self.old_count = 0
self.force_refresh = False
self.thread = None
self.revtext = GitDagLineEdit(context)
self.maxresults = standard.SpinBox()
self.zoom_out = qtutils.create_action_button(
tooltip=N_('Zoom Out'), icon=icons.zoom_out()
)
self.zoom_in = qtutils.create_action_button(
tooltip=N_('Zoom In'), icon=icons.zoom_in()
)
self.zoom_to_fit = qtutils.create_action_button(
tooltip=N_('Zoom to Fit'), icon=icons.zoom_fit_best()
)
self.treewidget = CommitTreeWidget(context, self)
self.diffwidget = diff.DiffWidget(context, self, is_commit=True)
self.filewidget = filelist.FileWidget(context, self)
self.graphview = GraphView(context, self)
self.treewidget.commits_selected.connect(self.commits_selected)
self.graphview.commits_selected.connect(self.commits_selected)
self.commits_selected.connect(self.select_commits)
self.commits_selected.connect(self.diffwidget.commits_selected)
self.commits_selected.connect(self.filewidget.commits_selected)
self.commits_selected.connect(self.graphview.select_commits)
self.commits_selected.connect(self.treewidget.select_commits)
self.filewidget.files_selected.connect(self.diffwidget.files_selected)
self.filewidget.difftool_selected.connect(self.difftool_selected)
self.filewidget.histories_selected.connect(self.histories_selected)
self.proxy = FocusRedirectProxy(
self.treewidget, self.graphview, self.filewidget
)
self.treewidget.menu_actions = viewer_actions(self.treewidget, self.proxy)
self.graphview.menu_actions = viewer_actions(self.graphview, self.proxy)
self.controls_layout = qtutils.hbox(
defs.no_margin, defs.spacing, self.revtext, self.maxresults
)
self.controls_widget = QtWidgets.QWidget()
self.controls_widget.setLayout(self.controls_layout)
self.log_dock = qtutils.create_dock('Log', N_('Log'), self, stretch=False)
self.log_dock.setWidget(self.treewidget)
log_dock_titlebar = self.log_dock.titleBarWidget()
log_dock_titlebar.add_corner_widget(self.controls_widget)
self.file_dock = qtutils.create_dock('Files', N_('Files'), self)
self.file_dock.setWidget(self.filewidget)
self.diff_panel = diff.DiffPanel(self.diffwidget, self.diffwidget.diff, self)
self.diff_options = diff.Options(self.diffwidget)
self.diffwidget.set_options(self.diff_options)
self.diff_options.hide_advanced_options()
self.diff_options.set_diff_type(main.Types.TEXT)
self.diff_dock = qtutils.create_dock('Diff', N_('Diff'), self)
self.diff_dock.setWidget(self.diff_panel)
diff_titlebar = self.diff_dock.titleBarWidget()
diff_titlebar.add_corner_widget(self.diff_options)
self.graph_controls_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.zoom_out,
self.zoom_in,
self.zoom_to_fit,
defs.spacing,
)
self.graph_controls_widget = QtWidgets.QWidget()
self.graph_controls_widget.setLayout(self.graph_controls_layout)
self.graphview_dock = qtutils.create_dock('Graph', N_('Graph'), self)
self.graphview_dock.setWidget(self.graphview)
graph_titlebar = self.graphview_dock.titleBarWidget()
graph_titlebar.add_corner_widget(self.graph_controls_widget)
self.lock_layout_action = qtutils.add_action_bool(
self, N_('Lock Layout'), self.set_lock_layout, False
)
self.refresh_action = qtutils.add_action(
self, N_('Refresh'), self.refresh, hotkeys.REFRESH
)
# Create the application menu
self.menubar = QtWidgets.QMenuBar(self)
self.setMenuBar(self.menubar)
# View Menu
self.view_menu = qtutils.add_menu(N_('View'), self.menubar)
self.view_menu.addAction(self.refresh_action)
self.view_menu.addAction(self.log_dock.toggleViewAction())
self.view_menu.addAction(self.graphview_dock.toggleViewAction())
self.view_menu.addAction(self.diff_dock.toggleViewAction())
self.view_menu.addAction(self.file_dock.toggleViewAction())
self.view_menu.addSeparator()
self.view_menu.addAction(self.lock_layout_action)
left = Qt.LeftDockWidgetArea
right = Qt.RightDockWidgetArea
self.addDockWidget(left, self.log_dock)
self.addDockWidget(left, self.diff_dock)
self.addDockWidget(right, self.graphview_dock)
self.addDockWidget(right, self.file_dock)
# Also re-loads dag.* from the saved state
self.init_state(context.settings, self.resize_to_desktop)
qtutils.connect_button(self.zoom_out, self.graphview.zoom_out)
qtutils.connect_button(self.zoom_in, self.graphview.zoom_in)
qtutils.connect_button(self.zoom_to_fit, self.graphview.zoom_to_fit)
self.treewidget.zoom_to_fit.connect(self.graphview.zoom_to_fit)
self.treewidget.diff_commits.connect(self.diff_commits)
self.graphview.diff_commits.connect(self.diff_commits)
self.filewidget.grab_file.connect(self.grab_file)
self.filewidget.grab_file_from_parent.connect(self.grab_file_from_parent)
self.maxresults.editingFinished.connect(self.display)
self.revtext.textChanged.connect(self.text_changed)
self.revtext.activated.connect(self.display)
self.revtext.enter.connect(self.display)
self.revtext.down.connect(self.focus_tree)
# The model is updated in another thread so use
# signals/slots to bring control back to the main GUI thread
self.model.updated.connect(self.model_updated, type=Qt.QueuedConnection)
qtutils.add_action(self, 'FocusInput', self.focus_input, hotkeys.FOCUS_INPUT)
qtutils.add_action(self, 'FocusTree', self.focus_tree, hotkeys.FOCUS_TREE)
qtutils.add_action(self, 'FocusDiff', self.focus_diff, hotkeys.FOCUS_DIFF)
qtutils.add_close_action(self)
self.set_params(params)
def set_params(self, params):
context = self.context
self.params = params
# Update fields affected by model
self.revtext.setText(params.ref)
self.maxresults.setValue(params.count)
self.update_window_title()
if self.thread is not None:
self.thread.stop()
self.thread = ReaderThread(context, params, self)
thread = self.thread
thread.begin.connect(self.thread_begin, type=Qt.QueuedConnection)
thread.status.connect(self.thread_status, type=Qt.QueuedConnection)
thread.add.connect(self.add_commits, type=Qt.QueuedConnection)
thread.end.connect(self.thread_end, type=Qt.QueuedConnection)
def focus_input(self):
"""Focus the revision input field"""
self.revtext.setFocus()
def focus_tree(self):
"""Focus the revision tree list widget"""
self.treewidget.setFocus()
def focus_diff(self):
"""Focus the diff widget"""
self.diffwidget.setFocus()
def text_changed(self, txt):
self.params.ref = txt
self.update_window_title()
def update_window_title(self):
project = self.model.project
if self.params.ref:
self.setWindowTitle(
N_('%(project)s: %(ref)s - DAG')
% {
'project': project,
'ref': self.params.ref,
}
)
else:
self.setWindowTitle(project + N_(' - DAG'))
def export_state(self):
state = standard.MainWindow.export_state(self)
state['count'] = self.params.count
state['log'] = self.treewidget.export_state()
state['word_wrap'] = self.diffwidget.options.enable_word_wrapping.isChecked()
return state
def apply_state(self, state):
result = standard.MainWindow.apply_state(self, state)
try:
count = state['count']
if self.params.overridden('count'):
count = self.params.count
except (KeyError, TypeError, ValueError, AttributeError):
count = self.params.count
result = False
self.params.set_count(count)
self.lock_layout_action.setChecked(state.get('lock_layout', False))
self.diffwidget.set_word_wrapping(state.get('word_wrap', False), update=True)
try:
log_state = state['log']
except (KeyError, ValueError):
log_state = None
if log_state:
self.treewidget.apply_state(log_state)
return result
def model_updated(self):
self.display()
self.update_window_title()
def refresh(self):
"""Unconditionally refresh the DAG"""
# self.force_refresh triggers an Unconditional redraw
self.force_refresh = True
cmds.do(cmds.Refresh, self.context)
def display(self):
"""Update the view when the Git refs change"""
ref = get(self.revtext)
count = get(self.maxresults)
context = self.context
model = self.model
# The DAG tries to avoid updating when the object IDs have not
# changed. Without doing this the DAG constantly redraws itself
# whenever inotify sends update events, which hurts usability.
#
# To minimize redraws we leverage `git rev-parse`. The strategy is to
# use `git rev-parse` on the input line, which converts each argument
# into object IDs. From there it's a simple matter of detecting when
# the object IDs changed.
#
# In addition to object IDs, we also need to know when the set of
# named references (branches, tags) changes so that an update is
# triggered when new branches and tags are created.
refs = set(model.local_branches + model.remote_branches + model.tags)
argv = utils.shell_split(ref or 'HEAD')
oids = gitcmds.parse_refs(context, argv)
update = (
self.force_refresh
or count != self.old_count
or oids != self.old_oids
or refs != self.old_refs
)
if update:
self.thread.stop()
self.params.set_ref(ref)
self.params.set_count(count)
self.thread.start()
self.old_oids = oids
self.old_count = count
self.old_refs = refs
self.force_refresh = False
def select_commits(self, commits):
self.selection = commits
def clear(self):
self.commits.clear()
self.commit_list = []
self.graphview.clear()
self.treewidget.clear()
def add_commits(self, commits):
self.commit_list.extend(commits)
# Keep track of commits
for commit_obj in commits:
self.commits[commit_obj.oid] = commit_obj
for tag in commit_obj.tags:
self.commits[tag] = commit_obj
self.graphview.add_commits(commits)
self.treewidget.add_commits(commits)
def thread_begin(self):
self.clear()
def thread_end(self):
self.restore_selection()
def thread_status(self, successful):
self.revtext.hint.set_error(not successful)
def restore_selection(self):
selection = self.selection
try:
commit_obj = self.commit_list[-1]
except IndexError:
# No commits, exist, early-out
return
new_commits = [self.commits.get(s.oid, None) for s in selection]
new_commits = [c for c in new_commits if c is not None]
if new_commits:
# The old selection exists in the new state
self.commits_selected.emit(sort_by_generation(new_commits))
else:
# The old selection is now empty. Select the top-most commit
self.commits_selected.emit([commit_obj])
self.graphview.set_initial_view()
def diff_commits(self, left, right):
paths = self.params.paths()
if paths:
difftool.difftool_launch(self.context, left=left, right=right, paths=paths)
else:
difftool.diff_commits(self.context, self, left, right)
# Qt overrides
def closeEvent(self, event):
self.revtext.close_popup()
self.thread.stop()
standard.MainWindow.closeEvent(self, event)
def histories_selected(self, histories):
argv = [self.model.currentbranch, '--']
argv.extend(histories)
rev_text = core.list2cmdline(argv)
self.revtext.setText(rev_text)
self.display()
def difftool_selected(self, files):
bottom, top = self.treewidget.selected_commit_range()
if not top:
return
difftool.difftool_launch(
self.context, left=bottom, left_take_parent=True, right=top, paths=files
)
def grab_file(self, filename):
"""Save the selected file from the file list widget"""
oid = self.treewidget.selected_oid()
model = browse.BrowseModel(oid, filename=filename)
browse.save_path(self.context, filename, model)
def grab_file_from_parent(self, filename):
"""Save the selected file from parent commit in the file list widget"""
oid = self.treewidget.selected_oid() + '^'
model = browse.BrowseModel(oid, filename=filename)
browse.save_path(self.context, filename, model)
class ReaderThread(QtCore.QThread):
begin = Signal()
add = Signal(object)
end = Signal()
status = Signal(object)
def __init__(self, context, params, parent):
QtCore.QThread.__init__(self, parent)
self.context = context
self.params = params
self._abort = False
self._stop = False
self._mutex = QtCore.QMutex()
self._condition = QtCore.QWaitCondition()
def run(self):
context = self.context
repo = dag.RepoReader(context, self.params)
repo.reset()
self.begin.emit()
commits = []
for commit in repo.get():
self._mutex.lock()
if self._stop:
self._condition.wait(self._mutex)
self._mutex.unlock()
if self._abort:
repo.reset()
return
commits.append(commit)
if len(commits) >= 512:
self.add.emit(commits)
commits = []
self.status.emit(repo.returncode == 0)
if commits:
self.add.emit(commits)
self.end.emit()
def start(self):
self._abort = False
self._stop = False
QtCore.QThread.start(self)
def pause(self):
self._mutex.lock()
self._stop = True
self._mutex.unlock()
def resume(self):
self._mutex.lock()
self._stop = False
self._mutex.unlock()
self._condition.wakeOne()
def stop(self):
self._abort = True
self.wait()
class Cache:
_label_font = None
@classmethod
def label_font(cls):
font = cls._label_font
if font is None:
font = cls._label_font = QtWidgets.QApplication.font()
font.setPointSize(6)
return font
class Edge(QtWidgets.QGraphicsItem):
item_type = qtutils.standard_item_type_value(1)
def __init__(self, source, dest):
QtWidgets.QGraphicsItem.__init__(self)
self.setAcceptedMouseButtons(Qt.NoButton)
self.source = source
self.dest = dest
self.commit = source.commit
self.setZValue(-2)
self.recompute_bound()
self.path = None
self.path_valid = False
# Choose a new color for new branch edges
if self.source.x() < self.dest.x():
color = EdgeColor.cycle()
line = Qt.SolidLine
elif self.source.x() != self.dest.x():
color = EdgeColor.current()
line = Qt.SolidLine
else:
color = EdgeColor.current()
line = Qt.SolidLine
self.pen = QtGui.QPen(color, 2.0, line, Qt.SquareCap, Qt.RoundJoin)
def recompute_bound(self):
dest_pt = Commit.item_bbox.center()
self.source_pt = self.mapFromItem(self.source, dest_pt)
self.dest_pt = self.mapFromItem(self.dest, dest_pt)
self.line = QtCore.QLineF(self.source_pt, self.dest_pt)
width = self.dest_pt.x() - self.source_pt.x()
height = self.dest_pt.y() - self.source_pt.y()
rect = QtCore.QRectF(self.source_pt, QtCore.QSizeF(width, height))
self.bound = rect.normalized()
def commits_were_invalidated(self):
self.recompute_bound()
self.prepareGeometryChange()
# The path should not be recomputed immediately because just small part
# of DAG is actually shown at same time. It will be recomputed on
# demand in course of 'paint' method.
self.path_valid = False
# Hence, just queue redrawing.
self.update()
# Qt overrides
def type(self):
return self.item_type
def boundingRect(self):
return self.bound
def recompute_path(self):
QRectF = QtCore.QRectF
QPointF = QtCore.QPointF
arc_rect = 10
connector_length = 5
path = QtGui.QPainterPath()
if self.source.x() == self.dest.x():
path.moveTo(self.source.x(), self.source.y())
path.lineTo(self.dest.x(), self.dest.y())
else:
# Define points starting from the source.
point1 = QPointF(self.source.x(), self.source.y())
point2 = QPointF(point1.x(), point1.y() - connector_length)
point3 = QPointF(point2.x() + arc_rect, point2.y() - arc_rect)
# Define points starting from the destination.
point4 = QPointF(self.dest.x(), self.dest.y())
point5 = QPointF(point4.x(), point3.y() - arc_rect)
point6 = QPointF(point5.x() - arc_rect, point5.y() + arc_rect)
start_angle_arc1 = 180
span_angle_arc1 = 90
start_angle_arc2 = 90
span_angle_arc2 = -90
# If the destination is at the left of the source, then we need to
# reverse some values.
if self.source.x() > self.dest.x():
point3 = QPointF(point2.x() - arc_rect, point3.y())
point6 = QPointF(point5.x() + arc_rect, point6.y())
span_angle_arc1 = 90
path.moveTo(point1)
path.lineTo(point2)
path.arcTo(QRectF(point2, point3), start_angle_arc1, span_angle_arc1)
path.lineTo(point6)
path.arcTo(QRectF(point6, point5), start_angle_arc2, span_angle_arc2)
path.lineTo(point4)
self.path = path
self.path_valid = True
def paint(self, painter, _option, _widget):
if not self.path_valid:
self.recompute_path()
painter.setPen(self.pen)
painter.drawPath(self.path)
class EdgeColor:
"""An edge color factory"""
current_color_index = 0
colors = [
QtGui.QColor(Qt.red),
QtGui.QColor(Qt.cyan),
QtGui.QColor(Qt.magenta),
QtGui.QColor(Qt.green),
# Orange; Qt.yellow is too low-contrast
qtutils.rgba(0xFF, 0x66, 0x00),
]
@classmethod
def update_colors(cls, theme):
"""Update the colors based on the color theme"""
if theme.is_dark or theme.is_palette_dark:
cls.colors.extend([
QtGui.QColor(Qt.red).lighter(),
QtGui.QColor(Qt.cyan).lighter(),
QtGui.QColor(Qt.magenta).lighter(),
QtGui.QColor(Qt.green).lighter(),
QtGui.QColor(Qt.yellow).lighter(),
])
else:
cls.colors.extend([
QtGui.QColor(Qt.blue),
QtGui.QColor(Qt.darkRed),
QtGui.QColor(Qt.darkCyan),
QtGui.QColor(Qt.darkMagenta),
QtGui.QColor(Qt.darkGreen),
QtGui.QColor(Qt.darkYellow),
QtGui.QColor(Qt.darkBlue),
])
@classmethod
def cycle(cls):
cls.current_color_index += 1
cls.current_color_index %= len(cls.colors)
color = cls.colors[cls.current_color_index]
color.setAlpha(128)
return color
@classmethod
def current(cls):
return cls.colors[cls.current_color_index]
@classmethod
def reset(cls):
cls.current_color_index = 0
class Commit(QtWidgets.QGraphicsItem):
item_type = qtutils.standard_item_type_value(2)
commit_radius = 12.0
merge_radius = 18.0
item_shape = QtGui.QPainterPath()
item_shape.addRect(
commit_radius / -2.0, commit_radius / -2.0, commit_radius, commit_radius
)
item_bbox = item_shape.boundingRect()
inner_rect = QtGui.QPainterPath()
inner_rect.addRect(
commit_radius / -2.0 + 2.0,
commit_radius / -2.0 + 2.0,
commit_radius - 4.0,
commit_radius - 4.0,
)
inner_rect = inner_rect.boundingRect()
commit_color = QtGui.QColor(Qt.white)
outline_color = commit_color.darker()
merge_color = QtGui.QColor(Qt.lightGray)
commit_selected_color = QtGui.QColor(Qt.green)
selected_outline_color = commit_selected_color.darker()
commit_pen = QtGui.QPen()
commit_pen.setWidth(1)
commit_pen.setColor(outline_color)
def __init__(
self,
commit,
selectable=QtWidgets.QGraphicsItem.ItemIsSelectable,
cursor=Qt.PointingHandCursor,
xpos=commit_radius / 2.0 + 1.0,
cached_commit_color=commit_color,
cached_merge_color=merge_color,
):
QtWidgets.QGraphicsItem.__init__(self)
self.commit = commit
self.selected = False
self.setZValue(0)
self.setFlag(selectable)
self.setCursor(cursor)
self.setToolTip(commit.oid[:12] + ': ' + commit.summary)
if commit.tags:
self.label = label = Label(commit)
label.setParentItem(self)
label.setPos(xpos + 1, -self.commit_radius / 2.0)
else:
self.label = None
if len(commit.parents) > 1:
self.brush = cached_merge_color
else:
self.brush = cached_commit_color
self.pressed = False
self.dragged = False
self.edges = {}
def itemChange(self, change, value):
if change == QtWidgets.QGraphicsItem.ItemSelectedHasChanged:
# Cache the pen for use in paint()
if value:
self.brush = self.commit_selected_color
color = self.selected_outline_color
else:
if len(self.commit.parents) > 1:
self.brush = self.merge_color
else:
self.brush = self.commit_color
color = self.outline_color
commit_pen = QtGui.QPen()
commit_pen.setWidth(1)
commit_pen.setColor(color)
self.commit_pen = commit_pen
return QtWidgets.QGraphicsItem.itemChange(self, change, value)
def type(self):
return self.item_type
def boundingRect(self):
return self.item_bbox
def shape(self):
return self.item_shape
def paint(self, painter, option, _widget):
# Do not draw outside the exposed rectangle.
painter.setClipRect(option.exposedRect)
# Draw ellipse
painter.setPen(self.commit_pen)
painter.setBrush(self.brush)
painter.drawEllipse(self.inner_rect)
def mousePressEvent(self, event):
QtWidgets.QGraphicsItem.mousePressEvent(self, event)
self.pressed = True
self.selected = self.isSelected()
def mouseMoveEvent(self, event):
if self.pressed:
self.dragged = True
QtWidgets.QGraphicsItem.mouseMoveEvent(self, event)
def mouseReleaseEvent(self, event):
QtWidgets.QGraphicsItem.mouseReleaseEvent(self, event)
if not self.dragged and self.selected and event.button() == Qt.LeftButton:
return
self.pressed = False
self.dragged = False
class Label(QtWidgets.QGraphicsItem):
item_type = qtutils.graphics_item_type_value(3)
head_color = QtGui.QColor(Qt.green)
other_color = QtGui.QColor(Qt.white)
remote_color = QtGui.QColor(Qt.yellow)
head_pen = QtGui.QPen()
head_pen.setColor(QtGui.QColor(Qt.black))
head_pen.setWidth(1)
text_pen = QtGui.QPen()
text_pen.setColor(QtGui.QColor(Qt.black))
text_pen.setWidth(1)
border = 1
item_spacing = 8
text_x_offset = 3
text_y_offset = 0
def __init__(self, commit):
QtWidgets.QGraphicsItem.__init__(self)
self.setZValue(-1)
self.commit = commit
def type(self):
return self.item_type
def boundingRect(self, cache=Cache):
QPainterPath = QtGui.QPainterPath
QRectF = QtCore.QRectF
width = 72
height = 18
current_width = 0
spacing = self.item_spacing
border_x = self.border + self.text_x_offset
border_y = self.border + self.text_y_offset
font = cache.label_font()
item_shape = QPainterPath()
base_rect = QRectF(0, 0, width, height)
base_rect = base_rect.adjusted(-border_x, -border_y, border_x, border_y)
item_shape.addRect(base_rect)
for tag in self.commit.tags:
text_shape = QPainterPath()
text_shape.addText(current_width, 0, font, tag)
text_rect = text_shape.boundingRect()
box_rect = text_rect.adjusted(-border_x, -border_y, border_x, border_y)
item_shape.addRect(box_rect)
current_width = item_shape.boundingRect().width() + spacing
return item_shape.boundingRect()
def paint(self, painter, _option, _widget, cache=Cache):
# Draw tags and branches
font = cache.label_font()
painter.setFont(font)
current_width = 3
border = self.border
x_offset = self.text_x_offset
y_offset = self.text_y_offset
spacing = self.item_spacing
QRectF = QtCore.QRectF
HEAD = 'HEAD'
remotes_prefix = 'remotes/'
tags_prefix = 'tags/'
heads_prefix = 'heads/'
remotes_len = len(remotes_prefix)
tags_len = len(tags_prefix)
heads_len = len(heads_prefix)
for tag in self.commit.tags:
if tag == HEAD:
painter.setPen(self.text_pen)
painter.setBrush(self.remote_color)
elif tag.startswith(remotes_prefix):
tag = tag[remotes_len:]
painter.setPen(self.text_pen)
painter.setBrush(self.other_color)
elif tag.startswith(tags_prefix):
tag = tag[tags_len:]
painter.setPen(self.text_pen)
painter.setBrush(self.remote_color)
elif tag.startswith(heads_prefix):
tag = tag[heads_len:]
painter.setPen(self.head_pen)
painter.setBrush(self.head_color)
else:
painter.setPen(self.text_pen)
painter.setBrush(self.other_color)
text_rect = painter.boundingRect(
QRectF(current_width, 0, 0, 0), Qt.TextSingleLine, tag
)
box_rect = text_rect.adjusted(-x_offset, -y_offset, x_offset, y_offset)
painter.drawRoundedRect(box_rect, border, border)
painter.drawText(text_rect, Qt.TextSingleLine, tag)
current_width += text_rect.width() + spacing
class GraphView(QtWidgets.QGraphicsView, ViewerMixin):
commits_selected = Signal(object)
diff_commits = Signal(object, object)
x_adjust = int(Commit.commit_radius * 4 / 3)
y_adjust = int(Commit.commit_radius * 4 / 3)
x_off = -18
y_off = -20
def __init__(self, context, parent):
QtWidgets.QGraphicsView.__init__(self, parent)
ViewerMixin.__init__(self)
EdgeColor.update_colors(context.app.theme)
theme = context.app.theme
highlight = theme.selection_color()
Commit.commit_selected_color = highlight
Commit.selected_outline_color = highlight.darker()
self.context = context
self.columns = {}
self.menu_actions = None
self.commits = []
self.items = {}
self.mouse_start = [0, 0]
self.saved_matrix = self.transform()
self.max_column = 0
self.min_column = 0
self.frontier = {}
self.tagged_cells = set()
self.x_start = 24
self.x_min = 24
self.x_offsets = collections.defaultdict(lambda: self.x_min)
self.is_panning = False
self.pressed = False
self.selecting = False
self.last_mouse = [0, 0]
self.zoom = 2
self.setDragMode(self.RubberBandDrag)
scene = QtWidgets.QGraphicsScene(self)
scene.setItemIndexMethod(QtWidgets.QGraphicsScene.BspTreeIndex)
scene.selectionChanged.connect(self.selection_changed)
self.setScene(scene)
self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setViewportUpdateMode(self.SmartViewportUpdate)
self.setCacheMode(QtWidgets.QGraphicsView.CacheBackground)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.NoAnchor)
background_color = qtutils.css_color(context.app.theme.background_color_rgb())
self.setBackgroundBrush(background_color)
qtutils.add_action(
self,
N_('Zoom In'),
self.zoom_in,
hotkeys.ZOOM_IN,
hotkeys.ZOOM_IN_SECONDARY,
)
qtutils.add_action(self, N_('Zoom Out'), self.zoom_out, hotkeys.ZOOM_OUT)
qtutils.add_action(self, N_('Zoom to Fit'), self.zoom_to_fit, hotkeys.FIT)
qtutils.add_action(
self, N_('Select Parent'), self._select_parent, hotkeys.MOVE_DOWN_TERTIARY
)
qtutils.add_action(
self,
N_('Select Oldest Parent'),
self._select_oldest_parent,
hotkeys.MOVE_DOWN,
)
qtutils.add_action(
self, N_('Select Child'), self._select_child, hotkeys.MOVE_UP_TERTIARY
)
qtutils.add_action(
self, N_('Select Newest Child'), self._select_newest_child, hotkeys.MOVE_UP
)
def clear(self):
EdgeColor.reset()
self.scene().clear()
self.items.clear()
self.x_offsets.clear()
self.x_min = 24
self.commits = []
# ViewerMixin interface
def selected_items(self):
"""Return the currently selected items"""
return self.scene().selectedItems()
def zoom_in(self):
self.scale_view(1.5)
def zoom_out(self):
self.scale_view(1.0 / 1.5)
def selection_changed(self):
# Broadcast selection to other widgets
selected_items = self.scene().selectedItems()
commits = sort_by_generation([item.commit for item in selected_items])
self.set_selecting(True)
self.commits_selected.emit(commits)
self.set_selecting(False)
def select_commits(self, commits):
if self.selecting:
return
with qtutils.BlockSignals(self.scene()):
self.select([commit.oid for commit in commits])
def select(self, oids):
"""Select the item for the oids"""
self.scene().clearSelection()
for oid in oids:
try:
item = self.items[oid]
except KeyError:
continue
item.setSelected(True)
item_rect = item.sceneTransform().mapRect(item.boundingRect())
self.ensureVisible(item_rect)
def _get_item_by_generation(self, commits, criteria_func):
"""Return the item for the commit matching criteria"""
if not commits:
return None
generation = None
for commit in commits:
if generation is None or criteria_func(generation, commit.generation):
oid = commit.oid
generation = commit.generation
try:
return self.items[oid]
except KeyError:
return None
def _oldest_item(self, commits):
"""Return the item for the commit with the oldest generation number"""
return self._get_item_by_generation(commits, lambda a, b: a > b)
def _newest_item(self, commits):
"""Return the item for the commit with the newest generation number"""
return self._get_item_by_generation(commits, lambda a, b: a < b)
def create_patch(self):
items = self.selected_items()
if not items:
return
context = self.context
selected_commits = sort_by_generation([n.commit for n in items])
oids = [c.oid for c in selected_commits]
all_oids = [c.oid for c in sort_by_generation(self.commits)]
cmds.do(cmds.FormatPatch, context, oids, all_oids)
def _select_parent(self):
"""Select the parent with the newest generation number"""
selected_item = self.selected_item()
if selected_item is None:
return
parent_item = self._newest_item(selected_item.commit.parents)
if parent_item is None:
return
selected_item.setSelected(False)
parent_item.setSelected(True)
self.ensureVisible(parent_item.mapRectToScene(parent_item.boundingRect()))
def _select_oldest_parent(self):
"""Select the parent with the oldest generation number"""
selected_item = self.selected_item()
if selected_item is None:
return
parent_item = self._oldest_item(selected_item.commit.parents)
if parent_item is None:
return
selected_item.setSelected(False)
parent_item.setSelected(True)
scene_rect = parent_item.mapRectToScene(parent_item.boundingRect())
self.ensureVisible(scene_rect)
def _select_child(self):
"""Select the child with the oldest generation number"""
selected_item = self.selected_item()
if selected_item is None:
return
child_item = self._oldest_item(selected_item.commit.children)
if child_item is None:
return
selected_item.setSelected(False)
child_item.setSelected(True)
scene_rect = child_item.mapRectToScene(child_item.boundingRect())
self.ensureVisible(scene_rect)
def _select_newest_child(self):
"""Select the Nth child with the newest generation number (N > 1)"""
selected_item = self.selected_item()
if selected_item is None:
return
if len(selected_item.commit.children) > 1:
children = selected_item.commit.children[1:]
else:
children = selected_item.commit.children
child_item = self._newest_item(children)
if child_item is None:
return
selected_item.setSelected(False)
child_item.setSelected(True)
scene_rect = child_item.mapRectToScene(child_item.boundingRect())
self.ensureVisible(scene_rect)
def set_initial_view(self):
items = []
selected = self.selected_items()
if selected:
items.extend(selected)
if not selected and self.commits:
commit = self.commits[-1]
items.append(self.items[commit.oid])
bounds = self.scene().itemsBoundingRect()
bounds.adjust(-64, 0, 0, 0)
self.setSceneRect(bounds)
self.fit_view_to_items(items)
def zoom_to_fit(self):
"""Fit selected items into the viewport"""
items = self.selected_items()
self.fit_view_to_items(items)
def fit_view_to_items(self, items):
if not items:
rect = self.scene().itemsBoundingRect()
else:
x_min = y_min = maxsize
x_max = y_max = -maxsize
for item in items:
pos = item.pos()
x_val = pos.x()
y_val = pos.y()
x_min = min(x_min, x_val)
x_max = max(x_max, x_val)
y_min = min(y_min, y_val)
y_max = max(y_max, y_val)
rect = QtCore.QRectF(x_min, y_min, abs(x_max - x_min), abs(y_max - y_min))
x_adjust = abs(GraphView.x_adjust)
y_adjust = abs(GraphView.y_adjust)
count = max(2.0, 10.0 - len(items) / 2.0)
y_offset = int(y_adjust * count)
x_offset = int(x_adjust * count)
rect.setX(rect.x() - x_offset // 2)
rect.setY(rect.y() - y_adjust // 2)
rect.setHeight(rect.height() + y_offset)
rect.setWidth(rect.width() + x_offset)
self.fitInView(rect, Qt.KeepAspectRatio)
self.scene().invalidate()
def handle_event(self, event_handler, event, update=True):
event_handler(self, event)
if update:
self.update()
def set_selecting(self, selecting):
self.selecting = selecting
def pan(self, event):
pos = event.pos()
x_offset = pos.x() - self.mouse_start[0]
y_offset = pos.y() - self.mouse_start[1]
if x_offset == 0 and y_offset == 0:
return
rect = QtCore.QRect(0, 0, abs(x_offset), abs(y_offset))
delta = self.mapToScene(rect).boundingRect()
x_translate = delta.width()
if x_offset < 0.0:
x_translate = -x_translate
y_translate = delta.height()
if y_offset < 0.0:
y_translate = -y_translate
matrix = self.transform()
matrix.reset()
matrix *= self.saved_matrix
matrix.translate(x_translate, y_translate)
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.setTransform(matrix)
def wheel_zoom(self, event):
"""Handle mouse wheel zooming."""
delta = qtcompat.wheel_delta(event)
zoom = math.pow(2.0, delta / 512.0)
factor = (
self.transform()
.scale(zoom, zoom)
.mapRect(QtCore.QRectF(0.0, 0.0, 1.0, 1.0))
.width()
)
if factor < 0.014 or factor > 42.0:
return
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.zoom = zoom
self.scale(zoom, zoom)
def wheel_pan(self, event):
"""Handle mouse wheel panning."""
unit = QtCore.QRectF(0.0, 0.0, 1.0, 1.0)
factor = 1.0 / self.transform().mapRect(unit).width()
tx, ty = qtcompat.wheel_translation(event)
matrix = self.transform().translate(tx * factor, ty * factor)
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.setTransform(matrix)
def scale_view(self, scale):
factor = (
self.transform()
.scale(scale, scale)
.mapRect(QtCore.QRectF(0, 0, 1, 1))
.width()
)
if factor < 0.07 or factor > 100.0:
return
self.zoom = scale
adjust_scrollbars = False
scrollbar = self.verticalScrollBar()
scrollbar_offset = 1.0
if scrollbar:
value = get(scrollbar)
minimum = scrollbar.minimum()
maximum = scrollbar.maximum()
scrollbar_range = maximum - minimum
distance = value - minimum
nonzero_range = scrollbar_range > 0.1
if nonzero_range:
scrollbar_offset = distance / scrollbar_range
adjust_scrollbars = True
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.scale(scale, scale)
scrollbar = self.verticalScrollBar()
if scrollbar and adjust_scrollbars:
minimum = scrollbar.minimum()
maximum = scrollbar.maximum()
scrollbar_range = maximum - minimum
value = minimum + int(float(scrollbar_range) * scrollbar_offset)
scrollbar.setValue(value)
def add_commits(self, commits):
"""Traverse commits and add them to the view."""
self.commits.extend(commits)
scene = self.scene()
for commit in commits:
item = Commit(commit)
self.items[commit.oid] = item
for ref in commit.tags:
self.items[ref] = item
scene.addItem(item)
self.layout_commits()
self.link(commits)
def link(self, commits):
"""Create edges linking commits with their parents"""
scene = self.scene()
for commit in commits:
try:
commit_item = self.items[commit.oid]
except KeyError:
continue # The history is truncated.
for parent in reversed(commit.parents):
try:
parent_item = self.items[parent.oid]
except KeyError:
continue # The history is truncated.
try:
edge = parent_item.edges[commit.oid]
except KeyError:
edge = Edge(parent_item, commit_item)
else:
continue
parent_item.edges[commit.oid] = edge
commit_item.edges[parent.oid] = edge
scene.addItem(edge)
def layout_commits(self):
positions = self.position_nodes()
# Each edge is accounted in two commits. Hence, accumulate invalid
# edges to prevent double edge invalidation.
invalid_edges = set()
for oid, (x_val, y_val) in positions.items():
item = self.items[oid]
pos = item.pos()
if pos != (x_val, y_val):
item.setPos(x_val, y_val)
for edge in item.edges.values():
invalid_edges.add(edge)
for edge in invalid_edges:
edge.commits_were_invalidated()
# Commit node layout technique
#
# Nodes are aligned by a mesh. Columns and rows are distributed using
# algorithms described below.
#
# Row assignment algorithm
#
# The algorithm aims consequent.
# 1. A commit should be above all its parents.
# 2. No commit should be at right side of a commit with a tag in same row.
# This prevents overlapping of tag labels with commits and other labels.
# 3. Commit density should be maximized.
#
# The algorithm requires that all parents of a commit were assigned column.
# Nodes must be traversed in generation ascend order. This guarantees that all
# parents of a commit were assigned row. So, the algorithm may operate in
# course of column assignment algorithm.
#
# Row assignment uses frontier. A frontier is a dictionary that contains
# minimum available row index for each column. It propagates during the
# algorithm. Set of cells with tags is also maintained to meet second aim.
#
# Initialization is performed by reset_rows method. Each new column should
# be declared using declare_column method. Getting row for a cell is
# implemented in alloc_cell method. Frontier must be propagated for any child
# of fork commit which occupies different column. This meets first aim.
#
# Column assignment algorithm
#
# The algorithm traverses nodes in generation ascend order. This guarantees
# that a node will be visited after all its parents.
#
# The set of occupied columns are maintained during work. Initially it is
# empty and no node occupied a column. Empty columns are allocated on demand.
# Free index for column being allocated is searched in following way.
# 1. Start from desired column and look towards graph center (0 column).
# 2. Start from center and look in both directions simultaneously.
# Desired column is defaulted to 0. Fork node should set desired column for
# children equal to its one. This prevents branch from jumping too far from
# its fork.
#
# Initialization is performed by reset_columns method. Column allocation is
# implemented in alloc_column method. Initialization and main loop are in
# recompute_grid method. The method also embeds row assignment algorithm by
# implementation.
#
# Actions for each node are follow.
# 1. If the node was not assigned a column then it is assigned empty one.
# 2. Allocate row.
# 3. Allocate columns for children.
# If a child have a column assigned then it should no be overridden. One of
# children is assigned same column as the node. If the node is a fork then the
# child is chosen in generation descent order. This is a heuristic and it only
# affects resulting appearance of the graph. Other children are assigned empty
# columns in same order. It is the heuristic too.
# 4. If no child occupies column of the node then leave it.
# It is possible in consequent situations.
# 4.1 The node is a leaf.
# 4.2 The node is a fork and all its children are already assigned side
# column. It is possible if all the children are merges.
# 4.3 Single node child is a merge that is already assigned a column.
# 5. Propagate frontier with respect to this node.
# Each frontier entry corresponding to column occupied by any node's child
# must be gather than node row index. This meets first aim of the row
# assignment algorithm.
# Note that frontier of child that occupies same row was propagated during
# step 2. Hence, it must be propagated for children on side columns.
def reset_columns(self):
# Some children of displayed commits might not be accounted in
# 'commits' list. It is common case during loading of big graph.
# But, they are assigned a column that must be reset. Hence, use
# depth-first traversal to reset all columns assigned.
for node in self.commits:
if node.column is None:
continue
stack = [node]
while stack:
node = stack.pop()
node.column = None
for child in node.children:
if child.column is not None:
stack.append(child)
self.columns = {}
self.max_column = 0
self.min_column = 0
def reset_rows(self):
self.frontier = {}
self.tagged_cells = set()
def declare_column(self, column):
if self.frontier:
# Align new column frontier by frontier of nearest column. If all
# columns were left then select maximum frontier value.
if not self.columns:
self.frontier[column] = max(list(self.frontier.values()))
return
# This is heuristic that mostly affects roots. Note that the
# frontier values for fork children will be overridden in course of
# propagate_frontier.
for offset in itertools.count(1):
for value in (column + offset, column - offset):
if value not in self.columns:
# Column is not occupied.
continue
try:
frontier = self.frontier[value]
except KeyError:
# Column 'c' was never allocated.
continue
frontier -= 1
# The frontier of the column may be higher because of
# tag overlapping prevention performed for previous head.
try:
if self.frontier[column] >= frontier:
break
except KeyError:
pass
self.frontier[column] = frontier
break
else:
continue
break
else:
# First commit must be assigned 0 row.
self.frontier[column] = 0
def alloc_column(self, column=0):
columns = self.columns
# First, look for free column by moving from desired column to graph
# center (column 0).
for c in range(column, 0, -1 if column > 0 else 1):
if c not in columns:
if c > self.max_column:
self.max_column = c
elif c < self.min_column:
self.min_column = c
break
else:
# If no free column was found between graph center and desired
# column then look for free one by moving from center along both
# directions simultaneously.
for c in itertools.count(0):
if c not in columns:
if c > self.max_column:
self.max_column = c
break
c = -c
if c not in columns:
if c < self.min_column:
self.min_column = c
break
self.declare_column(c)
columns[c] = 1
return c
def alloc_cell(self, column, tags):
# Get empty cell from frontier.
cell_row = self.frontier[column]
if tags:
# Prevent overlapping of tag with cells already allocated a row.
if self.x_off > 0:
can_overlap = list(range(column + 1, self.max_column + 1))
else:
can_overlap = list(range(column - 1, self.min_column - 1, -1))
for value in can_overlap:
frontier = self.frontier[value]
if frontier > cell_row:
cell_row = frontier
# Avoid overlapping with tags of commits at cell_row.
if self.x_off > 0:
can_overlap = list(range(self.min_column, column))
else:
can_overlap = list(range(self.max_column, column, -1))
for cell_row in itertools.count(cell_row):
for value in can_overlap:
if (value, cell_row) in self.tagged_cells:
# Overlapping. Try next row.
break
else:
# No overlapping was found.
break
# Note that all checks should be made for new cell_row value.
if tags:
self.tagged_cells.add((column, cell_row))
# Propagate frontier.
self.frontier[column] = cell_row + 1
return cell_row
def propagate_frontier(self, column, value):
current = self.frontier[column]
if current < value:
self.frontier[column] = value
def leave_column(self, column):
count = self.columns[column]
if count == 1:
del self.columns[column]
else:
self.columns[column] = count - 1
def recompute_grid(self):
self.reset_columns()
self.reset_rows()
for node in sort_by_generation(list(self.commits)):
if node.column is None:
# Node is either root or its parent is not in items. This
# happens when tree loading is in progress. Allocate new
# columns for such nodes.
node.column = self.alloc_column()
node.row = self.alloc_cell(node.column, node.tags)
# Allocate columns for children which are still without one. Also
# propagate frontier for children.
if node.is_fork():
sorted_children = sorted(
node.children, key=lambda c: c.generation, reverse=True
)
citer = iter(sorted_children)
for child in citer:
if child.column is None:
# Top most child occupies column of parent.
child.column = node.column
# Note that frontier is propagated in course of
# alloc_cell.
break
self.propagate_frontier(child.column, node.row + 1)
else:
# No child occupies same column.
self.leave_column(node.column)
# Note that the loop below will pass no iteration.
# Rest children are allocated new column.
for child in citer:
if child.column is None:
child.column = self.alloc_column(node.column)
self.propagate_frontier(child.column, node.row + 1)
elif node.children:
child = node.children[0]
if child.column is None:
child.column = node.column
# Note that frontier is propagated in course of alloc_cell.
elif child.column != node.column:
# Child node have other parents and occupies column of one
# of them.
self.leave_column(node.column)
# But frontier must be propagated with respect to this
# parent.
self.propagate_frontier(child.column, node.row + 1)
else:
# This is a leaf node.
self.leave_column(node.column)
def position_nodes(self):
self.recompute_grid()
x_start = self.x_start
x_min = self.x_min
x_off = self.x_off
y_off = self.y_off
positions = {}
for node in self.commits:
x_val = x_start + node.column * x_off
y_val = y_off + node.row * y_off
positions[node.oid] = (x_val, y_val)
x_min = min(x_min, x_val)
self.x_min = x_min
return positions
# Qt overrides
def contextMenuEvent(self, event):
self.context_menu_event(event)
def mousePressEvent(self, event):
if event.button() == Qt.MidButton:
pos = event.pos()
self.mouse_start = [pos.x(), pos.y()]
self.saved_matrix = self.transform()
self.is_panning = True
return
if event.button() == Qt.RightButton:
event.ignore()
return
if event.button() == Qt.LeftButton:
self.pressed = True
self.handle_event(QtWidgets.QGraphicsView.mousePressEvent, event)
def mouseMoveEvent(self, event):
if self.is_panning:
self.pan(event)
return
pos = self.mapToScene(event.pos())
self.last_mouse[0] = pos.x()
self.last_mouse[1] = pos.y()
self.handle_event(QtWidgets.QGraphicsView.mouseMoveEvent, event, update=False)
def mouseReleaseEvent(self, event):
self.pressed = False
if event.button() == Qt.MidButton:
self.is_panning = False
return
self.handle_event(QtWidgets.QGraphicsView.mouseReleaseEvent, event)
self.viewport().repaint()
def wheelEvent(self, event):
"""Handle Qt mouse wheel events."""
if event.modifiers() & Qt.ControlModifier:
self.wheel_zoom(event)
else:
self.wheel_pan(event)
def fitInView(self, rect, flags=Qt.IgnoreAspectRatio):
"""Override fitInView to remove unwanted margins
https://bugreports.qt.io/browse/QTBUG-42331 - based on QT sources
"""
if self.scene() is None or rect.isNull():
return
unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))
self.scale(1.0 / unity.width(), 1.0 / unity.height())
view_rect = self.viewport().rect()
scene_rect = self.transform().mapRect(rect)
xratio = view_rect.width() / scene_rect.width()
yratio = view_rect.height() / scene_rect.height()
if flags == Qt.KeepAspectRatio:
xratio = yratio = min(xratio, yratio)
elif flags == Qt.KeepAspectRatioByExpanding:
xratio = yratio = max(xratio, yratio)
self.scale(xratio, yratio)
self.centerOn(rect.center())
def sort_by_generation(commits):
"""Sort commits by their generation. Ensures consistent diffs and patch exports"""
if len(commits) <= 1:
return commits
commits.sort(key=lambda x: x.generation)
return commits
# Glossary
# ========
# oid -- Git objects IDs (i.e. SHA-1 / SHA-256 IDs)
# ref -- Git references that resolve to a commit-ish (HEAD, branches, tags)
| 84,912 | Python | .py | 2,047 | 31.401075 | 88 | 0.605781 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
87 | search.py | git-cola_git-cola/cola/widgets/search.py | """A widget for searching git commits"""
import time
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from ..i18n import N_
from ..interaction import Interaction
from ..git import STDOUT
from ..qtutils import connect_button
from ..qtutils import create_toolbutton
from ..qtutils import get
from .. import core
from .. import gitcmds
from .. import icons
from .. import utils
from .. import qtutils
from . import diff
from . import defs
from . import standard
def mkdate(timespec):
return '%04d-%02d-%02d' % time.localtime(timespec)[:3]
class SearchOptions:
def __init__(self):
self.query = ''
self.max_count = 500
self.start_date = ''
self.end_date = ''
class SearchWidget(standard.Dialog):
def __init__(self, context, parent):
standard.Dialog.__init__(self, parent)
self.context = context
self.setWindowTitle(N_('Search'))
self.mode_combo = QtWidgets.QComboBox()
self.browse_button = create_toolbutton(
icon=icons.folder(), tooltip=N_('Browse...')
)
self.query = QtWidgets.QLineEdit()
self.start_date = QtWidgets.QDateEdit()
self.start_date.setCurrentSection(QtWidgets.QDateTimeEdit.YearSection)
self.start_date.setCalendarPopup(True)
self.start_date.setDisplayFormat(N_('yyyy-MM-dd'))
self.end_date = QtWidgets.QDateEdit()
self.end_date.setCurrentSection(QtWidgets.QDateTimeEdit.YearSection)
self.end_date.setCalendarPopup(True)
self.end_date.setDisplayFormat(N_('yyyy-MM-dd'))
icon = icons.search()
self.search_button = qtutils.create_button(
text=N_('Search'), icon=icon, default=True
)
self.max_count = standard.SpinBox(value=500, mini=5, maxi=9995, step=5)
self.commit_list = QtWidgets.QListWidget()
self.commit_list.setMinimumSize(QtCore.QSize(10, 10))
self.commit_list.setAlternatingRowColors(True)
selection_mode = QtWidgets.QAbstractItemView.SingleSelection
self.commit_list.setSelectionMode(selection_mode)
self.commit_text = diff.DiffTextEdit(context, self, whitespace=False)
self.button_export = qtutils.create_button(
text=N_('Export Patches'), icon=icons.diff()
)
self.button_cherrypick = qtutils.create_button(
text=N_('Cherry Pick'), icon=icons.cherry_pick()
)
self.button_close = qtutils.close_button()
self.top_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.query,
self.start_date,
self.end_date,
self.browse_button,
self.search_button,
qtutils.STRETCH,
self.mode_combo,
self.max_count,
)
self.splitter = qtutils.splitter(
Qt.Vertical, self.commit_list, self.commit_text
)
self.bottom_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
qtutils.STRETCH,
self.button_close,
self.button_export,
self.button_cherrypick,
)
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.top_layout,
self.splitter,
self.bottom_layout,
)
self.setLayout(self.main_layout)
self.init_size(parent=parent)
def search(context):
"""Return a callback to handle various search actions."""
return search_commits(context, qtutils.active_window())
class SearchEngine:
def __init__(self, context, model):
self.context = context
self.model = model
def rev_args(self):
max_count = self.model.max_count
return {
'no_color': True,
'max-count': max_count,
'pretty': 'format:%H %aN - %s - %ar',
}
def common_args(self):
return (self.model.query, self.rev_args())
def search(self):
if self.validate():
return self.results()
return []
def validate(self):
return len(self.model.query) > 1
def revisions(self, *args, **kwargs):
git = self.context.git
revlist = git.log(*args, **kwargs)[STDOUT]
return gitcmds.parse_rev_list(revlist)
def results(self):
pass
class RevisionSearch(SearchEngine):
def results(self):
query, opts = self.common_args()
args = utils.shell_split(query)
return self.revisions(*args, **opts)
class PathSearch(SearchEngine):
def results(self):
query, args = self.common_args()
paths = ['--'] + utils.shell_split(query)
return self.revisions(all=True, *paths, **args)
class MessageSearch(SearchEngine):
def results(self):
query, kwargs = self.common_args()
return self.revisions(all=True, grep=query, **kwargs)
class AuthorSearch(SearchEngine):
def results(self):
query, kwargs = self.common_args()
return self.revisions(all=True, author=query, **kwargs)
class CommitterSearch(SearchEngine):
def results(self):
query, kwargs = self.common_args()
return self.revisions(all=True, committer=query, **kwargs)
class DiffSearch(SearchEngine):
def results(self):
git = self.context.git
query, kwargs = self.common_args()
return gitcmds.parse_rev_list(git.log('-S' + query, all=True, **kwargs)[STDOUT])
class DateRangeSearch(SearchEngine):
def validate(self):
return self.model.start_date < self.model.end_date
def results(self):
kwargs = self.rev_args()
start_date = self.model.start_date
end_date = self.model.end_date
return self.revisions(
date='iso', all=True, after=start_date, before=end_date, **kwargs
)
class Search(SearchWidget):
def __init__(self, context, model, parent):
"""
Search diffs and commit logs
:param model: SearchOptions instance
"""
SearchWidget.__init__(self, context, parent)
self.model = model
self.EXPR = N_('Search by Expression')
self.PATH = N_('Search by Path')
self.MESSAGE = N_('Search Commit Messages')
self.DIFF = N_('Search Diffs')
self.AUTHOR = N_('Search Authors')
self.COMMITTER = N_('Search Committers')
self.DATE_RANGE = N_('Search Date Range')
self.results = []
# Each search type is handled by a distinct SearchEngine subclass
self.engines = {
self.EXPR: RevisionSearch,
self.PATH: PathSearch,
self.MESSAGE: MessageSearch,
self.DIFF: DiffSearch,
self.AUTHOR: AuthorSearch,
self.COMMITTER: CommitterSearch,
self.DATE_RANGE: DateRangeSearch,
}
self.modes = (
self.EXPR,
self.PATH,
self.DATE_RANGE,
self.DIFF,
self.MESSAGE,
self.AUTHOR,
self.COMMITTER,
)
self.mode_combo.addItems(self.modes)
connect_button(self.search_button, self.search_callback)
connect_button(self.browse_button, self.browse_callback)
connect_button(self.button_export, self.export_patch)
connect_button(self.button_cherrypick, self.cherry_pick)
connect_button(self.button_close, self.accept)
self.mode_combo.currentIndexChanged.connect(self.mode_changed)
self.commit_list.itemSelectionChanged.connect(self.display)
self.set_start_date(mkdate(time.time() - (87640 * 31)))
self.set_end_date(mkdate(time.time() + 87640))
self.set_mode(self.EXPR)
self.query.setFocus()
def mode_changed(self, _idx):
mode = self.mode()
self.update_shown_widgets(mode)
if mode == self.PATH:
self.browse_callback()
def set_commits(self, commits):
widget = self.commit_list
widget.clear()
widget.addItems(commits)
def set_start_date(self, datestr):
set_date(self.start_date, datestr)
def set_end_date(self, datestr):
set_date(self.end_date, datestr)
def set_mode(self, mode):
idx = self.modes.index(mode)
self.mode_combo.setCurrentIndex(idx)
self.update_shown_widgets(mode)
def update_shown_widgets(self, mode):
date_shown = mode == self.DATE_RANGE
browse_shown = mode == self.PATH
self.query.setVisible(not date_shown)
self.browse_button.setVisible(browse_shown)
self.start_date.setVisible(date_shown)
self.end_date.setVisible(date_shown)
def mode(self):
return self.mode_combo.currentText()
def search_callback(self, *args):
engineclass = self.engines[self.mode()]
self.model.query = get(self.query)
self.model.max_count = get(self.max_count)
self.model.start_date = get(self.start_date)
self.model.end_date = get(self.end_date)
self.results = engineclass(self.context, self.model).search()
if self.results:
self.display_results()
else:
self.commit_list.clear()
self.commit_text.setText('')
def browse_callback(self):
paths = qtutils.open_files(N_('Choose Paths'))
if not paths:
return
filepaths = []
curdir = core.getcwd()
prefix_len = len(curdir) + 1
for path in paths:
if not path.startswith(curdir):
continue
relpath = path[prefix_len:]
if relpath:
filepaths.append(relpath)
query = core.list2cmdline(filepaths)
self.query.setText(query)
if query:
self.search_callback()
def display_results(self):
commits = [result[1] for result in self.results]
self.set_commits(commits)
def selected_revision(self):
result = qtutils.selected_item(self.commit_list, self.results)
return result[0] if result else None
def display(self, *args):
context = self.context
revision = self.selected_revision()
if revision is None:
self.commit_text.setText('')
else:
qtutils.set_clipboard(revision)
diff_text = gitcmds.commit_diff(context, revision)
self.commit_text.setText(diff_text)
def export_patch(self):
context = self.context
revision = self.selected_revision()
if revision is not None:
Interaction.log_status(
*gitcmds.export_patchset(context, revision, revision)
)
def cherry_pick(self):
git = self.context.git
revision = self.selected_revision()
if revision is not None:
Interaction.log_status(*git.cherry_pick(revision))
def set_date(widget, datestr):
fmt = Qt.ISODate
date = QtCore.QDate.fromString(datestr, fmt)
if date:
widget.setDate(date)
def search_commits(context, parent):
opts = SearchOptions()
widget = Search(context, opts, parent)
widget.show()
return widget
| 11,202 | Python | .py | 299 | 28.77592 | 88 | 0.625 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
88 | editremotes.py | git-cola_git-cola/cola/widgets/editremotes.py | import operator
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..git import STDOUT
from ..i18n import N_
from ..qtutils import get
from .. import cmds
from .. import core
from .. import gitcmds
from .. import icons
from .. import qtutils
from .. import utils
from . import completion
from . import defs
from . import standard
from . import text
def editor(context, run=True):
view = RemoteEditor(context, parent=qtutils.active_window())
if run:
view.show()
view.exec_()
return view
class RemoteEditor(standard.Dialog):
def __init__(self, context, parent=None):
standard.Dialog.__init__(self, parent)
self.setWindowTitle(N_('Edit Remotes'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.context = context
self.current_name = ''
self.current_url = ''
hint = N_('Edit remotes by selecting them from the list')
self.default_hint = hint
self.remote_list = []
self.remotes = QtWidgets.QListWidget()
self.remotes.setToolTip(N_('Remote git repositories - double-click to rename'))
self.editor = RemoteWidget(context, self)
self.save_button = qtutils.create_button(
text=N_('Save'), icon=icons.save(), default=True
)
self.reset_button = qtutils.create_button(
text=N_('Reset'), icon=icons.discard()
)
tooltip = N_(
'Add and remove remote repositories using the \n'
'Add(+) and Delete(-) buttons on the left-hand side.\n'
'\n'
'Remotes can be renamed by selecting one from the list\n'
'and pressing "enter", or by double-clicking.'
)
hint = self.default_hint
self.info = text.VimHintedPlainTextEdit(context, hint, parent=self)
self.info.setToolTip(tooltip)
text_width, text_height = qtutils.text_size(self.info.font(), 'M')
width = text_width * 42
height = text_height * 13
self.info.setMinimumWidth(width)
self.info.setMinimumHeight(height)
self.info_thread = RemoteInfoThread(context, self)
icon = icons.add()
tooltip = N_('Add new remote git repository')
self.add_button = qtutils.create_toolbutton(icon=icon, tooltip=tooltip)
self.refresh_button = qtutils.create_toolbutton(
icon=icons.sync(), tooltip=N_('Refresh')
)
self.delete_button = qtutils.create_toolbutton(
icon=icons.remove(), tooltip=N_('Delete remote')
)
self.close_button = qtutils.close_button()
self._edit_button_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.save_button, self.reset_button
)
self._edit_layout = qtutils.hbox(
defs.no_margin, defs.spacing, self.editor, self._edit_button_layout
)
self._display_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self._edit_layout, self.info
)
self._display_widget = QtWidgets.QWidget(self)
self._display_widget.setLayout(self._display_layout)
self._top_layout = qtutils.splitter(
Qt.Horizontal, self.remotes, self._display_widget
)
width = self._top_layout.width()
self._top_layout.setSizes([width // 4, width * 3 // 4])
self._button_layout = qtutils.hbox(
defs.margin,
defs.spacing,
self.add_button,
self.delete_button,
self.refresh_button,
qtutils.STRETCH,
self.close_button,
)
self._layout = qtutils.vbox(
defs.margin, defs.spacing, self._top_layout, self._button_layout
)
self.setLayout(self._layout)
qtutils.connect_button(self.add_button, self.add)
qtutils.connect_button(self.delete_button, self.delete)
qtutils.connect_button(self.refresh_button, self.refresh)
qtutils.connect_button(self.close_button, self.accept)
qtutils.connect_button(self.save_button, self.save)
qtutils.connect_button(self.reset_button, self.reset)
qtutils.add_close_action(self)
thread = self.info_thread
thread.result.connect(self.set_info, type=Qt.QueuedConnection)
self.editor.remote_name.returnPressed.connect(self.save)
self.editor.remote_url.returnPressed.connect(self.save)
self.editor.valid.connect(self.editor_valid)
self.remotes.itemChanged.connect(self.remote_item_renamed)
self.remotes.itemSelectionChanged.connect(self.selection_changed)
self.disable_editor()
self.init_state(None, self.resize_widget, parent)
self.remotes.setFocus(Qt.OtherFocusReason)
self.refresh()
def reset(self):
focus = self.focusWidget()
if self.current_name:
self.activate_remote(self.current_name, gather_info=False)
restore_focus(focus)
@property
def changed(self):
url = self.editor.url
name = self.editor.name
return url != self.current_url or name != self.current_name
def save(self):
if not self.changed:
return
context = self.context
name = self.editor.name
url = self.editor.url
old_url = self.current_url
old_name = self.current_name
name_changed = name and name != old_name
url_changed = url and url != old_url
focus = self.focusWidget()
name_ok = url_ok = False
# Run the corresponding command
if name_changed and url_changed:
name_ok, url_ok = cmds.do(cmds.RemoteEdit, context, old_name, name, url)
elif name_changed:
result = cmds.do(cmds.RemoteRename, context, old_name, name)
name_ok = result[0]
elif url_changed:
result = cmds.do(cmds.RemoteSetURL, context, name, url)
url_ok = result[0]
# Update state if the change succeeded
gather = False
if url_changed and url_ok:
self.current_url = url
gather = True
# A name change requires a refresh
if name_changed and name_ok:
self.current_name = name
self.refresh(select=False)
remotes = utils.Sequence(self.remote_list)
idx = remotes.index(name)
self.select_remote(idx)
gather = False # already done by select_remote()
restore_focus(focus)
if gather:
self.gather_info()
def editor_valid(self, valid):
changed = self.changed
self.reset_button.setEnabled(changed)
self.save_button.setEnabled(changed and valid)
def disable_editor(self):
self.save_button.setEnabled(False)
self.reset_button.setEnabled(False)
self.editor.setEnabled(False)
self.editor.name = ''
self.editor.url = ''
self.info.hint.set_value(self.default_hint)
self.info.set_value('')
def resize_widget(self, parent):
"""Set the initial size of the widget"""
width, height = qtutils.default_size(parent, 720, 445)
self.resize(width, height)
def set_info(self, info):
self.info.hint.set_value(self.default_hint)
self.info.set_value(info)
def select_remote(self, index):
if index >= 0:
item = self.remotes.item(index)
if item:
item.setSelected(True)
def refresh(self, select=True):
git = self.context.git
remotes = git.remote()[STDOUT].splitlines()
# Ignore notifications from self.remotes while mutating.
with qtutils.BlockSignals(self.remotes):
self.remotes.clear()
self.remotes.addItems(remotes)
self.remote_list = remotes
for idx in range(len(remotes)):
item = self.remotes.item(idx)
item.setFlags(item.flags() | Qt.ItemIsEditable)
if select:
if not self.current_name and remotes:
# Nothing is selected; select the first item
self.select_remote(0)
elif self.current_name and remotes:
# Reselect the previously selected item
remote_seq = utils.Sequence(remotes)
idx = remote_seq.index(self.current_name)
if idx >= 0:
item = self.remotes.item(idx)
if item:
item.setSelected(True)
def add(self):
if add_remote(self.context, self):
self.refresh(select=False)
# Newly added remote will be last; select it
self.select_remote(len(self.remote_list) - 1)
def delete(self):
remote = qtutils.selected_item(self.remotes, self.remote_list)
if not remote:
return
cmds.do(cmds.RemoteRemove, self.context, remote)
self.refresh(select=False)
def remote_item_renamed(self, item):
idx = self.remotes.row(item)
if idx < 0:
return
if idx >= len(self.remote_list):
return
old_name = self.remote_list[idx]
new_name = item.text()
if new_name == old_name:
return
if not new_name:
item.setText(old_name)
return
context = self.context
ok, status, _, _ = cmds.do(cmds.RemoteRename, context, old_name, new_name)
if ok and status == 0:
self.remote_list[idx] = new_name
self.activate_remote(new_name)
else:
item.setText(old_name)
def selection_changed(self):
remote = qtutils.selected_item(self.remotes, self.remote_list)
if not remote:
self.disable_editor()
return
self.activate_remote(remote)
def activate_remote(self, name, gather_info=True):
url = gitcmds.remote_url(self.context, name)
self.current_name = name
self.current_url = url
self.editor.setEnabled(True)
self.editor.name = name
self.editor.url = url
if gather_info:
self.gather_info()
def gather_info(self):
name = self.current_name
self.info.hint.set_value(N_('Gathering info for "%s"...') % name)
self.info.set_value('')
self.info_thread.remote = name
self.info_thread.start()
def add_remote(context, parent, name='', url='', readonly_url=False):
"""Bring up the "Add Remote" dialog"""
widget = AddRemoteDialog(context, parent, readonly_url=readonly_url)
if name:
widget.name = name
if url:
widget.url = url
if widget.run():
cmds.do(cmds.RemoteAdd, context, widget.name, widget.url)
result = True
else:
result = False
return result
def restore_focus(focus):
if focus:
focus.setFocus(Qt.OtherFocusReason)
if hasattr(focus, 'selectAll'):
focus.selectAll()
class RemoteInfoThread(QtCore.QThread):
result = Signal(object)
def __init__(self, context, parent):
QtCore.QThread.__init__(self, parent)
self.context = context
self.remote = None
def run(self):
remote = self.remote
if remote is None:
return
git = self.context.git
_, out, err = git.remote('show', '-n', remote)
self.result.emit(out + err)
class AddRemoteDialog(QtWidgets.QDialog):
def __init__(self, context, parent, readonly_url=False):
super().__init__(parent)
self.context = context
if parent:
self.setWindowModality(Qt.WindowModal)
self.context = context
self.widget = RemoteWidget(context, self, readonly_url=readonly_url)
self.add_button = qtutils.create_button(
text=N_('Add Remote'), icon=icons.ok(), 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.add_button,
)
self._layout = qtutils.vbox(
defs.margin, defs.spacing, self.widget, self._button_layout
)
self.setLayout(self._layout)
self.widget.valid.connect(self.add_button.setEnabled)
qtutils.connect_button(self.add_button, self.accept)
qtutils.connect_button(self.close_button, self.reject)
def set_name(self, value):
self.widget.name = value
def set_url(self, value):
self.widget.url = value
name = property(operator.attrgetter('widget.name'), set_name)
url = property(operator.attrgetter('widget.url'), set_url)
def run(self):
self.show()
self.raise_()
return self.exec_() == QtWidgets.QDialog.Accepted
def lineedit(context, hint):
"""Create a HintedLineEdit with a preset minimum width"""
widget = text.HintedLineEdit(context, hint)
width = qtutils.text_width(widget.font(), 'M')
widget.setMinimumWidth(width * 32)
return widget
class RemoteWidget(QtWidgets.QWidget):
name = property(
lambda self: get(self.remote_name),
lambda self, value: self.remote_name.set_value(value),
)
url = property(
lambda self: get(self.remote_url),
lambda self, value: self.remote_url.set_value(value),
)
valid = Signal(bool)
def __init__(self, context, parent, readonly_url=False):
super().__init__(parent)
self.setWindowModality(Qt.WindowModal)
self.context = context
self.setWindowTitle(N_('Add remote'))
self.remote_name = lineedit(context, N_('Name for the new remote'))
self.remote_url = lineedit(context, 'git://git.example.com/repo.git')
self.open_button = qtutils.create_button(
text=N_('Browse...'), icon=icons.folder(), tooltip=N_('Select repository')
)
self.url_layout = qtutils.hbox(
defs.no_margin, defs.spacing, self.remote_url, self.open_button
)
validate_remote = completion.RemoteValidator(self.remote_name)
self.remote_name.setValidator(validate_remote)
self._form = qtutils.form(
defs.margin,
defs.spacing,
(N_('Name'), self.remote_name),
(N_('URL'), self.url_layout),
)
self._layout = qtutils.vbox(defs.margin, defs.spacing, self._form)
self.setLayout(self._layout)
self.remote_name.textChanged.connect(self.validate)
self.remote_url.textChanged.connect(self.validate)
qtutils.connect_button(self.open_button, self.open_repo)
if readonly_url:
self.remote_url.setReadOnly(True)
self.open_button.setEnabled(False)
def validate(self, _text):
name = self.name
url = self.url
self.valid.emit(bool(name) and bool(url))
def open_repo(self):
git = self.context.git
repo = qtutils.opendir_dialog(N_('Open Git Repository'), core.getcwd())
if repo and git.is_git_repository(repo):
self.url = repo
| 15,263 | Python | .py | 385 | 30.361039 | 87 | 0.617454 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
89 | branch.py | git-cola_git-cola/cola/widgets/branch.py | """Provides widgets related to branches"""
from functools import partial
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..compat import uchr
from ..git import STDOUT
from ..i18n import N_
from ..interaction import Interaction
from ..models import main as main_mod
from ..widgets import defs
from ..widgets import standard
from ..qtutils import get
from .. import cmds
from .. import gitcmds
from .. import hotkeys
from .. import icons
from .. import qtutils
from . import log
from . import text
def defer_func(parent, title, func, *args, **kwargs):
"""Return a QAction bound against a partial func with arguments"""
return qtutils.add_action(parent, title, partial(func, *args, **kwargs))
def add_branch_to_menu(menu, branch, remote_branch, remote, upstream, func):
"""Add a remote branch to the context menu"""
branch_remote, _ = gitcmds.parse_remote_branch(remote_branch)
if branch_remote != remote:
menu.addSeparator()
action = defer_func(menu, remote_branch, func, branch, remote_branch)
if remote_branch == upstream:
action.setIcon(icons.star())
menu.addAction(action)
return branch_remote
class AsyncGitActionTask(qtutils.Task):
"""Run git action asynchronously"""
def __init__(self, git_helper, action, args, kwarg, update_refs):
qtutils.Task.__init__(self)
self.git_helper = git_helper
self.action = action
self.args = args
self.kwarg = kwarg
self.update_refs = update_refs
def task(self):
"""Runs action and captures the result"""
git_action = getattr(self.git_helper, self.action)
return git_action(*self.args, **self.kwarg)
class BranchesWidget(QtWidgets.QFrame):
"""A widget for displaying and performing operations on branches"""
def __init__(self, context, parent):
QtWidgets.QFrame.__init__(self, parent)
self.model = model = context.model
tooltip = N_('Toggle the branches filter')
icon = icons.ellipsis()
self.filter_button = qtutils.create_action_button(tooltip=tooltip, icon=icon)
self.order_icons = (
icons.alphabetical(),
icons.reverse_chronological(),
)
tooltip_order = N_(
'Set the sort order for branches and tags.\n'
'Toggle between date-based and version-name-based sorting.'
)
icon = self.order_icon(model.ref_sort)
self.sort_order_button = qtutils.create_action_button(
tooltip=tooltip_order, icon=icon
)
self.tree = BranchesTreeWidget(context, parent=self)
self.filter_widget = BranchesFilterWidget(self.tree)
self.filter_widget.hide()
self.setFocusProxy(self.tree)
self.setToolTip(N_('Branches'))
self.main_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.filter_widget, self.tree
)
self.setLayout(self.main_layout)
self.toggle_action = qtutils.add_action(
self, tooltip, self.toggle_filter, hotkeys.FILTER
)
qtutils.connect_button(self.filter_button, self.toggle_filter)
qtutils.connect_button(
self.sort_order_button, cmds.run(cmds.CycleReferenceSort, context)
)
model.refs_updated.connect(self.refresh, Qt.QueuedConnection)
def toggle_filter(self):
shown = not self.filter_widget.isVisible()
self.filter_widget.setVisible(shown)
if shown:
self.filter_widget.setFocus()
else:
self.tree.setFocus()
def order_icon(self, idx):
return self.order_icons[idx % len(self.order_icons)]
def refresh(self):
icon = self.order_icon(self.model.ref_sort)
self.sort_order_button.setIcon(icon)
class BranchesTreeWidget(standard.TreeWidget):
"""A tree widget for displaying branches"""
updated = Signal()
def __init__(self, context, parent=None):
standard.TreeWidget.__init__(self, parent)
self.context = context
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setHeaderHidden(True)
self.setAlternatingRowColors(False)
self.setColumnCount(1)
self.setExpandsOnDoubleClick(False)
self.current_branch = None
self.tree_helper = BranchesTreeHelper(self)
self.git_helper = GitHelper(context)
self.runtask = qtutils.RunTask(parent=self)
self._visible = False
self._needs_refresh = False
self._tree_states = None
self.updated.connect(self.refresh, type=Qt.QueuedConnection)
context.model.updated.connect(self.updated)
# Expand items when they are clicked
self.clicked.connect(self._toggle_expanded)
# Checkout branch when double clicked
self.doubleClicked.connect(self.checkout_action)
def refresh(self):
"""Refresh the UI widgets to match the current state"""
self._needs_refresh = True
self._refresh()
def _refresh(self):
"""Refresh the UI to match the updated state"""
# There is no need to refresh the UI when this widget is inactive.
if not self._visible:
return
model = self.context.model
self.current_branch = model.currentbranch
self._tree_states = self._save_tree_state()
ellipsis = icons.ellipsis()
local_tree = create_tree_entries(model.local_branches)
local_tree.basename = N_('Local')
local = create_toplevel_item(local_tree, icon=icons.branch(), ellipsis=ellipsis)
remote_tree = create_tree_entries(model.remote_branches)
remote_tree.basename = N_('Remote')
remote = create_toplevel_item(
remote_tree, icon=icons.branch(), ellipsis=ellipsis
)
tags_tree = create_tree_entries(model.tags)
tags_tree.basename = N_('Tags')
tags = create_toplevel_item(tags_tree, icon=icons.tag(), ellipsis=ellipsis)
self.clear()
self.addTopLevelItems([local, remote, tags])
if self._tree_states:
self._load_tree_state(self._tree_states)
self._tree_states = None
self._update_branches()
def showEvent(self, event):
"""Defer updating widgets until the widget is visible"""
if not self._visible:
self._visible = True
if self._needs_refresh:
self.refresh()
return super().showEvent(event)
def _toggle_expanded(self, index):
"""Toggle expanded/collapsed state when items are clicked"""
item = self.itemFromIndex(index)
if item and item.childCount():
self.setExpanded(index, not self.isExpanded(index))
def contextMenuEvent(self, event):
"""Build and execute the context menu"""
context = self.context
selected = self.selected_item()
if not selected:
return
# Only allow actions on leaf nodes that have a valid refname.
if not selected.refname:
return
root = get_toplevel_item(selected)
full_name = selected.refname
menu = qtutils.create_menu(N_('Actions'), self)
visualize_action = qtutils.add_action(
menu, N_('Visualize'), self.visualize_branch_action
)
visualize_action.setIcon(icons.visualize())
menu.addAction(visualize_action)
menu.addSeparator()
# all branches except current the current branch
if full_name != self.current_branch:
menu.addAction(
qtutils.add_action(menu, N_('Checkout'), self.checkout_action)
)
# remote branch
if root.name == N_('Remote'):
label = N_('Checkout as new branch')
action = self.checkout_new_branch_action
menu.addAction(qtutils.add_action(menu, label, action))
merge_menu_action = qtutils.add_action(
menu, N_('Merge into current branch'), self.merge_action
)
merge_menu_action.setIcon(icons.merge())
menu.addAction(merge_menu_action)
# local and remote branch
if root.name != N_('Tags'):
# local branch
if root.name == N_('Local'):
remote = gitcmds.tracked_branch(context, full_name)
if remote is not None:
menu.addSeparator()
pull_menu_action = qtutils.add_action(
menu, N_('Pull'), self.pull_action
)
pull_menu_action.setIcon(icons.pull())
menu.addAction(pull_menu_action)
push_menu_action = qtutils.add_action(
menu, N_('Push'), self.push_action
)
push_menu_action.setIcon(icons.push())
menu.addAction(push_menu_action)
rename_menu_action = qtutils.add_action(
menu, N_('Rename Branch'), self.rename_action
)
rename_menu_action.setIcon(icons.edit())
menu.addSeparator()
menu.addAction(rename_menu_action)
# not current branch
if full_name != self.current_branch:
delete_label = N_('Delete Branch')
if root.name == N_('Remote'):
delete_label = N_('Delete Remote Branch')
delete_menu_action = qtutils.add_action(
menu, delete_label, self.delete_action
)
delete_menu_action.setIcon(icons.discard())
menu.addSeparator()
menu.addAction(delete_menu_action)
# manage upstream branches for local branches
if root.name == N_('Local'):
upstream_menu = menu.addMenu(N_('Set Upstream Branch'))
upstream_menu.setIcon(icons.branch())
self.build_upstream_menu(upstream_menu)
menu.exec_(self.mapToGlobal(event.pos()))
def build_upstream_menu(self, menu):
"""Build the "Set Upstream Branch" sub-menu"""
context = self.context
model = context.model
selected_branch = self.selected_refname()
remote = None
upstream = None
branches = []
other_branches = []
if selected_branch:
remote = gitcmds.upstream_remote(context, selected_branch)
upstream = gitcmds.tracked_branch(context, branch=selected_branch)
if not remote and 'origin' in model.remotes:
remote = 'origin'
if remote:
prefix = remote + '/'
for branch in model.remote_branches:
if branch.startswith(prefix):
branches.append(branch)
else:
other_branches.append(branch)
else:
# This can be a pretty big list, let's try to split it apart
branch_remote = ''
target = branches
for branch in model.remote_branches:
new_branch_remote, _ = gitcmds.parse_remote_branch(branch)
if branch_remote and branch_remote != new_branch_remote:
target = other_branches
branch_remote = new_branch_remote
target.append(branch)
limit = 16
if not other_branches and len(branches) > limit:
branches, other_branches = (branches[:limit], branches[limit:])
# Add an action for each remote branch
current_remote = remote
for branch in branches:
current_remote = add_branch_to_menu(
menu,
selected_branch,
branch,
current_remote,
upstream,
self.set_upstream,
)
# This list could be longer so we tuck it away in a sub-menu.
# Selecting a branch from the non-default remote is less common.
if other_branches:
menu.addSeparator()
sub_menu = menu.addMenu(N_('Other branches'))
for branch in other_branches:
current_remote = add_branch_to_menu(
sub_menu,
selected_branch,
branch,
current_remote,
upstream,
self.set_upstream,
)
def set_upstream(self, branch, remote_branch):
"""Configure the upstream for a branch"""
context = self.context
remote, r_branch = gitcmds.parse_remote_branch(remote_branch)
if remote and r_branch:
cmds.do(cmds.SetUpstreamBranch, context, branch, remote, r_branch)
def _save_tree_state(self):
"""Save the tree state into a dictionary"""
states = {}
for item in self.items():
states.update(self.tree_helper.save_state(item))
return states
def _load_tree_state(self, states):
"""Restore expanded items after rebuilding UI widgets"""
# Disable animations to eliminate redraw flicker.
animated = self.isAnimated()
self.setAnimated(False)
for item in self.items():
self.tree_helper.load_state(item, states.get(item.name, {}))
self.tree_helper.set_current_item()
self.setAnimated(animated)
def _update_branches(self):
"""Query branch details using a background task"""
context = self.context
current_branch = self.current_branch
top_item = self.topLevelItem(0)
item = find_by_refname(top_item, current_branch)
if item is not None:
expand_item_parents(item)
item.setIcon(0, icons.star())
branch_details_task = BranchDetailsTask(
context, current_branch, self.git_helper
)
self.runtask.start(
branch_details_task, finish=self._update_branches_finished
)
def _update_branches_finished(self, task):
"""Update the UI with the branch details once the background task completes"""
current_branch, tracked_branch, ahead, behind = task.result
top_item = self.topLevelItem(0)
item = find_by_refname(top_item, current_branch)
if current_branch and tracked_branch and item is not None:
status_str = ''
if ahead > 0:
status_str += f'{uchr(0x2191)}{ahead}'
if behind > 0:
status_str += f' {uchr(0x2193)}{behind}'
if status_str:
item.setText(0, f'{item.text(0)}\t{status_str}')
def git_action_async(
self, action, args, kwarg=None, update_refs=False, remote_messages=False
):
"""Execute a git action in a background task"""
if kwarg is None:
kwarg = {}
task = AsyncGitActionTask(self.git_helper, action, args, kwarg, update_refs)
progress = standard.progress(
N_('Executing action %s') % action, N_('Updating'), self
)
if remote_messages:
result_handler = log.show_remote_messages(self, self.context)
else:
result_handler = None
self.runtask.start(
task,
progress=progress,
finish=self.git_action_completed,
result=result_handler,
)
def git_action_completed(self, task):
"""Update the with the results of an async git action"""
status, out, err = task.result
self.git_helper.show_result(task.action, status, out, err)
if task.update_refs:
self.context.model.update_refs()
def push_action(self):
"""Push the selected branch to its upstream remote"""
context = self.context
branch = self.selected_refname()
remote_branch = gitcmds.tracked_branch(context, branch)
context.settings.load()
push_settings = context.settings.get('push')
remote_messages = push_settings.get('remote_messages', False)
if remote_branch:
remote, branch_name = gitcmds.parse_remote_branch(remote_branch)
kwarg = {}
main_mod.autodetect_proxy(context, kwarg)
main_mod.no_color(kwarg)
if remote and branch_name:
# we assume that user wants to "Push" the selected local
# branch to a remote with same name
self.git_action_async(
'push',
[remote, branch_name],
update_refs=True,
remote_messages=remote_messages,
kwarg=kwarg,
)
def rename_action(self):
"""Rename the selected branch"""
branch = self.selected_refname()
new_branch, ok = qtutils.prompt(
N_('Enter New Branch Name'), title=N_('Rename branch'), text=branch
)
if ok and new_branch:
self.git_action_async('rename', [branch, new_branch], update_refs=True)
def pull_action(self):
"""Pull the selected branch into the current branch"""
context = self.context
branch = self.selected_refname()
if not branch:
return
remote_branch = gitcmds.tracked_branch(context, branch)
context.settings.load()
pull_settings = context.settings.get('pull')
remote_messages = pull_settings.get('remote_messages', False)
if remote_branch:
remote, branch_name = gitcmds.parse_remote_branch(remote_branch)
if remote and branch_name:
kwarg = {}
main_mod.autodetect_proxy(context, kwarg)
main_mod.no_color(kwarg)
self.git_action_async(
'pull',
[remote, branch_name],
update_refs=True,
remote_messages=remote_messages,
kwarg=kwarg,
)
def delete_action(self):
"""Delete the selected branch"""
branch = self.selected_refname()
if not branch or branch == self.current_branch:
return
remote = False
root = get_toplevel_item(self.selected_item())
if not root:
return
if root.name == N_('Remote'):
remote = True
if remote:
remote, branch = gitcmds.parse_remote_branch(branch)
if remote and branch:
cmds.do(cmds.DeleteRemoteBranch, self.context, remote, branch)
else:
cmds.do(cmds.DeleteBranch, self.context, branch)
def merge_action(self):
"""Merge the selected branch into the current branch"""
branch = self.selected_refname()
if branch and branch != self.current_branch:
self.git_action_async('merge', [branch])
def checkout_action(self):
"""Checkout the selected branch"""
branch = self.selected_refname()
if branch and branch != self.current_branch:
self.git_action_async('checkout', [branch], update_refs=True)
def checkout_new_branch_action(self):
"""Checkout a new branch"""
branch = self.selected_refname()
if branch and branch != self.current_branch:
_, new_branch = gitcmds.parse_remote_branch(branch)
self.git_action_async(
'checkout', ['-b', new_branch, branch], update_refs=True
)
def visualize_branch_action(self):
"""Visualize the selected branch"""
branch = self.selected_refname()
if branch:
cmds.do(cmds.VisualizeRevision, self.context, branch)
def selected_refname(self):
return getattr(self.selected_item(), 'refname', None)
class BranchDetailsTask(qtutils.Task):
"""Lookup branch details in a background task"""
def __init__(self, context, current_branch, git_helper):
super().__init__()
self.context = context
self.current_branch = current_branch
self.git_helper = git_helper
def task(self):
"""Query git for branch details"""
tracked_branch = gitcmds.tracked_branch(self.context, self.current_branch)
ahead = 0
behind = 0
if self.current_branch and tracked_branch:
origin = tracked_branch + '..' + self.current_branch
our_commits = self.git_helper.log(origin)[STDOUT]
ahead = our_commits.count('\n')
if our_commits:
ahead += 1
origin = self.current_branch + '..' + tracked_branch
their_commits = self.git_helper.log(origin)[STDOUT]
behind = their_commits.count('\n')
if their_commits:
behind += 1
return self.current_branch, tracked_branch, ahead, behind
class BranchTreeWidgetItem(QtWidgets.QTreeWidgetItem):
def __init__(self, name, refname=None, icon=None):
QtWidgets.QTreeWidgetItem.__init__(self)
self.name = name
self.refname = refname
self.setText(0, name)
self.setToolTip(0, name)
if icon is not None:
self.setIcon(0, icon)
self.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
class TreeEntry:
"""Tree representation for the branches widget
The branch widget UI displays the basename. For intermediate names, e.g.
"xxx" in the "xxx/abc" and "xxx/def" branches, the 'refname' will be None.
'children' contains a list of TreeEntry, and is empty when refname is
defined.
"""
def __init__(self, basename, refname, children):
self.basename = basename
self.refname = refname
self.children = children
def create_tree_entries(names):
"""Create a nested tree structure with a single root TreeEntry.
When names == ['xxx/abc', 'xxx/def'] the result will be::
TreeEntry(
basename=None,
refname=None,
children=[
TreeEntry(
basename='xxx',
refname=None,
children=[
TreeEntry(
basename='abc',
refname='xxx/abc',
children=[]
),
TreeEntry(
basename='def',
refname='xxx/def',
children=[]
)
]
)
]
)
"""
# Phase 1: build a nested dictionary representing the intermediate
# names in the branches, e.g. {'xxx': {'abc': {}, 'def': {}}}
tree_names = create_name_dict(names)
# Loop over the names again, this time we'll create tree entries
entries = {}
root = TreeEntry(None, None, [])
for item in names:
cur_names = tree_names
cur_entries = entries
tree = root
children = root.children
for part in item.split('/'):
if cur_names[part]:
# This has children
try:
tree, _ = cur_entries[part]
except KeyError:
# New entry
tree = TreeEntry(part, None, [])
cur_entries[part] = (tree, {})
# Append onto the parent children list only once
children.append(tree)
else:
# This is the actual branch
tree = TreeEntry(part, item, [])
children.append(tree)
cur_entries[part] = (tree, {})
# Advance into the nested child list
children = tree.children
# Advance into the inner dict
cur_names = cur_names[part]
_, cur_entries = cur_entries[part]
return root
def create_name_dict(names):
# Phase 1: build a nested dictionary representing the intermediate
# names in the branches, e.g. {'xxx': {'abc': {}, 'def': {}}}
tree_names = {}
for item in names:
part_names = tree_names
for part in item.split('/'):
# Descend into the inner names dict.
part_names = part_names.setdefault(part, {})
return tree_names
def create_toplevel_item(tree, icon=None, ellipsis=None):
"""Create a top-level BranchTreeWidgetItem and its children"""
item = BranchTreeWidgetItem(tree.basename, icon=ellipsis)
children = create_tree_items(tree.children, icon=icon, ellipsis=ellipsis)
if children:
item.addChildren(children)
return item
def create_tree_items(entries, icon=None, ellipsis=None):
"""Create children items for a tree item"""
result = []
for tree in entries:
item = BranchTreeWidgetItem(tree.basename, refname=tree.refname, icon=icon)
children = create_tree_items(tree.children, icon=icon, ellipsis=ellipsis)
if children:
item.addChildren(children)
if ellipsis is not None:
item.setIcon(0, ellipsis)
result.append(item)
return result
def expand_item_parents(item):
"""Expand tree parents from item"""
parent = item.parent()
while parent is not None:
if not parent.isExpanded():
parent.setExpanded(True)
parent = parent.parent()
def find_by_refname(item, refname):
"""Find child by full name recursive"""
result = None
for i in range(item.childCount()):
child = item.child(i)
if child.refname and child.refname == refname:
return child
result = find_by_refname(child, refname)
if result is not None:
return result
return result
def get_toplevel_item(item):
"""Returns top-most item found by traversing up the specified item"""
parents = [item]
parent = item.parent()
while parent is not None:
parents.append(parent)
parent = parent.parent()
return parents[-1]
class BranchesTreeHelper:
"""Save and restore the tree state"""
def __init__(self, tree):
self.tree = tree
self.current_item = None
def set_current_item(self):
"""Reset the current item"""
if self.current_item is not None:
self.tree.setCurrentItem(self.current_item)
self.current_item = None
def load_state(self, item, state):
"""Load expanded items from a dict"""
if not state:
return
if state.get('expanded', False) and not item.isExpanded():
item.setExpanded(True)
if state.get('selected', False) and not item.isSelected():
item.setSelected(True)
self.current_item = item
children_state = state.get('children', {})
if not children_state:
return
for i in range(item.childCount()):
child = item.child(i)
self.load_state(child, children_state.get(child.name, {}))
def save_state(self, item):
"""Save the selected and expanded item state into a dict"""
expanded = item.isExpanded()
selected = item.isSelected()
children = {}
entry = {
'children': children,
'expanded': expanded,
'selected': selected,
}
result = {item.name: entry}
for i in range(item.childCount()):
child = item.child(i)
children.update(self.save_state(child))
return result
class GitHelper:
def __init__(self, context):
self.context = context
self.git = context.git
def log(self, origin):
return self.git.log(origin, abbrev=7, pretty='format:%h', _readonly=True)
def push(self, remote, branch, **kwarg):
return self.git.push(remote, branch, verbose=True, **kwarg)
def pull(self, remote, branch, **kwarg):
return self.git.pull(remote, branch, no_ff=True, verbose=True, **kwarg)
def merge(self, branch):
return self.git.merge(branch, no_commit=True)
def rename(self, branch, new_branch):
return self.git.branch(branch, new_branch, m=True)
def checkout(self, *args, **options):
return self.git.checkout(*args, **options)
@staticmethod
def show_result(command, status, out, err):
Interaction.log_status(status, out, err)
if status != 0:
Interaction.command_error(N_('Error'), command, status, out, err)
class BranchesFilterWidget(QtWidgets.QWidget):
def __init__(self, tree, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.tree = tree
hint = N_('Filter branches...')
self.text = text.LineEdit(parent=self, clear_button=True)
self.text.setToolTip(hint)
self.setFocusProxy(self.text)
self._filter = None
self.main_layout = qtutils.hbox(defs.no_margin, defs.spacing, self.text)
self.setLayout(self.main_layout)
self.text.textChanged.connect(self.apply_filter)
self.tree.updated.connect(self.apply_filter, type=Qt.QueuedConnection)
def apply_filter(self):
value = get(self.text)
if value == self._filter:
return
self._apply_bold(self._filter, False)
self._filter = value
if value:
self._apply_bold(value, True)
def _apply_bold(self, value, is_bold):
match = Qt.MatchContains | Qt.MatchRecursive
children = self.tree.findItems(value, match)
for child in children:
if child.childCount() == 0:
font = child.font(0)
font.setBold(is_bold)
child.setFont(0, font)
| 29,798 | Python | .py | 713 | 31.086957 | 88 | 0.594952 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
90 | clone.py | git-cola_git-cola/cola/widgets/clone.py | import os
from functools import partial
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from .. import cmds
from .. import core
from .. import icons
from .. import utils
from .. import qtutils
from ..i18n import N_
from ..interaction import Interaction
from ..qtutils import get
from . import defs
from . import standard
from . import text
def clone(context, spawn=True, show=True):
"""Clone a repository and spawn a new git-cola instance"""
parent = qtutils.active_window()
progress = standard.progress('', '', parent)
return clone_repo(context, show, progress, task_finished, spawn)
def clone_repo(context, show, progress, finish, spawn):
"""Clone a repository asynchronously with progress animation"""
func = partial(start_clone_task, context, progress, finish, spawn)
prompt = prompt_for_clone(context, show=show)
prompt.result.connect(func)
return prompt
def prompt_for_clone(context, show=True):
"""Presents a GUI for cloning a repository"""
view = Clone(context, parent=qtutils.active_window())
if show:
view.show()
return view
def task_finished(task):
"""Report errors from the clone task if they exist"""
cmd = task.cmd
if cmd is None:
return
status = cmd.status
out = cmd.out
err = cmd.err
title = N_('Error: could not clone "%s"') % cmd.url
Interaction.command(title, 'git clone', status, out, err)
def start_clone_task(
context, progress, finish, spawn, url, destdir, submodules, shallow
):
# Use a thread to update in the background
runtask = context.runtask
progress.set_details(N_('Clone Repository'), N_('Cloning repository at %s') % url)
task = CloneTask(context, url, destdir, submodules, shallow, spawn)
runtask.start(task, finish=finish, progress=progress)
class CloneTask(qtutils.Task):
"""Clones a Git repository"""
def __init__(self, context, url, destdir, submodules, shallow, spawn):
qtutils.Task.__init__(self)
self.context = context
self.url = url
self.destdir = destdir
self.submodules = submodules
self.shallow = shallow
self.spawn = spawn
self.cmd = None
def task(self):
"""Runs the model action and captures the result"""
self.cmd = cmds.do(
cmds.Clone,
self.context,
self.url,
self.destdir,
self.submodules,
self.shallow,
spawn=self.spawn,
)
return self.cmd
class Clone(standard.Dialog):
# Signal binding for returning the input data
result = QtCore.Signal(object, object, bool, bool)
def __init__(self, context, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.model = context.model
self.setWindowTitle(N_('Clone Repository'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
# Repository location
self.url_label = QtWidgets.QLabel(N_('URL'))
hint = 'git://git.example.com/repo.git'
self.url = text.HintedLineEdit(context, hint, parent=self)
self.url.setToolTip(N_('Path or URL to clone (Env. $VARS okay)'))
# Initialize submodules
self.submodules = qtutils.checkbox(
text=N_('Inititalize submodules'), checked=False
)
# Reduce commit history
self.shallow = qtutils.checkbox(
text=N_('Reduce commit history to minimum'), checked=False
)
# Buttons
self.ok_button = qtutils.create_button(
text=N_('Clone'), icon=icons.ok(), default=True
)
self.close_button = qtutils.close_button()
# Form layout for inputs
self.input_layout = qtutils.form(
defs.no_margin, defs.button_spacing, (self.url_label, self.url)
)
self.button_layout = qtutils.hbox(
defs.margin,
defs.spacing,
self.submodules,
defs.button_spacing,
self.shallow,
qtutils.STRETCH,
self.close_button,
self.ok_button,
)
self.main_layout = qtutils.vbox(
defs.margin, defs.spacing, self.input_layout, self.button_layout
)
self.setLayout(self.main_layout)
qtutils.connect_button(self.close_button, self.close)
qtutils.connect_button(self.ok_button, self.prepare_to_clone)
self.url.textChanged.connect(lambda x: self.update_actions())
self.init_state(context.settings, self.resize, 720, 200)
self.update_actions()
def update_actions(self):
url = get(self.url).strip()
enabled = bool(url)
self.ok_button.setEnabled(enabled)
def prepare_to_clone(self):
"""Grabs and validates the input data"""
submodules = get(self.submodules)
shallow = get(self.shallow)
url = get(self.url)
url = utils.expandpath(url)
if not url:
return
# Pick a suitable basename by parsing the URL
newurl = url.replace('\\', '/').rstrip('/')
try:
default = newurl.rsplit('/', 1)[-1]
except IndexError:
default = ''
if default == '.git':
# The end of the URL is /.git, so assume it's a file path
default = os.path.basename(os.path.dirname(newurl))
if default.endswith('.git'):
# The URL points to a bare repo
default = default[:-4]
if url == '.':
# The URL is the current repo
default = os.path.basename(core.getcwd())
if not default:
Interaction.information(
N_('Error Cloning'), N_('Could not parse Git URL: "%s"') % url
)
Interaction.log(N_('Could not parse Git URL: "%s"') % url)
return
# Prompt the user for a directory to use as the parent directory
msg = N_('Select a parent directory for the new clone')
dirname = qtutils.opendir_dialog(msg, os.path.dirname(self.model.getcwd()))
if not dirname:
return
count = 1
destdir = os.path.join(dirname, default)
olddestdir = destdir
if core.exists(destdir):
# An existing path can be specified
msg = N_('"%s" already exists, cola will create a new directory') % destdir
Interaction.information(N_('Directory Exists'), msg)
# Make sure the directory doesn't exist
while core.exists(destdir):
destdir = olddestdir + str(count)
count += 1
# Return the input data and close the dialog
self.result.emit(url, destdir, submodules, shallow)
self.close()
| 6,816 | Python | .py | 177 | 30.231638 | 87 | 0.622293 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
91 | prefs.py | git-cola_git-cola/cola/widgets/prefs.py | from qtpy import QtCore
from qtpy import QtWidgets
from . import defs
from . import standard
from .. import cmds
from .. import hidpi
from .. import icons
from .. import qtutils
from .. import themes
from ..compat import ustr
from ..i18n import N_
from ..models import prefs
from ..models.prefs import Defaults
from ..models.prefs import fallback_editor
def preferences(context, model=None, parent=None):
if model is None:
model = prefs.PreferencesModel(context)
view = PreferencesView(context, model, parent=parent)
view.show()
view.raise_()
return view
class FormWidget(QtWidgets.QWidget):
def __init__(self, context, model, parent, source='global'):
QtWidgets.QWidget.__init__(self, parent)
self.context = context
self.cfg = context.cfg
self.model = model
self.config_to_widget = {}
self.widget_to_config = {}
self.source = source
self.defaults = {}
self.setLayout(QtWidgets.QFormLayout())
def add_row(self, label, widget):
self.layout().addRow(label, widget)
def set_config(self, config_dict):
self.config_to_widget.update(config_dict)
for config, (widget, default) in config_dict.items():
self.widget_to_config[config] = widget
self.defaults[config] = default
self.connect_widget_to_config(widget, config)
def connect_widget_to_config(self, widget, config):
if isinstance(widget, QtWidgets.QSpinBox):
widget.valueChanged.connect(self._int_config_changed(config))
elif isinstance(widget, QtWidgets.QCheckBox):
widget.toggled.connect(self._bool_config_changed(config))
elif isinstance(widget, QtWidgets.QLineEdit):
widget.editingFinished.connect(self._text_config_changed(config, widget))
widget.returnPressed.connect(self._text_config_changed(config, widget))
elif isinstance(widget, qtutils.ComboBox):
widget.currentIndexChanged.connect(
self._item_config_changed(config, widget)
)
def _int_config_changed(self, config):
def runner(value):
cmds.do(prefs.SetConfig, self.model, self.source, config, value)
return runner
def _bool_config_changed(self, config):
def runner(value):
cmds.do(prefs.SetConfig, self.model, self.source, config, value)
return runner
def _text_config_changed(self, config, widget):
def runner():
value = widget.text()
cmds.do(prefs.SetConfig, self.model, self.source, config, value)
return runner
def _item_config_changed(self, config, widget):
def runner():
value = widget.current_data()
cmds.do(prefs.SetConfig, self.model, self.source, config, value)
return runner
def update_from_config(self):
if self.source == 'global':
getter = self.cfg.get_user_or_system
else:
getter = self.cfg.get
for config, widget in self.widget_to_config.items():
value = getter(config)
if value is None:
value = self.defaults[config]
set_widget_value(widget, value)
def set_widget_value(widget, value):
"""Set a value on a widget without emitting notifications"""
with qtutils.BlockSignals(widget):
if isinstance(widget, QtWidgets.QSpinBox):
widget.setValue(value)
elif isinstance(widget, QtWidgets.QLineEdit):
widget.setText(value)
elif isinstance(widget, QtWidgets.QCheckBox):
widget.setChecked(value)
elif hasattr(widget, 'set_value'):
widget.set_value(value)
class RepoFormWidget(FormWidget):
def __init__(self, context, model, parent, source):
FormWidget.__init__(self, context, model, parent, source=source)
self.name = QtWidgets.QLineEdit()
self.email = QtWidgets.QLineEdit()
tooltip = N_(
'Default directory when exporting patches.\n'
'Relative paths are relative to the current repository.\n'
'Absolute path are used as-is.'
)
patches_directory = prefs.patches_directory(context)
self.patches_directory = standard.DirectoryPathLineEdit(patches_directory, self)
self.patches_directory.setToolTip(tooltip)
tooltip = N_(
"""
This option determines how the supplied commit message should be
cleaned up before committing.
The <mode> can be strip, whitespace, verbatim, scissors or default.
strip
Strip leading and trailing empty lines, trailing whitespace,
commentary and collapse consecutive empty lines.
whitespace
Same as strip except #commentary is not removed.
verbatim
Do not change the message at all.
scissors
Same as whitespace except that everything from (and including) the line
found below is truncated, if the message is to be edited.
"#" can be customized with core.commentChar.
# ------------------------ >8 ------------------------"""
)
self.commit_cleanup = qtutils.combo(
prefs.commit_cleanup_modes(), tooltip=tooltip
)
self.diff_context = standard.SpinBox(value=5, mini=2, maxi=9995)
self.merge_verbosity = standard.SpinBox(value=5, maxi=5)
self.merge_summary = qtutils.checkbox(checked=True)
self.autotemplate = qtutils.checkbox(checked=False)
self.merge_diffstat = qtutils.checkbox(checked=True)
self.display_untracked = qtutils.checkbox(checked=True)
self.show_path = qtutils.checkbox(checked=True)
self.http_proxy = QtWidgets.QLineEdit()
tooltip = N_(
'Enable file system change monitoring using '
'inotify on Linux and win32event on Windows'
)
self.inotify = qtutils.checkbox(checked=True)
self.inotify.setToolTip(tooltip)
self.logdate = qtutils.combo(prefs.date_formats())
tooltip = N_(
'The date-time format used when displaying dates in Git DAG.\n'
'This value is passed to git log --date=<format>'
)
self.logdate.setToolTip(tooltip)
tooltip = N_('Use gravatar.com to lookup icons for author emails')
self.enable_gravatar = qtutils.checkbox(checked=True, tooltip=tooltip)
tooltip = N_('Enable path autocompletion in tools')
self.autocomplete_paths = qtutils.checkbox(checked=True, tooltip=tooltip)
self.proxy_spacer = QtWidgets.QLabel()
tooltip = N_('Enable detection and configuration of HTTP proxy settings')
self.autodetect_proxy = qtutils.checkbox(checked=True, tooltip=tooltip)
self.add_row(N_('User Name'), self.name)
self.add_row(N_('Email Address'), self.email)
self.add_row(N_('Patches Directory'), self.patches_directory)
self.add_row(N_('Log Date Format'), self.logdate)
self.add_row(N_('Commit Message Cleanup'), self.commit_cleanup)
self.add_row(N_('Merge Verbosity'), self.merge_verbosity)
self.add_row(N_('Number of Diff Context Lines'), self.diff_context)
self.add_row(N_('Summarize Merge Commits'), self.merge_summary)
self.add_row(
N_('Automatically Load Commit Message Template'), self.autotemplate
)
self.add_row(N_('Show Full Paths in the Window Title'), self.show_path)
self.add_row(N_('Show Diffstat After Merge'), self.merge_diffstat)
self.add_row(N_('Display Untracked Files'), self.display_untracked)
self.add_row(N_('Enable Gravatar Icons'), self.enable_gravatar)
self.add_row(N_('Autocomplete Paths'), self.autocomplete_paths)
self.add_row('', self.proxy_spacer)
self.add_row(
N_('Automatically Detect and Configure Proxy Settings'),
self.autodetect_proxy,
)
self.add_row(N_('HTTP Proxy URL'), self.http_proxy)
self.set_config({
prefs.AUTOTEMPLATE: (self.autotemplate, Defaults.autotemplate),
prefs.AUTOCOMPLETE_PATHS: (
self.autocomplete_paths,
Defaults.autocomplete_paths,
),
prefs.AUTODETECT_PROXY: (
self.autodetect_proxy,
Defaults.autodetect_proxy,
),
prefs.COMMIT_CLEANUP: (self.commit_cleanup, Defaults.commit_cleanup),
prefs.DIFFCONTEXT: (self.diff_context, Defaults.diff_context),
prefs.DISPLAY_UNTRACKED: (
self.display_untracked,
Defaults.display_untracked,
),
prefs.ENABLE_GRAVATAR: (self.enable_gravatar, Defaults.enable_gravatar),
prefs.HTTP_PROXY: (self.http_proxy, Defaults.http_proxy),
prefs.INOTIFY: (self.inotify, Defaults.inotify),
prefs.LOGDATE: (self.logdate, Defaults.logdate),
prefs.MERGE_DIFFSTAT: (self.merge_diffstat, Defaults.merge_diffstat),
prefs.MERGE_SUMMARY: (self.merge_summary, Defaults.merge_summary),
prefs.MERGE_VERBOSITY: (self.merge_verbosity, Defaults.merge_verbosity),
prefs.PATCHES_DIRECTORY: (
self.patches_directory,
Defaults.patches_directory,
),
prefs.SHOW_PATH: (self.show_path, Defaults.show_path),
prefs.USER_NAME: (self.name, ''),
prefs.USER_EMAIL: (self.email, ''),
})
class SettingsFormWidget(FormWidget):
def __init__(self, context, model, parent):
FormWidget.__init__(self, context, model, parent)
self.fixed_font = QtWidgets.QFontComboBox()
self.font_size = standard.SpinBox(value=12, mini=6, maxi=192)
self.maxrecent = standard.SpinBox(maxi=99)
self.tabwidth = standard.SpinBox(maxi=42)
self.textwidth = standard.SpinBox(maxi=150)
self.editor = QtWidgets.QLineEdit()
self.historybrowser = QtWidgets.QLineEdit()
self.blameviewer = QtWidgets.QLineEdit()
self.difftool = QtWidgets.QLineEdit()
self.mergetool = QtWidgets.QLineEdit()
self.linebreak = qtutils.checkbox()
self.mouse_zoom = qtutils.checkbox()
self.keep_merge_backups = qtutils.checkbox()
self.sort_bookmarks = qtutils.checkbox()
self.save_window_settings = qtutils.checkbox()
self.check_spelling = qtutils.checkbox()
tooltip = N_('Detect conflict markers in unmerged files')
self.check_conflicts = qtutils.checkbox(checked=True, tooltip=tooltip)
self.expandtab = qtutils.checkbox(tooltip=N_('Insert tabs instead of spaces'))
tooltip = N_('Prevent "Stage" from staging all files when nothing is selected')
self.safe_mode = qtutils.checkbox(checked=False, tooltip=tooltip)
tooltip = N_('Check whether a commit has been published when amending')
self.check_published_commits = qtutils.checkbox(checked=True, tooltip=tooltip)
tooltip = N_(
'Refresh repository state whenever the window is focused or un-minimized'
)
self.refresh_on_focus = qtutils.checkbox(checked=False, tooltip=tooltip)
self.resize_browser_columns = qtutils.checkbox(checked=False)
tooltip = N_('Emit notifications when commits are pushed.')
self.notifyonpush = qtutils.checkbox(checked=False, tooltip=tooltip)
self.add_row(N_('Fixed-Width Font'), self.fixed_font)
self.add_row(N_('Font Size'), self.font_size)
self.add_row(N_('Text Width'), self.textwidth)
self.add_row(N_('Tab Width'), self.tabwidth)
self.add_row(N_('Editor'), self.editor)
self.add_row(N_('History Browser'), self.historybrowser)
self.add_row(N_('Blame Viewer'), self.blameviewer)
self.add_row(N_('Diff Tool'), self.difftool)
self.add_row(N_('Merge Tool'), self.mergetool)
self.add_row(N_('Recent repository count'), self.maxrecent)
self.add_row(N_('Auto-Wrap Lines'), self.linebreak)
self.add_row(N_('Insert spaces instead of tabs'), self.expandtab)
self.add_row(
N_('Check Published Commits when Amending'), self.check_published_commits
)
self.add_row(N_('Sort bookmarks alphabetically'), self.sort_bookmarks)
self.add_row(N_('Safe Mode'), self.safe_mode)
self.add_row(N_('Detect Conflict Markers'), self.check_conflicts)
self.add_row(N_('Keep *.orig Merge Backups'), self.keep_merge_backups)
self.add_row(N_('Save GUI Settings'), self.save_window_settings)
self.add_row(N_('Refresh on Focus'), self.refresh_on_focus)
self.add_row(N_('Resize File Browser columns'), self.resize_browser_columns)
self.add_row(N_('Check spelling'), self.check_spelling)
self.add_row(N_('Ctrl+MouseWheel to Zoom'), self.mouse_zoom)
self.add_row(N_('Notify on Push'), self.notifyonpush)
self.set_config({
prefs.SAVEWINDOWSETTINGS: (
self.save_window_settings,
Defaults.save_window_settings,
),
prefs.TABWIDTH: (self.tabwidth, Defaults.tabwidth),
prefs.EXPANDTAB: (self.expandtab, Defaults.expandtab),
prefs.TEXTWIDTH: (self.textwidth, Defaults.textwidth),
prefs.LINEBREAK: (self.linebreak, Defaults.linebreak),
prefs.MAXRECENT: (self.maxrecent, Defaults.maxrecent),
prefs.SORT_BOOKMARKS: (self.sort_bookmarks, Defaults.sort_bookmarks),
prefs.DIFFTOOL: (self.difftool, Defaults.difftool),
prefs.EDITOR: (self.editor, fallback_editor()),
prefs.HISTORY_BROWSER: (
self.historybrowser,
prefs.default_history_browser(),
),
prefs.BLAME_VIEWER: (self.blameviewer, Defaults.blame_viewer),
prefs.CHECK_CONFLICTS: (self.check_conflicts, Defaults.check_conflicts),
prefs.CHECK_PUBLISHED_COMMITS: (
self.check_published_commits,
Defaults.check_published_commits,
),
prefs.MERGE_KEEPBACKUP: (
self.keep_merge_backups,
Defaults.merge_keep_backup,
),
prefs.MERGETOOL: (self.mergetool, Defaults.mergetool),
prefs.REFRESH_ON_FOCUS: (self.refresh_on_focus, Defaults.refresh_on_focus),
prefs.RESIZE_BROWSER_COLUMNS: (
self.resize_browser_columns,
Defaults.resize_browser_columns,
),
prefs.SAFE_MODE: (self.safe_mode, Defaults.safe_mode),
prefs.SPELL_CHECK: (self.check_spelling, Defaults.spellcheck),
prefs.MOUSE_ZOOM: (self.mouse_zoom, Defaults.mouse_zoom),
prefs.NOTIFY_ON_PUSH: (self.notifyonpush, Defaults.notifyonpush),
})
self.fixed_font.currentFontChanged.connect(self.current_font_changed)
self.font_size.valueChanged.connect(self.font_size_changed)
def update_from_config(self):
"""Update widgets to the current config values"""
FormWidget.update_from_config(self)
context = self.context
with qtutils.BlockSignals(self.fixed_font):
font = qtutils.diff_font(context)
self.fixed_font.setCurrentFont(font)
with qtutils.BlockSignals(self.font_size):
font_size = font.pointSize()
self.font_size.setValue(font_size)
def font_size_changed(self, size):
font = self.fixed_font.currentFont()
font.setPointSize(size)
cmds.do(prefs.SetConfig, self.model, 'global', prefs.FONTDIFF, font.toString())
def current_font_changed(self, font):
cmds.do(prefs.SetConfig, self.model, 'global', prefs.FONTDIFF, font.toString())
class AppearanceFormWidget(FormWidget):
def __init__(self, context, model, parent):
FormWidget.__init__(self, context, model, parent)
# Theme selectors
self.themes = themes.get_all_themes()
self.theme = qtutils.combo_mapped(themes.options(themes=self.themes))
self.icon_theme = qtutils.combo_mapped(icons.icon_themes())
# The transform to ustr is needed because the config reader will convert
# "0", "1", and "2" into integers. The "1.5" value, though, is
# parsed as a string, so the transform is effectively a no-op.
self.high_dpi = qtutils.combo_mapped(hidpi.options(), transform=ustr)
self.high_dpi.setEnabled(hidpi.is_supported())
self.bold_headers = qtutils.checkbox()
self.status_show_totals = qtutils.checkbox()
self.status_indent = qtutils.checkbox()
self.block_cursor = qtutils.checkbox(checked=True)
self.add_row(N_('GUI theme'), self.theme)
self.add_row(N_('Icon theme'), self.icon_theme)
self.add_row(N_('High DPI'), self.high_dpi)
self.add_row(N_('Bold on dark headers instead of italic'), self.bold_headers)
self.add_row(N_('Show file counts in Status titles'), self.status_show_totals)
self.add_row(N_('Indent Status paths'), self.status_indent)
self.add_row(N_('Use a block cursor in diff editors'), self.block_cursor)
self.set_config({
prefs.BOLD_HEADERS: (self.bold_headers, Defaults.bold_headers),
prefs.HIDPI: (self.high_dpi, Defaults.hidpi),
prefs.STATUS_SHOW_TOTALS: (
self.status_show_totals,
Defaults.status_show_totals,
),
prefs.STATUS_INDENT: (self.status_indent, Defaults.status_indent),
prefs.THEME: (self.theme, Defaults.theme),
prefs.ICON_THEME: (self.icon_theme, Defaults.icon_theme),
prefs.BLOCK_CURSOR: (self.block_cursor, Defaults.block_cursor),
})
self.theme.currentIndexChanged.connect(self._theme_changed)
def _theme_changed(self, theme_idx):
"""Set the icon theme to dark/light when the main theme changes"""
# Set the icon theme to a theme that corresponds to the main settings.
try:
theme = self.themes[theme_idx]
except IndexError:
return
icon_theme = self.icon_theme.current_data()
if theme.name == 'default':
if icon_theme in ('light', 'dark'):
self.icon_theme.set_value('default')
elif theme.is_dark:
if icon_theme in ('default', 'light'):
self.icon_theme.set_value('dark')
elif not theme.is_dark:
if icon_theme in ('default', 'dark'):
self.icon_theme.set_value('light')
class AppearanceWidget(QtWidgets.QWidget):
def __init__(self, form, parent):
QtWidgets.QWidget.__init__(self, parent)
self.form = form
self.label = QtWidgets.QLabel(
'<center><b>'
+ N_('Restart the application after changing appearance settings.')
+ '</b></center>'
)
layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.form,
defs.spacing * 4,
self.label,
qtutils.STRETCH,
)
self.setLayout(layout)
def update_from_config(self):
self.form.update_from_config()
class PreferencesView(standard.Dialog):
def __init__(self, context, model, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.setWindowTitle(N_('Preferences'))
if parent is not None:
self.setWindowModality(QtCore.Qt.WindowModal)
self.resize(600, 360)
self.tab_bar = QtWidgets.QTabBar()
self.tab_bar.setDrawBase(False)
self.tab_bar.addTab(N_('All Repositories'))
self.tab_bar.addTab(N_('Current Repository'))
self.tab_bar.addTab(N_('Settings'))
self.tab_bar.addTab(N_('Appearance'))
self.user_form = RepoFormWidget(context, model, self, source='global')
self.repo_form = RepoFormWidget(context, model, self, source='local')
self.options_form = SettingsFormWidget(context, model, self)
self.appearance_form = AppearanceFormWidget(context, model, self)
self.appearance = AppearanceWidget(self.appearance_form, self)
self.stack_widget = QtWidgets.QStackedWidget()
self.stack_widget.addWidget(self.user_form)
self.stack_widget.addWidget(self.repo_form)
self.stack_widget.addWidget(self.options_form)
self.stack_widget.addWidget(self.appearance)
self.close_button = qtutils.close_button()
self.button_layout = qtutils.hbox(
defs.no_margin, defs.spacing, qtutils.STRETCH, self.close_button
)
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.tab_bar,
self.stack_widget,
self.button_layout,
)
self.setLayout(self.main_layout)
self.tab_bar.currentChanged.connect(self.stack_widget.setCurrentIndex)
self.stack_widget.currentChanged.connect(self.update_widget)
qtutils.connect_button(self.close_button, self.accept)
qtutils.add_close_action(self)
self.update_widget(0)
def update_widget(self, idx):
widget = self.stack_widget.widget(idx)
widget.update_from_config()
| 21,345 | Python | .py | 436 | 39.091743 | 88 | 0.642617 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
92 | toolbar.py | git-cola_git-cola/cola/widgets/toolbar.py | from functools import partial
from qtpy import QtGui
from qtpy.QtCore import Qt
from qtpy import QtWidgets
from ..i18n import N_
from .. import icons
from .. import qtutils
from . import defs
from . import standard
from .toolbarcmds import COMMANDS
TREE_LAYOUT = {
'Others': ['Others::LaunchEditor', 'Others::RevertUnstagedEdits'],
'File': [
'File::QuickOpen',
'File::NewRepo',
'File::OpenRepo',
'File::OpenRepoNewWindow',
'File::Refresh',
'File::EditRemotes',
'File::RecentModified',
'File::SaveAsTarZip',
'File::ApplyPatches',
'File::ExportPatches',
],
'Actions': [
'Actions::Fetch',
'Actions::Pull',
'Actions::Push',
'Actions::Stash',
'Actions::CreateTag',
'Actions::CherryPick',
'Actions::Merge',
'Actions::AbortMerge',
'Actions::UpdateSubmodules',
'Actions::Grep',
'Actions::Search',
],
'Commit@@verb': [
'Commit::Stage',
'Commit::AmendLast',
'Commit::UndoLastCommit',
'Commit::StageModified',
'Commit::StageUntracked',
'Commit::UnstageAll',
'Commit::Unstage',
'Commit::LoadCommitMessage',
'Commit::GetCommitMessageTemplate',
],
'Diff': ['Diff::Difftool', 'Diff::Expression', 'Diff::Branches', 'Diff::Diffstat'],
'Branch': [
'Branch::Review',
'Branch::Create',
'Branch::Checkout',
'Branch::Delete',
'Branch::DeleteRemote',
'Branch::Rename',
'Branch::BrowseCurrent',
'Branch::BrowseOther',
'Branch::VisualizeCurrent',
'Branch::VisualizeAll',
],
'Reset': [
'Commit::UndoLastCommit',
'Commit::UnstageAll',
'Actions::ResetSoft',
'Actions::ResetMixed',
'Actions::RestoreWorktree',
'Actions::ResetKeep',
'Actions::ResetHard',
],
'View': ['View::DAG', 'View::FileBrowser'],
}
# Backwards-compatibility: Commit::StageUntracked was previously
# exposed as Commit::StageUntracked.
RENAMED = {
'Commit::StageAll': 'Commit::StageUntracked',
}
def configure(toolbar, parent=None):
"""Launches the Toolbar configure dialog"""
if not parent:
parent = qtutils.active_window()
view = ToolbarView(toolbar, parent)
view.show()
return view
def get_toolbars(widget):
return widget.findChildren(ToolBar)
def add_toolbar(context, widget):
toolbars = get_toolbars(widget)
name = 'ToolBar%d' % (len(toolbars) + 1)
toolbar = ToolBar.create(context, name)
widget.addToolBar(toolbar)
configure(toolbar)
class ToolBarState:
"""export_state() and apply_state() providers for toolbars"""
def __init__(self, context, widget):
"""widget must be a QMainWindow for toolBarArea(), etc."""
self.context = context
self.widget = widget
def apply_state(self, toolbars):
context = self.context
widget = self.widget
for data in toolbars:
toolbar = ToolBar.create(context, data['name'])
toolbar.load_items(data['items'])
try:
toolbar.set_toolbar_style(data['toolbar_style'])
except KeyError:
# Maintain compatibility for toolbars created in git-cola <= 3.11.0
if data['show_icons']:
data['toolbar_style'] = ToolBar.STYLE_FOLLOW_SYSTEM
toolbar.set_toolbar_style(ToolBar.STYLE_FOLLOW_SYSTEM)
else:
data['toolbar_style'] = ToolBar.STYLE_TEXT_ONLY
toolbar.set_toolbar_style(ToolBar.STYLE_TEXT_ONLY)
toolbar.setVisible(data['visible'])
toolbar_area = decode_toolbar_area(data['area'])
if data['break']:
widget.addToolBarBreak(toolbar_area)
widget.addToolBar(toolbar_area, toolbar)
# floating toolbars must be set after added
if data['float']:
toolbar.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint)
toolbar.move(data['x'], data['y'])
def export_state(self):
result = []
widget = self.widget
toolbars = widget.findChildren(ToolBar)
for toolbar in toolbars:
toolbar_area = widget.toolBarArea(toolbar)
if toolbar_area == Qt.NoToolBarArea:
continue # filter out removed toolbars
items = [x.data() for x in toolbar.actions()]
# show_icons is for backwards compatibility with git-cola <= 3.11.0
show_icons = toolbar.toolbar_style() != ToolBar.STYLE_TEXT_ONLY
result.append({
'name': toolbar.windowTitle(),
'area': encode_toolbar_area(toolbar_area),
'break': widget.toolBarBreak(toolbar),
'float': toolbar.isFloating(),
'x': toolbar.pos().x(),
'y': toolbar.pos().y(),
'width': toolbar.width(),
'height': toolbar.height(),
'show_icons': show_icons,
'toolbar_style': toolbar.toolbar_style(),
'visible': toolbar.isVisible(),
'items': items,
})
return result
class ToolBar(QtWidgets.QToolBar):
SEPARATOR = 'Separator'
STYLE_FOLLOW_SYSTEM = 'follow-system'
STYLE_ICON_ONLY = 'icon'
STYLE_TEXT_ONLY = 'text'
STYLE_TEXT_BESIDE_ICON = 'text-beside-icon'
STYLE_TEXT_UNDER_ICON = 'text-under-icon'
STYLE_NAMES = [
N_('Follow System Style'),
N_('Icon Only'),
N_('Text Only'),
N_('Text Beside Icon'),
N_('Text Under Icon'),
]
STYLE_SYMBOLS = [
STYLE_FOLLOW_SYSTEM,
STYLE_ICON_ONLY,
STYLE_TEXT_ONLY,
STYLE_TEXT_BESIDE_ICON,
STYLE_TEXT_UNDER_ICON,
]
@staticmethod
def create(context, name):
return ToolBar(context, name, TREE_LAYOUT, COMMANDS)
def __init__(self, context, title, tree_layout, toolbar_commands):
QtWidgets.QToolBar.__init__(self)
self.setWindowTitle(title)
self.setObjectName(title)
self.setToolButtonStyle(Qt.ToolButtonFollowStyle)
self.context = context
self.tree_layout = tree_layout
self.commands = toolbar_commands
def set_toolbar_style(self, style_id):
style_to_qt = {
self.STYLE_FOLLOW_SYSTEM: Qt.ToolButtonFollowStyle,
self.STYLE_ICON_ONLY: Qt.ToolButtonIconOnly,
self.STYLE_TEXT_ONLY: Qt.ToolButtonTextOnly,
self.STYLE_TEXT_BESIDE_ICON: Qt.ToolButtonTextBesideIcon,
self.STYLE_TEXT_UNDER_ICON: Qt.ToolButtonTextUnderIcon,
}
default = Qt.ToolButtonFollowStyle
return self.setToolButtonStyle(style_to_qt.get(style_id, default))
def toolbar_style(self):
qt_to_style = {
Qt.ToolButtonFollowStyle: self.STYLE_FOLLOW_SYSTEM,
Qt.ToolButtonIconOnly: self.STYLE_ICON_ONLY,
Qt.ToolButtonTextOnly: self.STYLE_TEXT_ONLY,
Qt.ToolButtonTextBesideIcon: self.STYLE_TEXT_BESIDE_ICON,
Qt.ToolButtonTextUnderIcon: self.STYLE_TEXT_UNDER_ICON,
}
default = self.STYLE_FOLLOW_SYSTEM
return qt_to_style.get(self.toolButtonStyle(), default)
def load_items(self, items):
for data in items:
self.add_action_from_data(data)
def add_action_from_data(self, data):
parent = data['parent']
child = data['child']
child = RENAMED.get(child, child)
if child == self.SEPARATOR:
toolbar_action = self.addSeparator()
toolbar_action.setData(data)
return
tree_items = self.tree_layout.get(parent, [])
if child in tree_items and child in self.commands:
command = self.commands[child]
title = N_(command['title'])
callback = partial(command['action'], self.context)
tooltip = command.get('tooltip', None)
icon = None
command_icon = command.get('icon', None)
if command_icon:
icon = getattr(icons, command_icon, None)
if callable(icon):
icon = icon()
if icon:
toolbar_action = self.addAction(icon, title, callback)
else:
toolbar_action = self.addAction(title, callback)
toolbar_action.setData(data)
tooltip = command.get('tooltip', None)
if tooltip:
toolbar_action.setToolTip(f'{title}\n{tooltip}')
def delete_toolbar(self):
self.parent().removeToolBar(self)
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu()
tool_config = menu.addAction(N_('Configure Toolbar'), partial(configure, self))
tool_config.setIcon(icons.configure())
tool_delete = menu.addAction(N_('Delete Toolbar'), self.delete_toolbar)
tool_delete.setIcon(icons.remove())
menu.exec_(event.globalPos())
def encode_toolbar_area(toolbar_area):
"""Encode a Qt::ToolBarArea as a string"""
default = 'bottom'
return {
Qt.LeftToolBarArea: 'left',
Qt.RightToolBarArea: 'right',
Qt.TopToolBarArea: 'top',
Qt.BottomToolBarArea: 'bottom',
}.get(toolbar_area, default)
def decode_toolbar_area(string):
"""Decode an encoded toolbar area string into a Qt::ToolBarArea"""
default = Qt.BottomToolBarArea
return {
'left': Qt.LeftToolBarArea,
'right': Qt.RightToolBarArea,
'top': Qt.TopToolBarArea,
'bottom': Qt.BottomToolBarArea,
}.get(string, default)
class ToolbarView(standard.Dialog):
"""Provides the git-cola 'ToolBar' configure dialog"""
SEPARATOR_TEXT = '----------------------------'
def __init__(self, toolbar, parent=None):
standard.Dialog.__init__(self, parent)
self.setWindowTitle(N_('Configure Toolbar'))
self.toolbar = toolbar
self.left_list = ToolbarTreeWidget(self)
self.right_list = DraggableListWidget(self)
self.text_toolbar_name = QtWidgets.QLabel()
self.text_toolbar_name.setText(N_('Name'))
self.toolbar_name = QtWidgets.QLineEdit()
self.toolbar_name.setText(toolbar.windowTitle())
self.add_separator = qtutils.create_button(N_('Add Separator'))
self.remove_item = qtutils.create_button(N_('Remove Element'))
self.toolbar_style_label = QtWidgets.QLabel(N_('Toolbar Style:'))
self.toolbar_style = QtWidgets.QComboBox()
for style_name in ToolBar.STYLE_NAMES:
self.toolbar_style.addItem(style_name)
style_idx = get_index_from_style(toolbar.toolbar_style())
self.toolbar_style.setCurrentIndex(style_idx)
self.apply_button = qtutils.ok_button(N_('Apply'))
self.close_button = qtutils.close_button()
self.close_button.setDefault(True)
self.right_actions = qtutils.hbox(
defs.no_margin, defs.spacing, self.add_separator, self.remove_item
)
self.name_layout = qtutils.hbox(
defs.no_margin, defs.spacing, self.text_toolbar_name, self.toolbar_name
)
self.left_layout = qtutils.vbox(defs.no_margin, defs.spacing, self.left_list)
self.right_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.right_list, self.right_actions
)
self.top_layout = qtutils.hbox(
defs.no_margin, defs.spacing, self.left_layout, self.right_layout
)
self.actions_layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.toolbar_style_label,
self.toolbar_style,
qtutils.STRETCH,
self.close_button,
self.apply_button,
)
self.main_layout = qtutils.vbox(
defs.margin,
defs.spacing,
self.name_layout,
self.top_layout,
self.actions_layout,
)
self.setLayout(self.main_layout)
qtutils.connect_button(self.add_separator, self.add_separator_action)
qtutils.connect_button(self.remove_item, self.remove_item_action)
qtutils.connect_button(self.apply_button, self.apply_action)
qtutils.connect_button(self.close_button, self.accept)
self.load_right_items()
self.load_left_items()
self.init_size(parent=parent)
def load_right_items(self):
commands = self.toolbar.commands
for action in self.toolbar.actions():
data = action.data()
try:
command_name = data['child']
except KeyError:
continue
command_name = RENAMED.get(command_name, command_name)
if command_name == self.toolbar.SEPARATOR:
self.add_separator_action()
continue
try:
command = commands[command_name]
except KeyError:
continue
title = command['title']
icon = command.get('icon', None)
tooltip = command.get('tooltip', None)
self.right_list.add_item(title, tooltip, data, icon)
def load_left_items(self):
commands = self.toolbar.commands
for parent in self.toolbar.tree_layout:
top = self.left_list.insert_top(parent)
for item in self.toolbar.tree_layout[parent]:
item = RENAMED.get(item, item)
try:
command = commands[item]
except KeyError:
continue
icon = command.get('icon', None)
tooltip = command.get('tooltip', None)
child = create_child(parent, item, command['title'], tooltip, icon)
top.appendRow(child)
top.sortChildren(0, Qt.AscendingOrder)
def add_separator_action(self):
data = {'parent': None, 'child': self.toolbar.SEPARATOR}
self.right_list.add_separator(self.SEPARATOR_TEXT, data)
def remove_item_action(self):
items = self.right_list.selectedItems()
for item in items:
self.right_list.takeItem(self.right_list.row(item))
def apply_action(self):
self.toolbar.clear()
style = get_style_from_index(self.toolbar_style.currentIndex())
self.toolbar.set_toolbar_style(style)
self.toolbar.setWindowTitle(self.toolbar_name.text())
for item in self.right_list.get_items():
data = item.data(Qt.UserRole)
self.toolbar.add_action_from_data(data)
def get_style_from_index(index):
"""Return the symbolic toolbar style name for the given (combobox) index"""
return ToolBar.STYLE_SYMBOLS[index]
def get_index_from_style(style):
"""Return the toolbar style (combobox) index for the symbolic name"""
return ToolBar.STYLE_SYMBOLS.index(style)
class DraggableListMixin:
items = []
def __init__(self, widget, Base):
self.widget = widget
self.Base = Base
widget.setAcceptDrops(True)
widget.setSelectionMode(widget.SingleSelection)
widget.setDragEnabled(True)
widget.setDropIndicatorShown(True)
def dragEnterEvent(self, event):
widget = self.widget
self.Base.dragEnterEvent(widget, event)
def dragMoveEvent(self, event):
widget = self.widget
self.Base.dragMoveEvent(widget, event)
def dragLeaveEvent(self, event):
widget = self.widget
self.Base.dragLeaveEvent(widget, event)
def dropEvent(self, event):
widget = self.widget
event.setDropAction(Qt.MoveAction)
self.Base.dropEvent(widget, event)
def get_items(self):
widget = self.widget
base = self.Base
items = [base.item(widget, i) for i in range(base.count(widget))]
return items
class DraggableListWidget(QtWidgets.QListWidget):
Mixin = DraggableListMixin
def __init__(self, parent=None):
QtWidgets.QListWidget.__init__(self, parent)
self.setAcceptDrops(True)
self.setSelectionMode(self.SingleSelection)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self._mixin = self.Mixin(self, QtWidgets.QListWidget)
def dragEnterEvent(self, event):
return self._mixin.dragEnterEvent(event)
def dragMoveEvent(self, event):
return self._mixin.dragMoveEvent(event)
def dropEvent(self, event):
return self._mixin.dropEvent(event)
def add_separator(self, title, data):
item = QtWidgets.QListWidgetItem()
item.setText(title)
item.setData(Qt.UserRole, data)
self.addItem(item)
def add_item(self, title, tooltip, data, icon):
item = QtWidgets.QListWidgetItem()
item.setText(N_(title))
item.setData(Qt.UserRole, data)
if tooltip:
item.setToolTip(tooltip)
if icon:
icon_func = getattr(icons, icon)
item.setIcon(icon_func())
self.addItem(item)
def get_items(self):
return self._mixin.get_items()
class ToolbarTreeWidget(standard.TreeView):
def __init__(self, parent):
standard.TreeView.__init__(self, parent)
self.setDragEnabled(True)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setDropIndicatorShown(True)
self.setRootIsDecorated(True)
self.setHeaderHidden(True)
self.setAlternatingRowColors(False)
self.setSortingEnabled(False)
self.setModel(QtGui.QStandardItemModel())
def insert_top(self, title):
item = create_item(title, title)
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
self.model().insertRow(0, item)
self.model().sort(0)
return item
def create_child(parent, child, title, tooltip, icon):
data = {'parent': parent, 'child': child}
item = create_item(title, data)
if tooltip:
item.setToolTip(tooltip)
if icon:
icon_func = getattr(icons, icon, None)
item.setIcon(icon_func())
return item
def create_item(name, data):
item = QtGui.QStandardItem()
item.setEditable(False)
item.setDragEnabled(True)
item.setText(N_(name))
item.setData(data, Qt.UserRole)
return item
| 18,550 | Python | .py | 469 | 30.17484 | 87 | 0.617964 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
93 | status.py | git-cola_git-cola/cola/widgets/status.py | import itertools
import os
from functools import partial
from qtpy.QtCore import Qt
from qtpy import QtCore
from qtpy import QtWidgets
from ..i18n import N_
from ..models import prefs
from ..models import selection
from ..widgets import gitignore
from ..widgets import standard
from ..qtutils import get
from ..settings import Settings
from .. import actions
from .. import cmds
from .. import core
from .. import difftool
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import utils
from . import common
from . import completion
from . import defs
from . import text
# Top-level status widget item indexes.
HEADER_IDX = -1
STAGED_IDX = 0
UNMERGED_IDX = 1
MODIFIED_IDX = 2
UNTRACKED_IDX = 3
END_IDX = 4
# Indexes into the saved_selection entries.
NEW_PATHS_IDX = 0
OLD_PATHS_IDX = 1
SELECTION_IDX = 2
SELECT_FN_IDX = 3
class StatusWidget(QtWidgets.QFrame):
"""
Provides a git-status-like repository widget.
This widget observes the main model and broadcasts
Qt signals.
"""
def __init__(self, context, titlebar, parent):
QtWidgets.QFrame.__init__(self, parent)
self.context = context
tooltip = N_('Toggle the paths filter')
icon = icons.ellipsis()
self.filter_button = qtutils.create_action_button(tooltip=tooltip, icon=icon)
self.filter_widget = StatusFilterWidget(context)
self.filter_widget.hide()
self.tree = StatusTreeWidget(context, parent=self)
self.setFocusProxy(self.tree)
tooltip = N_('Exit "Diff" mode')
icon = icons.circle_slash_red()
self.exit_diff_mode_button = qtutils.create_action_button(
tooltip=tooltip, icon=icon, visible=False
)
self.main_layout = qtutils.vbox(
defs.no_margin, defs.no_spacing, self.filter_widget, self.tree
)
self.setLayout(self.main_layout)
self.toggle_action = qtutils.add_action(
self, tooltip, self.toggle_filter, hotkeys.FILTER
)
titlebar.add_corner_widget(self.exit_diff_mode_button)
titlebar.add_corner_widget(self.filter_button)
qtutils.connect_button(self.filter_button, self.toggle_filter)
qtutils.connect_button(
self.exit_diff_mode_button, cmds.run(cmds.ResetMode, self.context)
)
def toggle_filter(self):
"""Toggle the paths filter"""
shown = not self.filter_widget.isVisible()
self.filter_widget.setVisible(shown)
if shown:
self.filter_widget.setFocus()
else:
self.tree.setFocus()
def set_initial_size(self):
"""Set the initial size of the status widget"""
self.setMaximumWidth(222)
QtCore.QTimer.singleShot(1, lambda: self.setMaximumWidth(2**13))
def refresh(self):
"""Refresh the tree and rerun the diff to see updates"""
self.tree.show_selection()
def set_filter(self, txt):
"""Set the filter text"""
self.filter_widget.setVisible(True)
self.filter_widget.text.set_value(txt)
self.filter_widget.apply_filter()
def set_mode(self, mode):
"""React to changes in model's editing mode"""
exit_diff_mode_visible = mode == self.context.model.mode_diff
self.exit_diff_mode_button.setVisible(exit_diff_mode_visible)
def move_up(self):
self.tree.move_up()
def move_down(self):
self.tree.move_down()
def select_header(self):
self.tree.select_header()
class StatusTreeWidget(QtWidgets.QTreeWidget):
# Read-only access to the mode state
mode = property(lambda self: self._model.mode)
def __init__(self, context, parent=None):
QtWidgets.QTreeWidget.__init__(self, parent)
self.context = context
self.selection_model = context.selection
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.headerItem().setHidden(True)
self.setAllColumnsShowFocus(True)
self.setSortingEnabled(False)
self.setUniformRowHeights(True)
self.setAnimated(True)
self.setRootIsDecorated(False)
self.setAutoScroll(False)
self.setDragEnabled(True)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
self._alt_drag = False
if not prefs.status_indent(context):
self.setIndentation(0)
ok_icon = icons.ok()
compare = icons.compare()
question = icons.question()
self._add_toplevel_item(N_('Staged'), ok_icon, hide=True)
self._add_toplevel_item(N_('Unmerged'), compare, hide=True)
self._add_toplevel_item(N_('Modified'), compare, hide=True)
self._add_toplevel_item(N_('Untracked'), question, hide=True)
# Used to restore the selection
self.old_vscroll = None
self.old_hscroll = None
self.old_selection = None
self.old_contents = None
self.old_current_item = None
self.previous_contents = None
self.was_visible = True
self.expanded_items = set()
self.image_formats = qtutils.ImageFormats()
self.process_selection_action = qtutils.add_action(
self,
cmds.StageOrUnstage.name(),
self._stage_selection,
hotkeys.STAGE_SELECTION,
)
self.process_selection_action.setIcon(icons.add())
self.stage_or_unstage_all_action = qtutils.add_action(
self,
cmds.StageOrUnstageAll.name(),
cmds.run(cmds.StageOrUnstageAll, self.context),
hotkeys.STAGE_ALL,
)
self.stage_or_unstage_all_action.setIcon(icons.add())
self.revert_unstaged_edits_action = qtutils.add_action(
self,
cmds.RevertUnstagedEdits.name(),
cmds.run(cmds.RevertUnstagedEdits, context),
hotkeys.REVERT,
hotkeys.REVERT_ALT,
)
self.revert_unstaged_edits_action.setIcon(icons.undo())
self.launch_difftool_action = qtutils.add_action(
self,
difftool.LaunchDifftool.name(),
cmds.run(difftool.LaunchDifftool, context),
hotkeys.DIFF,
)
self.launch_difftool_action.setIcon(icons.diff())
self.launch_editor_action = actions.launch_editor_at_line(
context, self, *hotkeys.ACCEPT
)
self.default_app_action = common.default_app_action(
context, self, self.selected_group
)
self.parent_dir_action = common.parent_dir_action(
context, self, self.selected_group
)
self.worktree_dir_action = common.worktree_dir_action(context, self)
self.terminal_action = common.terminal_action(
context, self, func=self.selected_group
)
self.up_action = qtutils.add_action(
self,
N_('Move Up'),
self.move_up,
hotkeys.MOVE_UP,
hotkeys.MOVE_UP_SECONDARY,
)
self.down_action = qtutils.add_action(
self,
N_('Move Down'),
self.move_down,
hotkeys.MOVE_DOWN,
hotkeys.MOVE_DOWN_SECONDARY,
)
# Checkout the selected paths using "git checkout --ours".
self.checkout_ours_action = qtutils.add_action(
self, cmds.CheckoutOurs.name(), cmds.run(cmds.CheckoutOurs, context)
)
# Checkout the selected paths using "git checkout --theirs".
self.checkout_theirs_action = qtutils.add_action(
self, cmds.CheckoutTheirs.name(), cmds.run(cmds.CheckoutTheirs, context)
)
self.copy_path_action = qtutils.add_action(
self,
N_('Copy Path to Clipboard'),
partial(copy_path, context),
hotkeys.COPY,
)
self.copy_path_action.setIcon(icons.copy())
self.copy_relpath_action = qtutils.add_action(
self,
N_('Copy Relative Path to Clipboard'),
partial(copy_relpath, context),
hotkeys.CUT,
)
self.copy_relpath_action.setIcon(icons.copy())
self.copy_leading_paths_value = 1
self.copy_basename_action = qtutils.add_action(
self, N_('Copy Basename to Clipboard'), partial(copy_basename, context)
)
self.copy_basename_action.setIcon(icons.copy())
self.copy_customize_action = qtutils.add_action(
self, N_('Customize...'), partial(customize_copy_actions, context, self)
)
self.copy_customize_action.setIcon(icons.configure())
self.view_history_action = qtutils.add_action(
self, N_('View History...'), partial(view_history, context), hotkeys.HISTORY
)
self.view_blame_action = qtutils.add_action(
self, N_('Blame...'), partial(view_blame, context), hotkeys.BLAME
)
self.annex_add_action = qtutils.add_action(
self, N_('Add to Git Annex'), cmds.run(cmds.AnnexAdd, context)
)
self.lfs_track_action = qtutils.add_action(
self, N_('Add to Git LFS'), cmds.run(cmds.LFSTrack, context)
)
# MoveToTrash and Delete use the same shortcut.
# We will only bind one of them, depending on whether or not the
# MoveToTrash command is available. When available, the hotkey
# is bound to MoveToTrash, otherwise it is bound to Delete.
if cmds.MoveToTrash.AVAILABLE:
self.move_to_trash_action = qtutils.add_action(
self,
N_('Move files to trash'),
self._trash_untracked_files,
hotkeys.TRASH,
)
self.move_to_trash_action.setIcon(icons.discard())
delete_shortcut = hotkeys.DELETE_FILE
else:
self.move_to_trash_action = None
delete_shortcut = hotkeys.DELETE_FILE_SECONDARY
self.delete_untracked_files_action = qtutils.add_action(
self, N_('Delete Files...'), self._delete_untracked_files, delete_shortcut
)
self.delete_untracked_files_action.setIcon(icons.discard())
# The model is stored as self._model because self.model() is a
# QTreeWidgetItem method that returns a QAbstractItemModel.
self._model = context.model
self._model.previous_contents.connect(
self._set_previous_contents, type=Qt.QueuedConnection
)
self._model.about_to_update.connect(
self._about_to_update, type=Qt.QueuedConnection
)
self._model.updated.connect(self.refresh, type=Qt.QueuedConnection)
self._model.diff_text_changed.connect(
self._make_current_item_visible, type=Qt.QueuedConnection
)
self.itemSelectionChanged.connect(self.show_selection)
self.itemDoubleClicked.connect(cmds.run(cmds.StageOrUnstage, self.context))
self.itemCollapsed.connect(lambda x: self._update_column_widths())
self.itemExpanded.connect(lambda x: self._update_column_widths())
def _make_current_item_visible(self):
item = self.currentItem()
if item:
qtutils.scroll_to_item(self, item)
def _add_toplevel_item(self, txt, icon, hide=False):
context = self.context
font = self.font()
if prefs.bold_headers(context):
font.setBold(True)
else:
font.setItalic(True)
item = QtWidgets.QTreeWidgetItem(self)
item.setFont(0, font)
item.setText(0, txt)
item.setIcon(0, icon)
if prefs.bold_headers(context):
item.setBackground(0, self.palette().midlight())
if hide:
item.setHidden(True)
def _restore_selection(self):
"""Apply the old selection to the newly updated items"""
# This function is called after a new set of items have been added to
# the per-category file lists. Its purpose is to either restore the
# existing selection or to create a new intuitive selection based on
# a combination of the old items, the old selection and the new items.
if not self.old_selection or not self.old_contents:
return
# The old set of categorized files.
old_c = self.old_contents
# The old selection.
old_s = self.old_selection
# The current/new set of categorized files.
new_c = self.contents()
select_staged = partial(_select_item, self, new_c.staged, self._staged_item)
select_unmerged = partial(
_select_item, self, new_c.unmerged, self._unmerged_item
)
select_modified = partial(
_select_item, self, new_c.modified, self._modified_item
)
select_untracked = partial(
_select_item, self, new_c.untracked, self._untracked_item
)
saved_selection = [
(set(new_c.staged), old_c.staged, set(old_s.staged), select_staged),
(set(new_c.unmerged), old_c.unmerged, set(old_s.unmerged), select_unmerged),
(set(new_c.modified), old_c.modified, set(old_s.modified), select_modified),
(
set(new_c.untracked),
old_c.untracked,
set(old_s.untracked),
select_untracked,
),
]
# Restore the current item
if self.old_current_item:
category, idx = self.old_current_item
if _apply_toplevel_selection(self, category, idx):
return
# Reselect the current item
selection_info = saved_selection[category]
new = selection_info[NEW_PATHS_IDX]
old = selection_info[OLD_PATHS_IDX]
reselect = selection_info[SELECT_FN_IDX]
try:
item = old[idx]
except IndexError:
item = None
if item and item in new:
reselect(item, current=True)
# Restore previously selected items.
# When reselecting in this section we only care that the items are
# selected; we do not need to rerun the callbacks which were triggered
# above for the current item. Block signals to skip the callbacks.
#
# Reselect items that were previously selected and still exist in the
# current path lists. This handles a common case such as a Ctrl-R
# refresh which results in the same exact path state.
did_reselect = False
with qtutils.BlockSignals(self):
for new, old, sel, reselect in saved_selection:
for item in sel:
if item in new:
reselect(item, current=False)
did_reselect = True
# The status widget is used to interactively work your way down the
# list of Staged, Unmerged, Modified and Untracked items and perform
# an operation on them.
#
# For Staged items we intend to work our way down the list of Staged
# items while we unstage each item. For every other category we work
# our way down the list of {Unmerged,Modified,Untracked} items while
# we stage each item.
#
# The following block of code implements the behavior of selecting
# the next item based on the previous selection.
for new, old, sel, reselect in saved_selection:
# When modified is staged, select the next modified item
# When unmerged is staged, select the next unmerged item
# When unstaging, select the next staged item
# When staging untracked files, select the next untracked item
if len(new) >= len(old):
# The list did not shrink so it is not one of these cases.
continue
for item in sel:
# The item still exists so ignore it
if item in new or item not in old:
continue
# The item no longer exists in this list so search for
# its nearest neighbors and select them instead.
idx = old.index(item)
for j in itertools.chain(old[idx + 1 :], reversed(old[:idx])):
if j in new:
reselect(j, current=True)
return
# If we already reselected stuff then there's nothing more to do.
if did_reselect:
return
# If we got this far then nothing was reselected and made current.
# Try a few more heuristics that we can use to keep something selected.
if self.old_current_item:
category, idx = self.old_current_item
_transplant_selection_across_sections(
category, idx, self.previous_contents, saved_selection
)
def _restore_scrollbars(self):
"""Restore scrollbars to the stored values"""
qtutils.set_scrollbar_values(self, self.old_hscroll, self.old_vscroll)
self.old_hscroll = None
self.old_vscroll = None
def _stage_selection(self):
"""Stage or unstage files according to the selection"""
context = self.context
selected_indexes = self.selected_indexes()
is_header = any(category == HEADER_IDX for (category, idx) in selected_indexes)
if is_header:
is_staged = any(
idx == STAGED_IDX and category == HEADER_IDX
for (category, idx) in selected_indexes
)
is_modified = any(
idx == MODIFIED_IDX and category == HEADER_IDX
for (category, idx) in selected_indexes
)
is_untracked = any(
idx == UNTRACKED_IDX and category == HEADER_IDX
for (category, idx) in selected_indexes
)
# A header item: 'Staged', 'Modified' or 'Untracked'.
if is_staged:
# If we have the staged header selected then the only sensible
# thing to do is to unstage everything and nothing else, even
# if the modified or untracked headers are selected.
cmds.do(cmds.UnstageAll, context)
return # Everything was unstaged. There's nothing more to be done.
if is_modified and is_untracked:
# If both modified and untracked headers are selected then
# stage everything.
cmds.do(cmds.StageModifiedAndUntracked, context)
return # Nothing more to do.
# At this point we may stage all modified and untracked, and then
# possibly a subset of the other category (e.g. all modified and
# some untracked). We don't return here so that StageOrUnstage
# gets a chance to run below.
if is_modified:
cmds.do(cmds.StageModified, context)
elif is_untracked:
cmds.do(cmds.StageUntracked, context)
else:
# Do nothing for unmerged items, by design
pass
# Now handle individual files
cmds.do(cmds.StageOrUnstage, context)
def _staged_item(self, itemidx):
return self._subtree_item(STAGED_IDX, itemidx)
def _modified_item(self, itemidx):
return self._subtree_item(MODIFIED_IDX, itemidx)
def _unmerged_item(self, itemidx):
return self._subtree_item(UNMERGED_IDX, itemidx)
def _untracked_item(self, itemidx):
return self._subtree_item(UNTRACKED_IDX, itemidx)
def _unstaged_item(self, itemidx):
# is it modified?
item = self.topLevelItem(MODIFIED_IDX)
count = item.childCount()
if itemidx < count:
return item.child(itemidx)
# is it unmerged?
item = self.topLevelItem(UNMERGED_IDX)
count += item.childCount()
if itemidx < count:
return item.child(itemidx)
# is it untracked?
item = self.topLevelItem(UNTRACKED_IDX)
count += item.childCount()
if itemidx < count:
return item.child(itemidx)
# Nope..
return None
def _subtree_item(self, idx, itemidx):
parent = self.topLevelItem(idx)
return parent.child(itemidx)
def _set_previous_contents(self, staged, unmerged, modified, untracked):
"""Callback triggered right before the model changes its contents"""
self.previous_contents = selection.State(staged, unmerged, modified, untracked)
def _about_to_update(self):
self._save_scrollbars()
self._save_selection()
def _save_scrollbars(self):
"""Store the scrollbar values for later application"""
hscroll, vscroll = qtutils.get_scrollbar_values(self)
if hscroll is not None:
self.old_hscroll = hscroll
if vscroll is not None:
self.old_vscroll = vscroll
def current_item(self):
s = self.selected_indexes()
if not s:
return None
current = self.currentItem()
if not current:
return None
idx = self.indexFromItem(current)
if idx.parent().isValid():
parent_idx = idx.parent()
entry = (parent_idx.row(), idx.row())
else:
entry = (HEADER_IDX, idx.row())
return entry
def _save_selection(self):
self.old_contents = self.contents()
self.old_selection = self.selection()
self.old_current_item = self.current_item()
def refresh(self):
self._set_staged(self._model.staged)
self._set_modified(self._model.modified)
self._set_unmerged(self._model.unmerged)
self._set_untracked(self._model.untracked)
self._update_column_widths()
self._update_actions()
self._restore_selection()
self._restore_scrollbars()
def _update_actions(self, selected=None):
if selected is None:
selected = self.selection_model.selection()
can_revert_edits = bool(selected.staged or selected.modified)
self.revert_unstaged_edits_action.setEnabled(can_revert_edits)
enabled = self.selection_model.filename() is not None
self.default_app_action.setEnabled(enabled)
self.parent_dir_action.setEnabled(enabled)
self.copy_path_action.setEnabled(enabled)
self.copy_relpath_action.setEnabled(enabled)
self.copy_basename_action.setEnabled(enabled)
def _set_staged(self, items):
"""Adds items to the 'Staged' sub-tree."""
with qtutils.BlockSignals(self):
self._set_subtree(
items,
STAGED_IDX,
N_('Staged'),
staged=True,
deleted_set=self._model.staged_deleted,
)
def _set_modified(self, items):
"""Adds items to the 'Modified' sub-tree."""
with qtutils.BlockSignals(self):
self._set_subtree(
items,
MODIFIED_IDX,
N_('Modified'),
deleted_set=self._model.unstaged_deleted,
)
def _set_unmerged(self, items):
"""Adds items to the 'Unmerged' sub-tree."""
deleted_set = {path for path in items if not core.exists(path)}
with qtutils.BlockSignals(self):
self._set_subtree(
items, UNMERGED_IDX, N_('Unmerged'), deleted_set=deleted_set
)
def _set_untracked(self, items):
"""Adds items to the 'Untracked' sub-tree."""
with qtutils.BlockSignals(self):
self._set_subtree(items, UNTRACKED_IDX, N_('Untracked'), untracked=True)
def _set_subtree(
self, items, idx, parent_title, staged=False, untracked=False, deleted_set=None
):
"""Add a list of items to a treewidget item."""
parent = self.topLevelItem(idx)
hide = not bool(items)
parent.setHidden(hide)
# sip v4.14.7 and below leak memory in parent.takeChildren()
# so we use this backwards-compatible construct instead
while parent.takeChild(0) is not None:
pass
for item in items:
deleted = deleted_set is not None and item in deleted_set
treeitem = qtutils.create_treeitem(
item, staged=staged, deleted=deleted, untracked=untracked
)
parent.addChild(treeitem)
self._expand_items(idx, items)
if prefs.status_show_totals(self.context):
parent.setText(0, f'{parent_title} ({len(items)})')
def _update_column_widths(self):
self.resizeColumnToContents(0)
def _expand_items(self, idx, items):
"""Expand the top-level category "folder" once and only once."""
# Don't do this if items is empty; this makes it so that we
# don't add the top-level index into the expanded_items set
# until an item appears in a particular category.
if not items:
return
# Only run this once; we don't want to re-expand items that
# we've clicked on to re-collapse on updated().
if idx in self.expanded_items:
return
self.expanded_items.add(idx)
item = self.topLevelItem(idx)
if item:
self.expandItem(item)
def contextMenuEvent(self, event):
"""Create context menus for the repo status tree."""
menu = self._create_context_menu()
menu.exec_(self.mapToGlobal(event.pos()))
def _create_context_menu(self):
"""Set up the status menu for the repo status tree."""
sel = self.selection()
menu = qtutils.create_menu('Status', self)
selected_indexes = self.selected_indexes()
if selected_indexes:
category, idx = selected_indexes[0]
# A header item e.g. 'Staged', 'Modified', etc.
if category == HEADER_IDX:
return self._create_header_context_menu(menu, idx)
if sel.staged:
self._create_staged_context_menu(menu, sel)
elif sel.unmerged:
self._create_unmerged_context_menu(menu, sel)
else:
self._create_unstaged_context_menu(menu, sel)
if not menu.isEmpty():
menu.addSeparator()
if not self.selection_model.is_empty():
menu.addAction(self.default_app_action)
menu.addAction(self.parent_dir_action)
if self.terminal_action is not None:
menu.addAction(self.terminal_action)
menu.addAction(self.worktree_dir_action)
self._add_copy_actions(menu)
return menu
def _add_copy_actions(self, menu):
"""Add the "Copy" sub-menu"""
enabled = self.selection_model.filename() is not None
self.copy_path_action.setEnabled(enabled)
self.copy_relpath_action.setEnabled(enabled)
self.copy_basename_action.setEnabled(enabled)
copy_menu = QtWidgets.QMenu(N_('Copy...'), menu)
copy_icon = icons.copy()
copy_menu.setIcon(copy_icon)
copy_leading_path_action = QtWidgets.QWidgetAction(copy_menu)
copy_leading_path_action.setEnabled(enabled)
widget = CopyLeadingPathWidget(
N_('Copy Leading Path to Clipboard'), self.context, copy_menu
)
# Store the value of the leading paths spin-box so that the value does not reset
# every time the menu is shown and recreated.
widget.set_value(self.copy_leading_paths_value)
widget.spinbox.valueChanged.connect(
partial(setattr, self, 'copy_leading_paths_value')
)
copy_leading_path_action.setDefaultWidget(widget)
# Copy the leading path when the action is activated.
qtutils.connect_action(
copy_leading_path_action,
lambda widget=widget: copy_leading_path(context, widget.value()),
)
menu.addSeparator()
menu.addMenu(copy_menu)
copy_menu.addAction(self.copy_path_action)
copy_menu.addAction(self.copy_relpath_action)
copy_menu.addAction(copy_leading_path_action)
copy_menu.addAction(self.copy_basename_action)
settings = Settings.read()
copy_formats = settings.copy_formats
if copy_formats:
copy_menu.addSeparator()
context = self.context
for entry in copy_formats:
name = entry.get('name', '')
fmt = entry.get('format', '')
if name and fmt:
action = copy_menu.addAction(name, partial(copy_format, context, fmt))
action.setIcon(copy_icon)
action.setEnabled(enabled)
copy_menu.addSeparator()
copy_menu.addAction(self.copy_customize_action)
def _create_header_context_menu(self, menu, idx):
context = self.context
if idx == STAGED_IDX:
menu.addAction(
icons.remove(), N_('Unstage All'), cmds.run(cmds.UnstageAll, context)
)
elif idx == UNMERGED_IDX:
action = menu.addAction(
icons.add(),
cmds.StageUnmerged.name(),
cmds.run(cmds.StageUnmerged, context),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
elif idx == MODIFIED_IDX:
action = menu.addAction(
icons.add(),
cmds.StageModified.name(),
cmds.run(cmds.StageModified, context),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
elif idx == UNTRACKED_IDX:
action = menu.addAction(
icons.add(),
cmds.StageUntracked.name(),
cmds.run(cmds.StageUntracked, context),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
return menu
def _create_staged_context_menu(self, menu, s):
if s.staged[0] in self._model.submodules:
return self._create_staged_submodule_context_menu(menu, s)
context = self.context
if self._model.is_unstageable():
action = menu.addAction(
icons.remove(),
N_('Unstage Selected'),
cmds.run(cmds.Unstage, context, self.staged()),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
menu.addAction(self.launch_editor_action)
# Do all of the selected items exist?
all_exist = all(
i not in self._model.staged_deleted and core.exists(i)
for i in self.staged()
)
if all_exist:
menu.addAction(self.launch_difftool_action)
if self._model.is_undoable():
menu.addAction(self.revert_unstaged_edits_action)
menu.addAction(self.view_history_action)
menu.addAction(self.view_blame_action)
return menu
def _create_staged_submodule_context_menu(self, menu, s):
context = self.context
path = core.abspath(s.staged[0])
if len(self.staged()) == 1:
menu.addAction(
icons.cola(),
N_('Launch git-cola'),
cmds.run(cmds.OpenRepo, context, path),
)
menu.addSeparator()
action = menu.addAction(
icons.remove(),
N_('Unstage Selected'),
cmds.run(cmds.Unstage, context, self.staged()),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
menu.addAction(self.view_history_action)
return menu
def _create_unmerged_context_menu(self, menu, _s):
context = self.context
menu.addAction(self.launch_difftool_action)
action = menu.addAction(
icons.add(),
N_('Stage Selected'),
cmds.run(cmds.Stage, context, self.unstaged()),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
menu.addAction(
icons.remove(),
N_('Unstage Selected'),
cmds.run(cmds.Unstage, context, self.unstaged()),
)
menu.addAction(self.launch_editor_action)
menu.addAction(self.view_history_action)
menu.addAction(self.view_blame_action)
menu.addSeparator()
menu.addAction(self.checkout_ours_action)
menu.addAction(self.checkout_theirs_action)
return menu
def _create_unstaged_context_menu(self, menu, s):
context = self.context
modified_submodule = s.modified and s.modified[0] in self._model.submodules
if modified_submodule:
return self._create_modified_submodule_context_menu(menu, s)
if self._model.is_stageable():
action = menu.addAction(
icons.add(),
N_('Stage Selected'),
cmds.run(cmds.Stage, context, self.unstaged()),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
if not self.selection_model.is_empty():
menu.addAction(self.launch_editor_action)
# Do all of the selected items exist?
all_exist = all(
i not in self._model.unstaged_deleted and core.exists(i)
for i in self.staged()
)
if all_exist and s.modified and self._model.is_stageable():
menu.addAction(self.launch_difftool_action)
if s.modified and self._model.is_stageable() and self._model.is_undoable():
menu.addSeparator()
menu.addAction(self.revert_unstaged_edits_action)
if all_exist and s.untracked:
# Git Annex / Git LFS
annex = self._model.annex
lfs = core.find_executable('git-lfs')
if annex or lfs:
menu.addSeparator()
if annex:
menu.addAction(self.annex_add_action)
if lfs:
menu.addAction(self.lfs_track_action)
menu.addSeparator()
if self.move_to_trash_action is not None:
menu.addAction(self.move_to_trash_action)
menu.addAction(self.delete_untracked_files_action)
menu.addSeparator()
menu.addAction(
icons.edit(),
N_('Ignore...'),
partial(gitignore.gitignore_view, self.context),
)
if not self.selection_model.is_empty():
menu.addAction(self.view_history_action)
menu.addAction(self.view_blame_action)
return menu
def _create_modified_submodule_context_menu(self, menu, s):
context = self.context
path = core.abspath(s.modified[0])
if len(self.unstaged()) == 1:
menu.addAction(
icons.cola(),
N_('Launch git-cola'),
cmds.run(cmds.OpenRepo, context, path),
)
menu.addAction(
icons.pull(),
N_('Update this submodule'),
cmds.run(cmds.SubmoduleUpdate, context, path),
)
menu.addSeparator()
if self._model.is_stageable():
menu.addSeparator()
action = menu.addAction(
icons.add(),
N_('Stage Selected'),
cmds.run(cmds.Stage, context, self.unstaged()),
)
action.setShortcut(hotkeys.STAGE_SELECTION)
menu.addAction(self.view_history_action)
return menu
def _delete_untracked_files(self):
cmds.do(cmds.Delete, self.context, self.untracked())
def _trash_untracked_files(self):
cmds.do(cmds.MoveToTrash, self.context, self.untracked())
def selected_path(self):
s = self.single_selection()
return s.staged or s.unmerged or s.modified or s.untracked or None
def single_selection(self):
"""Scan across staged, modified, etc. and return a single item."""
staged = None
unmerged = None
modified = None
untracked = None
s = self.selection()
if s.staged:
staged = s.staged[0]
elif s.unmerged:
unmerged = s.unmerged[0]
elif s.modified:
modified = s.modified[0]
elif s.untracked:
untracked = s.untracked[0]
return selection.State(staged, unmerged, modified, untracked)
def selected_indexes(self):
"""Returns a list of (category, row) representing the tree selection."""
selected = self.selectedIndexes()
result = []
for idx in selected:
if idx.parent().isValid():
parent_idx = idx.parent()
entry = (parent_idx.row(), idx.row())
else:
entry = (HEADER_IDX, idx.row())
result.append(entry)
return result
def selection(self):
"""Return the current selection in the repo status tree."""
return selection.State(
self.staged(), self.unmerged(), self.modified(), self.untracked()
)
def contents(self):
"""Return all of the current files in a selection.State container"""
return selection.State(
self._model.staged,
self._model.unmerged,
self._model.modified,
self._model.untracked,
)
def all_files(self):
"""Return all of the current active files as a flat list"""
c = self.contents()
return c.staged + c.unmerged + c.modified + c.untracked
def selected_group(self):
"""A list of selected files in various states of being"""
return selection.pick(self.selection())
def selected_idx(self):
c = self.contents()
s = self.single_selection()
offset = 0
for content, sel in zip(c, s):
if not content:
continue
if sel is not None:
return offset + content.index(sel)
offset += len(content)
return None
def select_by_index(self, idx):
c = self.contents()
to_try = [
(c.staged, STAGED_IDX),
(c.unmerged, UNMERGED_IDX),
(c.modified, MODIFIED_IDX),
(c.untracked, UNTRACKED_IDX),
]
for content, toplevel_idx in to_try:
if not content:
continue
if idx < len(content):
parent = self.topLevelItem(toplevel_idx)
item = parent.child(idx)
if item is not None:
qtutils.select_item(self, item)
return
idx -= len(content)
def staged(self):
return qtutils.get_selected_values(self, STAGED_IDX, self._model.staged)
def unstaged(self):
return self.unmerged() + self.modified() + self.untracked()
def modified(self):
return qtutils.get_selected_values(self, MODIFIED_IDX, self._model.modified)
def unmerged(self):
return qtutils.get_selected_values(self, UNMERGED_IDX, self._model.unmerged)
def untracked(self):
return qtutils.get_selected_values(self, UNTRACKED_IDX, self._model.untracked)
def staged_items(self):
return qtutils.get_selected_items(self, STAGED_IDX)
def unstaged_items(self):
return self.unmerged_items() + self.modified_items() + self.untracked_items()
def modified_items(self):
return qtutils.get_selected_items(self, MODIFIED_IDX)
def unmerged_items(self):
return qtutils.get_selected_items(self, UNMERGED_IDX)
def untracked_items(self):
return qtutils.get_selected_items(self, UNTRACKED_IDX)
def show_selection(self):
"""Show the selected item."""
context = self.context
qtutils.scroll_to_item(self, self.currentItem())
# Sync the selection model
selected = self.selection()
selection_model = self.selection_model
selection_model.set_selection(selected)
self._update_actions(selected=selected)
selected_indexes = self.selected_indexes()
if not selected_indexes:
if self._model.is_amend_mode() or self._model.is_diff_mode():
cmds.do(cmds.SetDiffText, context, '')
else:
cmds.do(cmds.ResetMode, context)
return
# A header item e.g. 'Staged', 'Modified', etc.
category, idx = selected_indexes[0]
header = category == HEADER_IDX
if header:
cls = {
STAGED_IDX: cmds.DiffStagedSummary,
MODIFIED_IDX: cmds.Diffstat,
UNMERGED_IDX: cmds.UnmergedSummary,
UNTRACKED_IDX: cmds.UntrackedSummary,
}.get(idx, cmds.Diffstat)
cmds.do(cls, context)
return
staged = category == STAGED_IDX
modified = category == MODIFIED_IDX
unmerged = category == UNMERGED_IDX
untracked = category == UNTRACKED_IDX
if staged:
item = self.staged_items()[0]
elif unmerged:
item = self.unmerged_items()[0]
elif modified:
item = self.modified_items()[0]
elif untracked:
item = self.unstaged_items()[0]
else:
item = None # this shouldn't happen
assert item is not None
path = item.path
deleted = item.deleted
image = self.image_formats.ok(path)
# Update the diff text
if staged:
cmds.do(cmds.DiffStaged, context, path, deleted=deleted)
elif modified:
cmds.do(cmds.Diff, context, path, deleted=deleted)
elif unmerged:
cmds.do(cmds.Diff, context, path)
elif untracked:
cmds.do(cmds.ShowUntracked, context, path)
# Images are diffed differently.
# DiffImage transitions the diff mode to image.
# DiffText transitions the diff mode to text.
if image:
cmds.do(
cmds.DiffImage,
context,
path,
deleted,
staged,
modified,
unmerged,
untracked,
)
else:
cmds.do(cmds.DiffText, context)
def select_header(self):
"""Select an active header, which triggers a diffstat"""
for idx in (
STAGED_IDX,
UNMERGED_IDX,
MODIFIED_IDX,
UNTRACKED_IDX,
):
item = self.topLevelItem(idx)
if item.childCount() > 0:
self.clearSelection()
self.setCurrentItem(item)
return
def move_up(self):
"""Select the item above the currently selected item"""
idx = self.selected_idx()
all_files = self.all_files()
if idx is None:
selected_indexes = self.selected_indexes()
if selected_indexes:
category, toplevel_idx = selected_indexes[0]
if category == HEADER_IDX:
item = self.itemAbove(self.topLevelItem(toplevel_idx))
if item is not None:
qtutils.select_item(self, item)
return
if all_files:
self.select_by_index(len(all_files) - 1)
return
if idx - 1 >= 0:
self.select_by_index(idx - 1)
else:
self.select_by_index(len(all_files) - 1)
def move_down(self):
"""Select the item below the currently selected item"""
idx = self.selected_idx()
all_files = self.all_files()
if idx is None:
selected_indexes = self.selected_indexes()
if selected_indexes:
category, toplevel_idx = selected_indexes[0]
if category == HEADER_IDX:
item = self.itemBelow(self.topLevelItem(toplevel_idx))
if item is not None:
qtutils.select_item(self, item)
return
if all_files:
self.select_by_index(0)
return
if idx + 1 < len(all_files):
self.select_by_index(idx + 1)
else:
self.select_by_index(0)
def mousePressEvent(self, event):
"""Keep track of whether to drag URLs or just text"""
self._alt_drag = event.modifiers() & Qt.AltModifier
return super().mousePressEvent(event)
def mouseMoveEvent(self, event):
"""Keep track of whether to drag URLs or just text"""
self._alt_drag = event.modifiers() & Qt.AltModifier
return super().mouseMoveEvent(event)
def mimeData(self, items):
"""Return a list of absolute-path URLs"""
context = self.context
paths = qtutils.paths_from_items(items, item_filter=_item_filter)
include_urls = not self._alt_drag
return qtutils.mimedata_from_paths(context, paths, include_urls=include_urls)
def mimeTypes(self):
"""Return the mime types that this widget generates"""
return qtutils.path_mimetypes(include_urls=not self._alt_drag)
def _item_filter(item):
"""Filter items down to just those that exist on disk"""
return not item.deleted and core.exists(item.path)
def view_blame(context):
"""Signal that we should view blame for paths."""
cmds.do(cmds.BlamePaths, context)
def view_history(context):
"""Signal that we should view history for paths."""
cmds.do(cmds.VisualizePaths, context, context.selection.union())
def copy_path(context, absolute=True):
"""Copy a selected path to the clipboard"""
filename = context.selection.filename()
qtutils.copy_path(filename, absolute=absolute)
def copy_relpath(context):
"""Copy a selected relative path to the clipboard"""
copy_path(context, absolute=False)
def copy_basename(context):
filename = os.path.basename(context.selection.filename())
basename, _ = os.path.splitext(filename)
qtutils.copy_path(basename, absolute=False)
def copy_leading_path(context, strip_components):
"""Peal off trailing path components and copy the current path to the clipboard"""
filename = context.selection.filename()
value = filename
for _ in range(strip_components):
value = os.path.dirname(value)
qtutils.copy_path(value, absolute=False)
def copy_format(context, fmt):
"""Add variables usable in the custom Copy format strings"""
values = {}
values['path'] = path = context.selection.filename()
values['abspath'] = abspath = os.path.abspath(path)
values['absdirname'] = os.path.dirname(abspath)
values['dirname'] = os.path.dirname(path)
values['filename'] = os.path.basename(path)
values['basename'], values['ext'] = os.path.splitext(os.path.basename(path))
qtutils.set_clipboard(fmt % values)
def show_help(context):
"""Display the help for the custom Copy format strings"""
help_text = N_(
r"""
Format String Variables
-----------------------
%(path)s = relative file path
%(abspath)s = absolute file path
%(dirname)s = relative directory path
%(absdirname)s = absolute directory path
%(filename)s = file basename
%(basename)s = file basename without extension
%(ext)s = file extension
"""
)
title = N_('Help - Custom Copy Actions')
return text.text_dialog(context, help_text, title)
class StatusFilterWidget(QtWidgets.QWidget):
"""Filter paths displayed by the Status tool"""
def __init__(self, context, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.context = context
hint = N_('Filter paths...')
self.text = completion.GitStatusFilterLineEdit(context, hint=hint, parent=self)
self.text.setToolTip(hint)
self.setFocusProxy(self.text)
self._filter = None
self.main_layout = qtutils.hbox(defs.no_margin, defs.spacing, self.text)
self.setLayout(self.main_layout)
widget = self.text
widget.changed.connect(self.apply_filter)
widget.cleared.connect(self.apply_filter)
widget.enter.connect(self.apply_filter)
widget.editingFinished.connect(self.apply_filter)
def apply_filter(self):
"""Apply the text filter to the model"""
value = get(self.text)
if value == self._filter:
return
self._filter = value
paths = utils.shell_split(value)
self.context.model.update_path_filter(paths)
def customize_copy_actions(context, parent):
"""Customize copy actions"""
dialog = CustomizeCopyActions(context, parent)
dialog.show()
dialog.exec_()
class CustomizeCopyActions(standard.Dialog):
"""A dialog for defining custom Copy actions and format strings"""
def __init__(self, context, parent):
standard.Dialog.__init__(self, parent=parent)
self.setWindowTitle(N_('Custom Copy Actions'))
self.context = context
self.table = QtWidgets.QTableWidget(self)
self.table.setColumnCount(2)
self.table.setHorizontalHeaderLabels([N_('Action Name'), N_('Format String')])
self.table.setSortingEnabled(False)
self.table.verticalHeader().hide()
self.table.horizontalHeader().setStretchLastSection(True)
self.add_button = qtutils.create_button(N_('Add'))
self.remove_button = qtutils.create_button(N_('Remove'))
self.remove_button.setEnabled(False)
self.show_help_button = qtutils.create_button(N_('Show Help'))
self.show_help_button.setShortcut(hotkeys.QUESTION)
self.close_button = qtutils.close_button()
self.save_button = qtutils.ok_button(N_('Save'))
self.buttons = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
self.add_button,
self.remove_button,
self.show_help_button,
qtutils.STRETCH,
self.close_button,
self.save_button,
)
layout = qtutils.vbox(defs.margin, defs.spacing, self.table, self.buttons)
self.setLayout(layout)
qtutils.connect_button(self.add_button, self.add)
qtutils.connect_button(self.remove_button, self.remove)
qtutils.connect_button(self.show_help_button, partial(show_help, context))
qtutils.connect_button(self.close_button, self.reject)
qtutils.connect_button(self.save_button, self.save)
qtutils.add_close_action(self)
self.table.itemSelectionChanged.connect(self.table_selection_changed)
self.init_size(parent=parent)
QtCore.QTimer.singleShot(0, self.reload_settings)
def reload_settings(self):
"""Update the view to match the current settings"""
# Called once after the GUI is initialized
settings = self.context.settings
settings.load()
table = self.table
for entry in settings.copy_formats:
name_string = entry.get('name', '')
format_string = entry.get('format', '')
if name_string and format_string:
name = QtWidgets.QTableWidgetItem(name_string)
fmt = QtWidgets.QTableWidgetItem(format_string)
rows = table.rowCount()
table.setRowCount(rows + 1)
table.setItem(rows, 0, name)
table.setItem(rows, 1, fmt)
def export_state(self):
"""Export the current state into the saved settings"""
state = super().export_state()
standard.export_header_columns(self.table, state)
return state
def apply_state(self, state):
"""Restore state from the saved settings"""
result = super().apply_state(state)
standard.apply_header_columns(self.table, state)
return result
def add(self):
"""Add a custom Copy action and format string"""
self.table.setFocus()
rows = self.table.rowCount()
self.table.setRowCount(rows + 1)
name = QtWidgets.QTableWidgetItem(N_('Name'))
fmt = QtWidgets.QTableWidgetItem(r'%(path)s')
self.table.setItem(rows, 0, name)
self.table.setItem(rows, 1, fmt)
self.table.setCurrentCell(rows, 0)
self.table.editItem(name)
def remove(self):
"""Remove selected items"""
# Gather a unique set of rows and remove them in reverse order
rows = set()
items = self.table.selectedItems()
for item in items:
rows.add(self.table.row(item))
for row in reversed(sorted(rows)):
self.table.removeRow(row)
def save(self):
"""Save custom copy actions to the settings"""
copy_formats = []
for row in range(self.table.rowCount()):
name = self.table.item(row, 0)
fmt = self.table.item(row, 1)
if name and fmt:
entry = {
'name': name.text(),
'format': fmt.text(),
}
copy_formats.append(entry)
settings = self.context.settings
while settings.copy_formats:
settings.copy_formats.pop()
settings.copy_formats.extend(copy_formats)
settings.save()
self.accept()
def table_selection_changed(self):
"""Update the enabled state of action buttons based on the current selection"""
items = self.table.selectedItems()
self.remove_button.setEnabled(bool(items))
def _select_item(widget, path_list, widget_getter, item, current=False):
"""Select the widget item based on the list index"""
# The path lists and widget indexes have a 1:1 correspondence.
# Lookup the item filename in the list and use that index to
# retrieve the widget item and select it.
idx = path_list.index(item)
item = widget_getter(idx)
if current:
widget.setCurrentItem(item)
item.setSelected(True)
def _apply_toplevel_selection(widget, category, idx):
"""Select a top-level "header" item (ex: the Staged parent item)
Return True when a top-level item is selected.
"""
is_top_level_item = category == HEADER_IDX
if is_top_level_item:
root_item = widget.invisibleRootItem()
item = root_item.child(idx)
if item is not None and item.childCount() == 0:
# The item now has no children. Select a different top-level item
# corresponding to the previously selected item.
if idx == STAGED_IDX:
# If "Staged" was previously selected try "Modified" and "Untracked".
item = _get_first_item_with_children(
root_item.child(MODIFIED_IDX), root_item.child(UNTRACKED_IDX)
)
elif idx == UNMERGED_IDX:
# If "Unmerged" was previously selected try "Staged".
item = _get_first_item_with_children(root_item.child(STAGED_IDX))
elif idx == MODIFIED_IDX:
# If "Modified" was previously selected try "Staged" or "Untracked".
item = _get_first_item_with_children(
root_item.child(STAGED_IDX), root_item.child(UNTRACKED_IDX)
)
elif idx == UNTRACKED_IDX:
# If "Untracked" was previously selected try "Staged".
item = _get_first_item_with_children(root_item.child(STAGED_IDX))
if item is not None:
with qtutils.BlockSignals(widget):
widget.setCurrentItem(item)
item.setSelected(True)
widget.show_selection()
return is_top_level_item
def _get_first_item_with_children(*items):
"""Return the first item that contains child items"""
for item in items:
if item.childCount() > 0:
return item
return None
def _transplant_selection_across_sections(
category, idx, previous_contents, saved_selection
):
"""Transplant the selection to a different category"""
# This function is used when the selection would otherwise become empty.
# Apply heuristics to select the items based on the previous state.
if not previous_contents:
return
staged, unmerged, modified, untracked = saved_selection
prev_staged, prev_unmerged, prev_modified, prev_untracked = previous_contents
# The current set of paths.
staged_paths = staged[NEW_PATHS_IDX]
unmerged_paths = unmerged[NEW_PATHS_IDX]
modified_paths = modified[NEW_PATHS_IDX]
untracked_paths = untracked[NEW_PATHS_IDX]
# These callbacks select a path in the corresponding widget sub-tree lists.
select_staged = staged[SELECT_FN_IDX]
select_unmerged = unmerged[SELECT_FN_IDX]
select_modified = modified[SELECT_FN_IDX]
select_untracked = untracked[SELECT_FN_IDX]
if category == STAGED_IDX:
# Staged files can become Unmerged, Modified or Untracked.
# If we previously had a staged file selected then try to select
# it in either the Unmerged, Modified or Untracked sections.
try:
old_path = prev_staged[idx]
except IndexError:
return
if old_path in unmerged_paths:
select_unmerged(old_path, current=True)
elif old_path in modified_paths:
select_modified(old_path, current=True)
elif old_path in untracked_paths:
select_untracked(old_path, current=True)
elif category == UNMERGED_IDX:
# Unmerged files can become Staged, Modified or Untracked.
# If we previously had an unmerged file selected then try to select it in
# the Staged, Modified or Untracked sections.
try:
old_path = prev_unmerged[idx]
except IndexError:
return
if old_path in staged_paths:
select_staged(old_path, current=True)
elif old_path in modified_paths:
select_modified(old_path, current=True)
elif old_path in untracked_paths:
select_untracked(old_path, current=True)
elif category == MODIFIED_IDX:
# If we previously had a modified file selected then try to select
# it in either the Staged or Untracked sections.
try:
old_path = prev_modified[idx]
except IndexError:
return
if old_path in staged_paths:
select_staged(old_path, current=True)
elif old_path in untracked_paths:
select_untracked(old_path, current=True)
elif category == UNTRACKED_IDX:
# If we previously had an untracked file selected then try to select
# it in the Modified or Staged section. Modified is less common, but
# it's possible for a file to be untracked and then the user adds and
# modifies the file before we've refreshed our state.
try:
old_path = prev_untracked[idx]
except IndexError:
return
if old_path in modified_paths:
select_modified(old_path, current=True)
elif old_path in staged_paths:
select_staged(old_path, current=True)
class CopyLeadingPathWidget(QtWidgets.QWidget):
"""A widget that holds a label and a spin-box for the number of paths to strip"""
def __init__(self, title, context, parent):
QtWidgets.QWidget.__init__(self, parent)
self.context = context
self.icon = QtWidgets.QLabel(self)
self.label = QtWidgets.QLabel(self)
self.spinbox = standard.SpinBox(value=1, mini=1, maxi=99, parent=self)
self.spinbox.setToolTip(N_('The number of leading paths to strip'))
icon = icons.copy()
pixmap = icon.pixmap(defs.default_icon, defs.default_icon)
self.icon.setPixmap(pixmap)
self.label.setText(title)
layout = qtutils.hbox(
defs.small_margin,
defs.titlebar_spacing,
self.icon,
self.label,
qtutils.STRETCH,
self.spinbox,
)
self.setLayout(layout)
theme = context.app.theme
highlight_rgb = theme.highlight_color_rgb()
text_rgb, highlight_text_rgb = theme.text_colors_rgb()
disabled_text_rgb = theme.disabled_text_color_rgb()
stylesheet = """
* {{
show-decoration-selected: 1
}}
QLabel {{
color: {text_rgb};
show-decoration-selected: 1
}}
QLabel:hover {{
color: {highlight_text_rgb};
background-color: {highlight_rgb};
background-clip: padding;
show-decoration-selected: 1
}}
QLabel:disabled {{
color: {disabled_text_rgb};
}}
""".format(
disabled_text_rgb=disabled_text_rgb,
text_rgb=text_rgb,
highlight_text_rgb=highlight_text_rgb,
highlight_rgb=highlight_rgb,
)
self.setStyleSheet(stylesheet)
def value(self):
"""Return the current value of the spin-box"""
return self.spinbox.value()
def set_value(self, value):
"""Set the spin-box value"""
self.spinbox.setValue(value)
| 61,277 | Python | .py | 1,448 | 31.953729 | 88 | 0.609709 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
94 | text.py | git-cola_git-cola/cola/widgets/text.py | """Text widgets"""
from functools import partial
import math
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 ..qtutils import get
from .. import hotkeys
from .. import icons
from .. import qtutils
from .. import utils
from ..i18n import N_
from . import defs
def get_stripped(widget):
return widget.get().strip()
class LineEdit(QtWidgets.QLineEdit):
cursor_changed = Signal(int, int)
esc_pressed = Signal()
def __init__(self, parent=None, row=1, get_value=None, clear_button=False):
QtWidgets.QLineEdit.__init__(self, parent)
self._row = row
if get_value is None:
get_value = get_stripped
self._get_value = get_value
self.cursor_position = LineEditCursorPosition(self, row)
self.menu_actions = []
if clear_button and hasattr(self, 'setClearButtonEnabled'):
self.setClearButtonEnabled(True)
def get(self):
"""Return the raw Unicode value from Qt"""
return self.text()
def value(self):
"""Return the processed value, e.g. stripped"""
return self._get_value(self)
def set_value(self, value, block=False):
"""Update the widget to the specified value"""
if block:
with qtutils.BlockSignals(self):
self._set_value(value)
else:
self._set_value(value)
def _set_value(self, value):
"""Implementation helper to update the widget to the specified value"""
pos = self.cursorPosition()
self.setText(value)
self.setCursorPosition(pos)
def keyPressEvent(self, event):
key = event.key()
if key == Qt.Key_Escape:
self.esc_pressed.emit()
super().keyPressEvent(event)
class LineEditCursorPosition:
"""Translate cursorPositionChanged(int,int) into cursorPosition(int,int)"""
def __init__(self, widget, row):
self._widget = widget
self._row = row
# Translate cursorPositionChanged into cursor_changed(int, int)
widget.cursorPositionChanged.connect(lambda old, new: self.emit())
def emit(self):
widget = self._widget
row = self._row
col = widget.cursorPosition()
widget.cursor_changed.emit(row, col)
def reset(self):
self._widget.setCursorPosition(0)
class BaseTextEditExtension(QtCore.QObject):
def __init__(self, widget, get_value, readonly):
QtCore.QObject.__init__(self, widget)
self.widget = widget
self.cursor_position = TextEditCursorPosition(widget, self)
if get_value is None:
get_value = get_stripped
self._get_value = get_value
self._tabwidth = 8
self._readonly = readonly
self._init_flags()
self.init()
def _init_flags(self):
widget = self.widget
widget.setMinimumSize(QtCore.QSize(10, 10))
widget.setWordWrapMode(QtGui.QTextOption.WordWrap)
widget.setLineWrapMode(widget.__class__.NoWrap)
if self._readonly:
widget.setReadOnly(True)
widget.setAcceptDrops(False)
widget.setTabChangesFocus(True)
widget.setUndoRedoEnabled(False)
widget.setTextInteractionFlags(
Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse
)
def get(self):
"""Return the raw Unicode value from Qt"""
return self.widget.toPlainText()
def value(self):
"""Return a safe value, e.g. a stripped value"""
return self._get_value(self.widget)
def set_value(self, value, block=False):
"""Update the widget to the specified value"""
if block:
with qtutils.BlockSignals(self):
self._set_value(value)
else:
self._set_value(value)
def _set_value(self, value):
"""Implementation helper to update the widget to the specified value"""
# Save cursor position
offset, selection_text = self.offset_and_selection()
old_value = get(self.widget)
# Update text
self.widget.setPlainText(value)
# Restore cursor
if selection_text and selection_text in value:
# If the old selection exists in the new text then re-select it.
idx = value.index(selection_text)
cursor = self.widget.textCursor()
cursor.setPosition(idx)
cursor.setPosition(idx + len(selection_text), QtGui.QTextCursor.KeepAnchor)
self.widget.setTextCursor(cursor)
elif value == old_value:
# Otherwise, if the text is identical and there is no selection
# then restore the cursor position.
cursor = self.widget.textCursor()
cursor.setPosition(offset)
self.widget.setTextCursor(cursor)
else:
# If none of the above applied then restore the cursor position.
position = max(0, min(offset, len(value) - 1))
cursor = self.widget.textCursor()
cursor.setPosition(position)
self.widget.setTextCursor(cursor)
cursor = self.widget.textCursor()
cursor.movePosition(QtGui.QTextCursor.StartOfLine)
self.widget.setTextCursor(cursor)
def set_cursor_position(self, new_position):
cursor = self.widget.textCursor()
cursor.setPosition(new_position)
self.widget.setTextCursor(cursor)
def tabwidth(self):
return self._tabwidth
def set_tabwidth(self, width):
self._tabwidth = width
pixels = qtutils.text_width(self.widget.font(), 'M') * width
self.widget.setTabStopWidth(pixels)
def selected_line(self):
contents = self.value()
cursor = self.widget.textCursor()
offset = min(cursor.position(), len(contents) - 1)
while offset >= 1 and contents[offset - 1] and contents[offset - 1] != '\n':
offset -= 1
data = contents[offset:]
if '\n' in data:
line, _ = data.split('\n', 1)
else:
line = data
return line
def cursor(self):
return self.widget.textCursor()
def has_selection(self):
return self.cursor().hasSelection()
def selected_text(self):
"""Return the selected text"""
_, selection = self.offset_and_selection()
return selection
def offset_and_selection(self):
"""Return the cursor offset and selected text"""
cursor = self.cursor()
offset = cursor.selectionStart()
selection_text = cursor.selection().toPlainText()
return offset, selection_text
def mouse_press_event(self, event):
# Move the text cursor so that the right-click events operate
# on the current position, not the last left-clicked position.
widget = self.widget
if event.button() == Qt.RightButton:
if not widget.textCursor().hasSelection():
cursor = widget.cursorForPosition(event.pos())
widget.setTextCursor(cursor)
def add_links_to_menu(self, menu):
"""Add actions for opening URLs to a custom menu"""
links = self._get_links()
if links:
menu.addSeparator()
for url in links:
action = menu.addAction(N_('Open "%s"') % url)
action.setIcon(icons.external())
qtutils.connect_action(
action, partial(QtGui.QDesktopServices.openUrl, QtCore.QUrl(url))
)
def _get_links(self):
"""Return http links on the current line"""
_, selection = self.offset_and_selection()
if selection:
line = selection
else:
line = self.selected_line()
if not line:
return []
return [
word for word in line.split() if word.startswith(('http://', 'https://'))
]
def create_context_menu(self, event_pos):
"""Create a context menu for a widget"""
menu = self.widget.createStandardContextMenu(event_pos)
qtutils.add_menu_actions(menu, self.widget.menu_actions)
self.add_links_to_menu(menu)
return menu
def context_menu_event(self, event):
"""Default context menu event"""
event_pos = event.pos()
menu = self.widget.create_context_menu(event_pos)
menu.exec_(self.widget.mapToGlobal(event_pos))
# For extension by sub-classes
def init(self):
"""Called during init for class-specific settings"""
return
def set_textwidth(self, width):
"""Set the text width"""
return
def set_linebreak(self, brk):
"""Enable word wrapping"""
return
class PlainTextEditExtension(BaseTextEditExtension):
def set_linebreak(self, brk):
if brk:
wrapmode = QtWidgets.QPlainTextEdit.WidgetWidth
else:
wrapmode = QtWidgets.QPlainTextEdit.NoWrap
self.widget.setLineWrapMode(wrapmode)
class PlainTextEdit(QtWidgets.QPlainTextEdit):
cursor_changed = Signal(int, int)
leave = Signal()
def __init__(self, parent=None, get_value=None, readonly=False, options=None):
QtWidgets.QPlainTextEdit.__init__(self, parent)
self.ext = PlainTextEditExtension(self, get_value, readonly)
self.cursor_position = self.ext.cursor_position
self.mouse_zoom = True
self.options = options
self.menu_actions = []
def get(self):
"""Return the raw Unicode value from Qt"""
return self.ext.get()
# For compatibility with QTextEdit
def setText(self, value):
self.set_value(value)
def value(self):
"""Return a safe value, e.g. a stripped value"""
return self.ext.value()
def offset_and_selection(self):
"""Return the cursor offset and selected text"""
return self.ext.offset_and_selection()
def set_value(self, value, block=False):
self.ext.set_value(value, block=block)
def set_mouse_zoom(self, value):
"""Enable/disable text zooming in response to ctrl + mousewheel scroll events"""
self.mouse_zoom = value
def set_options(self, options):
"""Register an Options widget"""
self.options = options
def set_word_wrapping(self, enabled, update=False):
"""Enable/disable word wrapping"""
if update and self.options is not None:
with qtutils.BlockSignals(self.options.enable_word_wrapping):
self.options.enable_word_wrapping.setChecked(enabled)
if enabled:
self.setWordWrapMode(QtGui.QTextOption.WordWrap)
self.setLineWrapMode(QtWidgets.QPlainTextEdit.WidgetWidth)
else:
self.setWordWrapMode(QtGui.QTextOption.NoWrap)
self.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)
def has_selection(self):
return self.ext.has_selection()
def selected_line(self):
return self.ext.selected_line()
def selected_text(self):
"""Return the selected text"""
return self.ext.selected_text()
def set_tabwidth(self, width):
self.ext.set_tabwidth(width)
def set_textwidth(self, width):
self.ext.set_textwidth(width)
def set_linebreak(self, brk):
self.ext.set_linebreak(brk)
def mousePressEvent(self, event):
self.ext.mouse_press_event(event)
super().mousePressEvent(event)
def wheelEvent(self, event):
"""Disable control+wheelscroll text resizing"""
if not self.mouse_zoom and (event.modifiers() & Qt.ControlModifier):
event.ignore()
return
super().wheelEvent(event)
def create_context_menu(self, event_pos):
"""Create a custom context menu"""
return self.ext.create_context_menu(event_pos)
def contextMenuEvent(self, event):
"""Custom contextMenuEvent() for building our custom context menus"""
self.ext.context_menu_event(event)
class TextSearchWidget(QtWidgets.QWidget):
"""The search dialog that displays over a text edit field"""
def __init__(self, widget, parent):
super().__init__(parent)
self.setAutoFillBackground(True)
self._widget = widget
self._parent = parent
self.text = HintedDefaultLineEdit(N_('Find in diff'), parent=self)
self.prev_button = qtutils.create_action_button(
tooltip=N_('Find the previous occurrence of the phrase'), icon=icons.up()
)
self.next_button = qtutils.create_action_button(
tooltip=N_('Find the next occurrence of the phrase'), icon=icons.down()
)
self.match_case_checkbox = qtutils.checkbox(N_('Match Case'))
self.whole_words_checkbox = qtutils.checkbox(N_('Whole Words'))
self.close_button = qtutils.create_action_button(
tooltip=N_('Close the find bar'), icon=icons.close()
)
layout = qtutils.hbox(
defs.margin,
defs.button_spacing,
self.text,
self.prev_button,
self.next_button,
self.match_case_checkbox,
self.whole_words_checkbox,
qtutils.STRETCH,
self.close_button,
)
self.setLayout(layout)
self.setFocusProxy(self.text)
self.text.esc_pressed.connect(self.hide_search)
self.text.returnPressed.connect(self.search)
self.text.textChanged.connect(self.search)
self.search_next_action = qtutils.add_action(
parent,
N_('Find next item'),
self.search,
hotkeys.SEARCH_NEXT,
)
self.search_prev_action = qtutils.add_action(
parent,
N_('Find previous item'),
self.search_backwards,
hotkeys.SEARCH_PREV,
)
qtutils.connect_button(self.next_button, self.search)
qtutils.connect_button(self.prev_button, self.search_backwards)
qtutils.connect_button(self.close_button, self.hide_search)
qtutils.connect_checkbox(self.match_case_checkbox, lambda _: self.search())
qtutils.connect_checkbox(self.whole_words_checkbox, lambda _: self.search())
def search(self):
"""Emit a signal with the current search text"""
self.search_text(backwards=False)
def search_backwards(self):
"""Emit a signal with the current search text for a backwards search"""
self.search_text(backwards=True)
def hide_search(self):
"""Hide the search window"""
self.hide()
self._parent.setFocus()
def find_flags(self, backwards):
"""Return QTextDocument.FindFlags for the current search options"""
flags = QtGui.QTextDocument.FindFlag(0)
if backwards:
flags = flags | QtGui.QTextDocument.FindBackward
if self.match_case_checkbox.isChecked():
flags = flags | QtGui.QTextDocument.FindCaseSensitively
if self.whole_words_checkbox.isChecked():
flags = flags | QtGui.QTextDocument.FindWholeWords
return flags
def is_case_sensitive(self):
"""Are we searching using a case-insensitive search?"""
return self.match_case_checkbox.isChecked()
def search_text(self, backwards=False):
"""Search the diff text for the given text"""
text = self.text.get()
cursor = self._widget.textCursor()
if cursor.hasSelection():
selected_text = cursor.selectedText()
case_sensitive = self.is_case_sensitive()
if text_matches(case_sensitive, selected_text, text):
if backwards:
position = cursor.selectionStart()
else:
position = cursor.selectionEnd()
else:
if backwards:
position = cursor.selectionEnd()
else:
position = cursor.selectionStart()
cursor.setPosition(position)
self._widget.setTextCursor(cursor)
flags = self.find_flags(backwards)
if not self._widget.find(text, flags):
if backwards:
location = QtGui.QTextCursor.End
else:
location = QtGui.QTextCursor.Start
cursor.movePosition(location, QtGui.QTextCursor.MoveAnchor)
self._widget.setTextCursor(cursor)
self._widget.find(text, flags)
def text_matches(case_sensitive, a, b):
"""Compare text with case sensitivity taken into account"""
if case_sensitive:
return a == b
return a.lower() == b.lower()
class TextEditExtension(BaseTextEditExtension):
def init(self):
widget = self.widget
widget.setAcceptRichText(False)
def set_linebreak(self, brk):
if brk:
wrapmode = QtWidgets.QTextEdit.FixedColumnWidth
else:
wrapmode = QtWidgets.QTextEdit.NoWrap
self.widget.setLineWrapMode(wrapmode)
def set_textwidth(self, width):
self.widget.setLineWrapColumnOrWidth(width)
class TextEdit(QtWidgets.QTextEdit):
cursor_changed = Signal(int, int)
leave = Signal()
def __init__(self, parent=None, get_value=None, readonly=False):
QtWidgets.QTextEdit.__init__(self, parent)
self.ext = TextEditExtension(self, get_value, readonly)
self.cursor_position = self.ext.cursor_position
self.expandtab_enabled = False
self.menu_actions = []
def get(self):
"""Return the raw Unicode value from Qt"""
return self.ext.get()
def value(self):
"""Return a safe value, e.g. a stripped value"""
return self.ext.value()
def set_cursor_position(self, position):
"""Set the cursor position"""
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
def set_value(self, value, block=False):
self.ext.set_value(value, block=block)
def selected_line(self):
return self.ext.selected_line()
def selected_text(self):
"""Return the selected text"""
return self.ext.selected_text()
def set_tabwidth(self, width):
self.ext.set_tabwidth(width)
def set_textwidth(self, width):
self.ext.set_textwidth(width)
def set_linebreak(self, brk):
self.ext.set_linebreak(brk)
def set_expandtab(self, value):
self.expandtab_enabled = value
def mousePressEvent(self, event):
self.ext.mouse_press_event(event)
super().mousePressEvent(event)
def wheelEvent(self, event):
"""Disable control+wheelscroll text resizing"""
if event.modifiers() & Qt.ControlModifier:
event.ignore()
return
super().wheelEvent(event)
def should_expandtab(self, event):
return event.key() == Qt.Key_Tab and self.expandtab_enabled
def expandtab(self):
tabwidth = max(self.ext.tabwidth(), 1)
cursor = self.textCursor()
cursor.insertText(' ' * tabwidth)
def create_context_menu(self, event_pos):
"""Create a custom context menu"""
return self.ext.create_context_menu(event_pos)
def contextMenuEvent(self, event):
"""Custom contextMenuEvent() for building our custom context menus"""
self.ext.context_menu_event(event)
def keyPressEvent(self, event):
"""Override keyPressEvent to handle tab expansion"""
expandtab = self.should_expandtab(event)
if expandtab:
self.expandtab()
event.accept()
else:
QtWidgets.QTextEdit.keyPressEvent(self, event)
def keyReleaseEvent(self, event):
"""Override keyReleaseEvent to special-case tab expansion"""
expandtab = self.should_expandtab(event)
if expandtab:
event.ignore()
else:
QtWidgets.QTextEdit.keyReleaseEvent(self, event)
class TextEditCursorPosition:
def __init__(self, widget, ext):
self._widget = widget
self._ext = ext
widget.cursorPositionChanged.connect(self.emit)
def emit(self):
widget = self._widget
ext = self._ext
cursor = widget.textCursor()
position = cursor.position()
txt = widget.get()
before = txt[:position]
row = before.count('\n')
line = before.split('\n')[row]
col = cursor.columnNumber()
col += line[:col].count('\t') * (ext.tabwidth() - 1)
widget.cursor_changed.emit(row + 1, col)
def reset(self):
widget = self._widget
cursor = widget.textCursor()
cursor.setPosition(0)
widget.setTextCursor(cursor)
class MonoTextEdit(PlainTextEdit):
def __init__(self, context, parent=None, readonly=False):
PlainTextEdit.__init__(self, parent=parent, readonly=readonly)
self.setFont(qtutils.diff_font(context))
def get_value_hinted(widget):
text = get_stripped(widget)
hint = get(widget.hint)
if text == hint:
return ''
return text
class HintWidget(QtCore.QObject):
"""Extend a widget to provide hint messages
This primarily exists because setPlaceholderText() is only available
in Qt5, so this class provides consistent behavior across versions.
"""
def __init__(self, widget, hint):
QtCore.QObject.__init__(self, widget)
self._widget = widget
self._hint = hint
self._is_error = False
self.modern = modern = hasattr(widget, 'setPlaceholderText')
if modern:
widget.setPlaceholderText(hint)
# Palette for normal text
QPalette = QtGui.QPalette
palette = widget.palette()
hint_color = palette.color(QPalette.Disabled, QPalette.Text)
error_bg_color = QtGui.QColor(Qt.red).darker()
error_fg_color = QtGui.QColor(Qt.white)
hint_rgb = qtutils.rgb_css(hint_color)
error_bg_rgb = qtutils.rgb_css(error_bg_color)
error_fg_rgb = qtutils.rgb_css(error_fg_color)
env = {
'name': widget.__class__.__name__,
'error_fg_rgb': error_fg_rgb,
'error_bg_rgb': error_bg_rgb,
'hint_rgb': hint_rgb,
}
self._default_style = ''
self._hint_style = (
"""
%(name)s {
color: %(hint_rgb)s;
}
"""
% env
)
self._error_style = (
"""
%(name)s {
color: %(error_fg_rgb)s;
background-color: %(error_bg_rgb)s;
}
"""
% env
)
def init(self):
"""Deferred initialization"""
if self.modern:
self.widget().setPlaceholderText(self.value())
else:
self.widget().installEventFilter(self)
self.enable(True)
def widget(self):
"""Return the parent text widget"""
return self._widget
def active(self):
"""Return True when hint-mode is active"""
return self.value() == get_stripped(self._widget)
def value(self):
"""Return the current hint text"""
return self._hint
def set_error(self, is_error):
"""Enable/disable error mode"""
self._is_error = is_error
self.refresh()
def set_value(self, hint):
"""Change the hint text"""
if self.modern:
self._hint = hint
self._widget.setPlaceholderText(hint)
else:
# If hint-mode is currently active, re-activate it
active = self.active()
self._hint = hint
if active or self.active():
self.enable(True)
def enable(self, enable):
"""Enable/disable hint-mode"""
if not self.modern:
if enable and self._hint:
self._widget.set_value(self._hint, block=True)
self._widget.cursor_position.reset()
else:
self._widget.clear()
self._update_palette(enable)
def refresh(self):
"""Update the palette to match the current mode"""
self._update_palette(self.active())
def _update_palette(self, hint):
"""Update to palette for normal/error/hint mode"""
if self._is_error:
style = self._error_style
elif not self.modern and hint:
style = self._hint_style
else:
style = self._default_style
QtCore.QTimer.singleShot(
0, lambda: utils.catch_runtime_error(self._widget.setStyleSheet, style)
)
def eventFilter(self, _obj, event):
"""Enable/disable hint-mode when focus changes"""
etype = event.type()
if etype == QtCore.QEvent.FocusIn:
self.focus_in()
elif etype == QtCore.QEvent.FocusOut:
self.focus_out()
return False
def focus_in(self):
"""Disable hint-mode when focused"""
widget = self.widget()
if self.active():
self.enable(False)
widget.cursor_position.emit()
def focus_out(self):
"""Re-enable hint-mode when losing focus"""
widget = self.widget()
valid, value = utils.catch_runtime_error(get, widget)
if not valid:
# The widget may have just been destroyed during application shutdown.
# We're receiving a focusOut event but the widget can no longer be used.
# This can be safely ignored.
return
if not value:
self.enable(True)
class HintedPlainTextEdit(PlainTextEdit):
"""A hinted plain text edit"""
def __init__(self, context, hint, parent=None, readonly=False):
PlainTextEdit.__init__(
self, parent=parent, get_value=get_value_hinted, readonly=readonly
)
self.hint = HintWidget(self, hint)
self.hint.init()
self.context = context
self.setFont(qtutils.diff_font(context))
self.set_tabwidth(prefs.tabwidth(context))
# Refresh palettes when text changes
self.textChanged.connect(self.hint.refresh)
self.set_mouse_zoom(context.cfg.get(prefs.MOUSE_ZOOM, default=True))
def set_value(self, value, block=False):
"""Set the widget text or enable hint mode when empty"""
if value or self.hint.modern:
PlainTextEdit.set_value(self, value, block=block)
else:
self.hint.enable(True)
class HintedTextEdit(TextEdit):
"""A hinted text edit"""
def __init__(self, context, hint, parent=None, readonly=False):
TextEdit.__init__(
self, parent=parent, get_value=get_value_hinted, readonly=readonly
)
self.context = context
self.hint = HintWidget(self, hint)
self.hint.init()
# Refresh palettes when text changes
self.textChanged.connect(self.hint.refresh)
self.setFont(qtutils.diff_font(context))
def set_value(self, value, block=False):
"""Set the widget text or enable hint mode when empty"""
if value or self.hint.modern:
TextEdit.set_value(self, value, block=block)
else:
self.hint.enable(True)
def anchor_mode(select):
"""Return the QTextCursor mode to keep/discard the cursor selection"""
if select:
mode = QtGui.QTextCursor.KeepAnchor
else:
mode = QtGui.QTextCursor.MoveAnchor
return mode
# The vim-like read-only text view
class VimMixin:
def __init__(self, widget):
self.widget = widget
self.Base = widget.Base
# Common vim/Unix-ish keyboard actions
self.add_navigation('End', hotkeys.GOTO_END)
self.add_navigation('Up', hotkeys.MOVE_UP, shift=hotkeys.MOVE_UP_SHIFT)
self.add_navigation('Down', hotkeys.MOVE_DOWN, shift=hotkeys.MOVE_DOWN_SHIFT)
self.add_navigation('Left', hotkeys.MOVE_LEFT, shift=hotkeys.MOVE_LEFT_SHIFT)
self.add_navigation('Right', hotkeys.MOVE_RIGHT, shift=hotkeys.MOVE_RIGHT_SHIFT)
self.add_navigation('WordLeft', hotkeys.WORD_LEFT)
self.add_navigation('WordRight', hotkeys.WORD_RIGHT)
self.add_navigation('Start', hotkeys.GOTO_START)
self.add_navigation('StartOfLine', hotkeys.START_OF_LINE)
self.add_navigation('EndOfLine', hotkeys.END_OF_LINE)
qtutils.add_action(
widget,
'PageUp',
widget.page_up,
hotkeys.SECONDARY_ACTION,
hotkeys.TEXT_UP,
)
qtutils.add_action(
widget,
'PageDown',
widget.page_down,
hotkeys.PRIMARY_ACTION,
hotkeys.TEXT_DOWN,
)
qtutils.add_action(
widget,
'SelectPageUp',
lambda: widget.page_up(select=True),
hotkeys.SELECT_BACK,
hotkeys.SELECT_UP,
)
qtutils.add_action(
widget,
'SelectPageDown',
lambda: widget.page_down(select=True),
hotkeys.SELECT_FORWARD,
hotkeys.SELECT_DOWN,
)
def add_navigation(self, name, hotkey, shift=None):
"""Add a hotkey along with a shift-variant"""
widget = self.widget
direction = getattr(QtGui.QTextCursor, name)
qtutils.add_action(widget, name, lambda: self.move(direction), hotkey)
if shift:
qtutils.add_action(
widget, 'Shift' + name, lambda: self.move(direction, select=True), shift
)
def move(self, direction, select=False, n=1):
widget = self.widget
cursor = widget.textCursor()
mode = anchor_mode(select)
for _ in range(n):
if cursor.movePosition(direction, mode, 1):
self.set_text_cursor(cursor)
def page(self, offset, select=False):
widget = self.widget
rect = widget.cursorRect()
x = rect.x()
y = rect.y() + offset
new_cursor = widget.cursorForPosition(QtCore.QPoint(x, y))
if new_cursor is not None:
cursor = widget.textCursor()
mode = anchor_mode(select)
cursor.setPosition(new_cursor.position(), mode)
self.set_text_cursor(cursor)
def page_down(self, select=False):
widget = self.widget
widget.page(widget.height() // 2, select=select)
def page_up(self, select=False):
widget = self.widget
widget.page(-widget.height() // 2, select=select)
def set_text_cursor(self, cursor):
widget = self.widget
widget.setTextCursor(cursor)
widget.ensureCursorVisible()
widget.viewport().update()
def keyPressEvent(self, event):
"""Custom keyboard behaviors
The leave() signal is emitted when `Up` is pressed and we're already
at the beginning of the text. This allows the parent widget to
orchestrate some higher-level interaction, such as giving focus to
another widget.
When in the middle of the first line and `Up` is pressed, the cursor
is moved to the beginning of the line.
"""
widget = self.widget
if event.key() == Qt.Key_Up:
cursor = widget.textCursor()
position = cursor.position()
if position == 0:
# The cursor is at the beginning of the line.
# Emit a signal so that the parent can e.g. change focus.
widget.leave.emit()
elif get(widget)[:position].count('\n') == 0:
# The cursor is in the middle of the first line of text.
# We can't go up ~ jump to the beginning of the line.
# Select the text if shift is pressed.
select = event.modifiers() & Qt.ShiftModifier
mode = anchor_mode(select)
cursor.movePosition(QtGui.QTextCursor.StartOfLine, mode)
widget.setTextCursor(cursor)
return self.Base.keyPressEvent(widget, event)
class VimHintedPlainTextEdit(HintedPlainTextEdit):
"""HintedPlainTextEdit with vim hotkeys
This can only be used in read-only mode.
"""
Base = HintedPlainTextEdit
Mixin = VimMixin
def __init__(self, context, hint, parent=None):
HintedPlainTextEdit.__init__(self, context, hint, parent=parent, readonly=True)
self._mixin = self.Mixin(self)
def move(self, direction, select=False, n=1):
return self._mixin.page(direction, select=select, n=n)
def page(self, offset, select=False):
return self._mixin.page(offset, select=select)
def page_up(self, select=False):
return self._mixin.page_up(select=select)
def page_down(self, select=False):
return self._mixin.page_down(select=select)
def keyPressEvent(self, event):
return self._mixin.keyPressEvent(event)
class VimTextEdit(MonoTextEdit):
"""Text viewer with vim-like hotkeys
This can only be used in read-only mode.
"""
Base = MonoTextEdit
Mixin = VimMixin
def __init__(self, context, parent=None, readonly=True):
MonoTextEdit.__init__(self, context, parent=None, readonly=readonly)
self._mixin = self.Mixin(self)
def move(self, direction, select=False, n=1):
return self._mixin.page(direction, select=select, n=n)
def page(self, offset, select=False):
return self._mixin.page(offset, select=select)
def page_up(self, select=False):
return self._mixin.page_up(select=select)
def page_down(self, select=False):
return self._mixin.page_down(select=select)
def keyPressEvent(self, event):
return self._mixin.keyPressEvent(event)
class HintedDefaultLineEdit(LineEdit):
"""A line edit with hint text"""
def __init__(self, hint, tooltip=None, parent=None):
LineEdit.__init__(self, parent=parent, get_value=get_value_hinted)
if tooltip:
self.setToolTip(tooltip)
self.hint = HintWidget(self, hint)
self.hint.init()
self.textChanged.connect(lambda text: self.hint.refresh())
class HintedLineEdit(HintedDefaultLineEdit):
"""A monospace line edit with hint text"""
def __init__(self, context, hint, tooltip=None, parent=None):
super().__init__(hint, tooltip=tooltip, parent=parent)
self.setFont(qtutils.diff_font(context))
def text_dialog(context, text, title):
"""Show a wall of text in a dialog"""
parent = qtutils.active_window()
label = QtWidgets.QLabel(parent)
label.setFont(qtutils.diff_font(context))
label.setText(text)
label.setMargin(defs.large_margin)
text_flags = Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse
label.setTextInteractionFlags(text_flags)
widget = QtWidgets.QDialog(parent)
widget.setWindowModality(Qt.WindowModal)
widget.setWindowTitle(title)
scroll = QtWidgets.QScrollArea()
scroll.setWidget(label)
layout = qtutils.hbox(defs.margin, defs.spacing, scroll)
widget.setLayout(layout)
qtutils.add_action(
widget, N_('Close'), widget.accept, Qt.Key_Question, Qt.Key_Enter, Qt.Key_Return
)
widget.show()
return widget
class VimTextBrowser(VimTextEdit):
"""Text viewer with line number annotations"""
def __init__(self, context, parent=None, readonly=True):
VimTextEdit.__init__(self, context, parent=parent, readonly=readonly)
self.numbers = LineNumbers(self)
def resizeEvent(self, event):
super().resizeEvent(event)
self.numbers.refresh_size()
class TextDecorator(QtWidgets.QWidget):
"""Common functionality for providing line numbers in text widgets"""
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self.editor = parent
parent.blockCountChanged.connect(lambda x: self._refresh_viewport())
parent.cursorPositionChanged.connect(self.refresh)
parent.updateRequest.connect(self._refresh_rect)
def refresh(self):
"""Refresh the numbers display"""
rect = self.editor.viewport().rect()
self._refresh_rect(rect, 0)
def _refresh_rect(self, rect, dy):
if dy:
self.scroll(0, dy)
else:
self.update(0, rect.y(), self.width(), rect.height())
if rect.contains(self.editor.viewport().rect()):
self._refresh_viewport()
def _refresh_viewport(self):
self.editor.setViewportMargins(self.width_hint(), 0, 0, 0)
def refresh_size(self):
rect = self.editor.contentsRect()
geom = QtCore.QRect(rect.left(), rect.top(), self.width_hint(), rect.height())
self.setGeometry(geom)
def sizeHint(self):
return QtCore.QSize(self.width_hint(), 0)
class LineNumbers(TextDecorator):
"""Provide line numbers for QPlainTextEdit widgets"""
def __init__(self, parent):
TextDecorator.__init__(self, parent)
self.highlight_line = -1
def width_hint(self):
document = self.editor.document()
digits = int(math.log(max(1, document.blockCount()), 10)) + 2
text_width = qtutils.text_width(self.font(), '0')
return defs.large_margin + (text_width * digits)
def set_highlighted(self, line_number):
"""Set the line to highlight"""
self.highlight_line = line_number
def paintEvent(self, event):
"""Paint the line number"""
QPalette = QtGui.QPalette
painter = QtGui.QPainter(self)
editor = self.editor
palette = editor.palette()
painter.fillRect(event.rect(), palette.color(QPalette.Base))
content_offset = editor.contentOffset()
block = editor.firstVisibleBlock()
width = self.width()
event_rect_bottom = event.rect().bottom()
highlight = palette.color(QPalette.Highlight)
highlighted_text = palette.color(QPalette.HighlightedText)
disabled = palette.color(QPalette.Disabled, QPalette.Text)
while block.isValid():
block_geom = editor.blockBoundingGeometry(block)
block_top = block_geom.translated(content_offset).top()
if not block.isVisible() or block_top >= event_rect_bottom:
break
rect = block_geom.translated(content_offset).toRect()
block_number = block.blockNumber()
if block_number == self.highlight_line:
painter.fillRect(rect.x(), rect.y(), width, rect.height(), highlight)
painter.setPen(highlighted_text)
else:
painter.setPen(disabled)
number = '%s' % (block_number + 1)
painter.drawText(
rect.x(),
rect.y(),
self.width() - defs.large_margin,
rect.height(),
Qt.AlignRight | Qt.AlignVCenter,
number,
)
block = block.next()
class TextLabel(QtWidgets.QLabel):
"""A text label that elides its display"""
def __init__(self, parent=None, open_external_links=True, selectable=True):
QtWidgets.QLabel.__init__(self, parent)
self._display = ''
self._template = ''
self._text = ''
self._elide = False
self._metrics = QtGui.QFontMetrics(self.font())
policy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Minimum
)
self.setSizePolicy(policy)
if selectable:
interaction_flags = Qt.TextSelectableByMouse | Qt.LinksAccessibleByMouse
else:
interaction_flags = Qt.LinksAccessibleByMouse
self.setTextInteractionFlags(interaction_flags)
self.setOpenExternalLinks(open_external_links)
def elide(self):
self._elide = True
def set_text(self, text):
self.set_template(text, text)
def set_template(self, text, template):
self._display = text
self._text = text
self._template = template
self.update_text(self.width())
self.setText(self._display)
def update_text(self, width):
self._display = self._text
if not self._elide:
return
text = self._metrics.elidedText(self._template, Qt.ElideRight, width - 2)
if text != self._template:
self._display = text
def get(self):
"""Return the label's inner text value"""
return self._text
# Qt overrides
def setFont(self, font):
self._metrics = QtGui.QFontMetrics(font)
QtWidgets.QLabel.setFont(self, font)
def resizeEvent(self, event):
if self._elide:
self.update_text(event.size().width())
with qtutils.BlockSignals(self):
self.setText(self._display)
QtWidgets.QLabel.resizeEvent(self, event)
class PlainTextLabel(TextLabel):
"""A plaintext label that elides its display"""
def __init__(self, selectable=True, parent=None):
super().__init__(
selectable=selectable, parent=parent, open_external_links=False
)
self.setTextFormat(Qt.PlainText)
class RichTextLabel(TextLabel):
"""A richtext label that elides its display"""
def __init__(self, selectable=True, parent=None):
super().__init__(selectable=selectable, open_external_links=True, parent=parent)
self.setTextFormat(Qt.RichText)
| 41,580 | Python | .py | 1,019 | 31.602552 | 88 | 0.625933 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
95 | defs.py | git-cola_git-cola/cola/widgets/defs.py | import os
import math
try:
scale_factor = float(os.getenv('GIT_COLA_SCALE', '1'))
except ValueError:
scale_factor = 1.0
def scale(value, factor=scale_factor):
return int(value * factor)
no_margin = 0
small_margin = scale(2)
margin = scale(4)
large_margin = scale(12)
no_spacing = 0
spacing = scale(4)
titlebar_spacing = scale(8)
button_spacing = scale(12)
cursor_width = scale(2)
handle_width = scale(4)
tool_button_height = scale(28)
default_icon = scale(16)
small_icon = scale(12)
medium_icon = scale(48)
large_icon = scale(96)
huge_icon = scale(192)
max_size = scale(4096)
border = max(1, scale(0.5))
checkbox = scale(12)
radio = scale(22)
logo_text = 24
radio_border = max(1, scale(1.0 - (1.0 / math.pi)))
separator = scale(3)
dialog_w = scale(720)
dialog_h = scale(445)
msgbox_h = scale(128)
| 825 | Python | .py | 34 | 22.441176 | 58 | 0.71871 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
96 | log.py | git-cola_git-cola/cola/widgets/log.py | import time
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from .. import core
from .. import qtutils
from ..i18n import N_
from . import defs
from . import text
from . import standard
class LogWidget(QtWidgets.QFrame):
"""A simple dialog to display command logs."""
channel = Signal(object)
def __init__(self, context, parent=None, output=None, display_usage=True):
QtWidgets.QFrame.__init__(self, parent)
self.output_text = text.VimTextEdit(context, parent=self)
self.highlighter = LogSyntaxHighlighter(self.output_text.document())
if output:
self.set_output(output)
self.main_layout = qtutils.vbox(defs.no_margin, defs.spacing, self.output_text)
self.setLayout(self.main_layout)
self.setFocusProxy(self.output_text)
self.channel.connect(self.append, type=Qt.QueuedConnection)
clear_action = qtutils.add_action(self, N_('Clear'), self.output_text.clear)
self.output_text.menu_actions.append(clear_action)
if display_usage:
self._display_usage()
def _display_usage(self):
"""Show the default usage message"""
self.log(N_('Right-click links to open:'))
self.log(' Documentation: https://git-cola.readthedocs.io/en/latest/')
self.log(
' Keyboard Shortcuts: '
'https://git-cola.gitlab.io/share/doc/git-cola/hotkeys.html\n'
)
def clear(self):
self.output_text.clear()
def set_output(self, output):
self.output_text.set_value(output)
def log_status(self, status, out, err=None):
msg = []
if out:
msg.append(out)
if err:
msg.append(err)
if status:
msg.append(N_('exit code %s') % status)
self.log('\n'.join(msg))
def append(self, msg):
"""Append to the end of the log message"""
if not msg:
return
msg = core.decode(msg)
cursor = self.output_text.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
text_widget = self.output_text
# NOTE: the ': ' colon-SP-SP suffix is for the syntax highlighter
prefix = core.decode(time.strftime('%Y-%m-%d %H:%M:%S: ')) # ISO-8601
for line in msg.split('\n'):
cursor.insertText(prefix + line + '\n')
cursor.movePosition(QtGui.QTextCursor.End)
text_widget.setTextCursor(cursor)
def log(self, msg):
"""Add output to the log window"""
# Funnel through a Qt queued to allow thread-safe logging from
# asynchronous QRunnables, filesystem notification, etc.
self.channel.emit(msg)
class LogSyntaxHighlighter(QtGui.QSyntaxHighlighter):
"""Implements the log syntax highlighting"""
def __init__(self, doc):
QtGui.QSyntaxHighlighter.__init__(self, doc)
palette = QtGui.QPalette()
QPalette = QtGui.QPalette
self.disabled_color = palette.color(QPalette.Disabled, QPalette.Text)
def highlightBlock(self, block_text):
end = block_text.find(': ')
if end > 0:
self.setFormat(0, end + 1, self.disabled_color)
class RemoteMessage(standard.Dialog):
"""Provides a dialog to display remote messages"""
def __init__(self, context, message, parent=None):
standard.Dialog.__init__(self, parent=parent)
self.context = context
self.model = context.model
self.setWindowTitle(N_('Remote Messages'))
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.text = text.VimTextEdit(context, parent=self)
self.text.set_value(message)
# Set a monospace font, as some remote git messages include ASCII art
self.text.setFont(qtutils.default_monospace_font())
self.close_button = qtutils.close_button()
self.close_button.setDefault(True)
self.bottom_layout = qtutils.hbox(
defs.no_margin, defs.button_spacing, qtutils.STRETCH, self.close_button
)
self.main_layout = qtutils.vbox(
defs.no_margin, defs.spacing, self.text, self.bottom_layout
)
self.setLayout(self.main_layout)
qtutils.connect_button(self.close_button, self.close)
self.resize(defs.scale(720), defs.scale(400))
def show_remote_messages(parent, context):
"""Return a closure for the `result` callback from RunTask.start()"""
def show_remote_messages_callback(result):
"""Display the asynchronous "result" when remote tasks complete"""
_, out, err = result
output = '\n\n'.join(x for x in (out, err) if x)
if output:
message = N_('Right-click links to open:') + '\n\n' + output
else:
message = output
# Display a window if the remote sent a message
if message:
view = RemoteMessage(context, message, parent=parent)
view.show()
view.exec_()
return show_remote_messages_callback
| 5,084 | Python | .py | 119 | 34.428571 | 87 | 0.6418 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
97 | cfgactions.py | git-cola_git-cola/cola/widgets/cfgactions.py | import os
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from .. import core
from .. import gitcmds
from .. import icons
from .. import qtutils
from ..i18n import N_
from ..interaction import Interaction
from . import defs
from . import completion
from . import standard
from .text import LineEdit
def install():
Interaction.run_command = staticmethod(run_command)
Interaction.confirm_config_action = staticmethod(confirm_config_action)
def get_config_actions(context):
cfg = context.cfg
return cfg.get_guitool_names_and_shortcuts()
def confirm_config_action(context, name, opts):
dlg = ActionDialog(context, qtutils.active_window(), name, opts)
dlg.show()
if dlg.exec_() != QtWidgets.QDialog.Accepted:
return False
rev = dlg.revision()
if rev:
opts['revision'] = rev
args = dlg.args()
if args:
opts['args'] = args
return True
def run_command(title, command):
"""Show a command widget"""
view = GitCommandWidget(title, qtutils.active_window())
view.set_command(command)
view.show()
view.raise_()
view.run()
view.exec_()
return (view.exitstatus, view.out, view.err)
class GitCommandWidget(standard.Dialog):
"""Text viewer that reads the output of a command synchronously"""
# Keep us in scope otherwise PyQt kills the widget
def __init__(self, title, parent=None):
standard.Dialog.__init__(self, parent)
self.setWindowTitle(title)
if parent is not None:
self.setWindowModality(Qt.ApplicationModal)
# Construct the process
self.proc = QtCore.QProcess(self)
self.exitstatus = 0
self.out = ''
self.err = ''
self.command = []
# Create the text browser
self.output_text = QtWidgets.QTextBrowser(self)
self.output_text.setAcceptDrops(False)
self.output_text.setTabChangesFocus(True)
self.output_text.setUndoRedoEnabled(False)
self.output_text.setReadOnly(True)
self.output_text.setAcceptRichText(False)
# Create abort / close buttons
# Start with abort disabled - will be enabled when the process is run.
self.button_abort = qtutils.create_button(text=N_('Abort'), enabled=False)
self.button_close = qtutils.close_button()
# Put them in a horizontal layout at the bottom.
self.button_box = QtWidgets.QDialogButtonBox(self)
self.button_box.addButton(
self.button_abort, QtWidgets.QDialogButtonBox.RejectRole
)
self.button_box.addButton(
self.button_close, QtWidgets.QDialogButtonBox.AcceptRole
)
# Connect the signals to the process
self.proc.readyReadStandardOutput.connect(self.read_stdout)
self.proc.readyReadStandardError.connect(self.read_stderr)
self.proc.finished.connect(self.proc_finished)
self.proc.stateChanged.connect(self.proc_state_changed)
qtutils.connect_button(self.button_abort, self.abort)
qtutils.connect_button(self.button_close, self.close)
self._layout = qtutils.vbox(
defs.margin, defs.spacing, self.output_text, self.button_box
)
self.setLayout(self._layout)
self.resize(720, 420)
def set_command(self, command):
self.command = command
def run(self):
"""Runs the process"""
self.proc.start(self.command[0], self.command[1:])
def read_stdout(self):
text = self.read_stream(self.proc.readAllStandardOutput)
self.out += text
def read_stderr(self):
text = self.read_stream(self.proc.readAllStandardError)
self.err += text
def read_stream(self, func):
data = func().data()
text = core.decode(data)
self.append_text(text)
return text
def append_text(self, text):
cursor = self.output_text.textCursor()
cursor.movePosition(cursor.End)
cursor.insertText(text)
cursor.movePosition(cursor.End)
self.output_text.setTextCursor(cursor)
def abort(self):
if self.proc.state() != QtCore.QProcess.NotRunning:
# Terminate seems to do nothing in windows
self.proc.terminate()
# Kill the process.
QtCore.QTimer.singleShot(1000, self.proc.kill)
def closeEvent(self, event):
if self.proc.state() != QtCore.QProcess.NotRunning:
# The process is still running, make sure we really want to abort.
title = N_('Abort Action')
msg = N_(
'An action is still running.\n'
'Terminating it could result in data loss.'
)
info_text = N_('Abort the action?')
ok_text = N_('Abort Action')
if Interaction.confirm(
title, msg, info_text, ok_text, default=False, icon=icons.close()
):
self.abort()
event.accept()
else:
event.ignore()
else:
event.accept()
return standard.Dialog.closeEvent(self, event)
def proc_state_changed(self, newstate):
# State of process has changed - change the abort button state.
if newstate == QtCore.QProcess.NotRunning:
self.button_abort.setEnabled(False)
else:
self.button_abort.setEnabled(True)
def proc_finished(self, status):
self.exitstatus = status
class ActionDialog(standard.Dialog):
VALUES = {}
def __init__(self, context, parent, name, opts):
standard.Dialog.__init__(self, parent)
self.context = context
self.action_name = name
self.opts = opts
try:
values = self.VALUES[name]
except KeyError:
values = self.VALUES[name] = {}
self.setWindowModality(Qt.ApplicationModal)
title = opts.get('title')
if title:
self.setWindowTitle(os.path.expandvars(title))
self.prompt = QtWidgets.QLabel()
prompt = opts.get('prompt')
if prompt:
self.prompt.setText(os.path.expandvars(prompt))
self.argslabel = QtWidgets.QLabel()
if 'argprompt' not in opts or opts.get('argprompt') is True:
argprompt = N_('Arguments')
else:
argprompt = opts.get('argprompt')
self.argslabel.setText(argprompt)
self.argstxt = LineEdit()
if self.opts.get('argprompt'):
try:
# Remember the previous value
saved_value = values['argstxt']
self.argstxt.setText(saved_value)
except KeyError:
pass
else:
self.argslabel.setMinimumSize(10, 10)
self.argstxt.setMinimumSize(10, 10)
self.argstxt.hide()
self.argslabel.hide()
revs = (
(N_('Local Branch'), gitcmds.branch_list(context, remote=False)),
(N_('Tracking Branch'), gitcmds.branch_list(context, remote=True)),
(N_('Tag'), gitcmds.tag_list(context)),
)
if 'revprompt' not in opts or opts.get('revprompt') is True:
revprompt = N_('Revision')
else:
revprompt = opts.get('revprompt')
self.revselect = RevisionSelector(context, self, revs)
self.revselect.set_revision_label(revprompt)
if not opts.get('revprompt'):
self.revselect.hide()
# Close/Run buttons
self.closebtn = qtutils.close_button()
self.runbtn = qtutils.create_button(
text=N_('Run'), default=True, icon=icons.ok()
)
self.argslayt = qtutils.hbox(
defs.margin, defs.spacing, self.argslabel, self.argstxt
)
self.btnlayt = qtutils.hbox(
defs.margin, defs.spacing, qtutils.STRETCH, self.closebtn, self.runbtn
)
self.layt = qtutils.vbox(
defs.margin,
defs.spacing,
self.prompt,
self.argslayt,
self.revselect,
self.btnlayt,
)
self.setLayout(self.layt)
self.argstxt.textChanged.connect(self._argstxt_changed)
qtutils.connect_button(self.closebtn, self.reject)
qtutils.connect_button(self.runbtn, self.accept)
# Widen the dialog by default
self.resize(666, self.height())
def revision(self):
return self.revselect.revision()
def args(self):
return self.argstxt.text()
def _argstxt_changed(self, value):
"""Store the argstxt value so that we can remember it between calls"""
self.VALUES[self.action_name]['argstxt'] = value
class RevisionSelector(QtWidgets.QWidget):
def __init__(self, context, parent, revs):
QtWidgets.QWidget.__init__(self, parent)
self.context = context
self._revs = revs
self._revdict = dict(revs)
self._rev_label = QtWidgets.QLabel(self)
self._revision = completion.GitRefLineEdit(context, parent=self)
# Create the radio buttons
radio_btns = []
self._radio_btns = {}
for label, rev_list in self._revs:
radio = qtutils.radio(text=label)
radio.setObjectName(label)
qtutils.connect_button(radio, self._set_revision_list)
radio_btns.append(radio)
self._radio_btns[label] = radio
radio_btns.append(qtutils.STRETCH)
self._rev_list = QtWidgets.QListWidget()
label, rev_list = self._revs[0]
self._radio_btns[label].setChecked(True)
qtutils.set_items(self._rev_list, rev_list)
self._rev_layt = qtutils.hbox(
defs.no_margin, defs.spacing, self._rev_label, self._revision
)
self._radio_layt = qtutils.hbox(defs.margin, defs.spacing, *radio_btns)
self._layt = qtutils.vbox(
defs.no_margin,
defs.spacing,
self._rev_layt,
self._radio_layt,
self._rev_list,
)
self.setLayout(self._layt)
self._rev_list.itemSelectionChanged.connect(self.selection_changed)
def revision(self):
return self._revision.text()
def set_revision_label(self, txt):
self._rev_label.setText(txt)
def _set_revision_list(self):
sender = self.sender().objectName()
revs = self._revdict[sender]
qtutils.set_items(self._rev_list, revs)
def selection_changed(self):
items = self._rev_list.selectedItems()
if not items:
return
self._revision.setText(items[0].text())
| 10,670 | Python | .py | 273 | 29.930403 | 82 | 0.622689 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
98 | standard.py | git-cola_git-cola/cola/widgets/standard.py | from functools import partial
import os
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 qtpy.QtWidgets import QDockWidget
from ..i18n import N_
from ..interaction import Interaction
from ..settings import Settings, mklist
from ..models import prefs
from .. import core
from .. import hotkeys
from .. import icons
from .. import qtcompat
from .. import qtutils
from .. import utils
from . import defs
class WidgetMixin:
"""Mix-in for common utilities and serialization of widget state"""
closed = Signal(QtWidgets.QWidget)
def __init__(self):
self._unmaximized_rect = {}
def center(self):
parent = self.parent()
if parent is None:
return
left = parent.x()
width = parent.width()
center_x = left + width // 2
x = center_x - self.width() // 2
y = parent.y()
self.move(x, y)
def resize_to_desktop(self):
width, height = qtutils.desktop_size()
if utils.is_darwin():
self.resize(width, height)
else:
shown = self.isVisible()
# earlier show() fools Windows focus stealing prevention. The main
# window is blocked for the duration of "git rebase" and we don't
# want to present a blocked window with git-cola-sequence-editor
# hidden somewhere.
self.show()
self.setWindowState(Qt.WindowMaximized)
if not shown:
self.hide()
def name(self):
"""Returns the name of the view class"""
return self.__class__.__name__.lower()
def save_state(self, settings=None):
"""Save tool settings to the ~/.config/git-cola/settings file"""
save = True
sync = True
context = getattr(self, 'context', None)
if context:
cfg = context.cfg
save = cfg.get('cola.savewindowsettings', default=True)
sync = cfg.get('cola.sync', default=True)
if save:
if settings is None:
settings = Settings.read()
settings.save_gui_state(self, sync=sync)
def restore_state(self, settings=None):
"""Read and apply saved tool settings"""
if settings is None:
settings = Settings.read()
state = settings.get_gui_state(self)
if state:
result = self.apply_state(state)
else:
result = False
return result
def apply_state(self, state):
"""Import data for view save/restore"""
width = utils.asint(state.get('width'))
height = utils.asint(state.get('height'))
x = utils.asint(state.get('x'))
y = utils.asint(state.get('y'))
geometry = state.get('geometry', '')
if geometry:
from_base64 = QtCore.QByteArray.fromBase64
result = self.restoreGeometry(from_base64(core.encode(geometry)))
elif width and height:
# Users migrating from older versions won't have 'geometry'.
# They'll be upgraded to the new format on shutdown.
self.resize(width, height)
self.move(x, y)
result = True
else:
result = False
return result
def export_state(self):
"""Exports data for view save/restore"""
state = {}
geometry = self.saveGeometry()
state['geometry'] = geometry.toBase64().data().decode('ascii')
# Until 2020: co-exist with older versions
state['width'] = self.width()
state['height'] = self.height()
state['x'] = self.x()
state['y'] = self.y()
return state
def save_settings(self, settings=None):
"""Save tool state using the specified settings backend"""
return self.save_state(settings=settings)
def closeEvent(self, event):
"""Save settings when the top-level widget is closed"""
self.save_settings()
self.closed.emit(self)
self.Base.closeEvent(self, event)
def init_size(self, parent=None, settings=None, width=0, height=0):
"""Set a tool's initial size"""
if not width:
width = defs.dialog_w
if not height:
height = defs.dialog_h
self.init_state(settings, self.resize_to_parent, parent, width, height)
def init_state(self, settings, callback, *args, **kwargs):
"""Restore saved settings or set the initial location"""
if not self.restore_state(settings=settings):
callback(*args, **kwargs)
self.center()
def resize_to_parent(self, parent, w, h):
"""Set the initial size of the widget"""
width, height = qtutils.default_size(parent, w, h)
self.resize(width, height)
class MainWindowMixin(WidgetMixin):
def __init__(self):
WidgetMixin.__init__(self)
# Dockwidget options
self.dockwidgets = []
self.lock_layout = False
self.widget_version = 0
qtcompat.set_common_dock_options(self)
self.default_state = None
def init_state(self, settings, callback, *args, **kwargs):
"""Save the initial state before calling the parent initializer"""
self.default_state = self.saveState(self.widget_version)
super().init_state(settings, callback, *args, **kwargs)
def export_state(self):
"""Exports data for save/restore"""
state = WidgetMixin.export_state(self)
windowstate = self.saveState(self.widget_version)
state['lock_layout'] = self.lock_layout
state['windowstate'] = windowstate.toBase64().data().decode('ascii')
return state
def save_settings(self, settings=None):
if settings is None:
context = getattr(self, 'context', None)
if context is None:
settings = Settings.read()
else:
settings = context.settings
settings.load()
settings.add_recent(core.getcwd(), prefs.maxrecent(context))
return WidgetMixin.save_settings(self, settings=settings)
def apply_state(self, state):
result = WidgetMixin.apply_state(self, state)
windowstate = state.get('windowstate', '')
if windowstate:
from_base64 = QtCore.QByteArray.fromBase64
result = (
self.restoreState(
from_base64(core.encode(windowstate)), self.widget_version
)
and result
)
else:
result = False
self.lock_layout = state.get('lock_layout', self.lock_layout)
self.update_dockwidget_lock_state()
self.update_dockwidget_tooltips()
return result
def reset_layout(self):
self.restoreState(self.default_state, self.widget_version)
def set_lock_layout(self, lock_layout):
self.lock_layout = lock_layout
self.update_dockwidget_lock_state()
def update_dockwidget_lock_state(self):
if self.lock_layout:
features = QDockWidget.DockWidgetClosable
else:
features = (
QDockWidget.DockWidgetClosable
| QDockWidget.DockWidgetFloatable
| QDockWidget.DockWidgetMovable
)
for widget in self.dockwidgets:
widget.titleBarWidget().update_tooltips()
widget.setFeatures(features)
def update_dockwidget_tooltips(self):
for widget in self.dockwidgets:
widget.titleBarWidget().update_tooltips()
class ListWidget(QtWidgets.QListWidget):
"""QListWidget with vim j/k navigation hotkeys"""
def __init__(self, parent=None):
super().__init__(parent)
self.up_action = qtutils.add_action(
self,
N_('Move Up'),
self.move_up,
hotkeys.MOVE_UP,
hotkeys.MOVE_UP_SECONDARY,
)
self.down_action = qtutils.add_action(
self,
N_('Move Down'),
self.move_down,
hotkeys.MOVE_DOWN,
hotkeys.MOVE_DOWN_SECONDARY,
)
def selected_item(self):
return self.currentItem()
def selected_items(self):
return self.selectedItems()
def move_up(self):
self.move(-1)
def move_down(self):
self.move(1)
def move(self, direction):
item = self.selected_item()
if item:
row = (self.row(item) + direction) % self.count()
elif self.count() > 0:
row = (self.count() + direction) % self.count()
else:
return
new_item = self.item(row)
if new_item:
self.setCurrentItem(new_item)
class TreeMixin:
def __init__(self, widget, Base):
self.widget = widget
self.Base = Base
widget.setAlternatingRowColors(True)
widget.setUniformRowHeights(True)
widget.setAllColumnsShowFocus(True)
widget.setAnimated(True)
widget.setRootIsDecorated(False)
def keyPressEvent(self, event):
"""
Make LeftArrow to work on non-directories.
When LeftArrow is pressed on a file entry or an unexpanded
directory, then move the current index to the parent directory.
This simplifies navigation using the keyboard.
For power-users, we support Vim keybindings ;-P
"""
# Check whether the item is expanded before calling the base class
# keyPressEvent otherwise we end up collapsing and changing the
# current index in one shot, which we don't want to do.
widget = self.widget
index = widget.currentIndex()
was_expanded = widget.isExpanded(index)
was_collapsed = not was_expanded
# Vim keybindings...
event = _create_vim_navigation_key_event(event)
# Read the updated event key to take the mappings into account
key = event.key()
if key == Qt.Key_Up:
idxs = widget.selectedIndexes()
rows = [idx.row() for idx in idxs]
if len(rows) == 1 and rows[0] == 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.
widget.up.emit()
elif key == Qt.Key_Space:
widget.space.emit()
result = self.Base.keyPressEvent(widget, event)
# Let others hook in here before we change the indexes
widget.index_about_to_change.emit()
# Automatically select the first entry when expanding a directory
if key == Qt.Key_Right and was_collapsed and widget.isExpanded(index):
index = widget.moveCursor(widget.MoveDown, event.modifiers())
widget.setCurrentIndex(index)
# Process non-root entries with valid parents only.
elif key == Qt.Key_Left and index.parent().isValid():
# File entries have rowCount() == 0
model = widget.model()
if hasattr(model, 'itemFromIndex'):
item = model.itemFromIndex(index)
if hasattr(item, 'rowCount') and item.rowCount() == 0:
widget.setCurrentIndex(index.parent())
# Otherwise, do this for collapsed directories only
elif was_collapsed:
widget.setCurrentIndex(index.parent())
# If it's a movement key ensure we have a selection
elif key in (Qt.Key_Left, Qt.Key_Up, Qt.Key_Right, Qt.Key_Down):
# Try to select the first item if the model index is invalid
item = self.selected_item()
if item is None or not index.isValid():
index = widget.model().index(0, 0, QtCore.QModelIndex())
if index.isValid():
widget.setCurrentIndex(index)
return result
def item_from_index(self, item):
"""Return a QModelIndex from the provided item"""
if hasattr(self, 'itemFromIndex'):
index = self.itemFromIndex(item)
else:
index = self.model().itemFromIndex()
return index
def items(self):
root = self.widget.invisibleRootItem()
child = root.child
count = root.childCount()
return [child(i) for i in range(count)]
def selected_items(self):
"""Return all selected items"""
widget = self.widget
if hasattr(widget, 'selectedItems'):
return widget.selectedItems()
if hasattr(widget, 'itemFromIndex'):
item_from_index = widget.itemFromIndex
else:
item_from_index = widget.model().itemFromIndex
return [item_from_index(i) for i in widget.selectedIndexes()]
def selected_item(self):
"""Return the first selected item"""
selected_items = self.selected_items()
if not selected_items:
return None
return selected_items[0]
def current_item(self):
item = None
widget = self.widget
if hasattr(widget, 'currentItem'):
item = widget.currentItem()
else:
index = widget.currentIndex()
if index.isValid():
item = widget.model().itemFromIndex(index)
return item
def column_widths(self):
"""Return the tree's column widths"""
widget = self.widget
count = widget.header().count()
return [widget.columnWidth(i) for i in range(count)]
def set_column_widths(self, widths):
"""Set the tree's column widths"""
if widths:
widget = self.widget
count = widget.header().count()
if len(widths) > count:
widths = widths[:count]
for idx, value in enumerate(widths):
widget.setColumnWidth(idx, value)
def _create_vim_navigation_key_event(event):
"""Support minimal Vim-like keybindings by rewriting the QKeyEvents"""
key = event.key()
# Remap 'H' to 'Left'
if key == Qt.Key_H:
event = QtGui.QKeyEvent(event.type(), Qt.Key_Left, event.modifiers())
# Remap 'J' to 'Down'
elif key == Qt.Key_J:
event = QtGui.QKeyEvent(event.type(), Qt.Key_Down, event.modifiers())
# Remap 'K' to 'Up'
elif key == Qt.Key_K:
event = QtGui.QKeyEvent(event.type(), Qt.Key_Up, event.modifiers())
# Remap 'L' to 'Right'
elif key == Qt.Key_L:
event = QtGui.QKeyEvent(event.type(), Qt.Key_Right, event.modifiers())
return event
class DraggableTreeMixin(TreeMixin):
"""A tree widget with internal drag+drop reordering of rows
Expects that the widget provides an `items_moved` signal.
"""
def __init__(self, widget, Base):
super().__init__(widget, Base)
self._inner_drag = False
widget.setAcceptDrops(True)
widget.setSelectionMode(widget.SingleSelection)
widget.setDragEnabled(True)
widget.setDropIndicatorShown(True)
widget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
widget.setSortingEnabled(False)
def dragEnterEvent(self, event):
"""Accept internal drags only"""
widget = self.widget
self.Base.dragEnterEvent(widget, event)
self._inner_drag = event.source() == widget
if self._inner_drag:
event.acceptProposedAction()
else:
event.ignore()
def dragLeaveEvent(self, event):
widget = self.widget
self.Base.dragLeaveEvent(widget, event)
if self._inner_drag:
event.accept()
else:
event.ignore()
self._inner_drag = False
def dropEvent(self, event):
"""Re-select selected items after an internal move"""
if not self._inner_drag:
event.ignore()
return
widget = self.widget
clicked_items = self.selected_items()
event.setDropAction(Qt.MoveAction)
self.Base.dropEvent(widget, event)
if clicked_items:
widget.clearSelection()
for item in clicked_items:
item.setSelected(True)
widget.items_moved.emit(clicked_items)
self._inner_drag = False
event.accept() # must be called after dropEvent()
def mousePressEvent(self, event):
"""Clear the selection when a mouse click hits no item"""
widget = self.widget
clicked_item = widget.itemAt(event.pos())
if clicked_item is None:
widget.clearSelection()
return self.Base.mousePressEvent(widget, event)
class Widget(WidgetMixin, QtWidgets.QWidget):
Base = QtWidgets.QWidget
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
WidgetMixin.__init__(self)
class Dialog(WidgetMixin, QtWidgets.QDialog):
Base = QtWidgets.QDialog
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
WidgetMixin.__init__(self)
# Disable the Help button hint on Windows
if hasattr(Qt, 'WindowContextHelpButtonHint'):
help_hint = Qt.WindowContextHelpButtonHint
flags = self.windowFlags() & ~help_hint
self.setWindowFlags(flags)
def accept(self):
self.save_settings()
self.dispose()
return self.Base.accept(self)
def reject(self):
self.save_settings()
self.dispose()
return self.Base.reject(self)
def dispose(self):
"""Extension method for model de-registration in sub-classes"""
return
def close(self):
"""save_settings() is handled by accept() and reject()"""
self.dispose()
self.Base.close(self)
def closeEvent(self, event):
"""save_settings() is handled by accept() and reject()"""
self.dispose()
self.Base.closeEvent(self, event)
class MainWindow(MainWindowMixin, QtWidgets.QMainWindow):
Base = QtWidgets.QMainWindow
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
MainWindowMixin.__init__(self)
class TreeView(QtWidgets.QTreeView):
Mixin = TreeMixin
up = Signal()
space = Signal()
index_about_to_change = Signal()
def __init__(self, parent=None):
QtWidgets.QTreeView.__init__(self, parent)
self._mixin = self.Mixin(self, QtWidgets.QTreeView)
def keyPressEvent(self, event):
return self._mixin.keyPressEvent(event)
def current_item(self):
return self._mixin.current_item()
def selected_item(self):
return self._mixin.selected_item()
def selected_items(self):
return self._mixin.selected_items()
def items(self):
return self._mixin.items()
def column_widths(self):
return self._mixin.column_widths()
def set_column_widths(self, widths):
return self._mixin.set_column_widths(widths)
class TreeWidget(QtWidgets.QTreeWidget):
Mixin = TreeMixin
up = Signal()
space = Signal()
index_about_to_change = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self._mixin = self.Mixin(self, QtWidgets.QTreeWidget)
def keyPressEvent(self, event):
return self._mixin.keyPressEvent(event)
def current_item(self):
return self._mixin.current_item()
def selected_item(self):
return self._mixin.selected_item()
def selected_items(self):
return self._mixin.selected_items()
def items(self):
return self._mixin.items()
def column_widths(self):
return self._mixin.column_widths()
def set_column_widths(self, widths):
return self._mixin.set_column_widths(widths)
class DraggableTreeWidget(TreeWidget):
Mixin = DraggableTreeMixin
items_moved = Signal(object)
def mousePressEvent(self, event):
return self._mixin.mousePressEvent(event)
def dropEvent(self, event):
return self._mixin.dropEvent(event)
def dragLeaveEvent(self, event):
return self._mixin.dragLeaveEvent(event)
def dragEnterEvent(self, event):
return self._mixin.dragEnterEvent(event)
class ProgressDialog(QtWidgets.QProgressDialog):
"""Custom progress dialog
This dialog ignores the ESC key so that it is not
prematurely closed.
A thread is spawned to animate the progress label text.
"""
def __init__(self, title, label, parent):
QtWidgets.QProgressDialog.__init__(self, parent)
self._parent = parent
if parent is not None:
self.setWindowModality(Qt.WindowModal)
self.animation_thread = ProgressAnimationThread(label, self)
self.animation_thread.updated.connect(self.set_text, type=Qt.QueuedConnection)
self.reset()
self.setRange(0, 0)
self.setMinimumDuration(0)
self.setCancelButton(None)
self.setFont(qtutils.default_monospace_font())
self.set_details(title, label)
def set_details(self, title, label):
"""Update the window title and progress label"""
self.setWindowTitle(title)
self.setLabelText(label + ' ')
self.animation_thread.set_text(label)
def set_text(self, txt):
"""Set the label text"""
self.setLabelText(txt)
def keyPressEvent(self, event):
"""Customize keyPressEvent to remove the ESC key cancel feature"""
if event.key() != Qt.Key_Escape:
super().keyPressEvent(event)
def start(self):
"""Start the animation thread and use a wait cursor"""
self.show()
QtWidgets.QApplication.setOverrideCursor(Qt.WaitCursor)
self.animation_thread.start()
def stop(self):
"""Stop the animation thread and restore the normal cursor"""
self.animation_thread.stop()
self.animation_thread.wait()
QtWidgets.QApplication.restoreOverrideCursor()
self.hide()
class ProgressAnimationThread(QtCore.QThread):
"""Emits a pseudo-animated text stream for progress bars"""
# The updated signal is emitted on each tick.
updated = Signal(object)
def __init__(self, txt, parent, sleep_time=0.1):
QtCore.QThread.__init__(self, parent)
self.running = False
self.txt = txt
self.sleep_time = sleep_time
self.symbols = [
'. ..',
'.. .',
'... ',
' ... ',
' ...',
]
self.idx = -1
def set_text(self, txt):
"""Set the text prefix"""
self.txt = txt
def tick(self):
"""Tick to the next animated text value"""
self.idx = (self.idx + 1) % len(self.symbols)
return self.txt + self.symbols[self.idx]
def stop(self):
"""Stop the animation thread"""
self.running = False
def run(self):
"""Emit ticks until stopped"""
self.running = True
while self.running:
self.updated.emit(self.tick())
time.sleep(self.sleep_time)
class ProgressTickThread(QtCore.QThread):
"""Emits an int stream for progress bars"""
# The updated signal emits progress tick values.
updated = Signal(int)
# The activated signal is emitted when the progress bar is displayed.
activated = Signal()
def __init__(
self,
parent,
maximum,
start_time=1.0,
sleep_time=0.05,
):
QtCore.QThread.__init__(self, parent)
self.running = False
self.sleep_time = sleep_time
self.maximum = maximum
self.start_time = start_time
self.value = 0
self.step = 1
def tick(self):
"""Cycle to the next tick value
Returned values are in the inclusive (0, maximum + 1) range.
"""
self.value = (self.value + self.step) % (self.maximum + 1)
if self.value == self.maximum:
self.step = -1
elif self.value == 0:
self.step = 1
return self.value
def stop(self):
"""Stop the tick thread and reset to the initial state"""
self.running = False
self.value = 0
self.step = 1
def run(self):
"""Start the tick thread
The progress bar will not be activated until after the start_time
interval has elapsed.
"""
initial_time = time.time()
active = False
self.running = True
self.value = 0
self.step = 1
while self.running:
if active:
self.updated.emit(self.tick())
else:
now = time.time()
if self.start_time < (now - initial_time):
active = True
self.activated.emit()
time.sleep(self.sleep_time)
class SpinBox(QtWidgets.QSpinBox):
def __init__(
self, parent=None, value=None, mini=1, maxi=99999, step=0, prefix='', suffix=''
):
QtWidgets.QSpinBox.__init__(self, parent)
self.setPrefix(prefix)
self.setSuffix(suffix)
self.setWrapping(True)
self.setMinimum(mini)
self.setMaximum(maxi)
if step:
self.setSingleStep(step)
if value is not None:
self.setValue(value)
text_width = qtutils.text_width(self.font(), 'MMMMMM')
width = max(self.minimumWidth(), text_width)
self.setMinimumWidth(width)
class DirectoryPathLineEdit(QtWidgets.QWidget):
"""A combined line edit and file browser button"""
def __init__(self, path, parent):
QtWidgets.QWidget.__init__(self, parent)
self.line_edit = QtWidgets.QLineEdit()
self.line_edit.setText(path)
self.browse_button = qtutils.create_button(
tooltip=N_('Select directory'), icon=icons.folder()
)
layout = qtutils.hbox(
defs.no_margin,
defs.spacing,
self.browse_button,
self.line_edit,
)
self.setLayout(layout)
qtutils.connect_button(self.browse_button, self._select_directory)
def set_value(self, value):
"""Set the path value"""
self.line_edit.setText(value)
def value(self):
"""Return the current path value"""
return self.line_edit.text().strip()
def _select_directory(self):
"""Open a file browser and select a directory"""
output_dir = qtutils.opendir_dialog(N_('Select directory'), self.value())
if not output_dir:
return
# Make the directory relative only if it the current directory or
# or subdirectory from the current directory.
current_dir = core.getcwd()
if output_dir == current_dir:
output_dir = '.'
elif output_dir.startswith(current_dir + os.sep):
output_dir = os.path.relpath(output_dir)
self.set_value(output_dir)
def export_header_columns(widget, state):
"""Save QHeaderView column sizes"""
columns = []
header = widget.horizontalHeader()
for idx in range(header.count()):
columns.append(header.sectionSize(idx))
state['columns'] = columns
def apply_header_columns(widget, state):
"""Apply QHeaderView column sizes"""
columns = mklist(state.get('columns', []))
header = widget.horizontalHeader()
if header.stretchLastSection():
# Setting the size will make the section wider than necessary, which
# defeats the purpose of the stretch flag. Skip the last column when
# it's stretchy so that it retains the stretchy behavior.
columns = columns[:-1]
for idx, size in enumerate(columns):
header.resizeSection(idx, size)
class MessageBox(Dialog):
"""Improved QMessageBox replacement
QMessageBox has a lot of usability issues. It sometimes cannot be
resized, and it brings along a lots of annoying properties that we'd have
to workaround, so we use a simple custom dialog instead.
"""
def __init__(
self,
parent=None,
title='',
text='',
info='',
details='',
logo=None,
default=False,
ok_icon=None,
ok_text='',
cancel_text=None,
cancel_icon=None,
):
Dialog.__init__(self, parent=parent)
if parent:
self.setWindowModality(Qt.WindowModal)
if title:
self.setWindowTitle(title)
self.logo_label = QtWidgets.QLabel()
if logo:
# Render into a 1-inch wide pixmap
pixmap = logo.pixmap(defs.large_icon)
self.logo_label.setPixmap(pixmap)
else:
self.logo_label.hide()
self.text_label = QtWidgets.QLabel()
self.text_label.setText(text)
self.info_label = QtWidgets.QLabel()
if info:
self.info_label.setText(info)
else:
self.info_label.hide()
ok_icon = icons.mkicon(ok_icon, icons.ok)
self.button_ok = qtutils.create_button(text=ok_text, icon=ok_icon)
self.button_close = qtutils.close_button(text=cancel_text, icon=cancel_icon)
if ok_text:
self.button_ok.setText(ok_text)
else:
self.button_ok.hide()
self.details_text = QtWidgets.QPlainTextEdit()
self.details_text.setReadOnly(True)
if details:
self.details_text.setFont(qtutils.default_monospace_font())
self.details_text.setPlainText(details)
else:
self.details_text.hide()
self.info_layout = qtutils.vbox(
defs.large_margin,
defs.button_spacing,
self.text_label,
self.info_label,
qtutils.STRETCH,
)
self.top_layout = qtutils.hbox(
defs.large_margin,
defs.button_spacing,
self.logo_label,
self.info_layout,
qtutils.STRETCH,
)
self.buttons_layout = qtutils.hbox(
defs.no_margin,
defs.button_spacing,
qtutils.STRETCH,
self.button_close,
self.button_ok,
)
self.main_layout = qtutils.vbox(
defs.margin,
defs.button_spacing,
self.top_layout,
self.buttons_layout,
self.details_text,
)
self.main_layout.setStretchFactor(self.details_text, 2)
self.setLayout(self.main_layout)
if default:
self.button_ok.setDefault(True)
self.button_ok.setFocus()
else:
self.button_close.setDefault(True)
self.button_close.setFocus()
qtutils.connect_button(self.button_ok, self.accept)
qtutils.connect_button(self.button_close, self.reject)
self.init_state(None, self.set_initial_size)
def set_initial_size(self):
width = defs.dialog_w
height = defs.msgbox_h
self.resize(width, height)
def keyPressEvent(self, event):
"""Handle Y/N hotkeys"""
key = event.key()
if key == Qt.Key_Y:
QtCore.QTimer.singleShot(0, self.accept)
elif key in (Qt.Key_N, Qt.Key_Q):
QtCore.QTimer.singleShot(0, self.reject)
elif key == Qt.Key_Tab:
if self.button_ok.isVisible():
event.accept()
if self.focusWidget() == self.button_close:
self.button_ok.setFocus()
else:
self.button_close.setFocus()
return
Dialog.keyPressEvent(self, event)
def run(self):
self.show()
return self.exec_()
def apply_state(self, state):
"""Imports data for view save/restore"""
desktop_width, desktop_height = qtutils.desktop_size()
width = min(desktop_width, utils.asint(state.get('width')))
height = min(desktop_height, utils.asint(state.get('height')))
x = min(desktop_width, utils.asint(state.get('x')))
y = min(desktop_height, utils.asint(state.get('y')))
result = False
if width and height:
self.resize(width, height)
self.move(x, y)
result = True
return result
def export_state(self):
"""Exports data for view save/restore"""
desktop_width, desktop_height = qtutils.desktop_size()
state = {}
state['width'] = min(desktop_width, self.width())
state['height'] = min(desktop_height, self.height())
state['x'] = min(desktop_width, self.x())
state['y'] = min(desktop_height, self.y())
return state
def confirm(
title,
text,
informative_text,
ok_text,
icon=None,
default=True,
cancel_text=None,
cancel_icon=None,
):
"""Confirm that an action should take place"""
cancel_text = cancel_text or N_('Cancel')
logo = icons.from_style(QtWidgets.QStyle.SP_MessageBoxQuestion)
mbox = MessageBox(
parent=qtutils.active_window(),
title=title,
text=text,
info=informative_text,
ok_text=ok_text,
ok_icon=icon,
cancel_text=cancel_text,
cancel_icon=cancel_icon,
logo=logo,
default=default,
)
return mbox.run() == mbox.Accepted
def critical(title, message=None, details=None):
"""Show a warning with the provided title and message."""
if message is None:
message = title
logo = icons.from_style(QtWidgets.QStyle.SP_MessageBoxCritical)
mbox = MessageBox(
parent=qtutils.active_window(),
title=title,
text=message,
details=details,
logo=logo,
)
mbox.run()
def command_error(title, cmd, status, out, err):
"""Report an error message about a failed command"""
details = Interaction.format_out_err(out, err)
message = Interaction.format_command_status(cmd, status)
critical(title, message=message, details=details)
def information(title, message=None, details=None, informative_text=None):
"""Show information with the provided title and message."""
if message is None:
message = title
mbox = MessageBox(
parent=qtutils.active_window(),
title=title,
text=message,
info=informative_text,
details=details,
logo=icons.cola(),
)
mbox.run()
def progress(title, text, parent):
"""Create a new ProgressDialog"""
return ProgressDialog(title, text, parent)
class ProgressBar(QtWidgets.QProgressBar):
"""An indeterminate progress bar with animated scrolling"""
def __init__(self, parent, maximum, hide=(), disable=(), visible=False):
super().__init__(parent)
self.setTextVisible(False)
self.setMaximum(maximum)
if not visible:
self.setVisible(False)
self.progress_thread = ProgressTickThread(self, maximum)
self.progress_thread.updated.connect(self.setValue, type=Qt.QueuedConnection)
self.progress_thread.activated.connect(self.activate, type=Qt.QueuedConnection)
self._widgets_to_hide = hide
self._widgets_to_disable = disable
def start(self):
"""Start the progress tick thread"""
QtWidgets.QApplication.setOverrideCursor(Qt.WaitCursor)
for widget in self._widgets_to_disable:
widget.setEnabled(False)
self.progress_thread.start()
def activate(self):
"""Hide widgets and display the progress bar"""
for widget in self._widgets_to_hide:
widget.hide()
self.show()
def stop(self):
"""Stop the progress tick thread, re-enable and display widgets"""
self.progress_thread.stop()
self.progress_thread.wait()
for widget in self._widgets_to_disable:
widget.setEnabled(True)
self.hide()
for widget in self._widgets_to_hide:
widget.show()
QtWidgets.QApplication.restoreOverrideCursor()
def progress_bar(parent, maximum=10, hide=(), disable=()):
"""Return a text-less progress bar"""
widget = ProgressBar(parent, maximum, hide=hide, disable=disable)
return widget
def question(title, text, default=True, logo=None):
"""Launches a QMessageBox question with the provided title and message.
Passing "default=False" will make "No" the default choice."""
parent = qtutils.active_window()
if logo is None:
logo = icons.from_style(QtWidgets.QStyle.SP_MessageBoxQuestion)
msgbox = MessageBox(
parent=parent,
title=title,
text=text,
default=default,
logo=logo,
ok_text=N_('Yes'),
cancel_text=N_('No'),
)
return msgbox.run() == msgbox.Accepted
def save_as(filename, title):
return qtutils.save_as(filename, title=title)
def async_command(title, cmd, runtask):
task = qtutils.SimpleTask(partial(core.run_command, cmd))
task.connect(partial(async_command_result, title, cmd))
runtask.start(task)
def async_command_result(title, cmd, result):
status, out, err = result
cmd_string = core.list2cmdline(cmd)
Interaction.command(title, cmd_string, status, out, err)
def install():
"""Install the GUI-model interaction hooks"""
Interaction.critical = staticmethod(critical)
Interaction.confirm = staticmethod(confirm)
Interaction.question = staticmethod(question)
Interaction.information = staticmethod(information)
Interaction.command_error = staticmethod(command_error)
Interaction.save_as = staticmethod(save_as)
Interaction.async_command = staticmethod(async_command)
| 37,781 | Python | .py | 984 | 29.448171 | 87 | 0.617627 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |
99 | imageview.py | git-cola_git-cola/cola/widgets/imageview.py | # Copyright (c) 2018-2024 David Aguilar <[email protected]>
#
# Git Cola is GPL licensed, but this file has a more permissive license.
# This file is dual-licensed Git Cola GPL + pyqimageview MIT.
# imageview.py was originally based on the pyqimageview:
# https://github.com/nevion/pyqimageview/
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Jason Newton <[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.
import argparse
import os
import sys
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
try:
import numpy as np
have_numpy = True
except ImportError:
have_numpy = False
from .. import qtcompat
main_loop_type = 'qt'
def clamp(x, lo, hi):
return max(min(x, hi), lo)
class ImageView(QtWidgets.QGraphicsView):
image_changed = Signal()
def __init__(self, parent=None):
super().__init__(parent)
scene = QtWidgets.QGraphicsScene(self)
self.graphics_pixmap = QtWidgets.QGraphicsPixmapItem()
scene.addItem(self.graphics_pixmap)
self.setScene(scene)
self.zoom_factor = 1.125
self.rubberband = None
self.panning = False
self.first_show_occured = False
self.last_scene_roi = None
self.start_drag = QtCore.QPoint()
self.checkerboard = None
CHECK_MEDIUM = 8
CHECK_GRAY = 0x80
CHECK_LIGHT = 0xCC
check_pattern = QtGui.QImage(
CHECK_MEDIUM * 2, CHECK_MEDIUM * 2, QtGui.QImage.Format_RGB888
)
color_gray = QtGui.QColor(CHECK_GRAY, CHECK_GRAY, CHECK_GRAY)
color_light = QtGui.QColor(CHECK_LIGHT, CHECK_LIGHT, CHECK_LIGHT)
painter = QtGui.QPainter(check_pattern)
painter.fillRect(0, 0, CHECK_MEDIUM, CHECK_MEDIUM, color_gray)
painter.fillRect(
CHECK_MEDIUM, CHECK_MEDIUM, CHECK_MEDIUM, CHECK_MEDIUM, color_gray
)
painter.fillRect(0, CHECK_MEDIUM, CHECK_MEDIUM, CHECK_MEDIUM, color_light)
painter.fillRect(CHECK_MEDIUM, 0, CHECK_MEDIUM, CHECK_MEDIUM, color_light)
self.check_pattern = check_pattern
self.check_brush = QtGui.QBrush(check_pattern)
def load(self, filename):
image = QtGui.QImage()
image.load(filename)
ok = not image.isNull()
if ok:
self.pixmap = image
return ok
@property
def pixmap(self):
return self.graphics_pixmap.pixmap()
@pixmap.setter
def pixmap(self, image, image_format=None):
pixmap = None
if have_numpy and isinstance(image, np.ndarray):
if image.ndim == 3:
if image.shape[2] == 3:
if image_format is None:
image_format = QtGui.QImage.Format_RGB888
q_image = QtGui.QImage(
image.data, image.shape[1], image.shape[0], image_format
)
pixmap = QtGui.QPixmap.fromImage(q_image)
elif image.shape[2] == 4:
if image_format is None:
image_format = QtGui.QImage.Format_RGB32
q_image = QtGui.QImage(
image.data, image.shape[1], image.shape[0], image_format
)
pixmap = QtGui.QPixmap.fromImage(q_image)
else:
raise TypeError(image)
elif image.ndim == 2:
if image_format is None:
image_format = QtGui.QImage.Format_RGB888
q_image = QtGui.QImage(
image.data, image.shape[1], image.shape[0], image_format
)
pixmap = QtGui.QPixmap.fromImage(q_image)
else:
raise ValueError(image)
elif isinstance(image, QtGui.QImage):
pixmap = QtGui.QPixmap.fromImage(image)
elif isinstance(image, QtGui.QPixmap):
pixmap = image
else:
raise TypeError(image)
if pixmap.hasAlpha():
checkerboard = QtGui.QImage(
pixmap.width(), pixmap.height(), QtGui.QImage.Format_ARGB32
)
self.checkerboard = checkerboard
painter = QtGui.QPainter(checkerboard)
painter.fillRect(checkerboard.rect(), self.check_brush)
painter.drawPixmap(0, 0, pixmap)
pixmap = QtGui.QPixmap.fromImage(checkerboard)
self.graphics_pixmap.setPixmap(pixmap)
self.update_scene_rect()
self.fitInView(self.image_scene_rect, flags=Qt.KeepAspectRatio)
self.graphics_pixmap.update()
self.image_changed.emit()
# image property alias
@property
def image(self):
return self.pixmap
@image.setter
def image(self, image):
self.pixmap = image
def update_scene_rect(self):
pixmap = self.pixmap
self.setSceneRect(
QtCore.QRectF(
QtCore.QPointF(0, 0), QtCore.QPointF(pixmap.width(), pixmap.height())
)
)
@property
def image_scene_rect(self):
return QtCore.QRectF(
self.graphics_pixmap.pos(), QtCore.QSizeF(self.pixmap.size())
)
def resizeEvent(self, event):
super().resizeEvent(event)
self.update_scene_rect()
event.accept()
self.fitInView(self.last_scene_roi, Qt.KeepAspectRatio)
self.update()
def zoomROICentered(self, p, zoom_level_delta):
roi = self.current_scene_ROI
if not roi:
return
roi_dims = QtCore.QPointF(roi.width(), roi.height())
roi_scalef = 1
if zoom_level_delta > 0:
roi_scalef = 1.0 / self.zoom_factor
elif zoom_level_delta < 0:
roi_scalef = self.zoom_factor
nroi_dims = roi_dims * roi_scalef
nroi_dims.setX(max(nroi_dims.x(), 1))
nroi_dims.setY(max(nroi_dims.y(), 1))
nroi_center = p
nroi_dimsh = nroi_dims / 2.0
nroi_topleft = nroi_center - nroi_dimsh
nroi = QtCore.QRectF(
nroi_topleft.x(), nroi_topleft.y(), nroi_dims.x(), nroi_dims.y()
)
self.fitInView(nroi, Qt.KeepAspectRatio)
self.update()
def zoomROITo(self, p, zoom_level_delta):
roi = self.current_scene_ROI
if not roi:
return
roi_dims = QtCore.QPointF(roi.width(), roi.height())
roi_topleft = roi.topLeft()
roi_scalef = 1.0
if zoom_level_delta > 0:
roi_scalef = 1.0 / self.zoom_factor
elif zoom_level_delta < 0:
roi_scalef = self.zoom_factor
nroi_dims = roi_dims * roi_scalef
nroi_dims.setX(max(nroi_dims.x(), 1.0))
nroi_dims.setY(max(nroi_dims.y(), 1.0))
prel_scaled_x = (p.x() - roi_topleft.x()) / roi_dims.x()
prel_scaled_y = (p.y() - roi_topleft.y()) / roi_dims.y()
nroi_topleft_x = p.x() - prel_scaled_x * nroi_dims.x()
nroi_topleft_y = p.y() - prel_scaled_y * nroi_dims.y()
nroi = QtCore.QRectF(
nroi_topleft_x, nroi_topleft_y, nroi_dims.x(), nroi_dims.y()
)
self.fitInView(nroi, Qt.KeepAspectRatio)
self.update()
def _scene_ROI(self, geometry):
return QtCore.QRectF(
self.mapToScene(geometry.topLeft()), self.mapToScene(geometry.bottomRight())
)
@property
def current_scene_ROI(self):
return self.last_scene_roi
def mousePressEvent(self, event):
super().mousePressEvent(event)
button = event.button()
modifier = event.modifiers()
# pan
if modifier == Qt.ControlModifier and button == Qt.LeftButton:
self.start_drag = event.pos()
self.panning = True
# initiate/show ROI selection
if modifier == Qt.ShiftModifier and button == Qt.LeftButton:
self.start_drag = event.pos()
if self.rubberband is None:
self.rubberband = QtWidgets.QRubberBand(
QtWidgets.QRubberBand.Rectangle, self.viewport()
)
self.rubberband.setGeometry(QtCore.QRect(self.start_drag, QtCore.QSize()))
self.rubberband.show()
def mouseMoveEvent(self, event):
super().mouseMoveEvent(event)
# update selection display
if self.rubberband is not None:
self.rubberband.setGeometry(
QtCore.QRect(self.start_drag, event.pos()).normalized()
)
if self.panning:
end_drag = event.pos()
pan_vector = end_drag - self.start_drag
scene2view = self.transform()
# skip shear
sx = scene2view.m11()
sy = scene2view.m22()
scene_pan_x = pan_vector.x() / sx
scene_pan_y = pan_vector.y() / sy
scene_pan_vector = QtCore.QPointF(scene_pan_x, scene_pan_y)
roi = self.current_scene_ROI
top_left = roi.topLeft()
new_top_left = top_left - scene_pan_vector
scene_rect = self.sceneRect()
new_top_left.setX(
clamp(new_top_left.x(), scene_rect.left(), scene_rect.right())
)
new_top_left.setY(
clamp(new_top_left.y(), scene_rect.top(), scene_rect.bottom())
)
nroi = QtCore.QRectF(new_top_left, roi.size())
self.fitInView(nroi, Qt.KeepAspectRatio)
self.start_drag = end_drag
self.update()
def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
# consume rubber band selection
if self.rubberband is not None:
self.rubberband.hide()
# set view to ROI
rect = self.rubberband.geometry().normalized()
if rect.width() > 5 and rect.height() > 5:
roi = QtCore.QRectF(
self.mapToScene(rect.topLeft()), self.mapToScene(rect.bottomRight())
)
self.fitInView(roi, Qt.KeepAspectRatio)
self.rubberband = None
if self.panning:
self.panning = False
self.update()
def wheelEvent(self, event):
delta = qtcompat.wheel_delta(event)
# adjust zoom
if abs(delta) > 0:
scene_pos = self.mapToScene(event.pos())
if delta >= 0:
sign = 1
else:
sign = -1
self.zoomROITo(scene_pos, sign)
def reset(self):
self.update_scene_rect()
self.fitInView(self.image_scene_rect, flags=Qt.KeepAspectRatio)
self.update()
# override arbitrary and unwanted margins:
# https://bugreports.qt.io/browse/QTBUG-42331 - based on QT sources
def fitInView(self, rect, flags=Qt.IgnoreAspectRatio):
if self.scene() is None or not rect or rect.isNull():
return
self.last_scene_roi = rect
unity = self.transform().mapRect(QtCore.QRectF(0.0, 0.0, 1.0, 1.0))
self.scale(1.0 / unity.width(), 1.0 / unity.height())
viewrect = self.viewport().rect()
scene_rect = self.transform().mapRect(rect)
xratio = viewrect.width() / scene_rect.width()
yratio = viewrect.height() / scene_rect.height()
if flags == Qt.KeepAspectRatio:
xratio = yratio = min(xratio, yratio)
elif flags == Qt.KeepAspectRatioByExpanding:
xratio = yratio = max(xratio, yratio)
self.scale(xratio, yratio)
self.centerOn(rect.center())
class AppImageView(ImageView):
def __init__(self, parent=None):
ImageView.__init__(self, parent=parent)
self.main_widget = None
def mousePressEvent(self, event):
ImageView.mousePressEvent(self, event)
def mouseMoveEvent(self, event):
ImageView.mouseMoveEvent(self, event)
pos = event.pos()
scene_pos = self.mapToScene(pos)
msg = 'ui: %d, %d image: %d, %d' % (
pos.y(),
pos.x(),
int(scene_pos.y()),
int(scene_pos.x()),
)
self.main_widget.statusBar().showMessage(msg)
class ImageViewerWindow(QtWidgets.QMainWindow):
def __init__(self, image, input_path):
QtWidgets.QMainWindow.__init__(self)
self.image = image
self.input_path = input_path
self.image_view = AppImageView(parent=self)
self.image_view.main_widget = self
self.statusBar().showMessage('')
padding = self.frameGeometry().size() - self.geometry().size()
self.resize(image.size() + padding)
central = QtWidgets.QWidget(self)
self.vbox = QtWidgets.QVBoxLayout(central)
self.vbox.setContentsMargins(0, 0, 0, 0)
self.setCentralWidget(central)
self.layout().setContentsMargins(0, 0, 0, 0)
Expanding = QtWidgets.QSizePolicy.Expanding
height_for_width = self.image_view.sizePolicy().hasHeightForWidth()
policy = QtWidgets.QSizePolicy(Expanding, Expanding)
policy.setHorizontalStretch(1)
policy.setVerticalStretch(1)
policy.setHeightForWidth(height_for_width)
self.image_view.setSizePolicy(policy)
self.image_view.setMouseTracking(True)
self.image_view.setFocusPolicy(Qt.NoFocus)
self.image_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.image_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.vbox.addWidget(self.image_view)
screen = QtWidgets.QDesktopWidget().screenGeometry(self)
size = self.geometry()
self.move(
(screen.width() - size.width()) // 4, (screen.height() - size.height()) // 4
)
self.update_view()
self.image_view.reset()
def hideEvent(self, _event):
QtWidgets.QMainWindow.hide(self)
def update_view(self):
self.image_view.image = self.image
self.setWindowTitle(self.make_window_title())
def make_window_title(self):
return os.path.basename(self.input_path)
def keyPressEvent(self, event):
key = event.key()
global main_loop_type
if key == Qt.Key_Escape:
if main_loop_type == 'qt':
QtWidgets.QApplication.quit()
elif main_loop_type == 'ipython':
self.hide()
# import IPython
# IPython.get_ipython().ask_exit()
def sigint_handler(*args):
"""Handler for the SIGINT signal."""
sys.stderr.write('\r')
QtWidgets.QApplication.quit()
def main():
parser = argparse.ArgumentParser(description='image viewer')
parser.add_argument('image', help='path to the image')
opts = parser.parse_args()
input_image = opts.image
image = QtGui.QImage()
image.load(input_image)
app = QtWidgets.QApplication(sys.argv)
try:
import signal
signal.signal(signal.SIGINT, sigint_handler)
except ImportError:
pass
window = ImageViewerWindow(image, input_image)
window.show()
app.exec_()
if __name__ == '__main__':
main()
| 16,155 | Python | .py | 399 | 31.025063 | 88 | 0.611554 | git-cola/git-cola | 2,239 | 455 | 69 | GPL-2.0 | 9/5/2024, 5:06:50 PM (Europe/Amsterdam) |