main()   F
last analyzed

Complexity

Conditions 12

Size

Total Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 12
c 5
b 0
f 0
dl 0
loc 65
rs 2.6867

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like main() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#! /usr/bin/python3
2
# vim: set expandtab tabstop=4 shiftwidth=4 :
3
"""Module to retrieve webcomics and create ebooks"""
4
5
import book
6
import argparse
7
import logging
8
from comics import COMIC_NAMES
9
10
11
def get_file_content_until_tag(path, tag):
12
    """Get content from a filepath up to a given tag.
13
    If tag is not is the file, an exception is thrown."""
14
    content = []
15
    with open(path) as f:
16
        for l in f:
17
            content.append(l)
18
            if tag == l.strip():
19
                return content
20
    raise ValueError('Could not find "%s" in file "%s"' % (tag, path))
21
22
23
def add_new_lines_after_tag(path, new_lines, tag):
24
    """Add lines to file from a given tag.
25
    All content until tag is kept, all content after is lost."""
26
    content = get_file_content_until_tag(path, tag)
27
    with open(path, 'w') as f:
28
        f.write(''.join(content + new_lines))
29
30
31
def main():
32
    """Main function"""
33
    logger = logging.getLogger()
34
    arg_to_method = {
35
        'list': 'print_name',
36
        'update': 'update',
37
        'info': 'info',
38
        'check': 'check_everything_is_ok',
39
        'fix': 'try_to_get_missing_resources',
40
        'reset_new': 'reset_new',
41
        'delete_last': 'delete_last',
42
        'delete_all': 'delete_all',
43
    }
44
    comic_names = sorted(COMIC_NAMES.keys())
45
    parser = argparse.ArgumentParser(
46
        description='Downloads webcomics and generates ebooks for offline reading')
47
    parser.add_argument(
48
        '--comic', '-c',
49
        action='append',
50
        help=('comics to be considered (default: ALL)'),
51
        choices=comic_names,
52
        default=[])
53
    parser.add_argument(
54
        '--excluded', '-e',
55
        action='append',
56
        help=('comics to be excluded'),
57
        choices=comic_names,
58
        default=[])
59
    parser.add_argument(
60
        '--action', '-a',
61
        action='append',
62
        help=('actions required'),
63
        choices=list(arg_to_method) + ['book', 'gitignore', 'readme'],
64
        default=[])
65
    parser.add_argument(
66
        '--loglevel', '-l',
67
        type=int,
68
        action='store',
69
        help=('log level (as per the Python logging module)'),
70
        default=logging.CRITICAL)
71
    args = parser.parse_args()
72
    logger.setLevel(args.loglevel)
73
    if not args.comic:
74
        args.comic = comic_names
75
    if not args.action:
76
        args.action = ['update']
77
    comic_classes = [COMIC_NAMES[c] for c in sorted(set(args.comic) - set(args.excluded))]
78
    logging.debug('Starting')
79
    for action in args.action:
80
        method_name = arg_to_method.get(action)
81
        if method_name is not None:
82
            for com in comic_classes:
83
                getattr(com, method_name)()
84
        elif action == 'book':
85
            book.make_book(comic_classes)
86
        elif action == 'gitignore':
87
            path = '.gitignore'
88
            new_content = [com.gitignore() for com in comic_classes]
89
            add_new_lines_after_tag(path, new_content, '# Generated folders')
90
        elif action == 'readme':
91
            path = 'README.md'
92
            new_content = [com.readme() for com in comic_classes]
93
            add_new_lines_after_tag(path, new_content, '----------------')
94
        else:
95
            print("Unknown action : %s" % action)
96
97
if __name__ == "__main__":
98
    main()
99