1. Olemis Lang
  2. fsl

Source

fsl / fsl / test / tutils.py

import glob
import datetime
import types
import re

ROOTDIR = 'testdir'

FSLTOOL_FILES_DIR = 'fsltool_files'
LEXER_FILES_DIR = 'lexer_files'
INTERPRETER_FILES_DIR = 'interpreter_files'


def get_fsltool_file(filename):
    return FSLTOOL_FILES_DIR + '/' + filename


def get_lexer_file(filename):
    return LEXER_FILES_DIR + '/' + filename

def get_lexer_files(glob_pattern='*'):
    return glob.glob(LEXER_FILES_DIR + '/' + glob_pattern)


def get_interpreter_file(filename):
    return INTERPRETER_FILES_DIR + '/' + filename

def get_interpreter_files(glob_pattern='*'):
    return glob.glob(INTERPRETER_FILES_DIR + '/' + glob_pattern)


def get_all_files(glob_pattern='*'):
    return get_lexer_files(glob_pattern) + get_interpreter_files(glob_pattern)

### Date related #######################################################

def convdate(obj):
    """Convert `obj` to datetime.date instance, if possible.
    Supported object types:
    If `obj` is a datetime.date instance, it is returned as is.
    A tuple or list of length 3 is assumed to be (year, month, day).
    A string is parsed for the following formats: mm.dd.yyyy, yyyy-mm-dd.
    If `obj` cannot be converted, ValueError is raised."""

    # Todo: integer -> seconds since epoch; tuple of 9 -> time module format.

    if isinstance(obj, datetime.date):
        return obj

    if type(obj) in [types.TupleType, types.ListType] and len(obj)==3:
        return datetime.date(*obj) # tuple/list of (year, month, day)

    DATE_RE1 = '(\d{1,2})[.](\d{1,2})[.](\d{4})' # mm.dd.yyyy
    DATE_RE2 = '(\d{4})-(\d{2})-(\d{2})'         # yyyy-mm-dd

    if type(obj) in types.StringTypes:
        match = re.match(DATE_RE1, obj)
        if match:
            d, m, y = match.groups()
            d, m, y = int(d), int(m), int(y)
            return datetime.date(y, m, d) 

        match = re.match(DATE_RE2, obj)
        if match:
            y, m, d = match.groups()
            y, m, d = int(y), int(m), int(d)
            return datetime.date(y, m, d) 

    raise ValueError, 'Could not convert %s to date' % obj

def timedelta2hours(timedelta):
    if not isinstance(timedelta, datetime.timedelta):
        raise ValueError, 'timedelta must be instance of datetime.timedelta'
    return timedelta.days*24.0 + timedelta.seconds/3600.0