BitBake Configuration Parser:
[bitbake.git] / lib / bb / parse / parse_py / ConfHandler.py
1 #!/usr/bin/env python
2 # ex:ts=4:sw=4:sts=4:et
3 # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4 """class for handling configuration data files
5
6    Reads a .conf file and obtains its metadata
7
8    Copyright (C) 2003, 2004  Chris Larson
9    Copyright (C) 2003, 2004  Phil Blundell
10    
11    This program is free software; you can redistribute it and/or modify it under
12    the terms of the GNU General Public License as published by the Free Software
13    Foundation; either version 2 of the License, or (at your option) any later
14    version.
15    
16    This program is distributed in the hope that it will be useful, but WITHOUT
17    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18    FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License along with
21    this program; if not, write to the Free Software Foundation, Inc., 59 Temple
22    Place, Suite 330, Boston, MA 02111-1307 USA.""" 
23
24 import re, bb.data, os, sys
25 from bb import debug, fatal
26 from bb.parse import ParseError
27
28 #__config_regexp__  = re.compile( r"(?P<exp>export\s*)?(?P<var>[a-zA-Z0-9\-_+.${}]+)\s*(?P<colon>:)?(?P<ques>\?)?=\s*(?P<apo>['\"]?)(?P<value>.*)(?P=apo)$")
29 __config_regexp__  = re.compile( r"(?P<exp>export\s*)?(?P<var>[a-zA-Z0-9\-_+.${}/]+)(\[(?P<flag>[a-zA-Z0-9\-_+.]+)\])?\s*((?P<colon>:=)|(?P<ques>\?=)|(?P<append>\+=)|(?P<prepend>=\+)|(?P<predot>=\.)|(?P<postdot>\.=)|=)\s*(?P<apo>['\"]?)(?P<value>.*)(?P=apo)$")
30 __include_regexp__ = re.compile( r"include\s+(.+)" )
31
32 def init(data):
33     if not bb.data.getVar('TOPDIR', data):
34         bb.data.setVar('TOPDIR', os.getcwd(), data)
35     if not bb.data.getVar('BBPATH', data):
36         bb.data.setVar('BBPATH', os.path.join(sys.prefix, 'share', 'bitbake'), data)
37
38 def supports(fn, d):
39     return localpath(fn, d)[-5:] == ".conf"
40
41 def localpath(fn, d):
42     if os.path.exists(fn):
43         return fn
44
45     localfn = None
46     try:
47         localfn = bb.fetch.localpath(fn, d)
48     except bb.MalformedUrl:
49         pass
50
51     if not localfn:
52         localfn = fn
53     return localfn
54
55 def obtain(fn, data = bb.data.init()):
56     import sys, bb
57     fn = bb.data.expand(fn, data)
58     localfn = bb.data.expand(localpath(fn, data), data)
59
60     if localfn != fn:
61         dldir = bb.data.getVar('DL_DIR', data, 1)
62         if not dldir:
63             debug(1, "obtain: DL_DIR not defined")
64             return localfn
65         bb.mkdirhier(dldir)
66         try:
67             bb.fetch.init([fn])
68         except bb.fetch.NoMethodError:
69             (type, value, traceback) = sys.exc_info()
70             debug(1, "obtain: no method: %s" % value)
71             return localfn
72
73         try:
74             bb.fetch.go(data)
75         except bb.fetch.MissingParameterError:
76             (type, value, traceback) = sys.exc_info()
77             debug(1, "obtain: missing parameters: %s" % value)
78             return localfn
79         except bb.fetch.FetchError:
80             (type, value, traceback) = sys.exc_info()
81             debug(1, "obtain: failed: %s" % value)
82             return localfn
83     return localfn
84
85
86 def include(oldfn, fn, data = bb.data.init()):
87     if oldfn == fn: # prevent infinate recursion
88         return None
89
90     import bb
91     fn = bb.data.expand(fn, data)
92     oldfn = bb.data.expand(oldfn, data)
93
94     from bb.parse import handle
95     try:
96         ret = handle(fn, data, 1)
97     except IOError:
98         debug(2, "CONF file '%s' not found" % fn)
99
100 def handle(fn, data = bb.data.init(), include = 0):
101     if include:
102         inc_string = "including"
103     else:
104         inc_string = "reading"
105     init(data)
106
107     if include == 0:
108         bb.data.inheritFromOS(data)
109         oldfile = None
110     else:
111         oldfile = bb.data.getVar('FILE', data)
112
113     fn = obtain(fn, data)
114     bbpath = []
115     if not os.path.isabs(fn):
116         f = None
117         vbbpath = bb.data.getVar("BBPATH", data)
118         if vbbpath:
119             bbpath += vbbpath.split(":")
120         for p in bbpath:
121             currname = os.path.join(bb.data.expand(p, data), fn)
122             if os.access(currname, os.R_OK):
123                 f = open(currname, 'r')
124                 abs_fn = currname
125                 debug(1, "CONF %s %s" % (inc_string, currname))
126                 break
127         if f is None:
128             raise IOError("file '%s' not found" % fn)
129     else:
130         f = open(fn,'r')
131         debug(1, "CONF %s %s" % (inc_string,fn))
132         abs_fn = fn
133
134     if include:
135         bb.parse.mark_dependency(data, abs_fn)
136
137     lineno = 0
138     bb.data.setVar('FILE', fn, data)
139     while 1:
140         lineno = lineno + 1
141         s = f.readline()
142         if not s: break
143         w = s.strip()
144         if not w: continue          # skip empty lines
145         s = s.rstrip()
146         if s[0] == '#': continue    # skip comments
147         while s[-1] == '\\':
148             s2 = f.readline()[:-1].strip()
149             lineno = lineno + 1
150             s = s[:-1] + s2
151         feeder(lineno, s, fn, data)
152
153     if oldfile:
154         bb.data.setVar('FILE', oldfile, data)
155     return data
156
157 def feeder(lineno, s, fn, data = bb.data.init()):
158     m = __config_regexp__.match(s)
159     if m:
160         groupd = m.groupdict()
161         key = groupd["var"]
162         if "exp" in groupd and groupd["exp"] != None:
163             bb.data.setVarFlag(key, "export", 1, data)
164         if "ques" in groupd and groupd["ques"] != None:
165             val = bb.data.getVar(key, data)
166             if val == None:
167                 val = groupd["value"]
168         elif "colon" in groupd and groupd["colon"] != None:
169             val = bb.data.expand(groupd["value"], data)
170         elif "append" in groupd and groupd["append"] != None:
171             val = "%s %s" % ((bb.data.getVar(key, data) or ""), groupd["value"])
172         elif "prepend" in groupd and groupd["prepend"] != None:
173             val = "%s %s" % (groupd["value"], (bb.data.getVar(key, data) or ""))
174         elif "postdot" in groupd and groupd["postdot"] != None:
175             val = "%s%s" % ((bb.data.getVar(key, data) or ""), groupd["value"])
176         elif "predot" in groupd and groupd["predot"] != None:
177             val = "%s%s" % (groupd["value"], (bb.data.getVar(key, data) or ""))
178         else:
179             val = groupd["value"]
180         if 'flag' in groupd and groupd['flag'] != None:
181 #           bb.note("setVarFlag(%s, %s, %s, data)" % (key, groupd['flag'], val))
182             bb.data.setVarFlag(key, groupd['flag'], val, data)
183         else:
184             bb.data.setVar(key, val, data)
185         return
186
187     m = __include_regexp__.match(s)
188     if m:
189         s = bb.data.expand(m.group(1), data)
190 #       debug(2, "CONF %s:%d: including %s" % (fn, lineno, s))
191         include(fn, s, data)
192         return
193
194     raise ParseError("%s:%d: unparsed line: '%s'" % (fn, lineno, s));
195
196 # Add us to the handlers list
197 from bb.parse import handlers
198 handlers.append({'supports': supports, 'handle': handle, 'init': init})
199 del handlers