From 7d957201ac3634156ecc01b9406934628c1aa503 Mon Sep 17 00:00:00 2001 From: Christian Geier Date: Fri, 13 Nov 2015 00:20:21 +0100 Subject: [PATCH 1/3] removed unicode literals --- khal/controllers.py | 38 ++++----- khal/khalendar/backend.py | 174 +++++++++++++++++++------------------- khal/khalendar/event.py | 100 +++++++++++----------- khal/ui/__init__.py | 58 ++++++------- khal/ui/calendarwidget.py | 12 +-- 5 files changed, 183 insertions(+), 199 deletions(-) diff --git a/khal/controllers.py b/khal/controllers.py index 30be2b758..9a91fd39a 100644 --- a/khal/controllers.py +++ b/khal/controllers.py @@ -21,8 +21,6 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -from __future__ import unicode_literals - import icalendar from click import confirm, echo, style, prompt from vdirsyncer.utils.vobject import Item @@ -58,9 +56,9 @@ def construct_daynames(daylist, longdateformat): """ for date in daylist: if date == datetime.date.today(): - yield (date, 'Today:') + yield (date, u'Today:') elif date == datetime.date.today() + datetime.timedelta(days=1): - yield (date, 'Tomorrow:') + yield (date, u'Tomorrow:') else: yield (date, date.strftime(longdateformat)) @@ -127,7 +125,7 @@ def get_agenda(collection, locale, dates=None, firstweekday=0, event_column.extend([colored(line, event.color) for line in lines]) if event_column == []: - event_column = [style('No events', bold=True)] + event_column = [style(u'No events', bold=True)] return event_column @@ -161,7 +159,7 @@ def calendar(collection, date=None, firstweekday=0, encoding='utf-8', locale=Non rows = merge_columns(calendar_column, event_column) # XXX: Generate this as a unicode in the first place, rather than # casting it. - echo('\n'.join(rows).encode(encoding)) + echo(u'\n'.join(rows).encode(encoding)) def agenda(collection, date=None, encoding='utf-8', @@ -171,7 +169,7 @@ def agenda(collection, date=None, encoding='utf-8', show_all_days=show_all_days, full=full, **kwargs) # XXX: Generate this as a unicode in the first place, rather than # casting it. - echo(to_unicode('\n'.join(event_column), encoding)) + echo(to_unicode(u'\n'.join(event_column), encoding)) def new_from_string(collection, calendar_name, conf, date_list, location=None, repeat=None, @@ -207,11 +205,11 @@ def interactive(collection, conf): from . import ui pane = ui.ClassicView(collection, conf, - title='select an event', - description='do something') + title=u'select an event', + description=u'do something') ui.start_pane( pane, pane.cleanup, - program_info='{0} v{1}'.format(__productname__, __version__) + program_info=u'{0} v{1}'.format(__productname__, __version__) ) @@ -250,11 +248,11 @@ def import_event(vevent, collection, locale, batch, random_uid): else: choice = list() for num, name in enumerate(collection.writable_names): - choice.append('{}({})'.format(name, num)) - choice = ', '.join(choice) + choice.append(u'{}({})'.format(name, num)) + choice = u', '.join(choice) while True: - value = prompt('Which calendar do you want to import to? \n' - '{}'.format(choice), default=collection.default_calendar_name) + value = prompt(u'Which calendar do you want to import to? \n' + u'{}'.format(choice), default=collection.default_calendar_name) try: number = int(value) calendar_name = collection.writable_names[number] @@ -264,20 +262,20 @@ def import_event(vevent, collection, locale, batch, random_uid): if len(matches) == 1: calendar_name = matches[0] break - echo('invalid choice') + echo(u'invalid choice') - if batch or confirm("Do you want to import this event into `{}`?" - "".format(calendar_name)): + if batch or confirm(u"Do you want to import this event into `{}`?" + u"".format(calendar_name)): ics = aux.ics_from_list(vevent, random_uid) try: collection.new( Item(ics.to_ical().decode('utf-8')), collection=calendar_name) except DuplicateUid: - if batch or confirm("An event with the same UID already exists. " - "Do you want to update it?"): + if batch or confirm(u"An event with the same UID already exists. " + u"Do you want to update it?"): collection.force_update( Item(ics.to_ical().decode('utf-8')), collection=calendar_name) else: - logger.warn("Not importing event with UID `{}`".format(event.uid)) + logger.warn(u"Not importing event with UID `{}`".format(event.uid)) diff --git a/khal/khalendar/backend.py b/khal/khalendar/backend.py index 11ca23cc3..c35aaea4e 100644 --- a/khal/khalendar/backend.py +++ b/khal/khalendar/backend.py @@ -29,8 +29,6 @@ respective types """ -from __future__ import print_function, unicode_literals - import contextlib from datetime import datetime, timedelta from os import makedirs, path @@ -44,8 +42,7 @@ from .event import Event from . import aux from .. import log -from .exceptions import CouldNotCreateDbDir, OutdatedDbVersionError, \ - UpdateFailed +from .exceptions import CouldNotCreateDbDir, OutdatedDbVersionError, UpdateFailed logger = log.logger @@ -94,7 +91,7 @@ class SQLiteDb(object): def __init__(self, calendar, db_path, locale): if db_path is None: - db_path = xdg.BaseDirectory.save_data_path('khal') + '/khal.db' + db_path = xdg.BaseDirectory.save_data_path(u'khal') + u'/khal.db' self.db_path = path.expanduser(db_path) self.calendar = calendar self._create_dbdir() @@ -123,24 +120,24 @@ def _create_dbdir(self): """create the dbdir if it doesn't exist""" if self.db_path == ':memory:': return None - dbdir = self.db_path.rsplit('/', 1)[0] + dbdir = self.db_path.rsplit(u'/', 1)[0] if not path.isdir(dbdir): try: - logger.debug('trying to create the directory for the db') + logger.debug(u'trying to create the directory for the db') makedirs(dbdir, mode=0o770) - logger.debug('success') + logger.debug(u'success') except OSError as error: - logger.fatal('failed to create {0}: {1}'.format(dbdir, error)) + logger.fatal(u'failed to create {0}: {1}'.format(dbdir, error)) raise CouldNotCreateDbDir() def _check_table_version(self): """tests for curent db Version if the table is still empty, insert db_version """ - self.cursor.execute('SELECT version FROM version') + self.cursor.execute(u'SELECT version FROM version') result = self.cursor.fetchone() if result is None: - self.cursor.execute('INSERT INTO version (version) VALUES (?)', + self.cursor.execute(u'INSERT INTO version (version) VALUES (?)', (DB_VERSION, )) self.conn.commit() elif not result[0] == DB_VERSION: @@ -152,16 +149,16 @@ def _check_table_version(self): def _create_default_tables(self): """creates version and calendar tables and inserts table version number """ - self.cursor.execute('CREATE TABLE IF NOT EXISTS ' - 'version (version INTEGER)') - logger.debug("created version table") + self.cursor.execute(u'CREATE TABLE IF NOT EXISTS ' + u'version (version INTEGER)') + logger.debug(u"created version table") - self.cursor.execute('''CREATE TABLE IF NOT EXISTS calendars ( + self.cursor.execute(u'''CREATE TABLE IF NOT EXISTS calendars ( calendar TEXT NOT NULL UNIQUE, resource TEXT NOT NULL, ctag FLOAT )''') - self.cursor.execute('''CREATE TABLE IF NOT EXISTS events ( + self.cursor.execute(u'''CREATE TABLE IF NOT EXISTS events ( href TEXT NOT NULL, calendar TEXT NOT NULL, sequence INT, @@ -169,7 +166,7 @@ def _create_default_tables(self): item TEXT, primary key (href, calendar) );''') - self.cursor.execute('''CREATE TABLE IF NOT EXISTS recs_loc ( + self.cursor.execute(u'''CREATE TABLE IF NOT EXISTS recs_loc ( dtstart INT NOT NULL, dtend INT NOT NULL, href TEXT NOT NULL REFERENCES events( href ), @@ -179,7 +176,7 @@ def _create_default_tables(self): calendar TEXT NOT NULL, primary key (href, rec_inst, calendar) );''') - self.cursor.execute('''CREATE TABLE IF NOT EXISTS recs_float ( + self.cursor.execute(u'''CREATE TABLE IF NOT EXISTS recs_float ( dtstart INT NOT NULL, dtend INT NOT NULL, href TEXT NOT NULL REFERENCES events( href ), @@ -195,18 +192,18 @@ def _check_calendar_exists(self): """make sure an entry for the current calendar exists in `calendar` table """ - self.cursor.execute('''SELECT count(*) FROM calendars + self.cursor.execute(u'''SELECT count(*) FROM calendars WHERE calendar = ?;''', (self.calendar,)) result = self.cursor.fetchone() if result[0] != 0: - logger.debug("tables for calendar {0} exist".format(self.calendar)) + logger.debug(u"tables for calendar {0} exist".format(self.calendar)) else: - sql_s = 'INSERT INTO calendars (calendar, resource) VALUES (?, ?);' - stuple = (self.calendar, '') + sql_s = u'INSERT INTO calendars (calendar, resource) VALUES (?, ?);' + stuple = (self.calendar, u'') self.sql_ex(sql_s, stuple) - def sql_ex(self, statement, stuple=''): + def sql_ex(self, statement, stuple=u''): """wrapper for sql statements, does a "fetchall" """ self.cursor.execute(statement, stuple) result = self.cursor.fetchall() @@ -214,7 +211,7 @@ def sql_ex(self, statement, stuple=''): self.conn.commit() return result - def update(self, vevent_str, href, etag=''): + def update(self, vevent_str, href, etag=u''): """insert a new or update an existing card in the db This is mostly a wrapper around two SQL statements, doing some cleanup @@ -238,11 +235,11 @@ def update(self, vevent_str, href, etag=''): :type etag: str() """ if href is None: - raise ValueError('href may not be None') + raise ValueError(u'href may not be None') ical = icalendar.Event.from_ical(vevent_str) vevents = (aux.sanitize(c, self.locale['default_timezone'], href, self.calendar) for - c in ical.walk() if c.name == 'VEVENT') + c in ical.walk() if c.name == u'VEVENT') # Need to delete the whole event in case we are updating a # recurring event with an event which is either not recurring any # more or has EXDATEs, as those would be left in the recursion @@ -253,9 +250,9 @@ def update(self, vevent_str, href, etag=''): check_support(vevent, href, self.calendar) self._update_impl(vevent, href, self.calendar) - sql_s = ('INSERT INTO events ' - '(item, etag, href, calendar) ' - 'VALUES (?, ?, ?, ?);') + sql_s = (u'INSERT INTO events ' + u'(item, etag, href, calendar) ' + u'VALUES (?, ?, ?, ?);') stuple = (vevent_str, etag, href, self.calendar) self.sql_ex(sql_s, stuple) @@ -281,9 +278,9 @@ def _update_impl(self, vevent, href, calendar): dtype = DATETIME if ('TZID' in vevent['DTSTART'].params and dtype == DATETIME) or \ getattr(vevent['DTSTART'].dt, 'tzinfo', None): - recs_table = 'recs_loc' + recs_table = u'recs_loc' else: - recs_table = 'recs_float' + recs_table = u'recs_float' thisandfuture = (rrange == THISANDFUTURE) if thisandfuture: @@ -320,21 +317,21 @@ def _update_impl(self, vevent, href, calendar): if thisandfuture: recs_sql_s = ( - 'UPDATE {0} SET dtstart = rec_inst + ?, dtend = rec_inst + ?, ref = ? ' - 'WHERE rec_inst >= ? AND href = ? AND calendar = ?;'.format(recs_table)) + u'UPDATE {0} SET dtstart = rec_inst + ?, dtend = rec_inst + ?, ref = ? ' + u'WHERE rec_inst >= ? AND href = ? AND calendar = ?;'.format(recs_table)) stuple = (start_shift, start_shift + duration, ref, rec_inst, href, calendar) else: recs_sql_s = ( - 'INSERT OR REPLACE INTO {0} ' - '(dtstart, dtend, href, ref, dtype, rec_inst, calendar)' - 'VALUES (?, ?, ?, ?, ?, ?, ?);'.format(recs_table)) + u'INSERT OR REPLACE INTO {0} ' + u'(dtstart, dtend, href, ref, dtype, rec_inst, calendar)' + u'VALUES (?, ?, ?, ?, ?, ?, ?);'.format(recs_table)) stuple = (dbstart, dbend, href, ref, dtype, rec_inst, self.calendar) self.sql_ex(recs_sql_s, stuple) # end of loop def get_ctag(self): stuple = (self.calendar, ) - sql_s = 'SELECT ctag FROM calendars WHERE calendar = ?;' + sql_s = u'SELECT ctag FROM calendars WHERE calendar = ?;' try: ctag = self.sql_ex(sql_s, stuple)[0][0] return ctag @@ -343,7 +340,7 @@ def get_ctag(self): def set_ctag(self, ctag): stuple = (ctag, self.calendar, ) - sql_s = 'UPDATE calendars SET ctag = ? WHERE calendar = ?;' + sql_s = u'UPDATE calendars SET ctag = ? WHERE calendar = ?;' self.sql_ex(sql_s, stuple) self.conn.commit() @@ -354,7 +351,7 @@ def get_etag(self, href): return: etag rtype: str() """ - sql_s = 'SELECT etag FROM events WHERE href = ? AND calendar = ?;' + sql_s = u'SELECT etag FROM events WHERE href = ? AND calendar = ?;' try: etag = self.sql_ex(sql_s, (href, self.calendar))[0][0] return etag @@ -369,17 +366,17 @@ def delete(self, href, etag=None): we always delete :returns: None """ - for table in ['recs_loc', 'recs_float']: - sql_s = 'DELETE FROM {0} WHERE href = ? AND calendar = ?;'.format(table) + for table in [u'recs_loc', u'recs_float']: + sql_s = u'DELETE FROM {0} WHERE href = ? AND calendar = ?;'.format(table) self.sql_ex(sql_s, (href, self.calendar)) - sql_s = 'DELETE FROM events WHERE href = ? AND calendar = ?;' + sql_s = u'DELETE FROM events WHERE href = ? AND calendar = ?;' self.sql_ex(sql_s, (href, self.calendar)) def list(self): """ :returns: list of (href, etag) """ - sql_s = 'SELECT href, etag FROM events WHERE calendar = ?;' + sql_s = u'SELECT href, etag FROM events WHERE calendar = ?;' return list(set(self.sql_ex(sql_s, (self.calendar, )))) def get_time_range(self, start, end): @@ -394,13 +391,13 @@ def get_time_range(self, start, end): end = self.locale['local_timezone'].localize(end) start = aux.to_unix_time(start) end = aux.to_unix_time(end) - sql_s = ('SELECT recs_loc.href, dtstart, dtend, ref, dtype FROM ' - 'recs_loc JOIN events ON ' - 'recs_loc.href = events.href AND ' - 'recs_loc.calendar = events.calendar WHERE ' - '(dtstart >= ? AND dtstart <= ? OR ' - 'dtend >= ? AND dtend <= ? OR ' - 'dtstart <= ? AND dtend >= ?) AND events.calendar = ?;') + sql_s = (u'SELECT recs_loc.href, dtstart, dtend, ref, dtype FROM ' + u'recs_loc JOIN events ON ' + u'recs_loc.href = events.href AND ' + u'recs_loc.calendar = events.calendar WHERE ' + u'(dtstart >= ? AND dtstart <= ? OR ' + u'dtend >= ? AND dtend <= ? OR ' + u'dtstart <= ? AND dtend >= ?) AND events.calendar = ?;') stuple = (start, end, start, end, start, end, self.calendar) result = self.sql_ex(sql_s, stuple) for href, start, end, ref, dtype in result: @@ -419,13 +416,13 @@ def get_allday_range(self, start): # XXX rename get_float_range() strstart = aux.to_unix_time(start) strend = aux.to_unix_time(start + timedelta(days=1)) - sql_s = ('SELECT recs_float.href, dtstart, dtend, ref, dtype FROM ' - 'recs_float JOIN events ON ' - 'recs_float.href = events.href AND ' - 'recs_float.calendar = events.calendar WHERE ' - '(dtstart >= ? AND dtstart < ? OR ' - 'dtend > ? AND dtend <= ? OR ' - 'dtstart <= ? AND dtend > ? ) AND events.calendar = ?;') + sql_s = (u'SELECT recs_float.href, dtstart, dtend, ref, dtype FROM ' + u'recs_float JOIN events ON ' + u'recs_float.href = events.href AND ' + u'recs_float.calendar = events.calendar WHERE ' + u'(dtstart >= ? AND dtstart < ? OR ' + u'dtend > ? AND dtend <= ? OR ' + u'dtstart <= ? AND dtend > ? ) AND events.calendar = ?;') stuple = (strstart, strend, strstart, strend, strstart, strend, self.calendar) result = self.sql_ex(sql_s, stuple) for href, start, end, ref, dtype in result: @@ -442,12 +439,12 @@ def get_datetime_at(self, dtime): :type dtime: datetime.datetime """ dtime = aux.to_unix_time(dtime) - sql_s = ('SELECT recs_loc.href, dtstart, dtend, ref, dtype FROM ' - 'recs_loc JOIN events ON ' - 'recs_loc.href = events.href AND ' - 'recs_loc.calendar = events.calendar WHERE ' - '(dtstart <= ? AND dtend >= ? ) ' - 'AND events.calendar = ?;') + sql_s = (u'SELECT recs_loc.href, dtstart, dtend, ref, dtype FROM ' + u'recs_loc JOIN events ON ' + u'recs_loc.href = events.href AND ' + u'recs_loc.calendar = events.calendar WHERE ' + u'(dtstart <= ? AND dtend >= ? ) ' + u'AND events.calendar = ?;') stuple = (dtime, dtime, self.calendar) result = self.sql_ex(sql_s, stuple) for href, start, end, ref, dtype in result: @@ -465,12 +462,12 @@ def get_allday_at(self, dtime): if isinstance(dtime, datetime): dtime = dtime.date() dtime = aux.to_unix_time(dtime) - sql_s = ('SELECT recs_float.href, dtstart, dtend, ref, dtype FROM ' - 'recs_float JOIN events ON ' - 'recs_float.href = events.href AND ' - 'recs_float.calendar = events.calendar WHERE ' - '(dtstart <= ? AND dtend >= ? )' - 'AND events.calendar = ?;') + sql_s = (u'SELECT recs_float.href, dtstart, dtend, ref, dtype FROM ' + u'recs_float JOIN events ON ' + u'recs_float.href = events.href AND ' + u'recs_float.calendar = events.calendar WHERE ' + u'(dtstart <= ? AND dtend >= ? )' + u'AND events.calendar = ?;') stuple = (dtime, dtime, self.calendar) result = self.sql_ex(sql_s, stuple) for href, start, end, ref, dtype in result: @@ -485,7 +482,7 @@ def get(self, href, start=None, end=None, ref=None, dtype=None): if start and end are given, a specific Event from a Recursion set is returned, otherwise the Event returned exactly as saved in the db """ - sql_s = 'SELECT href, etag, item FROM events WHERE href = ? AND calendar = ?;' + sql_s = u'SELECT href, etag, item FROM events WHERE href = ? AND calendar = ?;' result = self.sql_ex(sql_s, (href, self.calendar)) href, etag, item = result[0] if dtype == DATE: @@ -503,9 +500,9 @@ def get(self, href, start=None, end=None, ref=None, dtype=None): def search(self, search_string): """search for events matching `search_string`""" - sql_s = ('SELECT href FROM events ' - 'WHERE item LIKE (?) and calendar = (?)') - stuple = ('%' + search_string + '%', self.calendar) + sql_s = (u'SELECT href FROM events ' + u'WHERE item LIKE (?) and calendar = (?)') + stuple = (u'%' + search_string + u'%', self.calendar) result = self.sql_ex(sql_s, stuple) for href, in result: event = self.get(href) @@ -523,19 +520,19 @@ def check_support(vevent, href, calendar): rec_id = vevent.get(RECURRENCE_ID) if rec_id is not None and rec_id.params.get('RANGE') == THISANDPRIOR: raise UpdateFailed( - 'The parameter `THISANDPRIOR` is not (and will not be) ' - 'supported by khal (as applications supporting the latest ' - 'standard MUST NOT create those. Therefore event {} from ' - 'calendar {} will not be shown in khal' + u'The parameter `THISANDPRIOR` is not (and will not be) ' + u'supported by khal (as applications supporting the latest ' + u'standard MUST NOT create those. Therefore event {} from ' + u'calendar {} will not be shown in khal' .format(href, calendar) ) rdate = vevent.get('RDATE') if rdate is not None and rdate.params.get('VALUE') == 'PERIOD': raise UpdateFailed( - '`RDATE;VALUE=PERIOD` is currently not supported by khal. ' - 'Therefore event {} from calendar {} will not be shown in khal.\n' - 'Please post exemplary events (please remove any private data) ' - 'to https://github.com/geier/khal/issues/152 .' + u'`RDATE;VALUE=PERIOD` is currently not supported by khal. ' + u'Therefore event {} from calendar {} will not be shown in khal.\n' + u'Please post exemplary events (please remove any private data) ' + u'to https://github.com/geier/khal/issues/152 .' .format(href, calendar) ) @@ -543,19 +540,18 @@ def check_support(vevent, href, calendar): class SQLiteDb_Birthdays(SQLiteDb): def update(self, vevent, href, etag=''): if href is None: - raise ValueError('href may not be None') + raise ValueError(u'href may not be None') ical = icalendar.Event.from_ical(vevent) vcard = ical.walk()[0] - # TODO deal with dates without a year, e.g. --0412 if 'BDAY' in vcard.keys(): bday = vcard['BDAY'] try: - if bday[0:2] == '--' and bday[3] != '-': + if bday[0:2] == u'--' and bday[3] != u'-': bday = '1900' + bday[2:] bday = parser.parse(bday).date() except ValueError: - logger.info('cannot parse BIRTHDAY in {} in collection ' - '{}'.format(href, self.calendar)) + logger.info(u'cannot parse BIRTHDAY in {} in collection ' + u'{}'.format(href, self.calendar)) return name = vcard['FN'] event = icalendar.Event() @@ -566,9 +562,9 @@ def update(self, vevent, href, etag=''): event.add('uid', href) event_str = event.to_ical().decode('utf-8') self._update_impl(event, href, self.calendar) - sql_s = ('INSERT INTO events ' - '(item, etag, href, calendar) ' - 'VALUES (?, ?, ?, ?);') + sql_s = (u'INSERT INTO events ' + u'(item, etag, href, calendar) ' + u'VALUES (?, ?, ?, ?);') stuple = (event_str, etag, href, self.calendar) self.sql_ex(sql_s, stuple) diff --git a/khal/khalendar/event.py b/khal/khalendar/event.py index ec644430a..77de007a5 100644 --- a/khal/khalendar/event.py +++ b/khal/khalendar/event.py @@ -22,8 +22,6 @@ """this module cointains the event model, hopefully soon in a cleaned up version""" -from __future__ import unicode_literals - from datetime import date, datetime, time, timedelta import icalendar @@ -210,19 +208,19 @@ def increment_sequence(self): def symbol_strings(self): if self._locale['unicode_symbols']: return dict( - recurring='\N{Clockwise gapped circle arrow}', - range='\N{Left right arrow}', - range_end='\N{Rightwards arrow to bar}', - range_start='\N{Rightwards arrow from bar}', - right_arrow='\N{Rightwards arrow}' + recurring=u'\N{Clockwise gapped circle arrow}', + range=u'\N{Left right arrow}', + range_end=u'\N{Rightwards arrow to bar}', + range_start=u'\N{Rightwards arrow from bar}', + right_arrow=u'\N{Rightwards arrow}' ) else: return dict( - recurring='R', - range='<->', - range_end='->|', - range_start='|->', - right_arrow='->' + recurring=u'R', + range=u'<->', + range_end=u'->|', + range_start=u'|->', + right_arrow=u'->' ) @property @@ -260,12 +258,12 @@ def uid(self): @property def organizer(self): if 'ORGANIZER' not in self._vevents[self.ref]: - return '' + return u'' organizer = self._vevents[self.ref]['ORGANIZER'] cn = organizer.params.get('CN', '') email = organizer.split(':')[-1] if cn: - return '{} ({})'.format(cn, email) + return u'{} ({})'.format(cn, email) else: return email @@ -278,8 +276,8 @@ def _create_calendar(): :rtype: icalendar.Calendar() """ calendar = icalendar.Calendar() - calendar.add('version', '2.0') - calendar.add('prodid', '-//CALENDARSERVER.ORG//NONSGML Version 1//EN') + calendar.add(u'version', u'2.0') + calendar.add(u'prodid', u'-//CALENDARSERVER.ORG//NONSGML Version 1//EN') return calendar @property @@ -337,7 +335,7 @@ def _recur_str(self): if self.recurring: recurstr = self.symbol_strings['recurring'] else: - recurstr = '' + recurstr = u'' return recurstr def relative_to(self, day, full=False): @@ -362,28 +360,28 @@ def relative_to(self, day, full=False): day_start = self._locale['local_timezone'].localize(datetime.combine(day, time.min)) day_end = self._locale['local_timezone'].localize(datetime.combine(day, time.max)) - tostr = '-' + tostr = u'-' if self.start_local < day_start: - startstr = self.symbol_strings['right_arrow'] + ' ' - tostr = '' + startstr = self.symbol_strings['right_arrow'] + u' ' + tostr = u'' else: startstr = self.start_local.strftime(self._locale['timeformat']) if self.end_local > day_end: - endstr = self.symbol_strings['right_arrow'] + ' ' - tostr = '' + endstr = self.symbol_strings['right_arrow'] + u' ' + tostr = u'' else: endstr = self.end_local.strftime(self._locale['timeformat']) - body = self.summary + body = self.summary if full: - if self.description.strip() != "": - body += ", " + self.description.strip() - if self.location.strip() != "": - body += ", " + self.location.strip() + if self.description.strip() != u'': + body += u', ' + self.description.strip() + if self.location.strip() != u'': + body += u', ' + self.location.strip() - comps = [startstr + tostr + endstr + ':', body, self._recur_str] - return ' '.join(filter(bool, comps)) + comps = [startstr + tostr + endstr + u':', body, self._recur_str] + return u' '.join(filter(bool, comps)) @property def event_description(self): # XXX rename me @@ -393,13 +391,13 @@ def event_description(self): # XXX rename me :returns: event description """ - location = '\nLocation: ' + self.location if self.location != '' else '' - description = '\nDescription: ' + self.description if \ - self.description != '' else '' - repitition = '\nRepeat: ' + to_unicode(self.recurpattern) if \ - self.recurpattern != '' else '' + location = u'\nLocation: ' + self.location if self.location != u'' else u'' + description = u'\nDescription: ' + self.description if \ + self.description != u'' else u'' + repitition = u'\nRepeat: ' + to_unicode(self.recurpattern) if \ + self.recurpattern != u'' else u'' - return '{}: {}{}{}{}'.format( + return u'{}: {}{}{}{}'.format( self._rangestr, self.summary, location, repitition, description) def duplicate(self): @@ -444,11 +442,11 @@ def _rangestr(self): starttime = self.start_local.strftime(self._locale['timeformat']) endtime = self.end_local.strftime(self._locale['timeformat']) datestr = self.end_local.strftime(self._locale['longdateformat']) - rangestr = starttime + '-' + endtime + ' ' + datestr + rangestr = starttime + u'-' + endtime + u' ' + datestr else: startstr = self.start_local.strftime(self._locale['longdatetimeformat']) endstr = self.end_local.strftime(self._locale['longdatetimeformat']) - rangestr = startstr + ' - ' + endstr + rangestr = startstr + u' - ' + endstr return rangestr @@ -460,7 +458,7 @@ class LocalizedEvent(DatetimeEvent): def start(self): """in case DTSTART has no tzinfo (or it is set to None) we assume it was meant to be set in the default_timezone""" - if getattr(self._start, 'tzinfo', None) is not None: + if getattr(self._start, u'tzinfo', None) is not None: return self._start return self._locale['default_timezone'].localize(self._start) @@ -507,11 +505,11 @@ def end(self): end = super(AllDayEvent, self).end if end == self.start: # https://github.com/geier/khal/issues/129 - logger.warning('{} ("{}"): The event\'s end date property ' - 'contains the same value as the start date, ' - 'which is invalid as per RFC 2445. Khal will ' - 'assume this is meant to be single-day event ' - 'on {}'.format(self.href, self.summary, + logger.warning(u'{} ("{}"): The event\'s end date property ' + u'contains the same value as the start date, ' + u'which is invalid as per RFC 2445. Khal will ' + u'assume this is meant to be single-day event ' + u'on {}'.format(self.href, self.summary, self.start)) end += timedelta(days=1) return end - timedelta(days=1) @@ -532,16 +530,16 @@ def relative_to(self, day, full=False): rangestr = self.symbol_strings['range_start'] elif self.start == self.end == day: # only on `day` - rangestr = '' + rangestr = u'' - body = self.summary + body = self.summary if full: - if self.description.strip() != "": - body += ", " + self.description.strip() - if self.location.strip() != "": - body += ", " + self.location.strip() + if self.description.strip() != u'': + body += u', ' + self.description.strip() + if self.location.strip() != u'': + body += u', ' + self.location.strip() - return ' '.join(filter(bool, (rangestr, body, self._recur_str))) + return u' '.join(filter(bool, (rangestr, body, self._recur_str))) @property def _rangestr(self): @@ -553,7 +551,7 @@ def _rangestr(self): else: startstr = self.start_local.strftime(self._locale['longdateformat']) endstr = self.end_local.strftime(self._locale['longdateformat']) - rangestr = startstr + ' - ' + endstr + rangestr = startstr + u' - ' + endstr return rangestr diff --git a/khal/ui/__init__.py b/khal/ui/__init__.py index 0080408fb..a32858953 100644 --- a/khal/ui/__init__.py +++ b/khal/ui/__init__.py @@ -20,8 +20,6 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -from __future__ import unicode_literals - from datetime import date, datetime, time import signal import sys @@ -72,19 +70,19 @@ def selectable(cls): @property def uid(self): - return self.event.calendar + '\n' + \ - str(self.event.href) + '\n' + str(self.event.etag) + return self.event.calendar + u'\n' + \ + str(self.event.href) + u'\n' + str(self.event.etag) def set_title(self, mark=''): if self.uid in self.eventcolumn.pane.deleted: mark = 'D' - self.set_text(mark + ' ' + self.event.relative_to(self.this_date)) + self.set_text(mark + u' ' + self.event.relative_to(self.this_date)) def toggle_delete(self): # TODO unify, either directly delete *normal* events as well # or stage recurring deletion as well def delete_this(_): - if self.event.ref == 'PROTO': + if self.event.ref == u'PROTO': instance = self.event.start else: instance = self.event.ref @@ -226,7 +224,7 @@ class EventColumn(urwid.WidgetWrap): def __init__(self, pane): self.pane = pane - self.divider = urwid.Divider('─') + self.divider = urwid.Divider(u'─') self.editor = False self.eventcount = 0 self._current_date = None @@ -341,8 +339,8 @@ def __init__(self, rrule): self.rrule = rrule recursive = self.rrule['freq'][0].lower() if self.rrule else NOREPEAT self.recursion_choice = Choice( - [NOREPEAT, "weekly", "monthly", "yearly"], recursive) - self.columns = CColumns([(10, urwid.Text('Repeat: ')), (11, self.recursion_choice)]) + [NOREPEAT, u"weekly", u"monthly", u"yearly"], recursive) + self.columns = CColumns([(10, urwid.Text(u'Repeat: ')), (11, self.recursion_choice)]) urwid.WidgetWrap.__init__(self, self.columns) @property @@ -375,17 +373,17 @@ def __init__(self, conf, event, collection=None): self.conf = conf self.collection = collection self.event = event - divider = urwid.Divider(' ') + divider = urwid.Divider(u' ') lines = [] - lines.append(urwid.Text('Title: ' + event.summary)) + lines.append(urwid.Text(u'Title: ' + event.summary)) # show organizer - if event.organizer != '': - lines.append(urwid.Text('Organizer: ' + event.organizer)) + if event.organizer != u'': + lines.append(urwid.Text(u'Organizer: ' + event.organizer)) - if event.location != '': - lines.append(urwid.Text('Location: ' + event.location)) + if event.location != u'': + lines.append(urwid.Text(u'Location: ' + event.location)) # start and end time/date if event.allday: @@ -393,26 +391,26 @@ def __init__(self, conf, event, collection=None): endstr = event.end_local.strftime(self.conf['locale']['dateformat']) else: startstr = event.start_local.strftime( - '{} {}'.format(self.conf['locale']['dateformat'], + u'{} {}'.format(self.conf['locale']['dateformat'], self.conf['locale']['timeformat']) ) if event.start_local.date == event.end_local.date: endstr = event.end_local.strftime(self.conf['locale']['timeformat']) else: endstr = event.end_local.strftime( - '{} {}'.format(self.conf['locale']['dateformat'], + u'{} {}'.format(self.conf['locale']['dateformat'], self.conf['locale']['timeformat']) ) if startstr == endstr: - lines.append(urwid.Text('Date: ' + startstr)) + lines.append(urwid.Text(u'Date: ' + startstr)) else: - lines.append(urwid.Text('Date: ' + startstr + ' - ' + endstr)) + lines.append(urwid.Text(u'Date: ' + startstr + u' - ' + endstr)) - lines.append(urwid.Text('Calendar: ' + event.calendar)) + lines.append(urwid.Text(u'Calendar: ' + event.calendar)) lines.append(divider) - if event.description != '': + if event.description != u'': lines.append(urwid.Text(event.description)) pile = CPile(lines) @@ -445,23 +443,23 @@ def __init__(self, pane, event): event.start_local, event.end_local, self.conf, self.pane.eventscolumn.original_widget.set_current_date) self.recursioneditor = RecursionEditor(self.event.recurobject) - self.summary = Edit(caption='Title: ', edit_text=event.summary) + self.summary = Edit(caption=u'Title: u', edit_text=event.summary) divider = urwid.Divider(' ') # TODO warning message if len(self.collection.writable_names) == 0 def decorate_choice(c): - return (c.color or '', c.name) + return (c.color or u'', c.name) self.calendar_chooser = Choice( [c for c in self.collection.calendars if not c.readonly], self.collection._calnames[self.event.calendar], decorate_choice ) - self.description = Edit(caption='Description: ', + self.description = Edit(caption=u'Description: ', edit_text=self.description, multiline=True) - self.location = Edit(caption='Location: ', + self.location = Edit(caption=u'Location: ', edit_text=self.location) self.pile = urwid.ListBox(CSimpleFocusListWalker([ urwid.Columns([ @@ -475,19 +473,19 @@ def decorate_choice(c): self.startendeditor, self.recursioneditor, divider, - urwid.Button('Save', on_press=self.save) + urwid.Button(u'Save', on_press=self.save) ])) urwid.WidgetWrap.__init__(self, self.pile) @property def title(self): # Window title - return 'Edit: {}'.format(self.summary.get_edit_text()) + return u'Edit: {}'.format(self.summary.get_edit_text()) def get_keys(self): - return [(['arrows'], 'navigate through properties'), - (['enter'], 'edit property'), - (['esc'], 'abort')] + return [(['arrowsu'], u'navigate through properties'), + (['enter'], u'edit property'), + (['esc'], u'abort')] @classmethod def selectable(cls): diff --git a/khal/ui/calendarwidget.py b/khal/ui/calendarwidget.py index fcfdc1268..caed8866d 100644 --- a/khal/ui/calendarwidget.py +++ b/khal/ui/calendarwidget.py @@ -20,8 +20,6 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -from __future__ import unicode_literals - import calendar from datetime import date from locale import getlocale, setlocale, LC_ALL @@ -91,7 +89,7 @@ def reset_styles(self): @property def marked(self): - if 'mark' in [self.halves[0].attr_map[None], self.halves[1].attr_map[None]]: + if u'mark' in [self.halves[0].attr_map[None], self.halves[1].attr_map[None]]: return True else: return False @@ -155,8 +153,8 @@ def set_focus_date(self, a_date): focus_position = property( urwid.Columns._get_focus_position, _set_focus_position, - doc=('Index of child widget in focus. Raises IndexError if read when ' - 'CColumns is empty, or when set to an invalid index.') + doc=(u'Index of child widget in focus. Raises IndexError if read when ' + u'CColumns is empty, or when set to an invalid index.') ) def keypress(self, size, key): @@ -538,10 +536,6 @@ def __init__(self, on_date_change, keybindings, on_press, except TypeError: # language code and encoding may be None mylocale = 'C' - if compat.VERSION == 2: - # XXX please remove me when removing unicode literals - mylocale = mylocale.encode('ascii') - _calendar = calendar.LocaleTextCalendar(firstweekday, mylocale) weekheader = _calendar.formatweekheader(2) dnames = weekheader.split(' ') From cd3563bfdeefca6ef280ffde228ddd688a8229d4 Mon Sep 17 00:00:00 2001 From: Christian Geier Date: Fri, 13 Nov 2015 00:43:19 +0100 Subject: [PATCH 2/3] pep8 --- khal/khalendar/event.py | 2 +- khal/khalendar/khalendar.py | 10 +++++----- khal/ui/__init__.py | 4 ++-- khal/ui/calendarwidget.py | 3 --- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/khal/khalendar/event.py b/khal/khalendar/event.py index 77de007a5..f88ecbeae 100644 --- a/khal/khalendar/event.py +++ b/khal/khalendar/event.py @@ -510,7 +510,7 @@ def end(self): u'which is invalid as per RFC 2445. Khal will ' u'assume this is meant to be single-day event ' u'on {}'.format(self.href, self.summary, - self.start)) + self.start)) end += timedelta(days=1) return end - timedelta(days=1) diff --git a/khal/khalendar/khalendar.py b/khal/khalendar/khalendar.py index 3128a99d2..269370564 100644 --- a/khal/khalendar/khalendar.py +++ b/khal/khalendar/khalendar.py @@ -388,16 +388,16 @@ def get_day_styles(self, day, focus): if self.hmethod == 'bg' or self.hmethod == 'background': prefix = 'bg ' if self.color != '': - return prefix+self.color + return prefix + self.color dcolors = list(set(map(lambda x: self.get_event_color(x), devents))) if len(dcolors) == 1: if devents[0].color == '': - return prefix+self.default_color + return prefix + self.default_color else: - return prefix+devents[0].color + return prefix + devents[0].color if self.multiple != '': - return prefix+self.multiple - return (prefix+dcolors[0], prefix+dcolors[1]) + return prefix + self.multiple + return (prefix + dcolors[0], prefix + dcolors[1]) def get_styles(self, date, focus): if focus: diff --git a/khal/ui/__init__.py b/khal/ui/__init__.py index a32858953..6875ec93f 100644 --- a/khal/ui/__init__.py +++ b/khal/ui/__init__.py @@ -392,14 +392,14 @@ def __init__(self, conf, event, collection=None): else: startstr = event.start_local.strftime( u'{} {}'.format(self.conf['locale']['dateformat'], - self.conf['locale']['timeformat']) + self.conf['locale']['timeformat']) ) if event.start_local.date == event.end_local.date: endstr = event.end_local.strftime(self.conf['locale']['timeformat']) else: endstr = event.end_local.strftime( u'{} {}'.format(self.conf['locale']['dateformat'], - self.conf['locale']['timeformat']) + self.conf['locale']['timeformat']) ) if startstr == endstr: diff --git a/khal/ui/calendarwidget.py b/khal/ui/calendarwidget.py index caed8866d..32d5254a8 100644 --- a/khal/ui/calendarwidget.py +++ b/khal/ui/calendarwidget.py @@ -26,9 +26,6 @@ import urwid -from .. import compat - - setlocale(LC_ALL, '') From 50c1c8401e28237b5898fbd8f1ee33922d2b1ace Mon Sep 17 00:00:00 2001 From: Christian Geier Date: Fri, 13 Nov 2015 00:46:01 +0100 Subject: [PATCH 3/3] got a bit trigger happy with adding `u`s --- khal/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/khal/ui/__init__.py b/khal/ui/__init__.py index 6875ec93f..28e42c07a 100644 --- a/khal/ui/__init__.py +++ b/khal/ui/__init__.py @@ -443,7 +443,7 @@ def __init__(self, pane, event): event.start_local, event.end_local, self.conf, self.pane.eventscolumn.original_widget.set_current_date) self.recursioneditor = RecursionEditor(self.event.recurobject) - self.summary = Edit(caption=u'Title: u', edit_text=event.summary) + self.summary = Edit(caption=u'Title: ', edit_text=event.summary) divider = urwid.Divider(' ')