[PATCH 1/2] nmbug-status: Clarify errors for illegible configs

W. Trevor King wking at tremily.us
Sat May 10 12:16:38 PDT 2014


Carl Worth pointed out that errors like:

  $ ./nmbug-status
  fatal: Not a git repository: '/home/cworth/.nmbug'
  fatal: Not a git repository: '/home/cworth/.nmbug'
  Traceback (most recent call last):
    File "./nmbug-status", line 254, in <module>
      config = read_config(path=args.config)
    File "./nmbug-status", line 73, in read_config
      return json.load(fp)
    File "/usr/lib/python2.7/json/__init__.py", line 290, in load
      **kw)
    File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
      return _default_decoder.decode(s)
    File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
      obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
      raise ValueError("No JSON object could be decoded")
  ValueError: No JSON object could be decoded

are not particularly clear.  With this commit, we'll get output like:

  $ ./nmbug-status
  fatal: Not a git repository: '/home/wking/.nmbug'
  No local branch 'config' in /home/wking/.nmbug.  Checkout a local
  config branch or explicitly set --config.

which is much more accessible.  I've also added user-friendly messages
for a number of other config-parsing errors.
---
 devel/nmbug/nmbug-status | 54 ++++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 45 insertions(+), 9 deletions(-)

diff --git a/devel/nmbug/nmbug-status b/devel/nmbug/nmbug-status
index 03621bd..75a6e47 100755
--- a/devel/nmbug/nmbug-status
+++ b/devel/nmbug/nmbug-status
@@ -49,28 +49,60 @@ if not hasattr(collections, 'OrderedDict'):  # Python 2.6 or earlier
     collections.OrderedDict = _OrderedDict
 
 
+class ConfigError (Exception):
+    """Errors with config file usage
+    """
+    pass
+
+
 def read_config(path=None, encoding=None):
     "Read config from json file"
     if not encoding:
         encoding = _ENCODING
     if path:
-        fp = open(path)
+        try:
+            with open(path, 'rb') as f:
+                config_bytes = f.read()
+        except IOError as e:
+            raise ConfigError('Could not read config from {}'.format(path))
     else:
         nmbhome = os.getenv('NMBGIT', os.path.expanduser('~/.nmbug'))
+        branch = 'config'
+        filename = 'status-config.json'
 
         # read only the first line from the pipe
         sha1_bytes = subprocess.Popen(
-            ['git', '--git-dir', nmbhome, 'show-ref', '-s', 'config'],
+            ['git', '--git-dir', nmbhome, 'show-ref', '-s', branch],
             stdout=subprocess.PIPE).stdout.readline()
         sha1 = sha1_bytes.decode(encoding).rstrip()
+        if not sha1:
+            raise ConfigError(
+                ("No local branch '{branch}' in {nmbgit}.  "
+                 'Checkout a local {branch} branch or explicitly set --config.'
+                ).format(branch=branch, nmbgit=nmbhome))
 
-        fp_byte_stream = subprocess.Popen(
+        p = subprocess.Popen(
             ['git', '--git-dir', nmbhome, 'cat-file', 'blob',
-             sha1+':status-config.json'],
-            stdout=subprocess.PIPE).stdout
-        fp = codecs.getreader(encoding=encoding)(stream=fp_byte_stream)
-
-    return json.load(fp)
+             '{}:{}'.format(sha1, filename)],
+            stdout=subprocess.PIPE)
+        config_bytes, err = p.communicate()
+        status = p.wait()
+        if status != 0:
+            raise ConfigError(
+                ("Missing status-config.json in branch '{branch}' of"
+                 '{nmbgit}.  Add the file or explicitly set --config.'
+                ).format(branch=branch, nmbgit=nmbhome))
+
+    config_json = config_bytes.decode(encoding)
+    try:
+        return json.loads(config_json)
+    except ValueError as e:
+        if not path:
+            path = "{} in branch '{}' of {}".format(
+                filename, branch, nmbhome)
+        raise ConfigError(
+            'Could not parse JSON from the config file {}:\n{}'.format(
+                path, e))
 
 
 class Thread (list):
@@ -254,7 +286,11 @@ parser.add_argument('--get-query', help='get query for view',
 
 args = parser.parse_args()
 
-config = read_config(path=args.config)
+try:
+    config = read_config(path=args.config)
+except ConfigError as e:
+    print(e)
+    sys.exit(1)
 
 _PAGES['text'] = Page()
 _PAGES['html'] = HtmlPage(
-- 
1.9.1.353.gc66d89d



More information about the notmuch mailing list