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) |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 133