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
diff --git a/checkbox_support/snap_utils/config.py b/checkbox_support/snap_utils/config.py
index 4ea8eb0..d5aac7d 100644
--- a/checkbox_support/snap_utils/config.py
+++ b/checkbox_support/snap_utils/config.py
@@ -1,11 +1,16 @@
1#!/usr/bin/env python3
2# Copyright 2017 Canonical Ltd.1# Copyright 2017 Canonical Ltd.
3# All rights reserved.2# All rights reserved.
4#3#
5# Written by:4# Written by:
6# Authors: Jonathan Cave <jonathan.cave@canonical.com>5# Jonathan Cave <jonathan.cave@canonical.com>
6# Maciej Kisielewski <maciej.kisielewski@canonical.com>
77
8import configparser
8import json9import json
10import os
11import re
12import subprocess
13import sys
914
10import requests15import requests
11import requests_unixsocket16import requests_unixsocket
@@ -52,3 +57,63 @@ def set_configuration(snap, key, value):
52 json_data = json.dumps({key: value})57 json_data = json.dumps({key: value})
53 query = SnapdQuery()58 query = SnapdQuery()
54 return query.put(path, json_data)['status']59 return query.put(path, json_data)['status']
60
61
62def get_snapctl_config(keys):
63 """Query snapctl for given keys."""
64 if len(keys) == 0:
65 return dict()
66 out = subprocess.check_output(['snapctl', 'get'] + keys).decode(
67 sys.stdout.encoding)
68 if len(keys) == 1:
69 # snapctl returns bare string with a value when quering for one only
70 return {keys[0]: out.strip()}
71 return json.loads(out)
72
73
74def get_configuration_set():
75 """
76 Get names and their default values declared in Snap's config_vars.
77
78 config_vars should list all the configuration variables in a `key=value`
79 syntax. The line can list variable name only, if the variable should not
80 have a default value. All keys should comprise of CAPS, numbers and
81 undescores (_).
82
83 The returned keys are lowercase, as required by snapctl.
84 """
85 config_set_path = os.path.expandvars("$SNAP/config_vars")
86 config_set = dict()
87 key_re = re.compile(r"^(?:[A-Z0-9]+_?)*[A-Z](?:_?[A-Z0-9])*$")
88 try:
89 for line in open(config_set_path, 'rt').readlines():
90 line = line.strip()
91 if not line or line.startswith('#'):
92 continue
93 k, _, v = line.partition('=')
94 if not key_re.match(k):
95 raise SystemExit("%s is not a valid configuration key" % k)
96 # snapd accepts lowercase and dashes only for config names
97 # so let's "mangle" the names to match the requirement
98 k = k.replace('_', '-').lower()
99 config_set[k] = v
100 except FileNotFoundError:
101 # silently ignore missing config_vars
102 pass
103 return config_set
104
105def write_checkbox_conf(configuration):
106 """Write checkbox.conf in $SNAP_DATA dir."""
107 config = configparser.ConfigParser()
108 config.optionxform = str
109 config.add_section('environment')
110 for key in sorted(configuration.keys()):
111 val = configuration[key]
112 # unmangle the key
113 key = key.replace('-', '_').upper()
114 config.set('environment', key, val)
115
116 checkbox_conf_path = os.path.expandvars("$SNAP_DATA/checkbox.conf")
117 os.makedirs(os.path.dirname(checkbox_conf_path), exist_ok=True)
118 with open(checkbox_conf_path, 'wt') as stream:
119 config.write(stream)

Subscribers

People subscribed via source and target branches