inji.globals   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 2
eloc 94
dl 0
loc 166
rs 10
c 0
b 0
f 0
ccs 20
cts 20
cp 1

1 Function

Rating   Name   Duplication   Size   Complexity  
A _os_release() 0 6 2
1
#!/usr/bin/env python3
2
3
# -*- coding: utf-8 -*-
4
5
# hold global variables and functions for direct use in templates
6
# https://jinja.palletsprojects.com/en/2.11.x/api/#the-global-namespace
7
# https://jinja.palletsprojects.com/en/2.11.x/templates/#list-of-global-functions
8
9 1
import builtins
10 1
from datetime import datetime, timezone
11 1
import json
12 1
import inspect
13 1
import markdown as _markdown
14 1
import platform as _platform
15 1
import socket
16 1
import sys
17 1
import re
18
19 1
from . import utils
20
21 1
def _os_release(k=None):
22 1
  ret = {}
23 1
  for line in open('/etc/os-release').read().strip().split('\n'):
24 1
    k,v = line.split('=', 1)
25 1
    ret[k] = v.strip('"')
26 1
  return ret
27
28 1
"""
29
_globals contains the dictionary of functions (implemented as lambda functions)
30
or variables (regular values) that are accessible inside template expressions.
31
"""
32 1
_globals = dict(
33
34
  bacon_ipsum = ( """ Return N paragraphs of bacon-ipsum """,
35
    lambda n=3: utils.get(
36
      'https://baconipsum.com/api/?type=all-meat&paras={}&start-with-lorem=1&format=html'.format(n)
37
    )
38
  ),
39
40
  cat  = ( """ Read a file in """,
41
    lambda *n: [ utils.load_file(x) for x in n ]
42
  ),
43
44
  date  = ( """ Return the timestamp for datetime.now() """,
45
    datetime.now()  # variable
46
  ),
47
48
  git_branch = ( """ Return the current git branch of HEAD """,
49
    lambda : utils.cmd(f"git rev-parse --abbrev-ref HEAD")
50
  ),
51
52
  GET = ( """ Issue a HTTP GET request against URL returning body content or an object if the response was JSON """,
53
    lambda url='http://httpbin.org/anything':
54
      utils.get(url)
55
  ),
56
57
  git_commit_id = ( """ Return the git commit ID of HEAD """,
58
    lambda fmt='%h': utils.cmd(f"git log --pretty=format:{fmt} -n 1 HEAD")
59
  ),
60
61
  git_remote_url = ( """ Return the URL of the named origin """,
62
    lambda origin='origin': utils.cmd(f'git remote get-url {origin}')
63
  ),
64
65
  git_remote_url_http = ( """ Return the HTTP URL of the named origin """,
66
    lambda origin='origin':
67
      re.sub( 'git@(.*):', 'https://\\1/',
68
        utils.cmd(f'git remote get-url {origin}')
69
      ),
70
  ),
71
72
  git_tag = ( """ Return the value of git describe --tag --always """,
73
    lambda fmt='current':
74
      utils.cmd('git describe --tag --always') if
75
        fmt=='current' else
76
        re.sub( '-[A-Fa-fg0-9\-]+$', '',
77
          utils.cmd('git describe --tag --always')
78
        )
79
  ),
80
81
  host_id = ( """ Return the host's ID """,
82
    lambda : utils.cmd('hostid')
83
  ),
84
85
  int = ( """ Cast value as an int """,
86
    lambda v: builtins.int(v)
87
  ),
88
89
  fqdn = ( """ Return the current host's fqdn """,
90
    lambda : socket.getfqdn()
91
  ),
92
93
  hostname = ( """ Return the current host's name """,
94
    lambda : socket.gethostname()
95
  ),
96
97
  machine_id = ( """ Return the machine's ID """,
98
    lambda :  utils.load_file('/var/lib/dbus/machine-id') or
99
              utils.load_file('/etc/machine-id')
100
  ),
101
102
  markdown = ( """ Load content from a markdown file and convert it to html """,
103
    lambda f,
104
      output_format='html5',
105
      extensions=[
106
        'admonition',
107
        'extra',
108
        'meta',
109
        'sane_lists',
110
        'smarty',
111
        'toc',
112
        'wikilinks',
113
        'wikilinks',
114
      ],
115
      extension_configs = {
116
        'codehilite': {
117
          'linenums': True,
118
          'guess_lang': False,
119
        }
120
      }
121
    : _markdown.markdown(
122
        utils.load_file(f),
123
        extensions=extensions,
124
        output_format=output_format
125
      )
126
  ),
127
128
  now  = ( """ Return the timestamp for datetime.now() """,
129
    lambda : datetime.now()
130
  ),
131
132
  os = ( """ Dictionary holding the contents of /etc/os-release """,
133
    _os_release()
134
  ),
135
136
  os_release = ( """ Lookup key in /etc/os-release and return its value """,
137
    lambda k: _os_release()[k]
138
  ),
139
140
  platform = ( """ Access functions in the platform module """,
141
    dict(set(inspect.getmembers(_platform, inspect.isfunction)))
142
  ),
143
144
  run = (
145
    """
146
    Run a command and return its STDOUT
147
    e.g. hello {{ run('id -un') }}
148
    """,
149
    lambda v: utils.cmd(v)
150
  ),
151
152
  ip_api = ( """ Return an attribute from the http://ip-api.com/json response object (i.e. status, country, countryCode, region, regionName, city, zip, lat, lon, timezone, isp, org, as, query) """,
153
    lambda key='country':
154
      utils.ip_api(key)
155
  ),
156
157
  whatismyip = ( """ Return the host's public (IPv4) address """,
158
    lambda : utils.whatismyip()
159
  ),
160
161
)
162
163
164 1
for k,v in _globals.items():
165
  setattr(sys.modules[__name__], k, v[1])
166