Skip to content

Instantly share code, notes, and snippets.

@xmonader

xmonader/dmi.nim Secret

Last active April 26, 2018 20:53
Show Gist options
  • Save xmonader/577afbd179a00cef664e5b192c7e07e2 to your computer and use it in GitHub Desktop.
Save xmonader/577afbd179a00cef664e5b192c7e07e2 to your computer and use it in GitHub Desktop.
dmi.nim
# dmidecode
# Copyright xmonader
# Parse DMIDecode output into reasonable structures.
import sequtils, tables, strutils
type
ParserState = enum
noOp, sectionName, readKeyValue, readList
type
Property* = ref object
val*: string
items: seq[string]
type
Section* = ref object
handleLine*, title*: string
props* : Table[string, Property]
method addItem(this: Property, item: string) =
this.items.add(item)
proc getIndentLevel(line: string) : int =
for i, c in pairs(line):
if c.isSpaceAscii:
return i
return 0
proc parseDMI* (source: string) : Table[string, Section]=
var
state : ParserState = noOp
lines = strutils.splitLines(source)
sects = initTable[string, Section]()
p: Property
s: Section
k, v: string
for i, l in pairs(lines):
echo "line: " & l
echo "state: " & $state
if l.startsWith("Handle"):
s = Section()
s.handleline = l
state = sectionName
continue
if l == "": # can be just new line before reading any sections.
if s != nil:
sects[s.title] = s
continue
if state == sectionName:
s.title = l
state = readKeyValue
elif state == readKeyValue:
let pair = strutils.split(":")
k = strutils.strip(pair[0], true, true)
if len(pair) == 2:
v = strutils.strip(pair[1], true, true)
else:
v = ""
p = Property(val:v)
if i < len(lines) and getIndentlevel(l) < getIndentlevel(lines[i+1]):
state = readList
else:
s.props[k] = p
elif state == readList:
p.add_item(l.strip())
if getindentlevel(l) > getindentlevel(lines[i+1]):
state = readKeyValue
s.props[k] = p
return sects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment