Completed
Push — master ( 8352c5...c127e6 )
by russianidiot
01:52
created

jinja2stdout()   F

Complexity

Conditions 11

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
c 1
b 0
f 0
dl 0
loc 40
rs 3.1764

How to fix   Complexity   

Complexity

Complex classes like jinja2stdout() 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/env python
2
import os
3
import sys
4
import jinja2
5
from moduledict import moduledict
6
from import_path import import_path
7
8
9
def jinja2stdout(src):
10
    HOME = os.environ["HOME"]
11
    jinja = os.path.join(HOME, ".jinja")
12
    if not os.path.exists(jinja):
13
        raise OSError("%s NOT EXISTS" % jinja)
14
    # if src.find(jinja)>=0:
15
    # r=src.replace("%s/" % jinja,"")
16
    # .hidden/ paths NOT WORK in github pages
17
    # build errors:
18
    # 1) git submodule errors - recursive
19
    # 2) .md errors
20
    kwargs = dict()
21
    env = jinja2.Environment(
22
        loader=jinja2.FileSystemLoader([]),
23
        auto_reload=False,
24
        cache_size=-1,
25
        extensions=["jinja2.ext.do", ]
26
    )
27
    relpath = None
28
    jinja = os.path.join(HOME, ".jinja")
29
    SEARCHPATH = os.environ.get("SEARCHPATH", None)
30
    for sp in [jinja, SEARCHPATH]:
31
        if sp and os.path.exists(sp) and os.path.isdir(sp):
32
            env.loader.searchpath += [sp]
33
            if src.find(sp) >= 0:
34
                relpath = src.replace(sp + "/", "")
35
    dir = os.path.dirname(src)
36
    files = []
37
    while dir and dir != "/":
38
        file = os.path.join(dir, "config.py")
39
        if os.path.exists(file):
40
            files.append(file)
41
        dir = os.path.dirname(dir)
42
    files = reversed(files)
43
    for file in files:
44
        cfg = moduledict(import_path(file))
45
        kwargs.update(cfg)
46
    env.globals.update(kwargs)
47
    tmpl = env.get_template(relpath)
48
    return tmpl.render()
49
50
if __name__ == "__main__":
51
    argv = sys.argv
52
    if len(argv) != 2 or (len(argv) == 2 and argv[1] == "--help"):
53
        print("usage: jinja2html.py template")
54
        if len(argv) == 2 and argv[1] == "--help":
55
            sys.exit(0)
56
        exit(1)
57
    if not os.path.exists(argv[1]):
58
        raise OSError("%s NOT EXISTS" % argv[1])
59
    r = jinja2stdout(argv[1])
60
    if r:
61
        print(r)
62