now handles spaces in command names (in the naming of the export folder)
[pyvconv.git] / commands.py
blob9859fc34f751be766efc021fc8b9bb24ed631ee8
1 # Pyvconv - A simple frontend for ffmpeg/mencoder
2 # Copyright (C) 2008, Kristian Rumberg (kristianrumberg@gmail.com)
4 # Permission to use, copy, modify, and/or distribute this software for any
5 # purpose with or without fee is hereby granted, provided that the above
6 # copyright notice and this permission notice appear in all copies.
8 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 import os
17 import libxml2
18 import re
20 class Error(Exception):
21 def __init__(self, value):
22 Exception.__init__(self)
23 self.value = value
24 def __str__(self):
25 return repr(self.value)
27 class Variable:
28 def __init__(self, namestr, defaultstr, exprstr = None):
29 self.namestr = namestr
30 self.defaultstr = defaultstr
31 self.exprstr = exprstr
33 def __str__(self):
34 return self.namestr
36 def has_value(self):
37 return self.defaultstr != None
39 def get_value(self):
40 if self.defaultstr == None:
41 raise Error("Error: Trying to eval variable " + self.namestr + " with no value")
42 return self.defaultstr
44 class OptionalSetting:
45 def __init__(self, namestr, exprstr):
46 self.namestr = namestr
47 self.exprstr = exprstr
49 def get_name(self):
50 return self.namestr
52 def get_value(self, var_list):
53 instr = self.exprstr
54 for var in var_list:
55 if var_list[var].has_value():
56 p = re.compile( "\$\{" + var + "\}")
57 instr = p.sub( var_list[var].get_value(), instr)
58 if instr.find("$") != -1:
59 instr = "" # if not all variables were found, return empty option
60 return instr
62 class Command:
63 def __init__(self, namestr, callstr, var_list, optset_list):
64 self.namestr = namestr
65 self.callstr = callstr
66 self.var_list = var_list
67 self.optset_list = optset_list
69 def get_name(self):
70 return self.namestr
72 def put_var(self, var):
73 self.var_list[str(var)] = var
75 def get_vars(self):
76 return self.var_list
78 def __str__(self):
79 instr = self.callstr
81 p = re.compile("\$\[(\w+)\]")
82 for o in p.findall(instr):
83 if o not in self.optset_list:
84 raise Error("Error: Optional variable not defined")
85 instr = p.sub(self.optset_list[o].get_value(self.var_list), instr)
87 p = re.compile("\$\{(\w+)\}")
88 for o in p.findall(instr):
89 if o not in self.var_list:
90 raise Error("Error: Variable \"" + o + "\" has not been assigned")
91 val = self.var_list[o].get_value()
92 instr = instr.replace("${" + o + "}", val)
94 if instr.find("$") != -1:
95 raise Error("Error: all variables were not expanded")
96 return instr
98 class CommandList:
99 def __init__(self):
100 self.cmdcall_dict = {}
101 self._read_config()
103 def _read_properties(self, propnode, mand_propnames, opt_propnames = []):
104 propdict = {}
106 for p in propnode:
107 if p.name in mand_propnames:
108 propdict[p.name] = str(p.content)
109 elif p.name != "text" and p.name not in opt_propnames:
110 raise Error("Error parsing XML: only name and call are accepted properties in the element command, found " + str(p.name))
112 if len(mand_propnames) != len(propdict.keys()):
113 raise Error("Error parsing XML: must supply both name and call in element command")
115 for p in propnode:
116 if p.name in opt_propnames:
117 propdict[p.name] = str(p.content)
118 elif p.name != "text" and p.name not in mand_propnames:
119 raise Error("Error parsing XML: only name and call are accepted properties in the element command, found " + str(p.name))
121 return propdict
123 def _get_config_path(self):
124 homeconf = os.path.expanduser("~") + "/.pyvconv/commands.xml"
125 if os.path.isfile("commands.xml"):
126 return "commands.xml"
127 elif os.path.isfile(homeconf):
128 return homeconf
129 else:
130 raise Error("Error: No config found")
132 def _read_config(self):
133 doc = libxml2.parseFile(self._get_config_path())
134 cmd_xmllist = doc.xpathEval( '//command')
136 # read all commands from XML description
137 for cmdnode in cmd_xmllist:
138 if cmdnode.type == "element" and cmdnode.name == "command":
140 var_list = {}
141 optset_list = {}
143 if cmdnode.children:
144 for varsetnode in cmdnode.children:
145 if varsetnode.type == "element" and varsetnode.name == "variable":
146 props = self._read_properties(varsetnode.properties, ["name", "expr"], ["default"])
147 defprop = None
148 if "default" in props:
149 defprop = props["default"]
150 var_list[props["name"]] = Variable(props["name"], defprop, props["expr"])
152 elif varsetnode.type == "element" and varsetnode.name == "optionalsetting":
153 props = self._read_properties(varsetnode.properties, ["name", "expr"])
154 optset_list[props["name"]] = OptionalSetting(props["name"], props["expr"])
156 elif varsetnode.name != "text":
157 raise Error("Error parsing XML: only variable and optionalsetting elements allowed in command")
159 props = self._read_properties(cmdnode.properties, ["name", "call"])
160 self.cmdcall_dict[props["name"]] = Command(props["name"], props["call"], var_list, optset_list)
162 else:
163 raise Error("Error parsing XML: only command elements are supported")
165 def __iter__(self):
166 return self.cmdcall_dict.values().__iter__()
168 def __getitem__(self, name):
169 return self.cmdcall_dict[name]