/usr/bin/ini2spectacle is in spectacle 0.22-1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | #!/usr/bin/python -tt
# vim: ai ts=4 sts=4 et sw=4
# Copyright (c) 2009 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; version 2 of the License
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""Overview of ini2yaml
(1) ini2yaml reads the ini file and divides it into segments.
(2) Parses the 'header' segment. Write out the key,value pairs
(3) Expand the 'Files' if found
(4) Parse the sub-packages segments if found
"""
import os
import sys
import re
import shutil
import optparse
from ConfigParser import RawConfigParser
# spectacle modules
from spectacle.convertor import *
from spectacle.dumper import *
from spectacle import logger
class SBConvertor(Convertor):
""" Convertor for SpecBuild ini files """
def __init__(self):
sb_cv_table = {
'BuildRequires': 'PkgBR',
'PkgConfig': 'PkgConfigBR',
'Extras': 'ExtraSources',
'Extra': 'extra',
}
Convertor.__init__(self, sb_cv_table)
class SBConfigParser(RawConfigParser):
""" SpecBuild ini specific parser """
# keys whose value need to split to list
multi_keys = ('Sources',
'Patches',
'Extras',
'LocaleOptions',
)
# keys whose value may have ver numbers
reqs_keys = ('BuildRequires',
'PreRequires',
'Requires',
'PostRequires',
'PkgConfig',
'Provides',
'Obsoletes',
'Conflicts',
)
# keys whose value need to be expand(reading extra file)
expand_keys = ('Files',
'Description',
'PostMakeExtras',
'PostMakeInstallExtras',
)
# boolean keys
bool_keys = ('UseAsNeeded',
'NoAutoReq',
'NoAutoProv',
'AddCheck',
)
# keys need to be placed to 'extra'
extra_keys = ['Files',
'PostMakeExtras',
'PostMakeInstallExtras',
]
# must have keys
must_keys = {'Release': '1',
'Configure': 'configure',
}
def __init__(self, include_files):
RawConfigParser.__init__(self)
if include_files:
self.extra_keys.remove('Files')
self.record_used_files = []
self._check_Makefile()
def _check_Makefile(self):
""" Check whether Makefile in working dir should be moved """
if os.path.exists('Makefile'):
try:
cont = file('Makefile').read()
if re.search('\s+spec-builder\s+', cont):
# The Makefile is for spec-builder
self.record_used_files.append('Makefile')
except:
pass
def read(self, filenames):
""" override super read to record input files """
if isinstance(filenames, basestring):
filenames = [filenames]
self.record_used_files.extend(filenames)
return RawConfigParser.read(self, filenames)
def optionxform(self, option):
# Capitalize the first char
lead = option[0]
if lead.upper() != lead:
return lead.upper() + option[1:]
else:
return option
def _expand_single(self, filename):
""" Helper function to expand *.desc """
if os.path.exists(filename):
self.record_used_files.append(filename)
return file(filename).read().strip()
else:
logger.warning("Warning: missing expected file %s" % filename)
return None
def _cook_config(self):
""" Helper function to update fields for spec-builder specific ones
"""
all_items = {}
main_extra = {} # for extra keys of main pkg
for section in self.sections():
items = self._sections[section]
# Convert space seperated string to list
for key in self.multi_keys:
if key in items:
self.set(section, key, map(str.strip, items[key].split()))
# Convert dependent like entry to list
for key in self.reqs_keys:
if key in items:
reqs = []
for entry in re.findall('\S+\s+[<>=]+\s+\S+|\S+', items[key]):
reqs.append(entry.split(',')[0])
self.set(section, key, reqs)
# special cases for 'ConfigOptions'
if 'ConfigOptions' in items:
self.set(section, 'ConfigOptions',
map(lambda s: '--'+s,
[opt for opt in map(str.strip, items['ConfigOptions'].split('--')) if opt]))
# special cases for 'LocaleOptions'
if 'LocaleOptions' in items and 'LocaleName' not in items:
self.set(section, 'LocaleName', '%{name}')
# Convert boolean keys
for key in self.bool_keys:
if key in items:
if items[key].upper() in ('NO', 'FALSE', '0'):
del items[key]
else:
self.set(section, key, 'yes')
# Convert keys which need expanding from external file
for key in self.expand_keys:
if key in items:
content = self._expand_single(items[key])
if content:
if key == 'Files':
# 'Files' need split to list
self.set(section, key, content.split('\n'))
else:
self.set(section, key, content)
else:
# if file empty or file not exists, remove the empty key
del items[key]
# move extra keys to 'extra' key
extra = {}
for key in self.extra_keys:
if key in items:
extra[key] = items[key]
del items[key]
if extra:
if section not in ('header', 'configuration'):
self.set(section, 'extra', extra)
else:
main_extra.update(extra)
for section in self.sections():
if section in ('header', 'configuration'):
all_items.update(dict(self.items(section)))
if main_extra:
all_items['extra'] = main_extra
# Checking must-have keys
for key, default in self.must_keys.iteritems():
if key not in all_items:
all_items[key] = default
# Re-structure sub packages to inner level
if 'SubPackages' in all_items:
subpkg_list = all_items['SubPackages'].split()
all_items['SubPackages'] = []
for subpkg in subpkg_list:
try:
all_items['SubPackages'].append(dict(self.items(subpkg)))
all_items['SubPackages'][-1].update({'Name': subpkg})
except NoSectionError, e:
logger.warning('Needed section for sub-package %s not found' % subpkg)
raise e
return all_items
def cooked_items(self):
""" return all items, cooked to the input of convertor """
return self._cook_config()
def parse_options(args):
import spectacle.__version__
usage = "Usage: %prog [options] [ini-path]"
parser = optparse.OptionParser(usage, version=spectacle.__version__.VERSION)
parser.add_option("-o", "--output", type="string",
dest="outfile_path", default=None,
help="Path of output yaml file")
parser.add_option("-f", "--include-files", action="store_true",
dest="include_files", default=False,
help="To store files list in YAML file")
return parser.parse_args()
if __name__ == '__main__':
""" Main Function """
(options, args) = parse_options(sys.argv[1:])
if not args:
# no ini-path specified, search in CWD
import glob
inils = glob.glob('*.ini')
if not inils:
logger.error('Cannot find valid spec-builder file(*.ini) in current directory, please specify one.')
elif len(inils) > 1:
logger.error('Find multiple spec-builder files(*.ini) in current directory, please specify one.')
ini_fpath = inils[0]
else:
ini_fpath = args[0]
# Check if the input file exists
if not os.path.exists(ini_fpath):
# input file does not exist
logger.error("%s: File does not exist" % ini_fpath)
# check the working path
if ini_fpath.find('/') != -1 and os.path.dirname(ini_fpath) != os.path.curdir:
wdir = os.path.dirname(ini_fpath)
logger.info('Changing to working dir: %s' % wdir)
os.chdir(wdir)
ini_fname = os.path.basename(ini_fpath)
if options.outfile_path:
out_fpath = options.outfile_path
else:
if ini_fname.endswith('.ini'):
out_fpath = ini_fname[:-3] + 'yaml'
else:
out_fpath = ini_fname + '.yaml'
"""Read the input file"""
config = SBConfigParser(include_files = options.include_files)
config.read(ini_fname)
convertor = SBConvertor()
"""Dump them to spectacle file"""
dumper = SpectacleDumper(format='yaml', opath = out_fpath)
spec_fpath = dumper.dump(convertor.convert(config.cooked_items()))
logger.info('Yaml file %s created' % out_fpath)
if spec_fpath:
logger.info('Spec file %s was created with extra data' % spec_fpath)
# move old spec-builder files to backup dir
backDir = 'spec-builder.backup'
try:
os.mkdir(backDir)
except:
pass
if os.path.exists(backDir) and not os.path.isfile(backDir):
logger.info('The following used spec-builder files are moved to dir: %s' % backDir)
for file in config.record_used_files:
logger.info('\t' + os.path.basename(file))
shutil.move(file, backDir)
|