Example #1
0
    def test_diff_that_empties_file(self):
        fixture_path = helper.fixture('diff-empty.txt')
        parser = DiffParser('filename', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(hunks[0].lines[0],
                '@@ -1,2 +0,0 @@')
        self.assertEqual(hunks[-1].lines[-1],
                '-second')
        self.assertEqual(hunks[0].old_start, 1)
        self.assertEqual(hunks[0].old_count, 2)
        self.assertEqual(hunks[0].new_start, 0)
        self.assertEqual(hunks[0].new_count, 0)
        self.assertEqual(parser.generate_patch(1, 1),
                         '--- a/filename\n'
                         '+++ b/filename\n'
                         '@@ -1,2 +1 @@\n'
                         '-first\n'
                         ' second\n')
        self.assertEqual(parser.generate_patch(0, 2),
                         '--- a/filename\n'
                         '+++ b/filename\n'
                         '@@ -1,2 +0,0 @@\n'
                         '-first\n'
                         '-second\n')
Example #2
0
def test_diff():
    fixture_path = helper.fixture('diff.txt')
    parser = diffparse.DiffParser('cola/diffparse.py', core.read(fixture_path))
    hunks = parser.hunks

    assert len(hunks) == 3
    assert hunks[0].first_line_idx == 0
    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 hunks[1].first_line_idx == 23
    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 hunks[2].first_line_idx == 41
    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')
Example #3
0
    def test_diff_that_empties_file(self):
        fixture_path = helper.fixture('diff-empty.txt')
        parser = DiffParser('filename', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(hunks[0].lines[0],
                '@@ -1,2 +0,0 @@')
        self.assertEqual(hunks[-1].lines[-1],
                '-second')
        self.assertEqual(hunks[0].old_start, 1)
        self.assertEqual(hunks[0].old_count, 2)
        self.assertEqual(hunks[0].new_start, 0)
        self.assertEqual(hunks[0].new_count, 0)
        self.assertEqual(parser.generate_patch(1, 1),
                         '--- a/filename\n'
                         '+++ b/filename\n'
                         '@@ -1,2 +1 @@\n'
                         '-first\n'
                         ' second\n')
        self.assertEqual(parser.generate_patch(0, 2),
                         '--- a/filename\n'
                         '+++ b/filename\n'
                         '@@ -1,2 +0,0 @@\n'
                         '-first\n'
                         '-second\n')
Example #4
0
 def test_core_encode(self):
     """Test the core.encode function
     """
     filename = helper.fixture('unicode.txt')
     expect = core.encode('unicøde')
     actual = core.encode(core.read(filename).strip())
     self.assertEqual(expect, actual)
Example #5
0
def show_shortcuts():
    try:
        from PyQt4 import QtWebKit
    except ImportError:
        # redhat disabled QtWebKit in their qt build but don't punish the
        # users
        qtutils.critical(
            N_('This PyQt4 does not include QtWebKit.\n'
               'The keyboard shortcuts feature is unavailable.'))
        return

    try:
        html = show_shortcuts.html
    except AttributeError:
        hotkeys_html = resources.doc(N_('hotkeys.html'))
        html = show_shortcuts.html = core.read(hotkeys_html)

    try:
        widget = show_shortcuts.widget
    except AttributeError:
        parent = qtutils.active_window()
        widget = show_shortcuts.widget = QtGui.QDialog(parent)
        widget.setWindowModality(Qt.WindowModal)
        widget.setWindowTitle(N_('Shortcuts'))

        web = QtWebKit.QWebView(parent)
        web.setHtml(html)

        layout = qtutils.hbox(defs.no_margin, defs.spacing, web)
        widget.setLayout(layout)
        widget.resize(800, min(parent.height(), 600))
        qtutils.add_action(widget, N_('Close'), widget.accept,
                           hotkeys.QUESTION, *hotkeys.ACCEPT)
    widget.show()
    return widget
Example #6
0
 def do(self):
     path = self.path
     if not path or not core.isfile(path):
         raise UsageError(N_('Error: Cannot find commit template'),
                          N_('%s: No such file or directory.') % path)
     self.model.set_directory(os.path.dirname(path))
     self.model.set_commitmsg(core.read(path))
Example #7
0
    def test_diff_at_start(self):
        fixture_path = helper.fixture('diff-start.txt')
        parser = diffparse.DiffParser('foo bar/a', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(hunks[0].lines[0], '@@ -1 +1,4 @@\n')
        self.assertEqual(hunks[-1].lines[-1], '+c\n')
        self.assertEqual(hunks[0].old_start, 1)
        self.assertEqual(hunks[0].old_count, 1)
        self.assertEqual(hunks[0].new_start, 1)
        self.assertEqual(hunks[0].new_count, 4)
        self.assertEqual(
            parser.generate_patch(1, 3), '--- a/foo bar/a\n'
            '+++ b/foo bar/a\n'
            '@@ -1 +1,3 @@\n'
            ' bar\n'
            '+a\n'
            '+b\n')
        self.assertEqual(
            parser.generate_patch(0, 4), '--- a/foo bar/a\n'
            '+++ b/foo bar/a\n'
            '@@ -1 +1,4 @@\n'
            ' bar\n'
            '+a\n'
            '+b\n'
            '+c\n')
Example #8
0
 def do(self):
     path = self.path
     if not path or not core.isfile(path):
         raise UsageError(N_('Error: Cannot find commit template'),
                          N_('%s: No such file or directory.') % path)
     self.model.set_directory(os.path.dirname(path))
     self.model.set_commitmsg(core.read(path))
Example #9
0
 def test_core_encode(self):
     """Test the core.encode function
     """
     filename = helper.fixture('unicode.txt')
     expect = core.encode('unicøde')
     actual = core.encode(core.read(filename).strip())
     self.assertEqual(expect, actual)
Example #10
0
def show_shortcuts():
    try:
        from PyQt4 import QtWebKit
    except ImportError:
        # redhat disabled QtWebKit in their qt build but don't punish the
        # users
        qtutils.critical(N_('This PyQt4 does not include QtWebKit.\n'
                            'The keyboard shortcuts feature is unavailable.'))
        return

    try:
        html = show_shortcuts.html
    except AttributeError:
        hotkeys_html = resources.doc(N_('hotkeys.html'))
        html = show_shortcuts.html = core.read(hotkeys_html)

    try:
        widget = show_shortcuts.widget
    except AttributeError:
        parent = qtutils.active_window()
        widget = show_shortcuts.widget = QtGui.QDialog(parent)
        widget.setWindowModality(Qt.WindowModal)
        widget.setWindowTitle(N_('Shortcuts'))

        web = QtWebKit.QWebView(parent)
        web.setHtml(html)

        layout = qtutils.hbox(defs.no_margin, defs.spacing, web)
        widget.setLayout(layout)
        widget.resize(800, min(parent.height(), 600))
        qtutils.add_action(widget, N_('Close'), widget.accept,
                           hotkeys.QUESTION, *hotkeys.ACCEPT)
    widget.show()
    return widget
Example #11
0
    def test_diff_at_start(self):
        fixture_path = helper.fixture('diff-start.txt')
        parser = DiffParser('foo bar/a', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(hunks[0].lines[0], '@@ -1 +1,4 @@')
        self.assertEqual(hunks[-1].lines[-1], '+c')
        self.assertEqual(hunks[0].old_start, 1)
        self.assertEqual(hunks[0].old_count, 1)
        self.assertEqual(hunks[0].new_start, 1)
        self.assertEqual(hunks[0].new_count, 4)
        self.assertEqual(parser.generate_patch(1, 3),
                         '--- a/foo bar/a\n'
                         '+++ b/foo bar/a\n'
                         '@@ -1 +1,3 @@\n'
                         ' bar\n'
                         '+a\n'
                         '+b\n')
        self.assertEqual(parser.generate_patch(0, 4),
                         '--- a/foo bar/a\n'
                         '+++ b/foo bar/a\n'
                         '@@ -1 +1,4 @@\n'
                         ' bar\n'
                         '+a\n'
                         '+b\n'
                         '+c\n')
Example #12
0
 def test_core_encode(self):
     """Test the core.encode function
     """
     filename = helper.fixture('unicode.txt')
     fh = open(filename)
     content = core.read(fh).strip()
     fh.close()
     self.assertEqual(content, core.encode(u'unicøde'))
Example #13
0
 def test_core_encode(self):
     """Test the core.encode function
     """
     filename = helper.fixture("unicode.txt")
     fh = open(filename)
     content = core.read(fh).strip()
     fh.close()
     self.assertEqual(content, core.encode(u"unicøde"))
Example #14
0
def read_git_file(path):
    if path is None:
        return None
    if is_git_file(path):
        data = core.read(path).strip()
        if data.startswith('gitdir: '):
            return data[len('gitdir: '):]
    return None
Example #15
0
def read_git_file(path):
    if path is None:
        return None
    if is_git_file(path):
        data = core.read(path).strip()
        if data.startswith('gitdir: '):
            return data[len('gitdir: '):]
    return None
Example #16
0
def read_git_file(f):
    if f is None:
        return None
    if is_git_file(f):
        fh = open(f)
        data = core.decode(core.read(fh)).rstrip()
        fh.close()
        if data.startswith("gitdir: "):
            return core.decode(data[len("gitdir: ") :])
    return None
Example #17
0
    def diff_text_for(self, filename):
        size = _config.get('cola.readsize', 1024 * 2)
        try:
            result = core.read(filename, size=size)
        except:
            result = ''

        if len(result) == size:
            result += '...'
        return result
Example #18
0
    def diff_text_for(self, filename):
        size = _config.get('cola.readsize', 1024 * 2)
        try:
            result = core.read(filename, size=size)
        except:
            result = ''

        if len(result) == size:
            result += '...'
        return result
Example #19
0
def read_git_file(f):
    if f is None:
        return None
    if is_git_file(f):
        fh = open(f)
        data = core.decode(core.read(fh)).rstrip()
        fh.close()
        if data.startswith('gitdir: '):
            return core.decode(data[len('gitdir: '):])
    return None
Example #20
0
    def diff_text_for(self, filename):
        cfg = gitcfg.current()
        size = cfg.get("cola.readsize", 1024 * 2)
        try:
            result = core.read(filename, size=size, encoding="utf-8", errors="ignore")
        except:
            result = ""

        if len(result) == size:
            result += "..."
        return result
Example #21
0
def _install_custom_language():
    """Allow a custom language to be set in ~/.config/git-cola/language"""
    lang_file = resources.config_home('language')
    if not core.exists(lang_file):
        return
    try:
        lang = core.read(lang_file).strip()
    except:
        return
    if lang:
        compat.setenv('LANGUAGE', lang)
Example #22
0
    def diff_text_for(self, filename):
        cfg = gitcfg.current()
        size = cfg.get('cola.readsize', 1024 * 2)
        try:
            result = core.read(filename, size=size)
        except:
            result = ''

        if len(result) == size:
            result += '...'
        return result
Example #23
0
    def diff_text_for(self, filename):
        cfg = gitcfg.current()
        size = cfg.get('cola.readsize', 1024 * 2)
        try:
            result = core.read(filename, size=size)
        except:
            result = ''

        if len(result) == size:
            result += '...'
        return result
Example #24
0
 def do(self):
     if not self.filenames:
         return
     new_additions = '\n'.join(self.filenames) + '\n'
     for_status = new_additions
     if core.exists('.gitignore'):
         current_list = core.read('.gitignore')
         new_additions = current_list.rstrip() + '\n' + new_additions
     core.write('.gitignore', new_additions)
     Interaction.log_status(0, 'Added to .gitignore:\n%s' % for_status, '')
     self.model.update_file_status()
Example #25
0
 def do(self):
     if not self.filenames:
         return
     new_additions = '\n'.join(self.filenames) + '\n'
     for_status = new_additions
     if core.exists('.gitignore'):
         current_list = core.read('.gitignore')
         new_additions = current_list.rstrip() + '\n' + new_additions
     core.write('.gitignore', new_additions)
     Interaction.log_status(0, 'Added to .gitignore:\n%s' % for_status, '')
     self.model.update_file_status()
Example #26
0
    def test_diff(self):
        fixture_path = helper.fixture('diff.txt')
        parser = diffparse.DiffParser(
            'cola/diffparse.py', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(len(hunks), 3)
        self.assertEqual(hunks[0].first_line_idx, 0)
        self.assertEqual(len(hunks[0].lines), 23)
        self.assertEqual(
            hunks[0].lines[0],
            '@@ -6,10 +6,21 @@ from cola import gitcmds\n')
        self.assertEqual(
            hunks[0].lines[1],
            ' from cola import gitcfg\n')
        self.assertEqual(hunks[0].lines[2], ' \n')
        self.assertEqual(hunks[0].lines[3], ' \n')
        self.assertEqual(hunks[0].lines[4], '+class DiffSource(object):\n')
        self.assertEqual(
            hunks[0].lines[-1],
            r"         self._header_start_re = re.compile('^@@ -(\d+)"
            r" \+(\d+),(\d+) @@.*')"
            '\n')

        self.assertEqual(hunks[1].first_line_idx, 23)
        self.assertEqual(len(hunks[1].lines), 18)
        self.assertEqual(
            hunks[1].lines[0],
            '@@ -29,13 +40,11 @@ class DiffParser(object):\n')
        self.assertEqual(
            hunks[1].lines[1],
            '         self.diff_sel = []\n')
        self.assertEqual(
            hunks[1].lines[2],
            '         self.selected = []\n')
        self.assertEqual(
            hunks[1].lines[3],
            '         self.filename = filename\n')
        self.assertEqual(
            hunks[1].lines[4],
            '+        self.diff_source = diff_source or DiffSource()\n')
        self.assertEqual(
            hunks[1].lines[-1],
            '         self.header = header\n')

        self.assertEqual(hunks[2].first_line_idx, 41)
        self.assertEqual(len(hunks[2].lines), 16)
        self.assertEqual(
            hunks[2].lines[0],
            '@@ -43,11 +52,10 @@ class DiffParser(object):\n')
        self.assertEqual(
            hunks[2].lines[-1],
            '         """Writes a new diff corresponding to the user\'s'
            ' selection."""\n')
Example #27
0
 def do(self):
     if not self.filenames:
         return
     new_additions = "\n".join(self.filenames) + "\n"
     for_status = new_additions
     if core.exists(".gitignore"):
         current_list = core.read(".gitignore")
         new_additions = current_list.rstrip() + "\n" + new_additions
     core.write(".gitignore", new_additions)
     Interaction.log_status(0, "Added to .gitignore:\n%s" % for_status, "")
     self.model.update_file_status()
Example #28
0
    def diff_text_for(self, filename):
        cfg = gitcfg.current()
        size = cfg.get('cola.readsize', 1024 * 2)
        try:
            result = core.read(filename, size=size,
                               encoding='utf-8', errors='ignore')
        except:
            result = ''

        if len(result) == size:
            result += '...'
        return result
Example #29
0
def test_diff_at_end():
    fixture_path = helper.fixture('diff-end.txt')
    parser = diffparse.DiffParser('rijndael.js', core.read(fixture_path))
    hunks = parser.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
Example #30
0
    def diff_text_for(self, filename):
        cfg = gitcfg.current()
        size = cfg.get('cola.readsize', 1024 * 2)
        try:
            result = core.read(filename, size=size,
                               encoding='utf-8', errors='ignore')
        except:
            result = ''

        if len(result) == size:
            result += '...'
        return result
Example #31
0
def read_git_file(path):
    """Read the path from a .git-file

    `None` is returned when <path> is not a .git-file.

    """
    result = None
    if path and is_git_file(path):
        header = 'gitdir: '
        data = core.read(path).strip()
        if data.startswith(header):
            result = data[len(header):]
    return result
Example #32
0
def _install_custom_language():
    """Allow a custom language to be set in ~/.config/git-cola/language"""
    lang_file = xdg.config_home('language')
    if not os.path.exists(lang_file):
        return
    try:
        fp = open(lang_file, 'r')
        lang = core.read(fp).strip()
        fp.close()
    except:
        return
    if lang:
        compat.putenv('LANGUAGE', lang)
Example #33
0
 def do(self):
     new_additions = ''
     for fname in self.filenames:
         new_additions = new_additions + fname + '\n'
     for_status = new_additions
     if new_additions:
         if core.exists('.gitignore'):
             current_list = core.read('.gitignore')
             new_additions = new_additions + current_list
         core.write('.gitignore', new_additions)
         Interaction.log_status(0, 'Added to .gitignore:\n%s' % for_status,
                                '')
         self.model.update_file_status()
Example #34
0
def read_git_file(path):
    """Read the path from a .git-file

    `None` is returned when <path> is not a .git-file.

    """
    result = None
    if path and is_git_file(path):
        header = 'gitdir: '
        data = core.read(path).strip()
        if data.startswith(header):
            result = data[len(header):]
    return result
Example #35
0
def _install_custom_language():
    """Allow a custom language to be set in ~/.config/git-cola/language"""
    lang_file = xdg.config_home('language')
    if not os.path.exists(lang_file):
        return
    try:
        fp = open(lang_file, 'r')
        lang = core.read(fp).strip()
        fp.close()
    except:
        return
    if lang:
        compat.putenv('LANGUAGE', lang)
Example #36
0
 def do(self):
     new_additions = ''
     for fname in self.filenames:
         new_additions = new_additions + fname + '\n'
     for_status = new_additions
     if new_additions:
         if core.exists('.gitignore'):
             current_list = core.read('.gitignore')
             new_additions = new_additions + current_list
         core.write('.gitignore', new_additions)
         Interaction.log_status(
                 0, 'Added to .gitignore:\n%s' % for_status, '')
         self.model.update_file_status()
Example #37
0
    def test_diff_at_end(self):
        fixture_path = helper.fixture('diff-end.txt')
        parser = diffparse.DiffParser('rijndael.js', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(hunks[0].lines[0], '@@ -1,39 +1 @@\n')
        self.assertEqual(
            hunks[-1].lines[-1],
            "+module.exports = require('./build/Release/rijndael');\n")
        self.assertEqual(hunks[0].old_start, 1)
        self.assertEqual(hunks[0].old_count, 39)
        self.assertEqual(hunks[0].new_start, 1)
        self.assertEqual(hunks[0].new_count, 1)
Example #38
0
    def test_diff_at_end(self):
        fixture_path = helper.fixture('diff-end.txt')
        parser = DiffParser('rijndael.js', core.read(fixture_path))
        hunks = parser.hunks

        self.assertEqual(hunks[0].lines[0], '@@ -1,39 +1 @@')
        self.assertEqual(
                hunks[-1].lines[-1],
                "+module.exports = require('./build/Release/rijndael');")
        self.assertEqual(hunks[0].old_start, 1)
        self.assertEqual(hunks[0].old_count, 39)
        self.assertEqual(hunks[0].new_start, 1)
        self.assertEqual(hunks[0].new_count, 1)
Example #39
0
    def _update_commitmsg(self):
        """Check for git merge message files, or clear it when the merge completes"""
        if self.amending():
            return
        # Check if there's a message file in .git/
        merge_msg_path = gitcmds.merge_message_path()
        if merge_msg_path:
            msg = core.read(merge_msg_path)
            if msg != self._auto_commitmsg:
                self._auto_commitmsg = msg
                self._prev_commitmsg = self.commitmsg
                self.set_commitmsg(msg)

        elif self._auto_commitmsg and self._auto_commitmsg == self.commitmsg:
            self._auto_commitmsg = ''
            self.set_commitmsg(self._prev_commitmsg)
Example #40
0
    def _update_commitmsg(self):
        """Check for git merge message files, or clear it when the merge completes"""
        if self.amending():
            return
        # Check if there's a message file in .git/
        merge_msg_path = gitcmds.merge_message_path()
        if merge_msg_path:
            msg = core.read(merge_msg_path)
            if msg != self._auto_commitmsg:
                self._auto_commitmsg = msg
                self._prev_commitmsg = self.commitmsg
                self.set_commitmsg(msg)

        elif self._auto_commitmsg and self._auto_commitmsg == self.commitmsg:
            self._auto_commitmsg = ''
            self.set_commitmsg(self._prev_commitmsg)
Example #41
0
def _read_git_head(head, default="master", git=git):
    """Pure-python .git/HEAD reader"""
    # Legacy .git/HEAD symlinks
    if core.islink(head):
        refs_heads = core.realpath(git.git_path("refs", "heads"))
        path = core.abspath(head).replace("\\", "/")
        if path.startswith(refs_heads + "/"):
            return path[len(refs_heads) + 1 :]

    # Common .git/HEAD "ref: refs/heads/master" file
    elif core.isfile(head):
        data = core.read(head).rstrip()
        ref_prefix = "ref: "
        if data.startswith(ref_prefix):
            return data[len(ref_prefix) :]
        # Detached head
        return data

    return default
Example #42
0
def _read_git_head(head, default='master', git=git):
    """Pure-python .git/HEAD reader"""
    # Legacy .git/HEAD symlinks
    if core.islink(head):
        refs_heads = core.realpath(git.git_path('refs', 'heads'))
        path = core.abspath(head).replace('\\', '/')
        if path.startswith(refs_heads + '/'):
            return path[len(refs_heads)+1:]

    # Common .git/HEAD "ref: refs/heads/master" file
    elif core.isfile(head):
        data = core.read(head).rstrip()
        ref_prefix = 'ref: '
        if data.startswith(ref_prefix):
            return data[len(ref_prefix):]
        # Detached head
        return data

    return default
Example #43
0
def _read_git_head(head, default='master', git=git):
    """Pure-python .git/HEAD reader"""
    # Legacy .git/HEAD symlinks
    if core.islink(head):
        refs_heads = core.realpath(git.git_path('refs', 'heads'))
        path = core.abspath(head).replace('\\', '/')
        if path.startswith(refs_heads + '/'):
            return path[len(refs_heads) + 1:]

    # Common .git/HEAD "ref: refs/heads/master" file
    elif core.isfile(head):
        data = core.read(head).rstrip()
        ref_prefix = 'ref: '
        if data.startswith(ref_prefix):
            return data[len(ref_prefix):]
        # Detached head
        return data

    return default
Example #44
0
def test_diff_that_empties_file():
    fixture_path = helper.fixture('diff-empty.txt')
    parser = diffparse.DiffParser('filename', core.read(fixture_path))
    hunks = parser.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 parser.generate_patch(1, 1) == ('--- a/filename\n'
                                           '+++ b/filename\n'
                                           '@@ -1,2 +1 @@\n'
                                           '-first\n'
                                           ' second\n')
    assert parser.generate_patch(0, 2) == ('--- a/filename\n'
                                           '+++ b/filename\n'
                                           '@@ -1,2 +0,0 @@\n'
                                           '-first\n'
                                           '-second\n')
Example #45
0
def find_git():
    """Return the path of git.exe, or None if we can't find it."""
    if not utils.is_win32():
        return None  # UNIX systems have git in their $PATH

    # If the user wants to use a Git/bin/ directory from a non-standard
    # directory then they can write its location into
    # ~/.config/git-cola/git-bindir
    git_bindir = os.path.expanduser(os.path.join('~', '.config', 'git-cola',
                                                 'git-bindir'))
    if core.exists(git_bindir):
        custom_path = core.read(git_bindir).strip()
        if custom_path and core.exists(custom_path):
            return custom_path

    # Try to find Git's bin/ directory in one of the typical locations
    pf = os.environ.get('ProgramFiles', 'C:\\Program Files')
    pf32 = os.environ.get('ProgramFiles(x86)', 'C:\\Program Files (x86)')
    for p in [pf32, pf, 'C:\\']:
        candidate = os.path.join(p, 'Git\\bin')
        if os.path.isdir(candidate):
            return candidate

    return None
Example #46
0
def find_git():
    """Return the path of git.exe, or None if we can't find it."""
    if not utils.is_win32():
        return None  # UNIX systems have git in their $PATH

    # If the user wants to use a Git/bin/ directory from a non-standard
    # directory then they can write its location into
    # ~/.config/git-cola/git-bindir
    git_bindir = os.path.expanduser(os.path.join('~', '.config', 'git-cola',
                                                 'git-bindir'))
    if core.exists(git_bindir):
        custom_path = core.read(git_bindir).strip()
        if custom_path and core.exists(custom_path):
            return custom_path

    # Try to find Git's bin/ directory in one of the typical locations
    pf = os.environ.get('ProgramFiles', 'C:\\Program Files')
    pf32 = os.environ.get('ProgramFiles(x86)', 'C:\\Program Files (x86)')
    for p in [pf32, pf, 'C:\\']:
        candidate = os.path.join(p, 'Git\\bin')
        if os.path.isdir(candidate):
            return candidate

    return None
Example #47
0
def test_diff_at_start():
    fixture_path = helper.fixture('diff-start.txt')
    parser = diffparse.DiffParser('foo bar/a', core.read(fixture_path))
    hunks = parser.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 parser.generate_patch(1, 3) == ('--- a/foo bar/a\n'
                                           '+++ b/foo bar/a\n'
                                           '@@ -1 +1,3 @@\n'
                                           ' bar\n'
                                           '+a\n'
                                           '+b\n')
    assert parser.generate_patch(0, 4) == ('--- a/foo bar/a\n'
                                           '+++ b/foo bar/a\n'
                                           '@@ -1 +1,4 @@\n'
                                           ' bar\n'
                                           '+a\n'
                                           '+b\n'
                                           '+c\n')
Example #48
0
def slurp(path, size=-1):
    """Slurps a filepath into a string."""
    fh = open(core.encode(path))
    slushy = core.read(fh, size=size)
    fh.close()
    return core.decode(slushy)
Example #49
0
    def __init__(self, model, parent):
        QtGui.QWidget.__init__(self, parent)

        self.model = model
        self.notifying = False
        self.spellcheck_initialized = False

        self._linebreak = None
        self._textwidth = None
        self._tabwidth = None

        # Actions
        self.signoff_action = qtutils.add_action(self, cmds.SignOff.name(),
                                                 cmds.run(cmds.SignOff),
                                                 cmds.SignOff.SHORTCUT)
        self.signoff_action.setToolTip(N_('Sign off on this commit'))

        self.commit_action = qtutils.add_action(self,
                                                N_('Commit@@verb'),
                                                self.commit,
                                                cmds.Commit.SHORTCUT)
        self.commit_action.setToolTip(N_('Commit staged changes'))
        self.clear_action = qtutils.add_action(self, N_('Clear...'), self.clear)

        # Widgets
        self.summary = CommitSummaryLineEdit()
        self.summary.setMinimumHeight(defs.tool_button_height)
        self.summary.extra_actions.append(self.clear_action)
        self.summary.extra_actions.append(None)
        self.summary.extra_actions.append(self.signoff_action)
        self.summary.extra_actions.append(self.commit_action)

        self.description = CommitMessageTextEdit()
        self.description.extra_actions.append(self.clear_action)
        self.description.extra_actions.append(None)
        self.description.extra_actions.append(self.signoff_action)
        self.description.extra_actions.append(self.commit_action)

        commit_button_tooltip = N_('Commit staged changes\n'
                                   'Shortcut: Ctrl+Enter')
        self.commit_button = qtutils.create_toolbutton(
                text=N_('Commit@@verb'), tooltip=commit_button_tooltip,
                icon=qtutils.save_icon())

        self.actions_menu = QtGui.QMenu()
        self.actions_button = qtutils.create_toolbutton(
                icon=qtutils.options_icon(), tooltip=N_('Actions...'))
        self.actions_button.setMenu(self.actions_menu)
        self.actions_button.setPopupMode(QtGui.QToolButton.InstantPopup)
        qtutils.hide_button_menu_indicator(self.actions_button)

        self.actions_menu.addAction(self.signoff_action)
        self.actions_menu.addAction(self.commit_action)
        self.actions_menu.addSeparator()

        # Amend checkbox
        self.amend_action = self.actions_menu.addAction(
                N_('Amend Last Commit'))
        self.amend_action.setCheckable(True)
        self.amend_action.setShortcut(cmds.AmendMode.SHORTCUT)
        self.amend_action.setShortcutContext(Qt.ApplicationShortcut)

        # Bypass hooks
        self.bypass_commit_hooks_action = self.actions_menu.addAction(
                N_('Bypass Commit Hooks'))
        self.bypass_commit_hooks_action.setCheckable(True)
        self.bypass_commit_hooks_action.setChecked(False)

        # Sign commits
        cfg = gitcfg.current()
        self.sign_action = self.actions_menu.addAction(
                N_('Create Signed Commit'))
        self.sign_action.setCheckable(True)
        self.sign_action.setChecked(cfg.get('cola.signcommits', False))

        # Spell checker
        self.check_spelling_action = self.actions_menu.addAction(
                N_('Check Spelling'))
        self.check_spelling_action.setCheckable(True)
        self.check_spelling_action.setChecked(False)

        # Line wrapping
        self.autowrap_action = self.actions_menu.addAction(
                N_('Auto-Wrap Lines'))
        self.autowrap_action.setCheckable(True)
        self.autowrap_action.setChecked(prefs.linebreak())

        # Commit message
        self.actions_menu.addSeparator()
        self.load_commitmsg_menu = self.actions_menu.addMenu(
                N_('Load Previous Commit Message'))
        self.connect(self.load_commitmsg_menu, SIGNAL('aboutToShow()'),
                     self.build_commitmsg_menu)

        self.fixup_commit_menu = self.actions_menu.addMenu(
                N_('Fixup Previous Commit'))
        self.connect(self.fixup_commit_menu, SIGNAL('aboutToShow()'),
                     self.build_fixup_menu)

        self.toplayout = qtutils.hbox(defs.no_margin, defs.spacing,
                                      self.actions_button, self.summary,
                                      self.commit_button)
        self.toplayout.setContentsMargins(defs.margin, defs.no_margin,
                                          defs.no_margin, defs.no_margin)

        self.mainlayout = qtutils.vbox(defs.no_margin, defs.spacing,
                                       self.toplayout, self.description)
        self.setLayout(self.mainlayout)

        qtutils.connect_button(self.commit_button, self.commit)

        # Broadcast the amend mode
        qtutils.connect_action_bool(self.amend_action, cmds.run(cmds.AmendMode))
        qtutils.connect_action_bool(self.check_spelling_action,
                                    self.toggle_check_spelling)

        # Handle the one-off autowrapping
        qtutils.connect_action_bool(self.autowrap_action, self.set_linebreak)

        qtutils.add_action(self.summary, N_('Move Down'),
                           self.focus_description,
                           Qt.Key_Return, Qt.Key_Enter)

        qtutils.add_action(self.summary, N_('Move Down'),
                           self.summary_cursor_down,
                           Qt.Key_Down)

        self.model.add_observer(self.model.message_commit_message_changed,
                                self.set_commit_message)

        self.connect(self.summary, SIGNAL('cursorPosition(int,int)'),
                     self.emit_position)

        self.connect(self.description, SIGNAL('cursorPosition(int,int)'),
                     # description starts at line 2
                     lambda row, col: self.emit_position(row + 2, col))

        # Keep model informed of changes
        self.connect(self.summary, SIGNAL('textChanged(QString)'),
                     self.commit_summary_changed)

        self.connect(self.description, SIGNAL('textChanged()'),
                     self.commit_message_changed)

        self.connect(self.description, SIGNAL('leave()'),
                     self.focus_summary)

        self.setFont(qtutils.diff_font())

        self.summary.enable_hint(True)
        self.description.enable_hint(True)

        self.commit_button.setEnabled(False)
        self.commit_action.setEnabled(False)

        self.setFocusProxy(self.summary)

        self.set_tabwidth(prefs.tabwidth())
        self.set_textwidth(prefs.textwidth())
        self.set_linebreak(prefs.linebreak())

        # Loading message
        commit_msg = ''
        commit_msg_path = commit_message_path()
        if commit_msg_path:
            commit_msg = core.read(commit_msg_path)
        self.set_commit_message(commit_msg)

        # Allow tab to jump from the summary to the description
        self.setTabOrder(self.summary, self.description)
Example #50
0
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
Example #51
0
 def test_decode_utf8(self):
     filename = helper.fixture('cyrillic-utf-8.txt')
     actual = core.read(filename)
     self.assertEqual(actual.encoding, 'utf-8')
Example #52
0
 def test_decode_non_utf8(self):
     filename = helper.fixture('cyrillic-cp1251.txt')
     actual = core.read(filename)
     self.assertEqual(actual.encoding, 'iso-8859-15')
Example #53
0
    def __init__(self, model, parent):
        QtGui.QWidget.__init__(self, parent)

        self.model = model
        self.notifying = False
        self.spellcheck_initialized = False

        self._linebreak = None
        self._textwidth = None
        self._tabwidth = None

        # Actions
        self.signoff_action = qtutils.add_action(self, cmds.SignOff.name(),
                                                 cmds.run(cmds.SignOff),
                                                 cmds.SignOff.SHORTCUT)
        self.signoff_action.setToolTip(N_('Sign off on this commit'))

        self.commit_action = qtutils.add_action(self,
                                                N_('Commit@@verb'),
                                                self.commit,
                                                cmds.Commit.SHORTCUT)
        self.commit_action.setToolTip(N_('Commit staged changes'))

        # Widgets
        self.summary = CommitSummaryLineEdit()
        self.summary.setMinimumHeight(defs.tool_button_height)
        self.summary.extra_actions.append(self.signoff_action)
        self.summary.extra_actions.append(self.commit_action)

        self.description = CommitMessageTextEdit()
        self.description.extra_actions.append(self.signoff_action)
        self.description.extra_actions.append(self.commit_action)

        commit_button_tooltip = N_('Commit staged changes\n'
                                   'Shortcut: Ctrl+Enter')
        self.commit_button = qtutils.create_toolbutton(
                text=N_('Commit@@verb'), tooltip=commit_button_tooltip,
                icon=qtutils.save_icon())

        self.actions_menu = QtGui.QMenu()
        self.actions_button = qtutils.create_toolbutton(
                icon=qtutils.options_icon(), tooltip=N_('Actions...'))
        self.actions_button.setMenu(self.actions_menu)
        self.actions_button.setPopupMode(QtGui.QToolButton.InstantPopup)
        qtutils.hide_button_menu_indicator(self.actions_button)

        self.actions_menu.addAction(self.signoff_action)
        self.actions_menu.addAction(self.commit_action)
        self.actions_menu.addSeparator()

        # Amend checkbox
        self.amend_action = self.actions_menu.addAction(
                N_('Amend Last Commit'))
        self.amend_action.setCheckable(True)
        self.amend_action.setShortcut(cmds.AmendMode.SHORTCUT)
        self.amend_action.setShortcutContext(Qt.ApplicationShortcut)

        # Bypass hooks
        self.bypass_commit_hooks_action = self.actions_menu.addAction(
                N_('Bypass Commit Hooks'))
        self.bypass_commit_hooks_action.setCheckable(True)
        self.bypass_commit_hooks_action.setChecked(False)

        # Sign commits
        cfg = gitcfg.current()
        self.sign_action = self.actions_menu.addAction(
                N_('Create Signed Commit'))
        self.sign_action.setCheckable(True)
        self.sign_action.setChecked(cfg.get('cola.signcommits', False))

        # Spell checker
        self.check_spelling_action = self.actions_menu.addAction(
                N_('Check Spelling'))
        self.check_spelling_action.setCheckable(True)
        self.check_spelling_action.setChecked(False)

        # Line wrapping
        self.autowrap_action = self.actions_menu.addAction(
                N_('Auto-Wrap Lines'))
        self.autowrap_action.setCheckable(True)
        self.autowrap_action.setChecked(prefs.linebreak())

        # Commit message
        self.actions_menu.addSeparator()
        self.load_commitmsg_menu = self.actions_menu.addMenu(
                N_('Load Previous Commit Message'))
        self.connect(self.load_commitmsg_menu, SIGNAL('aboutToShow()'),
                     self.build_commitmsg_menu)

        self.fixup_commit_menu = self.actions_menu.addMenu(
                N_('Fixup Previous Commit'))
        self.connect(self.fixup_commit_menu, SIGNAL('aboutToShow()'),
                     self.build_fixup_menu)

        self.toplayout = qtutils.hbox(defs.no_margin, defs.spacing,
                                      self.actions_button, self.summary,
                                      self.commit_button)
        self.toplayout.setContentsMargins(defs.margin, defs.no_margin,
                                          defs.no_margin, defs.no_margin)

        self.mainlayout = qtutils.vbox(defs.no_margin, defs.spacing,
                                       self.toplayout, self.description)
        self.setLayout(self.mainlayout)

        qtutils.connect_button(self.commit_button, self.commit)

        # Broadcast the amend mode
        qtutils.connect_action_bool(self.amend_action, cmds.run(cmds.AmendMode))
        qtutils.connect_action_bool(self.check_spelling_action,
                                    self.toggle_check_spelling)

        # Handle the one-off autowrapping
        qtutils.connect_action_bool(self.autowrap_action, self.set_linebreak)

        qtutils.add_action(self.summary, N_('Move Down'),
                           self.focus_description,
                           Qt.Key_Return, Qt.Key_Enter)

        qtutils.add_action(self.summary, N_('Move Down'),
                           self.summary_cursor_down,
                           Qt.Key_Down)

        self.model.add_observer(self.model.message_commit_message_changed,
                                self.set_commit_message)

        self.connect(self.summary, SIGNAL('cursorPosition(int,int)'),
                     self.emit_position)

        self.connect(self.description, SIGNAL('cursorPosition(int,int)'),
                     # description starts at line 2
                     lambda row, col: self.emit_position(row + 2, col))

        # Keep model informed of changes
        self.connect(self.summary, SIGNAL('textChanged(QString)'),
                     self.commit_summary_changed)

        self.connect(self.description, SIGNAL('textChanged()'),
                     self.commit_message_changed)

        self.connect(self.description, SIGNAL('leave()'),
                     self.focus_summary)

        self.setFont(qtutils.diff_font())

        self.summary.enable_hint(True)
        self.description.enable_hint(True)

        self.commit_button.setEnabled(False)
        self.commit_action.setEnabled(False)

        self.setFocusProxy(self.summary)

        self.set_tabwidth(prefs.tabwidth())
        self.set_textwidth(prefs.textwidth())
        self.set_linebreak(prefs.linebreak())

        # Loading message
        commit_msg = ''
        commit_msg_path = commit_message_path()
        if commit_msg_path:
            commit_msg = core.read(commit_msg_path)
        self.set_commit_message(commit_msg)

        # Allow tab to jump from the summary to the description
        self.setTabOrder(self.summary, self.description)
Example #54
0
 def setUp(self):
     self.parser = diffparse.DiffLines()
     fixture_path = helper.fixture('diff.txt')
     self.text = core.read(fixture_path)
Example #55
0
 def setUp(self):
     self.parser = diffparse.DiffLines()
     fixture_path = helper.fixture('diff.txt')
     self.text = core.read(fixture_path)
Example #56
0
def pipe(cmd):
    p = os.popen(cmd)
    out = core.read(p).strip()
    p.close()
    return out
Example #57
0
def slurp(path):
    """Slurps a filepath into a string."""
    fh = open(core.encode(path))
    slushy = core.read(fh)
    fh.close()
    return core.decode(slushy)