fix help command
[tools/mic.git] / mic / creator.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2011 Intel, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 # for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18 import os, sys, re
19 from optparse import SUPPRESS_HELP
20
21 from mic import msger, rt_util
22 from mic.utils import cmdln, errors, rpmmisc
23 from conf import configmgr
24 from plugin import pluginmgr
25
26 class Creator(cmdln.Cmdln):
27     """${name}: create an image
28
29     Usage:
30         ${name} SUBCOMMAND <ksfile> [OPTS]
31
32     ${command_list}
33     ${option_list}
34     """
35
36     name = 'mic create(cr)'
37
38     def __init__(self, *args, **kwargs):
39         cmdln.Cmdln.__init__(self, *args, **kwargs)
40         self._subcmds = []
41
42         # get cmds from pluginmgr
43         # mix-in do_subcmd interface
44         for subcmd, klass in pluginmgr.get_plugins('imager').iteritems():
45             if not hasattr(klass, 'do_create'):
46                 msger.warning("Unsurpport subcmd: %s" % subcmd)
47                 continue
48
49             func = getattr(klass, 'do_create')
50             setattr(self.__class__, "do_"+subcmd, func)
51             self._subcmds.append(subcmd)
52
53     def get_optparser(self):
54         optparser = cmdln.CmdlnOptionParser(self)
55         optparser.add_option('-d', '--debug', action='store_true',
56                              dest='debug',
57                              help=SUPPRESS_HELP)
58         optparser.add_option('-v', '--verbose', action='store_true',
59                              dest='verbose',
60                              help=SUPPRESS_HELP)
61         optparser.add_option('', '--logfile', type='string', dest='logfile',
62                              default=None,
63                              help='Path of logfile')
64         optparser.add_option('-c', '--config', type='string', dest='config',
65                              default=None,
66                              help='Specify config file for mic')
67         optparser.add_option('-k', '--cachedir', type='string', action='store',
68                              dest='cachedir', default=None,
69                              help='Cache directory to store the downloaded')
70         optparser.add_option('-o', '--outdir', type='string', action='store',
71                              dest='outdir', default=None,
72                              help='Output directory')
73         optparser.add_option('-A', '--arch', type='string', dest='arch',
74                              default=None,
75                              help='Specify repo architecture')
76         optparser.add_option('', '--release', type='string', dest='release',
77                              default=None, metavar='RID',
78                              help='Generate a release of RID with all necessary'
79                                   ' files, when @BUILD_ID@ is contained in '
80                                   'kickstart file, it will be replaced by RID')
81         optparser.add_option("", "--record-pkgs", type="string",
82                              dest="record_pkgs", default=None,
83                              help='Record the info of installed packages, '
84                                   'multiple values can be specified which '
85                                   'joined by ",", valid values: "name", '
86                                   '"content", "license"')
87         optparser.add_option('', '--pkgmgr', type='string', dest='pkgmgr',
88                              default=None,
89                              help='Specify backend package manager')
90         optparser.add_option('', '--local-pkgs-path', type='string',
91                              dest='local_pkgs_path', default=None,
92                              help='Path for local pkgs(rpms) to be installed')
93         optparser.add_option('', '--runtime', type='string',
94                              dest='runtime', default=None,
95                              #help='Specify  runtime mode, avaiable: bootstrap')
96                              help=SUPPRESS_HELP)
97         # --taring-to is alias to --pack-to
98         optparser.add_option('', '--taring-to', type='string',
99                              dest='pack_to', default=None,
100                              help=SUPPRESS_HELP)
101         optparser.add_option('', '--pack-to', type='string',
102                              dest='pack_to', default=None,
103                              help='Pack the images together into the specified'
104                                   ' achive, extension supported: .zip, .tar, '
105                                   '.tar.gz, .tar.bz2, etc. by default, .tar '
106                                   'will be used')
107         optparser.add_option('', '--copy-kernel', action='store_true',
108                              dest='copy_kernel',
109                              help='Copy kernel files from image /boot directory'
110                                   ' to the image output directory.')
111         optparser.add_option('', '--repourl', action='append',
112                              dest='repourl', default=[],
113                              help=SUPPRESS_HELP)
114         return optparser
115
116     def preoptparse(self, argv):
117         optparser = self.get_optparser()
118
119         largs = []
120         rargs = []
121         while argv:
122             arg = argv.pop(0)
123
124             if arg in ('-h', '--help'):
125                 rargs.append(arg)
126
127             elif optparser.has_option(arg):
128                 largs.append(arg)
129
130                 if optparser.get_option(arg).takes_value():
131                     try:
132                         largs.append(argv.pop(0))
133                     except IndexError:
134                         raise errors.Usage("option %s requires arguments" % arg)
135
136             else:
137                 if arg.startswith("--"):
138                     if "=" in arg:
139                         opt = arg.split("=")[0]
140                     else:
141                         opt = None
142                 elif arg.startswith("-") and len(arg) > 2:
143                     opt = arg[0:2]
144                 else:
145                     opt = None
146
147                 if opt and optparser.has_option(opt):
148                     largs.append(arg)
149                 else:
150                     rargs.append(arg)
151
152         return largs + rargs
153
154     def postoptparse(self):
155         abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
156
157         if self.options.verbose:
158             msger.set_loglevel('verbose')
159         if self.options.debug:
160             msger.set_loglevel('debug')
161
162         if self.options.logfile:
163             msger.set_interactive(False)
164             msger.set_logfile(self.options.logfile)
165             configmgr.create['logfile'] = self.options.logfile
166
167         if self.options.config:
168             configmgr.reset()
169             configmgr._siteconf = self.options.config
170
171         if self.options.outdir is not None:
172             configmgr.create['outdir'] = abspath(self.options.outdir)
173         if self.options.cachedir is not None:
174             configmgr.create['cachedir'] = abspath(self.options.cachedir)
175         os.environ['ZYPP_LOCKFILE_ROOT'] = configmgr.create['cachedir']
176
177         if self.options.local_pkgs_path is not None:
178             if not os.path.exists(self.options.local_pkgs_path):
179                 msger.error('Local pkgs directory: \'%s\' not exist' \
180                               % self.options.local_pkgs_path)
181             configmgr.create['local_pkgs_path'] = self.options.local_pkgs_path
182
183         if self.options.release:
184             configmgr.create['release'] = self.options.release
185
186         if self.options.record_pkgs:
187             configmgr.create['record_pkgs'] = []
188             for infotype in self.options.record_pkgs.split(','):
189                 if infotype not in ('name', 'content', 'license'):
190                     raise errors.Usage('Invalid pkg recording: %s, valid ones:'
191                                        ' "name", "content", "license"' \
192                                        % infotype)
193
194                 configmgr.create['record_pkgs'].append(infotype)
195
196         if self.options.arch is not None:
197             supported_arch = sorted(rpmmisc.archPolicies.keys(), reverse=True)
198             if self.options.arch in supported_arch:
199                 configmgr.create['arch'] = self.options.arch
200             else:
201                 raise errors.Usage('Invalid architecture: "%s".\n'
202                                    '  Supported architectures are: \n'
203                                    '  %s' % (self.options.arch,
204                                                ', '.join(supported_arch)))
205
206         if self.options.pkgmgr is not None:
207             configmgr.create['pkgmgr'] = self.options.pkgmgr
208
209         if self.options.runtime:
210             configmgr.create['runtime'] = self.options.runtime
211
212         if self.options.pack_to is not None:
213             configmgr.create['pack_to'] = self.options.pack_to
214
215         if self.options.copy_kernel:
216             configmgr.create['copy_kernel'] = self.options.copy_kernel
217
218         if self.options.repourl:
219             for item in self.options.repourl:
220                 try:
221                     key, val = item.split('=')
222                 except:
223                     continue
224                 configmgr.create['repourl'][key] = val
225
226     def main(self, argv=None):
227         if argv is None:
228             argv = sys.argv
229         else:
230             argv = argv[:] # don't modify caller's list
231
232         self.optparser = self.get_optparser()
233         if self.optparser:
234             try:
235                 argv = self.preoptparse(argv)
236                 self.options, args = self.optparser.parse_args(argv)
237
238             except cmdln.CmdlnUserError, ex:
239                 msg = "%s: %s\nTry '%s help' for info.\n"\
240                       % (self.name, ex, self.name)
241                 msger.error(msg)
242
243             except cmdln.StopOptionProcessing, ex:
244                 return 0
245         else:
246             # optparser=None means no process for opts
247             self.options, args = None, argv[1:]
248
249         if not args:
250             return self.emptyline()
251
252         self.postoptparse()
253
254         return self.cmd(args)
255
256     def precmd(self, argv): # check help before cmd
257
258         if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
259             return argv
260
261         if len(argv) == 1:
262             return ['help', argv[0]]
263
264         if os.geteuid() != 0:
265             raise msger.error("Root permission is required, abort")
266
267         return argv
268
269     def do_auto(self, subcmd, opts, *args):
270         """${cmd_name}: auto detect image type from magic header
271
272         Usage:
273             ${name} ${cmd_name} <ksfile>
274
275         ${cmd_option_list}
276         """
277         def parse_magic_line(re_str, pstr, ptype='mic'):
278             ptn = re.compile(re_str)
279             m = ptn.match(pstr)
280             if not m or not m.groups():
281                 return None
282
283             inline_argv = m.group(1).strip()
284             if ptype == 'mic':
285                 m2 = re.search('(?P<format>\w+)', inline_argv)
286             elif ptype == 'mic2':
287                 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
288                                inline_argv)
289             else:
290                 return None
291
292             if m2:
293                 cmdname = m2.group('format')
294                 inline_argv = inline_argv.replace(m2.group(0), '')
295                 return (cmdname, inline_argv)
296
297             return None
298
299         if len(args) != 1:
300             raise errors.Usage("Extra arguments given")
301
302         if not os.path.exists(args[0]):
303             raise errors.CreatorError("Can't find the file: %s" % args[0])
304
305         with open(args[0], 'r') as rf:
306             first_line = rf.readline()
307
308         mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
309         mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
310
311         result = parse_magic_line(mic_re, first_line, 'mic') \
312                  or parse_magic_line(mic2_re, first_line, 'mic2')
313         if not result:
314             raise errors.KsError("Invalid magic line in file: %s" % args[0])
315
316         if result[0] not in self._subcmds:
317             raise errors.KsError("Unsupport format '%s' in %s"
318                                  % (result[0], args[0]))
319
320         argv = ' '.join(result + args).split()
321         self.main(argv)
322