Merge ~kissiel/checkbox-support:snap_utils into checkbox-support:master

Proposed by Maciej Kisielewski
Status: Merged
Approved by: Maciej Kisielewski
Approved revision: 583262d8628d01ae241c50538cb70a038bfa96d5
Merged at revision: e4a75724e75f85cc5a048b09079c8e30b4ede7fc
Proposed branch: ~kissiel/checkbox-support:snap_utils
Merge into: checkbox-support:master
Diff against target: 87 lines (+67/-2)
1 file modified
checkbox_support/snap_utils/config.py (+67/-2)
Reviewer Review Type Date Requested Status
Jonathan Cave (community) Approve
Maciej Kisielewski Needs Resubmitting
Review via email: mp+331718@code.launchpad.net

Description of the change

add functions to load config set from within snap and to write checkbox.conf

To post a comment you must log in.
Revision history for this message
Jonathan Cave (jocave) wrote :

Looks good apart from two minor niggles...

review: Needs Fixing
Revision history for this message
Maciej Kisielewski (kissiel) wrote :

Third party meaning not distributed with python?
What does it help with?

---
print() removed

Revision history for this message
Jonathan Cave (jocave) wrote :

Yeah I suppose it is to highlight when an external dependency is required beyond the standard library, but not a local library. Might help for distribution.

Just something I remembered from the PEP8 doc (second bullet point: https://www.python.org/dev/peps/pep-0008/#imports)

Revision history for this message
Maciej Kisielewski (kissiel) wrote :

TIL, thanks!
Fixed both, squashed, pushed.

review: Needs Resubmitting
Revision history for this message
Jonathan Cave (jocave) wrote :

Thanks!

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/checkbox_support/snap_utils/config.py b/checkbox_support/snap_utils/config.py
2index 4ea8eb0..d5aac7d 100644
3--- a/checkbox_support/snap_utils/config.py
4+++ b/checkbox_support/snap_utils/config.py
5@@ -1,11 +1,16 @@
6-#!/usr/bin/env python3
7 # Copyright 2017 Canonical Ltd.
8 # All rights reserved.
9 #
10 # Written by:
11-# Authors: Jonathan Cave <jonathan.cave@canonical.com>
12+# Jonathan Cave <jonathan.cave@canonical.com>
13+# Maciej Kisielewski <maciej.kisielewski@canonical.com>
14
15+import configparser
16 import json
17+import os
18+import re
19+import subprocess
20+import sys
21
22 import requests
23 import requests_unixsocket
24@@ -52,3 +57,63 @@ def set_configuration(snap, key, value):
25 json_data = json.dumps({key: value})
26 query = SnapdQuery()
27 return query.put(path, json_data)['status']
28+
29+
30+def get_snapctl_config(keys):
31+ """Query snapctl for given keys."""
32+ if len(keys) == 0:
33+ return dict()
34+ out = subprocess.check_output(['snapctl', 'get'] + keys).decode(
35+ sys.stdout.encoding)
36+ if len(keys) == 1:
37+ # snapctl returns bare string with a value when quering for one only
38+ return {keys[0]: out.strip()}
39+ return json.loads(out)
40+
41+
42+def get_configuration_set():
43+ """
44+ Get names and their default values declared in Snap's config_vars.
45+
46+ config_vars should list all the configuration variables in a `key=value`
47+ syntax. The line can list variable name only, if the variable should not
48+ have a default value. All keys should comprise of CAPS, numbers and
49+ undescores (_).
50+
51+ The returned keys are lowercase, as required by snapctl.
52+ """
53+ config_set_path = os.path.expandvars("$SNAP/config_vars")
54+ config_set = dict()
55+ key_re = re.compile(r"^(?:[A-Z0-9]+_?)*[A-Z](?:_?[A-Z0-9])*$")
56+ try:
57+ for line in open(config_set_path, 'rt').readlines():
58+ line = line.strip()
59+ if not line or line.startswith('#'):
60+ continue
61+ k, _, v = line.partition('=')
62+ if not key_re.match(k):
63+ raise SystemExit("%s is not a valid configuration key" % k)
64+ # snapd accepts lowercase and dashes only for config names
65+ # so let's "mangle" the names to match the requirement
66+ k = k.replace('_', '-').lower()
67+ config_set[k] = v
68+ except FileNotFoundError:
69+ # silently ignore missing config_vars
70+ pass
71+ return config_set
72+
73+def write_checkbox_conf(configuration):
74+ """Write checkbox.conf in $SNAP_DATA dir."""
75+ config = configparser.ConfigParser()
76+ config.optionxform = str
77+ config.add_section('environment')
78+ for key in sorted(configuration.keys()):
79+ val = configuration[key]
80+ # unmangle the key
81+ key = key.replace('-', '_').upper()
82+ config.set('environment', key, val)
83+
84+ checkbox_conf_path = os.path.expandvars("$SNAP_DATA/checkbox.conf")
85+ os.makedirs(os.path.dirname(checkbox_conf_path), exist_ok=True)
86+ with open(checkbox_conf_path, 'wt') as stream:
87+ config.write(stream)

Subscribers

People subscribed via source and target branches