]> git.ozlabs.org Git - bitfield/blobdiff - bitfield
Add -n option to usage
[bitfield] / bitfield
index d470c7ce2958d5f7a22eff2e7f42ba4aba31d064..ae9ab29eed906e4f7015bdd396e14b963aad4cc8 100644 (file)
--- a/bitfield
+++ b/bitfield
@@ -13,7 +13,10 @@ from pyparsing import Literal, Word, ZeroOrMore, Group, Dict, Optional, \
         printables, ParseException, restOfLine
 from getopt import getopt, GetoptError
 
-conf = os.path.join(os.getenv("HOME"), ".bitfields.conf")
+# List of paths to look for configuration files. If a directory is specified,
+# it will be (recursively) scanned for .conf files.
+configs = [os.path.join(os.getenv("HOME"), ".bitfields.conf"),
+               os.path.join(os.getenv("HOME"), ".bitfields.d")]
 
 class bitfield:
        def __init__(self, start_bit, end_bit, name):
@@ -44,10 +47,6 @@ class bitfield:
                        return self.values[value]
                return None
 
-       def __str__(self):
-               return "[%2d:%-2d] %s 0x%x" % (int(self.start_bit),
-                       int(self.end_bit), self.name, self.mask())
-
        @staticmethod
        def parse_bitfield(line):
                a = line.split(None, 1)
@@ -80,27 +79,23 @@ class register:
        def add_field(self, field,):
                self.fields.append(field)
 
-       def decode(self, value):
+       def decode(self, value, ignore_zero):
                field_width = (self.width + 3) / 4
                name_width = max(map(lambda f: len(f.name), self.fields))
                str = "0x%0*lx [%d]\n" % (field_width, value, value)
                for field in self.fields:
                        v = field.mask(self.width, value);
+                       if ignore_zero and v == 0:
+                               continue
                        desc = field.value(v)
                        if desc is not None:
-                               str += "%*s: 0x%s [%s]\n" \
+                               str += "%*s: 0x%x [%s]\n" \
                                        % (name_width, field.name, v, desc)
                        else:
                                str += "%*s: 0x%x\n" \
                                        % (name_width, field.name, v)
                return str
 
-       def __str__(self):
-               str = self.name + "\n"
-               for f in self.fields:
-                       str += "\t%s\n" % f
-               return str
-
 def list_regs(regs):
        for (id, r) in regs.iteritems():
                print "%18s : %s" % (id, r.name)
@@ -114,33 +109,19 @@ class ConfigurationError(Exception):
                self.file = file
                self.message = message
 
-def parse_config(file):
-       lbrack = Literal("[").suppress()
-       rbrack = Literal("]").suppress()
-       colon  = Literal(":").suppress()
-       semi   = Literal(";")
-
-       comment = semi + Optional( restOfLine )
-
-       nonrbrack = "".join( [ c for c in printables if c != "]" ] ) + " \t"
-       nonequals = "".join( [ c for c in printables if c != ":" ] ) + " \t"
-
-       sectionDef = lbrack + Word( nonrbrack ) + rbrack
-       keyDef = ~lbrack + Word( nonequals ) + colon + restOfLine
-
-       bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
-       bnf.ignore(comment)
-
+def parse_config(bnf, regs, file):
        f = open(file)
 
-       tokens = bnf.parseString("".join(f.readlines()))
-
-       regs = {}
+       tokens = bnf.parseString(f.read())
 
        for tok in tokens:
                ts = tok.asList()
                id = ts.pop(0)
 
+               if regs.has_key(id):
+                       raise ConfigurationError(file,
+                               "Register %s is already defined" % id)
+
                # default to 64 bit registers
                width = 64
                name = None
@@ -159,19 +140,19 @@ def parse_config(file):
                                                "Invalid field in %s" % id)
                                fields.append(f)
                        elif t[0] == 'value':
-                               f = fields[-1]
-                               if f is None:
+                               if len(fields) == 0:
                                        raise ConfigurationError(file,
                                                "No field for value in %s" % id)
                                v = bitfield.parse_value(t[1])
                                if v is None:
                                        raise ConfigurationError(file,
                                                "Invalid value in %s" % id)
-                               f.add_value(v[0], v[1])
+
+                               fields[-1].add_value(v[0], v[1])
 
                if name is None or name == '':
                        raise ConfigurationError(file,
-                               "No name for entry %s" %id)
+                               "No name for entry %s" % id)
 
                if len(fields) == 0:
                        raise ConfigurationError(file,
@@ -183,28 +164,74 @@ def parse_config(file):
 
                regs[id] = r
 
-       return regs
+def parse_config_dir(data, dir, fnames):
+       (bnf, regs) = data
+       for fname in fnames:
+               full_fname = os.path.join(dir, fname)
+
+               if os.path.isdir(full_fname):
+                       continue
 
+               if fname.endswith('.conf'):
+                       parse_config(bnf, regs, full_fname)
+
+def parse_all_configs(configs):
+       regs = {}
+
+       # set up the bnf to be used for each file
+       lbrack = Literal("[").suppress()
+       rbrack = Literal("]").suppress()
+       colon  = Literal(":").suppress()
+       semi   = Literal(";")
+
+       comment = semi + Optional(restOfLine)
+
+       nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
+       noncolon  = "".join([c for c in printables if c != ":"]) + " \t"
+
+       sectionDef = lbrack + Word(nonrbrack) + rbrack
+       keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
+
+       bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
+       bnf.ignore(comment)
+
+       # bundle into a single var that can be passed to os.path.walk
+       conf_data = (bnf, regs)
+
+       for conf in configs:
+               if not os.path.exists(conf):
+                       continue
+               if os.path.isdir(conf):
+                       os.path.walk(conf, parse_config_dir, conf_data)
+               else:
+                       parse_config(bnf, regs, conf)
+       return regs
 
 def usage(prog):
-       print "Usage: %s <-l> | <-s pattern> | register [value...]" % prog
+       print "Usage: %s <-l> | <-s pattern> | [-n] register [value...]" % prog
 
 def main():
        try:
-               (opts, args) = getopt(sys.argv[1:], "hls:", \
-                       ["help", "list", "search="])
+               (opts, args) = getopt(sys.argv[1:], "hlns:", \
+                       ["help", "list", "non-zero", "search="])
        except GetoptError:
                usage(sys.argv[0])
                return 1
 
        try:
-               regs = parse_config(conf)
-
+               regs = parse_all_configs(configs)
        except ConfigurationError, e:
                print "Error parsing configuration file %s:\n\t%s" % \
                        (e.file, e.message)
                return 1
 
+       if regs == {}:
+               print "No configuration available"
+               return 1
+
+       options = {}
+       options['non-zero'] = False
+
        for o, a in opts:
                if o in ("-h", "--help"):
                        usage(sys.argv[0])
@@ -218,18 +245,19 @@ def main():
                        list_regs(search_regs(regs, a))
                        return
 
+               if o in ("-n", "--non-zero"):
+                       options['non-zero'] = True
 
        if not args:
                usage(sys.argv[0])
                return 1
 
-       a = args.pop(0)
-       if not regs.has_key(a):
-               print "No such register '%s'. Valid regs are:" % a
-               list_regs(regs)
+       reg_id = args.pop(0)
+       if not regs.has_key(reg_id):
+               print "No such register '%s'" % reg_id
                return 1
 
-       r = regs[a]
+       r = regs[reg_id]
        print "decoding as %s" % r.name
 
        if args:
@@ -242,7 +270,7 @@ def main():
 
        for value in values:
                i = long(value.strip(), 0)
-               print r.decode(i)
+               print r.decode(i, options['non-zero'])
 
        return 0