Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def rrulefstr(repeat, until, locale):
if repeat in ["daily", "weekly", "monthly", "yearly"]:
rrule_settings = {'freq': repeat}
if until:
until_dt, is_date = guessdatetimefstr(until.split(' '), locale)
rrule_settings['until'] = until_dt
return rrule_settings
else:
logger.fatal("Invalid value for the repeat option. \
Possible values are: daily, weekly, monthly or yearly")
raise FatalError()
categories = list([category.strip() for category in categories.split(',')])
try:
event = new_vevent(
locale=conf['locale'], location=location, categories=categories,
repeat=repeat, until=until, alarms=alarms, dtstart=dtstart,
dtend=dtend, summary=summary, description=description, timezone=timezone,
)
except ValueError as error:
raise FatalError(error)
event = Event.fromVEvents(
[event], calendar=calendar_name, locale=conf['locale'])
try:
collection.new(event)
except ReadOnlyCalendarError:
raise FatalError(
'ERROR: Cannot modify calendar "{}" as it is read-only'.format(calendar_name)
)
if conf['default']['print_new'] == 'event':
if format is None:
format = conf['view']['event_format']
echo(event.format(format, dt.datetime.now(), env=env))
elif conf['default']['print_new'] == 'path':
path = os.path.join(
collection._calendars[event.calendar]['path'],
event.href
)
echo(path)
return event
def new_from_args(collection, calendar_name, conf, dtstart=None, dtend=None,
summary=None, description=None, allday=None, location=None,
categories=None, repeat=None, until=None, alarms=None,
timezone=None, format=None, env=None):
"""Create a new event from arguments and add to vdirs"""
if isinstance(categories, str):
categories = list([category.strip() for category in categories.split(',')])
try:
event = new_vevent(
locale=conf['locale'], location=location, categories=categories,
repeat=repeat, until=until, alarms=alarms, dtstart=dtstart,
dtend=dtend, summary=summary, description=description, timezone=timezone,
)
except ValueError as error:
raise FatalError(error)
event = Event.fromVEvents(
[event], calendar=calendar_name, locale=conf['locale'])
try:
collection.new(event)
except ReadOnlyCalendarError:
raise FatalError(
'ERROR: Cannot modify calendar "{}" as it is read-only'.format(calendar_name)
)
if conf['default']['print_new'] == 'event':
if format is None:
format = conf['view']['event_format']
echo(event.format(format, dt.datetime.now(), env=env))
elif conf['default']['print_new'] == 'path':
path = os.path.join(
else:
end = start + default_timedelta_datetime
elif end.lower() == 'eod':
end = dt.datetime.combine(start.date(), dt.time.max)
elif end.lower() == 'week':
start -= dt.timedelta(days=(start.weekday() - locale['firstweekday']))
end = start + dt.timedelta(days=8)
else:
try:
delta = guesstimedeltafstr(end)
if allday and delta.total_seconds() % (3600 * 24):
# TODO better error class, no logging in here
logger.fatal(
"Cannot give delta containing anything but whole days for allday events"
)
raise FatalError()
elif delta.total_seconds() == 0:
logger.fatal(
"Events that last no time are not allowed"
)
raise FatalError()
end = start + delta
except (ValueError, DateTimeParseError):
split = end.split(" ")
end, end_allday = guessdatetimefstr(
split, locale, default_day=start.date(), in_future=False)
if len(split) != 0:
continue
if allday:
end += dt.timedelta(days=1)
start, end = start_end_from_daterange(
daterange, conf['locale'],
default_timedelta_date=conf['default']['timedelta'],
default_timedelta_datetime=conf['default']['timedelta'],
)
logger.debug('Getting all events between {} and {}'.format(start, end))
elif datepoint is not None:
if not datepoint:
datepoint = ['now']
try:
start, allday = parse_datetime.guessdatetimefstr(
datepoint, conf['locale'], dt.date.today(),
)
except ValueError:
raise FatalError('Invalid value of `{}` for a datetime'.format(' '.join(datepoint)))
if allday:
logger.debug('Got date {}'.format(start))
raise FatalError('Please supply a datetime, not a date.')
end = start + dt.timedelta(seconds=1)
if day_format is None:
day_format = style(
start.strftime(conf['locale']['longdatetimeformat']),
bold=True,
)
logger.debug('Getting all events between {} and {}'.format(start, end))
event_column = []
once = set() if once else None
if env is None:
env = {}
logger.fatal("Found an existing config file at {}.".format(config_file))
logger.fatal(
"If you want to create a new configuration file, "
"please remove the old one first. Exiting.")
raise FatalError()
dateformat = choose_datetime_format()
print()
timeformat = choose_time_format()
print()
vdirs = get_vdirs_from_vdirsyncer_config()
print()
if not vdirs:
try:
vdirs = create_vdir()
except OSError as error:
raise FatalError(error)
if not vdirs:
print("\nWARNING: no vdir configured, khal will not be usable like this!\n")
config = create_config(vdirs, dateformat=dateformat, timeformat=timeformat)
config_path = join(xdg.BaseDirectory.xdg_config_home, 'khal', 'config')
if not confirm(
"Do you want to write the config to {}? "
"(Choosing `No` will abort)".format(config_path), default=True):
raise FatalError('User aborted...')
config_dir = join(xdg.BaseDirectory.xdg_config_home, 'khal')
if not exists(config_dir) and not isdir(config_dir):
try:
makedirs(config_dir)
except OSError as error:
print(
default_timedelta_datetime=conf['default']['timedelta'],
)
logger.debug('Getting all events between {} and {}'.format(start, end))
elif datepoint is not None:
if not datepoint:
datepoint = ['now']
try:
start, allday = parse_datetime.guessdatetimefstr(
datepoint, conf['locale'], dt.date.today(),
)
except ValueError:
raise FatalError('Invalid value of `{}` for a datetime'.format(' '.join(datepoint)))
if allday:
logger.debug('Got date {}'.format(start))
raise FatalError('Please supply a datetime, not a date.')
end = start + dt.timedelta(seconds=1)
if day_format is None:
day_format = style(
start.strftime(conf['locale']['longdatetimeformat']),
bold=True,
)
logger.debug('Getting all events between {} and {}'.format(start, end))
event_column = []
once = set() if once else None
if env is None:
env = {}
original_start = conf['locale']['local_timezone'].localize(start)
while start < end:
if start.date() == end.date():
"""base class for all of khal's Exceptions"""
pass
class FatalError(Error):
"""execution cannot continue"""
pass
class DateTimeParseError(FatalError):
pass
class ConfigurationError(FatalError):
pass
class UnsupportedFeatureError(Error):
"""something Failed but we know why"""
pass
class UnsupportedRecurrence(Error):
"""raised if the RRULE is not understood by dateutil.rrule"""
pass
class InvalidDate(Error):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
starttz = getattr(self._vevents[self.ref]['DTSTART'].dt, 'tzinfo', None)
except KeyError:
msg = (
"Cannot understand event {} from "
"calendar {}, you might want to file an issue at "
"https://github.com/pimutils/khal/issues"
.format(kwargs.get('href'), kwargs.get('calendar'))
)
logger.fatal(msg)
raise FatalError( # because in ikhal you won't see the logger's output
msg
)
if starttz is None:
starttz = self._locale['default_timezone']
try:
endtz = getattr(self._vevents[self.ref]['DTEND'].dt, 'tzinfo', None)
except KeyError:
endtz = starttz
if endtz is None:
endtz = self._locale['default_timezone']
if is_aware(self._start):
self._start = self._start.astimezone(starttz)
else:
self._start = starttz.localize(self._start)
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Error(Exception):
"""base class for all of khal's Exceptions"""
pass
class FatalError(Error):
"""execution cannot continue"""
pass
class DateTimeParseError(FatalError):
pass
class ConfigurationError(FatalError):
pass
class UnsupportedFeatureError(Error):
"""something Failed but we know why"""
pass
class UnsupportedRecurrence(Error):
"""raised if the RRULE is not understood by dateutil.rrule"""