Exemplo n.º 1
0
    def test_priority_color2(self):
        config("test/data/ColorsTest2.conf")
        color = Colors().get_priority_colors()

        self.assertEqual(color['A'], '\033[0;35m')
        self.assertEqual(color['B'], '\033[0;1;36m')
        self.assertEqual(color['C'], '\033[0;37m')
Exemplo n.º 2
0
    def test_priority_color1(self):
        config("test/data/ColorsTest1.conf")
        color = Colors().get_priority_colors()

        self.assertEqual(color['A'], '\033[0;38;5;1m')
        self.assertEqual(color['B'], '\033[0;38;5;2m')
        self.assertEqual(color['C'], '\033[0;38;5;3m')
Exemplo n.º 3
0
    def test_priority_color4(self):
        config("test/data/ColorsTest4.conf")
        color = Colors().get_priority_colors()

        self.assertEqual(color['A'], NEUTRAL_COLOR)
        self.assertEqual(color['B'], NEUTRAL_COLOR)
        self.assertEqual(color['C'], NEUTRAL_COLOR) 
Exemplo n.º 4
0
def _advance_recurring_todo_helper(p_todo, p_offset):
    """
    Given a Todo item, return a new instance of a Todo item with the dates
    shifted according to the recurrence rule.

    The new date is calculated from the given p_offset value.

    When no recurrence tag is present, an exception is raised.
    """

    todo = Todo(p_todo.source())
    pattern = todo.tag_value('rec')

    if not pattern:
        raise NoRecurrenceException()

    length = todo.length()
    new_due = relative_date_to_date(pattern, p_offset)

    if not new_due:
        raise NoRecurrenceException()

    # pylint: disable=E1103
    todo.set_tag(config().tag_due(), new_due.isoformat())

    if todo.start_date():
        new_start = new_due - timedelta(length)
        todo.set_tag(config().tag_start(), new_start.isoformat())

    todo.set_creation_date(date.today())

    return todo
Exemplo n.º 5
0
    def test_alias_default_cmd02(self):
        config("test/data/aliases.conf", {('topydo', 'default_command'): 'foo'})

        args = []
        real_cmd, final_args = get_subcommand(args)
        self.assertTrue(issubclass(real_cmd, DeleteCommand))
        self.assertEqual(final_args, ["-f", "test"])
Exemplo n.º 6
0
    def test_new_uid(self):
        """ Make sure that item has new text ID after append. """
        config("test/data/todolist-uid.conf")
        todo = self.todolist.todo('t5c')
        self.todolist.append(todo, "A")

        self.assertNotEqual(self.todolist.number(todo), 't5c')
Exemplo n.º 7
0
    def test_uid3(self):
        """
        Must be able to handle integers when text identifiers are enabled.
        """

        config("test/data/todolist-uid.conf")
        self.assertRaises(InvalidTodoException, self.todolist.todo, 1)
Exemplo n.º 8
0
    def _process_flags(self):
        args = sys.argv[1:]

        if PY2:
            args = [arg.decode('utf-8') for arg in args]

        try:
            opts, args = getopt.getopt(args, MAIN_OPTS)
        except getopt.GetoptError as e:
            error(str(e))
            sys.exit(1)

        alt_config_path = None
        overrides = {}

        for opt, value in opts:
            if opt == "-a":
                self.do_archive = False
            elif opt == "-c":
                alt_config_path = value
            elif opt == "-t":
                overrides[('topydo', 'filename')] = value
            elif opt == "-d":
                overrides[('topydo', 'archive_filename')] = value
            elif opt == "-v":
                version()
            else:
                self._usage()

        if alt_config_path:
            config(alt_config_path, overrides)
        elif len(overrides):
            config(p_overrides=overrides)

        return args
Exemplo n.º 9
0
    def test_alias04(self):
        config("test/data/aliases.conf")

        args = ["star", "foo"]
        real_cmd, final_args = get_subcommand(args)
        self.assertTrue(issubclass(real_cmd, TagCommand))
        self.assertEqual(final_args, ["foo", "star", "1"])
Exemplo n.º 10
0
    def _execute_multi_specific(self):
        def _get_offset(p_todo):
            offset = p_todo.tag_value(
                config().tag_due(), date.today().isoformat())
            offset_date = date_string_to_date(offset)

            if offset_date < date.today():
                offset_date = date.today()

            return offset_date

        pattern = self.args[-1]
        self.printer.add_filter(PrettyPrinterNumbers(self.todolist))

        for todo in self.todos:
            offset = _get_offset(todo)
            new_due = relative_date_to_date(pattern, offset)

            if new_due:
                if self.move_start_date and todo.has_tag(config().tag_start()):
                    length = todo.length()
                    new_start = new_due - timedelta(length)
                    # pylint: disable=E1103
                    todo.set_tag(config().tag_start(), new_start.isoformat())

                # pylint: disable=E1103
                todo.set_tag(config().tag_due(), new_due.isoformat())

                self.todolist.set_dirty()
                self.out(self.printer.print_todo(todo))
            else:
                self.error("Invalid date pattern given.")
                break
Exemplo n.º 11
0
    def test_alias_default_cmd03(self):
        config("test/data/aliases.conf", {('topydo', 'default_command'): 'nonexisting_default'})

        args = ['nonexisting']
        real_cmd, final_args = get_subcommand(args)
        self.assertFalse(real_cmd)
        self.assertEqual(final_args, ['nonexisting'])
Exemplo n.º 12
0
    def execute(self):
        if not super().execute():
            return False

        try:
            number = self.argument(0)
            text = " ".join(self.args[1:])

            if text:
                todo = self.todolist.todo(number)
                new_text_parsed = parse_line(text)
                new_tags = new_text_parsed['tags']
                for tag in (config().tag_start(), config().tag_due()):
                    if tag in new_tags:
                        todo.remove_tag(tag)
                self.todolist.append(todo, text)
                self.postprocess_input_todo(todo)

                self.printer.add_filter(PrettyPrinterNumbers(self.todolist))
                self.out(self.printer.print_todo(todo))
            else:
                self.error(self.usage())
        except InvalidCommandArgument:
            self.error(self.usage())
        except InvalidTodoException:
            self.error("Invalid todo number given.")
Exemplo n.º 13
0
    def filter(self, p_todo_str, p_todo):
        """ Applies the colors. """
        if config().colors():
            p_todo_str = TopydoString(p_todo_str, p_todo)

            priority_color = config().priority_color(p_todo.priority())

            colors = [
                (r'\B@(\S*\w)', AbstractColor.CONTEXT),
                (r'\B\+(\S*\w)', AbstractColor.PROJECT),
                (r'\b\S+:[^/\s]\S*\b', AbstractColor.META),
                (r'(^|\s)(\w+:){1}(//\S+)', AbstractColor.LINK),
            ]

            # color by priority
            p_todo_str.set_color(0, priority_color)

            for pattern, color in colors:
                for match in re.finditer(pattern, p_todo_str.data):
                    p_todo_str.set_color(match.start(), color)
                    p_todo_str.set_color(match.end(), priority_color)

            p_todo_str.append('', AbstractColor.NEUTRAL)

        return p_todo_str
Exemplo n.º 14
0
 def test_importance_ignore_weekends_due_not_next_monday(self):
     # Today is sunday
     # due on a monday, but over a month away.
     # So 2 + 0 (no priority) + 0 (no star) + 0 (due > 14 days)
     config(p_overrides={('sort', 'ignore_weekends'): '1'})
     todo = Todo("Foo " + config().tag_due() + ":" + "2016-11-28")
     self.assertEqual(importance(todo), 2)
Exemplo n.º 15
0
    def test_uid2(self):
        """ Changing the priority should not change the identifier. """
        config("test/data/todolist-uid.conf")

        todo = self.todolist.todo("t5c")
        self.todolist.set_priority(todo, "B")
        self.assertEqual(self.todolist.todo("t5c").source(), "(B) Foo @Context2 Not@Context +Project1 Not+Project")
Exemplo n.º 16
0
    def test_alias02(self):
        config("test/data/aliases.conf")

        args = ["format"]
        real_cmd, final_args = get_subcommand(args)
        self.assertTrue(issubclass(real_cmd, ListCommand))
        self.assertEqual(final_args, ["-F", "|I| x c d {(}p{)} s k", "-n", "25"])
Exemplo n.º 17
0
    def _create_color_palette(self):
        project_color = to_urwid_color(config().project_color())
        context_color = to_urwid_color(config().context_color())
        metadata_color = to_urwid_color(config().metadata_color())
        link_color = to_urwid_color(config().link_color())

        palette = [
            (PaletteItem.PROJECT, '', '', '', project_color, ''),
            (PaletteItem.PROJECT_FOCUS, '', 'light gray', '', project_color, None),
            (PaletteItem.CONTEXT, '', '', '', context_color, ''),
            (PaletteItem.CONTEXT_FOCUS, '', 'light gray', '', context_color, None),
            (PaletteItem.METADATA, '', '', '', metadata_color, ''),
            (PaletteItem.METADATA_FOCUS, '', 'light gray', '', metadata_color, None),
            (PaletteItem.LINK, '', '', '', link_color, ''),
            (PaletteItem.LINK_FOCUS, '', 'light gray', '', link_color, None),
            (PaletteItem.DEFAULT_FOCUS, 'black', 'light gray'),
            (PaletteItem.MARKED, '', 'light blue'),
        ]

        for C in ascii_uppercase:
            pri_color_cfg = config().priority_color(C)

            pri_color = to_urwid_color(pri_color_cfg)
            pri_color_focus = pri_color if not pri_color_cfg.is_neutral() else 'black'

            palette.append((
                'pri_' + C, '', '', '', pri_color, ''
            ))
            palette.append((
                'pri_' + C + '_focus', '', 'light gray', '', pri_color_focus, None
            ))

        return palette
Exemplo n.º 18
0
    def test_alias03(self):
        config("test/data/aliases.conf")

        args = ["smile"]
        real_cmd, final_args = get_subcommand(args)
        self.assertTrue(issubclass(real_cmd, ListCommand))
        self.assertEqual(final_args, [u"\u263b"])
Exemplo n.º 19
0
    def test_group11(self):
        config(p_overrides={('sort', 'group_string'): 'project'})
        todolist = load_file_to_todolist("test/data/ListCommandGroupTest.txt")

        command = ListCommand(["test:test_group1"], todolist, self.out, self.error)
        command.execute()

        self.assertFalse(todolist.dirty)

        self.assertEqual(self.output, """\
Project: A
==========
| 1| +A only test:test_group1
| 3| +A and +B test:test_group1

Project: B
==========
| 3| +A and +B test:test_group1
| 2| +B only test:test_group1

Project: None
=============
| 4| No project test:test_group1
""")
        self.assertEqual(self.errors, "")
Exemplo n.º 20
0
    def _process_flags(self):
        args = sys.argv[1:]

        try:
            opts, args = getopt.getopt(args, MAIN_OPTS, MAIN_LONG_OPTS)
        except getopt.GetoptError as e:
            error(str(e))
            sys.exit(1)

        alt_config_path = None
        overrides = {}

        for opt, value in opts:
            if opt == "-a":
                self.do_archive = False
            elif opt == "-c":
                alt_config_path = value
            elif opt == "-C":
                overrides[('topydo', 'force_colors')] = '1'
                overrides[('topydo', 'colors')] = value
            elif opt == "-t":
                overrides[('topydo', 'filename')] = value
            elif opt == "-d":
                overrides[('topydo', 'archive_filename')] = value
            elif opt in ("-v", "--version"):
                version()
            else:
                CLIApplicationBase._usage()

        if alt_config_path:
            config(alt_config_path, overrides)
        elif len(overrides):
            config(p_overrides=overrides)

        return args
Exemplo n.º 21
0
    def _post_execute(self):
        """
        Should be called when executing the user requested command has been
        completed. It will do some maintenance and write out the final result
        to the todo.txt file.
        """

        if self.todolist.dirty:
            # do not archive when the value of the filename is an empty string
            # (i.e. explicitly left empty in the configuration
            if self.do_archive and config().archive():
                self._archive()
            elif config().archive() and self.backup:
                archive = _retrieve_archive()[0]
                self.backup.add_archive(archive)

            self._post_archive_action()

            if config().keep_sorted():
                from topydo.commands.SortCommand import SortCommand
                self._execute(SortCommand, [])

            if self.backup:
                self.backup.save(self.todolist)

            self.todofile.write(self.todolist.print_todos())
            self.todolist.dirty = False

        self.backup = None
Exemplo n.º 22
0
    def test_alias01(self):
        config("test/data/aliases.conf")

        args = ["foo"]
        real_cmd, final_args = get_subcommand(args)
        self.assertTrue(issubclass(real_cmd, DeleteCommand))
        self.assertEqual(final_args, ["-f", "test"])
Exemplo n.º 23
0
        def _postprocess_input_todo(p_todo):
            """
            Post-processes a parsed todo when adding it to the list.

            * It converts relative dates to absolute ones.
            * Automatically inserts a creation date if not present.
            * Handles more user-friendly dependencies with before:, partof: and
            after: tags
            """
            def convert_date(p_tag):
                value = p_todo.tag_value(p_tag)

                if value:
                    dateobj = relative_date_to_date(value)
                    if dateobj:
                        p_todo.set_tag(p_tag, dateobj.isoformat())

            def add_dependencies(p_tag):
                for value in p_todo.tag_values(p_tag):
                    try:
                        dep = self.todolist.todo(value)

                        if p_tag == 'after':
                            self.todolist.add_dependency(p_todo, dep)
                        elif p_tag == 'before' or p_tag == 'partof':
                            self.todolist.add_dependency(dep, p_todo)
                        elif p_tag.startswith('parent'):
                            for parent in self.todolist.parents(dep):
                                self.todolist.add_dependency(parent, p_todo)
                        elif p_tag.startswith('child'):
                            for child in self.todolist.children(dep):
                                self.todolist.add_dependency(p_todo, child)
                    except InvalidTodoException:
                        pass

                    p_todo.remove_tag(p_tag, value)

            convert_date(config().tag_start())
            convert_date(config().tag_due())

            keywords = [
                'after',
                'before',
                'child-of',
                'childof',
                'children-of',
                'childrenof',
                'parent-of',
                'parentof',
                'parents-of',
                'parentsof',
                'partof',
            ]

            for keyword in keywords:
                add_dependencies(keyword)

            if config().auto_creation_date():
                p_todo.set_creation_date(date.today())
Exemplo n.º 24
0
    def test_list39(self):
        config("test/data/todolist-uid.conf")

        command = ListCommand(["-i", "t5c,foo"], self.todolist, self.out, self.error)
        command.execute()

        self.assertEqual(self.output, "|t5c| (C) 2015-11-05 Foo @Context2 Not@Context +Project1 Not+Project\n")
        self.assertEqual(self.errors, "")
Exemplo n.º 25
0
 def data(self):
     return {
         'title': self.titleedit.edit_text or self.filteredit.edit_text,
         'sortexpr': self.sortedit.edit_text or config().sort_string(),
         'groupexpr': self.groupedit.edit_text or config().group_string(),
         'filterexpr': self.filteredit.edit_text,
         'show_all': self.allradio.state,
     }
Exemplo n.º 26
0
    def test_alias_quotation(self):
        config("test/data/aliases.conf")

        args = ["quot"]
        with self.assertRaises(ConfigError) as ce:
            get_subcommand(args)

        self.assertEqual(str(ce.exception), 'No closing quotation')
Exemplo n.º 27
0
def get_subcommand(p_args):
    """
    Retrieves the to-be executed Command and returns a tuple
    (Command, args).

    If args is an empty list, then the Command that corresponds with the
    default command specified in the configuration will be returned.

    If the first argument is 'help' and the second a valid subcommand, the
    help text this function returns the Command instance of that subcommand
    with a single argument 'help' (every Command has a help text).

    If no valid command could be found, the subcommand part of the tuple
    is None.
    """

    def import_subcommand(p_subcommand):
        """
        Returns the class of the requested subcommand. An invalid p_subcommand
        will result in an ImportError, since this is a programming mistake
        (most likely an error in the _SUBCOMMAND_MAP).
        """
        classname = _SUBCOMMAND_MAP[p_subcommand]
        modulename = "topydo.commands.{}".format(classname)

        __import__(modulename, globals(), locals(), [classname], 0)
        return getattr(sys.modules[modulename], classname)

    result = None
    args = p_args

    try:
        subcommand = p_args[0]

        if subcommand in _SUBCOMMAND_MAP:
            result = import_subcommand(subcommand)
            args = args[1:]
        elif subcommand == "help":
            try:
                subcommand = args[1]

                if subcommand in _SUBCOMMAND_MAP:
                    args = [subcommand, "help"]
                    return get_subcommand(args)
            except IndexError:
                # will result in empty result
                pass
        else:
            p_command = config().default_command()
            if p_command in _SUBCOMMAND_MAP:
                result = import_subcommand(p_command)
                # leave args unchanged
    except IndexError:
        p_command = config().default_command()
        if p_command in _SUBCOMMAND_MAP:
            result = import_subcommand(p_command)

    return (result, args)
Exemplo n.º 28
0
    def test_list34(self):
        """ Test non-integer value for -n """
        config(p_overrides={('ls', 'list_limit'): '2'})

        command = ListCommand(["-n", "foo"], self.todolist, self.out, self.error)
        command.execute()

        self.assertEqual(self.output, "|  1| (C) 2015-11-05 Foo @Context2 Not@Context +Project1 Not+Project\n|  4| (C) Drink beer @ home\n")
        self.assertEqual(self.errors, "")
Exemplo n.º 29
0
    def test_startdate3(self):
        """ Start date equals due date. """
        self.todo.set_tag(config().tag_due(), date.today().isoformat())
        self.todo.set_tag(config().tag_start(), date.today().isoformat())

        new_start = date.today() + timedelta(7)
        new_todo = advance_recurring_todo(self.todo)

        self.assertEqual(new_todo.start_date(), new_start)
Exemplo n.º 30
0
    def _execute_not_multi(self):
        if self.edit_archive:
            archive = config().archive()

            return self._open_in_editor(archive) == 0
        else:
            todo = config().todotxt()

            return self._open_in_editor(todo) == 0
Exemplo n.º 31
0
    def test_list_format10(self):
        config(p_overrides={('ls', 'list_format'): '|%i| %k'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """|1|
|2| lazy:bar
|3|
|4| key:value
|5|
|6| date:2014-12-12
"""
        self.assertEqual(self.output, result)
Exemplo n.º 32
0
    def get_completions(self, p_document, _):
        # include all characters except whitespaces (for + and @)
        word_before_cursor = p_document.get_word_before_cursor(True)
        is_first_word = not re.match(r'\s*\S+\s',
                                     p_document.current_line_before_cursor)

        if word_before_cursor.startswith(config().tag_due() + ':'):
            return _dates(word_before_cursor)
        elif word_before_cursor.startswith(config().tag_start() + ':'):
            return _dates(word_before_cursor)
        else:
            return self._completion_generator(word_before_cursor,
                                              is_first_word)
Exemplo n.º 33
0
    def test_list_format11(self):
        config(p_overrides={('ls', 'list_format'): '|%I| %K'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """|1| due:2015-09-30 t:2015-09-29
|2| due:2015-11-08 lazy:bar t:2015-11-07
|3|
|4| key:value
|5| ical:foobar id:1 p:2
|6| date:2014-12-12
"""
        self.assertEqual(self.output, result)
Exemplo n.º 34
0
    def test_list_format12(self):
        config(p_overrides={('ls', 'list_format'): '|%I| \%'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """|1| %
|2| %
|3| %
|4| %
|5| %
|6| %
"""
        self.assertEqual(self.output, result)
Exemplo n.º 35
0
    def test_list_format01(self):
        config(p_overrides={('ls', 'list_format'): '|%I| %x %{(}p{)} %c %s %K'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """|1| (D) 2015-08-31 Bar @Context1 +Project2 due:2015-09-30 t:2015-09-29
|2| (Z) 2015-11-06 Lorem ipsum dolorem sit amet. Red @fox +jumped over the and jar due:2015-11-08 lazy:bar t:2015-11-07
|3| (C) 2015-07-12 Foo @Context2 Not@Context +Project1 Not+Project
|4| (C) Baz @Context1 +Project1 key:value
|5| Drink beer @ home ical:foobar id:1 p:2
|6| x 2014-12-12 Completed but with date:2014-12-12
"""
        self.assertEqual(self.output, result)
Exemplo n.º 36
0
    def __init__(self, p_args, p_todolist, #pragma: no branch
                 p_out=lambda a: None,
                 p_err=lambda a: None,
                 p_prompt=lambda a: None):
        super().__init__(
            p_args, p_todolist, p_out, p_err, p_prompt)

        self.printer = None
        self.sort_expression = config().sort_string()
        self.group_expression = config().group_string()
        self.show_all = False
        self.ids = None
        self.format = config().list_format()
Exemplo n.º 37
0
    def test_priority_color4(self):
        config("test/data/ColorsTest4.conf")
        todo_a = Todo('(A) Foo')
        todo_b = Todo('(B) Bar')
        todo_c = Todo('(C) FooBar')

        color_a = config().priority_color(todo_a.priority()).as_ansi()
        color_b = config().priority_color(todo_b.priority()).as_ansi()
        color_c = config().priority_color(todo_c.priority()).as_ansi()

        self.assertEqual(color_a, '')
        self.assertEqual(color_b, '')
        self.assertEqual(color_c, '')
Exemplo n.º 38
0
    def test_list12(self):
        config("test/data/listcommand.conf")

        command = ListCommand(["-x", "project"], self.todolist, self.out,
                              self.error)
        command.execute()

        self.assertFalse(self.todolist.dirty)
        self.assertEqual(
            self.output,
            "|1| (C) 2015-11-05 Foo @Context2 Not@Context +Project1 Not+Project\n|3| (C) Baz @Context1 +Project1 key:value\n|2| (D) Bar @Context1 +Project2\n"
        )
        self.assertEqual(self.errors, "")
Exemplo n.º 39
0
    def test_list34(self):
        """ Test non-integer value for -n """
        config(p_overrides={('ls', 'list_limit'): '2'})

        command = ListCommand(["-n", "foo"], self.todolist, self.out,
                              self.error)
        command.execute()

        self.assertEqual(
            self.output,
            "|1| (C) 2015-11-05 Foo @Context2 Not@Context +Project1 Not+Project\n|4| (C) Drink beer @ home\n"
        )
        self.assertEqual(self.errors, "")
Exemplo n.º 40
0
def columns(p_alt_layout_path=None):
    """
    Returns list with complete column configuration dicts.
    """
    def _get_column_dict(p_cp, p_column):
        column_dict = dict()

        filterexpr = p_cp.get(p_column, 'filterexpr')

        try:
            title = p_cp.get(p_column, 'title')
        except NoOptionError:
            title = filterexpr

        column_dict['title'] = title or 'Yet another column'
        column_dict['filterexpr'] = filterexpr
        column_dict['sortexpr'] = p_cp.get(p_column, 'sortexpr')
        column_dict['groupexpr'] = p_cp.get(p_column, 'groupexpr')
        column_dict['show_all'] = p_cp.getboolean(p_column, 'show_all')

        return column_dict

    defaults = {
        'filterexpr': '',
        'sortexpr': config().sort_string(),
        'groupexpr': config().group_string(),
        'show_all': '0',
    }

    cp = RawConfigParser(defaults, strict=False)
    files = [
        "topydo_columns.ini",
        "topydo_columns.conf",
        ".topydo_columns",
        home_config_path('.topydo_columns'),
        home_config_path('.config/topydo/columns'),
        "/etc/topydo_columns.conf",
    ]

    if p_alt_layout_path is not None:
        files.insert(0, expanduser(p_alt_layout_path))
    for filename in files:
        if cp.read(filename):
            break

    column_list = []

    for column in cp.sections():
        column_list.append(_get_column_dict(cp, column))

    return column_list
Exemplo n.º 41
0
    def test_list19(self):
        """ Force showing all tags. """
        config('test/data/listcommand-tags.conf')

        command = ListCommand(["-s", "text", "-x", "Project1"], self.todolist,
                              self.out, self.error)
        command.execute()

        self.assertFalse(self.todolist.dirty)
        self.assertEqual(
            self.output,
            "|3| (C) Baz @Context1 +Project1 id:1 key:value\n|1| (C) 2015-11-05 Foo @Context2 Not@Context +Project1 Not+Project\n"
        )
        self.assertEqual(self.errors, "")
Exemplo n.º 42
0
    def test_list_format09(self, mock_terminal_size):
        mock_terminal_size.return_value = self.terminal_size(100, 25)

        config(p_overrides={('ls', 'list_format'): '%C | %D | %T | %X'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """3 months ago | a month ago | a month ago |
today | in 2 days | in a day |
4 months ago | | |
| | |
| | |
| | | x 11 months ago
"""
        self.assertEqual(self.output, result)
Exemplo n.º 43
0
    def test_list_format08(self, mock_terminal_size):
        mock_terminal_size.return_value = self.terminal_size(100, 25)

        config(p_overrides={('ls', 'list_format'): '%c %d %t %x'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """2015-08-31 2015-09-30 2015-09-29
2015-11-06 2015-11-08 2015-11-07
2015-07-12


x 2014-12-12
"""
        self.assertEqual(self.output, result)
Exemplo n.º 44
0
    def __init__(
            self,
            p_args,
            p_todolist,  #pragma: no branch
            p_out=lambda a: None,
            p_err=lambda a: None,
            p_prompt=lambda a: None):
        super().__init__(p_args, p_todolist, p_out, p_err, p_prompt)

        self.sort_expression = config().sort_string()
        self.show_all = False
        self.limit = config().list_limit()
        # Commands using last argument differently (i.e as something other than
        # todo ID/expression) have to set attribute below to True.
        self.last_argument = False
Exemplo n.º 45
0
    def test_add_dep08(self):
        config("test/data/todolist-uid.conf")

        command = AddCommand.AddCommand(["Foo"], self.todolist, self.out,
                                        self.error)
        command.execute()

        command = AddCommand.AddCommand(["Bar after:7ui"], self.todolist,
                                        self.out, self.error)
        command.execute()

        self.assertEqual(self.todolist.todo('7ui').source(),
                         "{} Foo p:1".format(self.today))
        self.assertEqual(self.todolist.todo('8to').source(),
                         "{} Bar id:1".format(self.today))
Exemplo n.º 46
0
    def test_list50(self):
        """
        Fallback to normal alphabet for too short alphabets, fallback on
        default alphabet.
        """
        config(p_overrides={('topydo', 'identifier_alphabet'): 'a', ('topydo', 'identifiers'): 'text'})

        # self.todolist was loaded with old identifier settings
        todolist = load_file_to_todolist("test/data/ListCommandTest.txt")

        command = ListCommand(["-F", "%I", "Foo"], todolist, self.out, self.error)
        command.execute()

        self.assertEqual(self.output, "t5c\n")
        self.assertEqual(self.errors, '')
Exemplo n.º 47
0
    def test_list_format42(self, mock_terminal_size):
        mock_terminal_size.return_value = self.terminal_size(100, 25)

        config('test/data/listformat.conf', p_overrides={('ls', 'indent'): '3'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """   |1| (D) 2015-08-31 Bar @Context1 +Project2                           due:2015-09-30 t:2015-09-29
   |2| (Z) 2015-11-06 Lorem ipsum dolorem sit amet. Red @fo... due:2015-11-08 lazy:bar t:2015-11-07
   |3| (C) 2015-07-12 Foo @Context2 Not@Context +Project1 Not+Project
   |4| (C) Baz @Context1 +Project1                                                        key:value
   |5| Drink beer @ home                                                       ical:foobar id:1 p:2
   |6| x 2014-12-12 Completed but with                                              date:2014-12-12
"""
        self.assertEqual(self.output, result)
Exemplo n.º 48
0
    def test_list_format07(self, mock_terminal_size):
        mock_terminal_size.return_value = self.terminal_size(100, 25)

        config(p_overrides={('ls', 'list_format'): '|%I| %x %p %S %k	%{(}h{)}'})
        command = ListCommand(["-x"], self.todolist, self.out, self.error)
        command.execute()

        result = """|1| D Bar @Context1 +Project2                                (due a month ago, started a month ago)
|2| Z Lorem ipsum dolorem sit amet. Red @fox +jumped o... lazy:bar (due in 2 days, starts in a day)
|3| C Foo @Context2 Not@Context +Project1 Not+Project
|4| C Baz @Context1 +Project1 key:value
|5| Drink beer @ home
|6| x 2014-12-12 Completed but with date:2014-12-12
"""
        self.assertEqual(self.output, result)
Exemplo n.º 49
0
    def test_empty_color_values(self):
        config("test/data/ColorsTest5.conf")
        pri_color = Colors().get_priority_colors()
        project_color = Colors().get_project_color()
        context_color = Colors().get_context_color()
        link_color = Colors().get_link_color()
        metadata_color = Colors().get_metadata_color()

        self.assertEqual(pri_color['A'], NEUTRAL_COLOR)
        self.assertEqual(pri_color['B'], NEUTRAL_COLOR)
        self.assertEqual(pri_color['C'], NEUTRAL_COLOR)
        self.assertEqual(project_color, '')
        self.assertEqual(context_color, '')
        self.assertEqual(link_color, '')
        self.assertEqual(metadata_color, '')
Exemplo n.º 50
0
    def test_empty_colorscheme(self):
        config("test/data/config1")
        pri_color = Colors().get_priority_colors()
        project_color = Colors().get_project_color()
        context_color = Colors().get_context_color()
        link_color = Colors().get_link_color()
        metadata_color = Colors().get_metadata_color()

        self.assertEqual(pri_color['A'], '\033[0;36m')
        self.assertEqual(pri_color['B'], '\033[0;33m')
        self.assertEqual(pri_color['C'], '\033[0;34m')
        self.assertEqual(project_color, '\033[1;31m')
        self.assertEqual(context_color, '\033[1;35m')
        self.assertEqual(link_color, '\033[4;36m')
        self.assertEqual(metadata_color, '\033[1;32m')
Exemplo n.º 51
0
def lookup_color(p_color):
    """
    Converts an AbstractColor to a normal Color. Returns the Color itself
    when a normal color is passed.
    """
    if not lookup_color.colors:
        lookup_color.colors[AbstractColor.NEUTRAL] = Color('NEUTRAL')
        lookup_color.colors[AbstractColor.PROJECT] = config().project_color()
        lookup_color.colors[AbstractColor.CONTEXT] = config().context_color()
        lookup_color.colors[AbstractColor.META] = config().metadata_color()
        lookup_color.colors[AbstractColor.LINK] = config().link_color()

    try:
        return lookup_color.colors[p_color]
    except KeyError:
        return p_color
Exemplo n.º 52
0
 def ids(self):
     """ Returns set with all todo IDs. """
     if config().identifiers() == 'text':
         ids = self._id_todo_map.keys()
     else:
         ids = [str(i + 1) for i in range(self.count())]
     return set(ids)
Exemplo n.º 53
0
    def add_list(self, p_srcs):
        todos = [Todo(src) for src in p_srcs]
        if config().auto_delete_whitespace():
            todos = [todo for todo in todos if re.search(r'\S', todo.source())]
        self.add_todos(todos)

        return todos
Exemplo n.º 54
0
    def _handle_ls(self):
        """ Handles the ls subsubcommand. """
        try:
            arg1 = self.argument(1)
            arg2 = self.argument(2)

            todos = []
            if arg2 == 'to':
                # dep ls 1 to ...
                number = arg1
                todo = self.todolist.todo(number)
                todos = self.todolist.children(todo)
            elif arg1 == 'to':
                # dep ls ... to 1
                number = arg2
                todo = self.todolist.todo(number)
                todos = self.todolist.parents(todo)
            else:
                self.error(self.usage())

            if todos:
                sorter = Sorter(config().sort_string())
                instance_filter = Filter.InstanceFilter(todos)
                view = View(sorter, [instance_filter], self.todolist)
                self.out(self.printer.print_list(view.todos))
        except InvalidTodoException:
            self.error("Invalid todo number given.")
        except InvalidCommandArgument:
            self.error(self.usage())
Exemplo n.º 55
0
    def _filters(self):
        filters = []

        def arg_filters():
            result = []
            for arg in self.args:
                if re.match(Filter.ORDINAL_TAG_MATCH, arg):
                    argfilter = Filter.OrdinalTagFilter(arg)
                elif len(arg) > 1 and arg[0] == '-':
                    # when a word starts with -, exclude it
                    argfilter = Filter.GrepFilter(arg[1:])
                    argfilter = Filter.NegationFilter(argfilter)
                else:
                    argfilter = Filter.GrepFilter(arg)

                result.append(argfilter)

            return result

        if not self.show_all:
            filters.append(Filter.DependencyFilter(self.todolist))
            filters.append(Filter.RelevanceFilter())

        filters += arg_filters()

        if not self.show_all:
            filters.append(Filter.LimitFilter(config().list_limit()))

        return filters
Exemplo n.º 56
0
    def test_config4(self):
        """ Test that value in file is overridden by parameter. """
        overrides = {('topydo', 'default_command'): 'edit'}

        self.assertEqual(
            config("test/data/config1",
                   p_overrides=overrides).default_command(), 'edit')
Exemplo n.º 57
0
    def _backup(self, p_command, p_args=[], p_label=None):
        if config().backup_count() > 0 and p_command and not self.is_read_only(p_command):
            call = [p_command.name()]+ p_args

            from topydo.lib.ChangeSet import ChangeSet
            label = p_label if p_label else call
            self.backup = ChangeSet(self.todolist, p_label=label)
Exemplo n.º 58
0
    def _print(self):
        """
        Prints the todos in the right format.

        Defaults to normal text output (with possible colors and other pretty
        printing). If a format was specified on the commandline, this format is
        sent to the output.
        """
        if self.printer is None:
            # create a standard printer with some filters
            indent = config().list_indent()
            final_format = ' ' * indent + self.format

            filters = []
            filters.append(PrettyPrinterFormatFilter(self.todolist, final_format))

            self.printer = pretty_printer_factory(self.todolist, filters)

        try:
            if self.group_expression:
                self.out(self.printer.print_groups(self._view().groups))
            else:
                self.out(self.printer.print_list(self._view().todos))
        except ListFormatError:
            self.error('Error while parsing format string (list_format config'
                       ' option or -F)')
Exemplo n.º 59
0
    def test_config27(self):
        """ column_keymap test. """
        keymap, keystates = config("test/data/ConfigTest6.conf").column_keymap()

        self.assertEqual(keymap['pp'], 'postpone')
        self.assertEqual(keymap['ps'], 'postpone_s')
        self.assertEqual(keymap['pr'], 'pri')

        self.assertEqual(keymap['pra'], 'cmd pri {} a')

        self.assertIn('p', keystates)
        self.assertIn('g', keystates)
        self.assertIn('pp', keystates)
        self.assertIn('ps', keystates)
        self.assertIn('pr', keystates)

        self.assertEqual(keymap['up'], 'up')
        self.assertIn('u', keystates)

        self.assertEqual(keymap['<Left>'], 'prev_column')
        self.assertNotIn('<Lef', keystates)

        self.assertEqual(keymap['<Esc>d'], 'delete_column')
        self.assertNotIn('<Esc', keystates)
        self.assertIn('<Esc>', keystates)
Exemplo n.º 60
0
    def __init__(self, p_args, p_todolist, p_output, p_error, p_input):
        super().__init__(p_args, p_todolist, p_output, p_error, p_input)

        self.editor = config().editor()
        self.is_expression = False
        self.edit_archive = False
        self.last_argument = False