<commit_before># Copyright 2014 OpenStack Foundation
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import datetime
import logging
import textwrap

from six.moves.urllib import parse as urlparse
import urwid

from gertty import gitrepo
from gertty import keymap
from gertty import mywid
from gertty import sync
from gertty.view import side_diff as view_side_diff
from gertty.view import unified_diff as view_unified_diff
from gertty.view import mouse_scroll_decorator
import gertty.view

class EditTopicDialog(mywid.ButtonDialog):
    signals = ['save', 'cancel']
    def __init__(self, app, topic):
        self.app = app
        save_button = mywid.FixedButton('Save')
        cancel_button = mywid.FixedButton('Cancel')
        urwid.connect_signal(save_button, 'click',
                             lambda button:self._emit('save'))
        urwid.connect_signal(cancel_button, 'click',
                             lambda button:self._emit('cancel'))
        super(EditTopicDialog, self).__init__("Edit Topic",
                                              "Edit the change topic.",
                                              entry_prompt="Topic: ",
                                              entry_text=topic,
                                              buttons=[save_button,
                                                       cancel_button],
                                              ring=app.ring)

    def keypress(self, size, key):
        if not self.app.input_buffer:
            key = super(EditTopicDialog, self).keypress(size, key)
        keys = self.app.input_buffer + [key]
        commands = self.app.config.keymap.getCommands(keys)
        if keymap.ACTIVATE in commands:
            self._emit('save')
            return None
        return key

class CherryPickDialog(urwid.WidgetWrap, mywid.LineBoxTitlePropertyMixin):
    signals = ['save', 'cancel']
    def __init__(self, app, change):
        save_button = mywid.FixedButton('Propose Change')
        cancel_button = mywid.FixedButton('Cancel')
        urwid.connect_signal(save_button, 'click',
                             lambda button:self._emit('save'))
        urwid.connect_signal(cancel_button, 'click',
                             lambda button:self._emit('cancel'))
        button_widgets = [('pack', save_button),
                          ('pack', cancel_button)]
        button_columns = urwid.Columns(button_widgets, dividechars=2)
        rows = []
        self.entry = mywid.MyEdit(edit_text=change.revisions[-1].message,
                                  multiline=True, ring=app.ring)
        self.branch_buttons = []
        rows.append(urwid.Text(u"Branch:"))
        for branch in change.project.branches:
            b = mywid.FixedRadioButton(self.branch_buttons, branch.name,
                                       state=(branch.name == change.branch))
            rows.append(b)
        rows.append(urwid.Divider())
        rows.append(urwid.Text(u"Commit message:"))
        rows.append(self.entry)
        rows.append(urwid.Divider())
        rows.append(button_columns)
        pile = urwid.Pile(rows)
        fill = urwid.Filler(pile, valign='top')
        super(CherryPickDialog, self).__init__(urwid.LineBox(fill,
                                                             'Propose Change to Branch'))

class ReviewDialog(urwid.WidgetWrap, mywid.LineBoxTitlePropertyMixin):
    signals = ['submit', 'save', 'cancel']
    def __init__(self, app, revision_key, message=''):
        self.revision_key = revision_key
        self.app = app
        save_button = mywid.FixedButton(u'Save')
        submit_button = mywid.FixedButton(u'Save and Submit')
        cancel_button = mywid.FixedButton(u'Cancel')
        urwid.connect_signal(save_button, 'click',
            lambda button:self._emit('save'))
        urwid.connect_signal(submit_button, 'click',
            lambda button:self._emit('submit'))
        urwid.connect_signal(cancel_button, 'click',
            lambda button:self._emit('cancel'))

        rows = []
        categories = []
        values = {}
        descriptions = {}
        self.button_groups = {}
        with self.app.db.getSession() as session:
            revision = session.getRevision(self.revision_key)
            change = revision.change
            buttons = [('pack', save_button)]
            if revision.can_submit:
                buttons.append(('pack', submit_button))
            buttons.append(('pack', cancel_button))
            buttons = urwid.Columns(buttons, dividechars=2)
            if revision == change.revisions[-1]:
                for label in change.labels:
                    d = descriptions.setdefault(label.category, {})
                    d[label.value] = label.description
                    vmin = d.setdefault('min', label.value)
                    if label.value < vmin:
                        d['min'] = label.value
                    vmax = d.setdefault('max', label.value)
                    if label.value > vmax:
                        d['max'] = label.value
                for label in change.permitted_labels:
                    if label.category not in categories:
                        categories.append(label.category)
                        values[label.category] = []
                    values[label.category].append(label.value)
                draft_approvals = {}
                for approval in change.draft_approvals:
                    draft_approvals[approval.category] = approval
                for category in categories:
                    rows.append(urwid.Text(category))
                    group = []
                    self.button_groups[category] = group
                    current = draft_approvals.get(category)
                    if current is None:
                        current = 0
                    else:
                        current = current.value
                    for value in sorted(values[category], reverse=True):
                        if value > 0:
                            strvalue = '+%s' % value
                        elif value == 0:
                            strvalue = ' 0'
                        else:
                            strvalue = str(value)
                        strvalue += '  ' + descriptions[category][value]
                        b = urwid.RadioButton(group, strvalue, state=(value == current))
                        b._value = value
                        if value > 0:
                            if value == descriptions[category]['max']:
                                b = urwid.AttrMap(b, 'max-label')
                            else:
                                b = urwid.AttrMap(b, 'positive-label')
                        elif value < 0:
                            if value == descriptions[category]['min']:
                                b = urwid.AttrMap(b, 'min-label')
                            else:
                                b = urwid.AttrMap(b, 'negative-label')
                        rows.append(b)
                    rows.append(urwid.Divider())
            m = revision.getPendingMessage()
            if not m:
                m = revision.getDraftMessage()
            if m:
                message = m.message
        self.message = mywid.MyEdit("Message: \n", edit_text=message,
                                    multiline=True, ring=app.ring)
        rows.append(self.message)
        rows.append(urwid.Divider())
        rows.append(buttons)
        pile = urwid.Pile(rows)
        fill = urwid.Filler(pile, valign='top')
        super(ReviewDialog, self).__init__(urwid.LineBox(fill, 'Review'))<commit_msg>Fix unicode in change messages<commit_after># Copyright 2014 OpenStack Foundation
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import datetime
import logging
import textwrap

from six.moves.urllib import parse as urlparse
import urwid

from gertty import gitrepo
from gertty import keymap
from gertty import mywid
from gertty import sync
from gertty.view import side_diff as view_side_diff
from gertty.view import unified_diff as view_unified_diff
from gertty.view import mouse_scroll_decorator
import gertty.view

class EditTopicDialog(mywid.ButtonDialog):
    signals = ['save', 'cancel']
    def __init__(self, app, topic):
        self.app = app
        save_button = mywid.FixedButton('Save')
        cancel_button = mywid.FixedButton('Cancel')
        urwid.connect_signal(save_button, 'click',
                             lambda button:self._emit('save'))
        urwid.connect_signal(cancel_button, 'click',
                             lambda button:self._emit('cancel'))
        super(EditTopicDialog, self).__init__("Edit Topic",
                                              "Edit the change topic.",
                                              entry_prompt="Topic: ",
                                              entry_text=topic,
                                              buttons=[save_button,
                                                       cancel_button],
                                              ring=app.ring)

    def keypress(self, size, key):
        if not self.app.input_buffer:
            key = super(EditTopicDialog, self).keypress(size, key)
        keys = self.app.input_buffer + [key]
        commands = self.app.config.keymap.getCommands(keys)
        if keymap.ACTIVATE in commands:
            self._emit('save')
            return None
        return key

class CherryPickDialog(urwid.WidgetWrap, mywid.LineBoxTitlePropertyMixin):
    signals = ['save', 'cancel']
    def __init__(self, app, change):
        save_button = mywid.FixedButton('Propose Change')
        cancel_button = mywid.FixedButton('Cancel')
        urwid.connect_signal(save_button, 'click',
                             lambda button:self._emit('save'))
        urwid.connect_signal(cancel_button, 'click',
                             lambda button:self._emit('cancel'))
        button_widgets = [('pack', save_button),
                          ('pack', cancel_button)]
        button_columns = urwid.Columns(button_widgets, dividechars=2)
        rows = []
        self.entry = mywid.MyEdit(edit_text=change.revisions[-1].message,
                                  multiline=True, ring=app.ring)
        self.branch_buttons = []
        rows.append(urwid.Text(u"Branch:"))
        for branch in change.project.branches:
            b = mywid.FixedRadioButton(self.branch_buttons, branch.name,
                                       state=(branch.name == change.branch))
            rows.append(b)
        rows.append(urwid.Divider())
        rows.append(urwid.Text(u"Commit message:"))
        rows.append(self.entry)
        rows.append(urwid.Divider())
        rows.append(button_columns)
        pile = urwid.Pile(rows)
        fill = urwid.Filler(pile, valign='top')
        super(CherryPickDialog, self).__init__(urwid.LineBox(fill,
                                                             'Propose Change to Branch'))

class ReviewDialog(urwid.WidgetWrap, mywid.LineBoxTitlePropertyMixin):
    signals = ['submit', 'save', 'cancel']
    def __init__(self, app, revision_key, message=''):
        self.revision_key = revision_key
        self.app = app
        save_button = mywid.FixedButton(u'Save')
        submit_button = mywid.FixedButton(u'Save and Submit')
        cancel_button = mywid.FixedButton(u'Cancel')
        urwid.connect_signal(save_button, 'click',
            lambda button:self._emit('save'))
        urwid.connect_signal(submit_button, 'click',
            lambda button:self._emit('submit'))
        urwid.connect_signal(cancel_button, 'click',
            lambda button:self._emit('cancel'))

        rows = []
        categories = []
        values = {}
        descriptions = {}
        self.button_groups = {}
        with self.app.db.getSession() as session:
            revision = session.getRevision(self.revision_key)
            change = revision.change
            buttons = [('pack', save_button)]
            if revision.can_submit:
                buttons.append(('pack', submit_button))
            buttons.append(('pack', cancel_button))
            buttons = urwid.Columns(buttons, dividechars=2)
            if revision == change.revisions[-1]:
                for label in change.labels:
                    d = descriptions.setdefault(label.category, {})
                    d[label.value] = label.description
                    vmin = d.setdefault('min', label.value)
                    if label.value < vmin:
                        d['min'] = label.value
                    vmax = d.setdefault('max', label.value)
                    if label.value > vmax:
                        d['max'] = label.value
                for label in change.permitted_labels:
                    if label.category not in categories:
                        categories.append(label.category)
                        values[label.category] = []
                    values[label.category].append(label.value)
                draft_approvals = {}
                for approval in change.draft_approvals:
                    draft_approvals[approval.category] = approval
                for category in categories:
                    rows.append(urwid.Text(category))
                    group = []
                    self.button_groups[category] = group
                    current = draft_approvals.get(category)
                    if current is None:
                        current = 0
                    else:
                        current = current.value
                    for value in sorted(values[category], reverse=True):
                        if value > 0:
                            strvalue = '+%s' % value
                        elif value == 0:
                            strvalue = ' 0'
                        else:
                            strvalue = str(value)
                        strvalue += '  ' + descriptions[category][value]
                        b = urwid.RadioButton(group, strvalue, state=(value == current))
                        b._value = value
                        if value > 0:
                            if value == descriptions[category]['max']:
                                b = urwid.AttrMap(b, 'max-label')
                            else:
                                b = urwid.AttrMap(b, 'positive-label')
                        elif value < 0:
                            if value == descriptions[category]['min']:
                                b = urwid.AttrMap(b, 'min-label')
                            else:
                                b = urwid.AttrMap(b, 'negative-label')
                        rows.append(b)
                    rows.append(urwid.Divider())
            m = revision.getPendingMessage()
            if not m:
                m = revision.getDraftMessage()
            if m:
                message = m.message
        self.message = mywid.MyEdit(u"Message: \n", edit_text=message,
                                    multiline=True, ring=app.ring)
        rows.append(self.message)
        rows.append(urwid.Divider())
        rows.append(buttons)
        pile = urwid.Pile(rows)
        fill = urwid.Filler(pile, valign='top')
        super(ReviewDialog, self).__init__(urwid.LineBox(fill, 'Review'))
{'fraction_non_alphanumeric': 0.09573044641771074, 'fraction_numerical': 0.0026760734703807324, 'mean_word_length': 1.6029760962482191, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 44, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5247565', 'n_tokens_mistral': 4180, 'n_tokens_neox': 4042, 'n_words': 947}