http://scons.tigris.org/issues/show_bug.cgi?id=2345
[scons.git] / src / engine / SCons / Tool / packaging / __init__.py
1 """SCons.Tool.Packaging
2
3 SCons Packaging Tool.
4 """
5
6 #
7 # __COPYRIGHT__
8 #
9 # Permission is hereby granted, free of charge, to any person obtaining
10 # a copy of this software and associated documentation files (the
11 # "Software"), to deal in the Software without restriction, including
12 # without limitation the rights to use, copy, modify, merge, publish,
13 # distribute, sublicense, and/or sell copies of the Software, and to
14 # permit persons to whom the Software is furnished to do so, subject to
15 # the following conditions:
16 #
17 # The above copyright notice and this permission notice shall be included
18 # in all copies or substantial portions of the Software.
19 #
20 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
21 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
22 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 #
28 from __future__ import generators  ### KEEP FOR COMPATIBILITY FIXERS
29
30 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
31
32 import SCons.Environment
33 from SCons.Variables import *
34 from SCons.Errors import *
35 from SCons.Util import is_List, make_path_relative
36 from SCons.Warnings import warn, Warning
37
38 import os, imp
39 import SCons.Defaults
40
41 __all__ = [ 'src_targz', 'src_tarbz2', 'src_zip', 'tarbz2', 'targz', 'zip', 'rpm', 'msi', 'ipk' ]
42
43 #
44 # Utility and Builder function
45 #
46 def Tag(env, target, source, *more_tags, **kw_tags):
47     """ Tag a file with the given arguments, just sets the accordingly named
48     attribute on the file object.
49
50     TODO: FIXME
51     """
52     if not target:
53         target=source
54         first_tag=None
55     else:
56         first_tag=source
57
58     if first_tag:
59         kw_tags[first_tag[0]] = ''
60
61     if len(kw_tags) == 0 and len(more_tags) == 0:
62         raise UserError("No tags given.")
63
64     # XXX: sanity checks
65     for x in more_tags:
66         kw_tags[x] = ''
67
68     if not SCons.Util.is_List(target):
69         target=[target]
70     else:
71         # hmm, sometimes the target list, is a list of a list
72         # make sure it is flattened prior to processing.
73         # TODO: perhaps some bug ?!?
74         target=env.Flatten(target)
75
76     for t in target:
77         for (k,v) in kw_tags.items():
78             # all file tags have to start with PACKAGING_, so we can later
79             # differentiate between "normal" object attributes and the
80             # packaging attributes. As the user should not be bothered with
81             # that, the prefix will be added here if missing.
82             #if not k.startswith('PACKAGING_'):
83             if k[:10] != 'PACKAGING_':
84                 k='PACKAGING_'+k
85             setattr(t, k, v)
86
87 def Package(env, target=None, source=None, **kw):
88     """ Entry point for the package tool.
89     """
90     # check if we need to find the source files ourself
91     if not source:
92         source = env.FindInstalledFiles()
93
94     if len(source)==0:
95         raise UserError("No source for Package() given")
96
97     # decide which types of packages shall be built. Can be defined through
98     # four mechanisms: command line argument, keyword argument,
99     # environment argument and default selection( zip or tar.gz ) in that
100     # order.
101     try: kw['PACKAGETYPE']=env['PACKAGETYPE']
102     except KeyError: pass
103
104     if not kw.get('PACKAGETYPE'):
105         from SCons.Script import GetOption
106         kw['PACKAGETYPE'] = GetOption('package_type')
107
108     if kw['PACKAGETYPE'] == None:
109         if 'Tar' in env['BUILDERS']:
110             kw['PACKAGETYPE']='targz'
111         elif 'Zip' in env['BUILDERS']:
112             kw['PACKAGETYPE']='zip'
113         else:
114             raise UserError("No type for Package() given")
115
116     PACKAGETYPE=kw['PACKAGETYPE']
117     if not is_List(PACKAGETYPE):
118         PACKAGETYPE=PACKAGETYPE.split(',')
119
120     # load the needed packagers.
121     def load_packager(type):
122         try:
123             file,path,desc=imp.find_module(type, __path__)
124             return imp.load_module(type, file, path, desc)
125         except ImportError, e:
126             raise EnvironmentError("packager %s not available: %s"%(type,str(e)))
127
128     packagers=list(map(load_packager, PACKAGETYPE))
129
130     # set up targets and the PACKAGEROOT
131     try:
132         # fill up the target list with a default target name until the PACKAGETYPE
133         # list is of the same size as the target list.
134         if not target: target = []
135
136         size_diff      = len(PACKAGETYPE)-len(target)
137         default_name   = "%(NAME)s-%(VERSION)s"
138
139         if size_diff>0:
140             default_target = default_name%kw
141             target.extend( [default_target]*size_diff )
142
143         if 'PACKAGEROOT' not in kw:
144             kw['PACKAGEROOT'] = default_name%kw
145
146     except KeyError, e:
147         raise SCons.Errors.UserError( "Missing Packagetag '%s'"%e.args[0] )
148
149     # setup the source files
150     source=env.arg2nodes(source, env.fs.Entry)
151
152     # call the packager to setup the dependencies.
153     targets=[]
154     try:
155         for packager in packagers:
156             t=[target.pop(0)]
157             t=packager.package(env,t,source, **kw)
158             targets.extend(t)
159
160         assert( len(target) == 0 )
161
162     except KeyError, e:
163         raise SCons.Errors.UserError( "Missing Packagetag '%s' for %s packager"\
164                                       % (e.args[0],packager.__name__) )
165     except TypeError, e:
166         # this exception means that a needed argument for the packager is
167         # missing. As our packagers get their "tags" as named function
168         # arguments we need to find out which one is missing.
169         from inspect import getargspec
170         args,varargs,varkw,defaults=getargspec(packager.package)
171         if defaults!=None:
172             args=args[:-len(defaults)] # throw away arguments with default values
173         args.remove('env')
174         args.remove('target')
175         args.remove('source')
176         # now remove any args for which we have a value in kw.
177         args=[x for x in args if x not in kw]
178
179         if len(args)==0:
180             raise # must be a different error, so reraise
181         elif len(args)==1:
182             raise SCons.Errors.UserError( "Missing Packagetag '%s' for %s packager"\
183                                           % (args[0],packager.__name__) )
184         else:
185             raise SCons.Errors.UserError( "Missing Packagetags '%s' for %s packager"\
186                                           % (", ".join(args),packager.__name__) )
187
188     target=env.arg2nodes(target, env.fs.Entry)
189     targets.extend(env.Alias( 'package', targets ))
190     return targets
191
192 #
193 # SCons tool initialization functions
194 #
195
196 added = None
197
198 def generate(env):
199     from SCons.Script import AddOption
200     global added
201     if not added:
202         added = 1
203         AddOption('--package-type',
204                   dest='package_type',
205                   default=None,
206                   type="string",
207                   action="store",
208                   help='The type of package to create.')
209
210     try:
211         env['BUILDERS']['Package']
212         env['BUILDERS']['Tag']
213     except KeyError:
214         env['BUILDERS']['Package'] = Package
215         env['BUILDERS']['Tag'] = Tag
216
217 def exists(env):
218     return 1
219
220 # XXX
221 def options(opts):
222     opts.AddVariables(
223         EnumVariable( 'PACKAGETYPE',
224                      'the type of package to create.',
225                      None, allowed_values=list(map( str, __all__ )),
226                      ignorecase=2
227                   )
228     )
229
230 #
231 # Internal utility functions
232 #
233
234 def copy_attr(f1, f2):
235     """ copies the special packaging file attributes from f1 to f2.
236     """
237     #pattrs = [x for x in dir(f1) if not hasattr(f2, x) and\
238     #                                x.startswith('PACKAGING_')]
239     copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_'
240     pattrs = list(filter(copyit, dir(f1)))
241     for attr in pattrs:
242         setattr(f2, attr, getattr(f1, attr))
243 def putintopackageroot(target, source, env, pkgroot, honor_install_location=1):
244     """ Uses the CopyAs builder to copy all source files to the directory given
245     in pkgroot.
246
247     If honor_install_location is set and the copied source file has an
248     PACKAGING_INSTALL_LOCATION attribute, the PACKAGING_INSTALL_LOCATION is
249     used as the new name of the source file under pkgroot.
250
251     The source file will not be copied if it is already under the the pkgroot
252     directory.
253
254     All attributes of the source file will be copied to the new file.
255     """
256     # make sure the packageroot is a Dir object.
257     if SCons.Util.is_String(pkgroot):  pkgroot=env.Dir(pkgroot)
258     if not SCons.Util.is_List(source): source=[source]
259
260     new_source = []
261     for file in source:
262         if SCons.Util.is_String(file): file = env.File(file)
263
264         if file.is_under(pkgroot):
265             new_source.append(file)
266         else:
267             if hasattr(file, 'PACKAGING_INSTALL_LOCATION') and\
268                        honor_install_location:
269                 new_name=make_path_relative(file.PACKAGING_INSTALL_LOCATION)
270             else:
271                 new_name=make_path_relative(file.get_path())
272
273             new_file=pkgroot.File(new_name)
274             new_file=env.CopyAs(new_file, file)[0]
275             copy_attr(file, new_file)
276             new_source.append(new_file)
277
278     return (target, new_source)
279
280 def stripinstallbuilder(target, source, env):
281     """ strips the install builder action from the source list and stores
282     the final installation location as the "PACKAGING_INSTALL_LOCATION" of
283     the source of the source file. This effectively removes the final installed
284     files from the source list while remembering the installation location.
285
286     It also warns about files which have no install builder attached.
287     """
288     def has_no_install_location(file):
289         return not (file.has_builder() and\
290             hasattr(file.builder, 'name') and\
291             (file.builder.name=="InstallBuilder" or\
292              file.builder.name=="InstallAsBuilder"))
293
294     if len(list(filter(has_no_install_location, source))):
295         warn(Warning, "there are files to package which have no\
296         InstallBuilder attached, this might lead to irreproducible packages")
297
298     n_source=[]
299     for s in source:
300         if has_no_install_location(s):
301             n_source.append(s)
302         else:
303             for ss in s.sources:
304                 n_source.append(ss)
305                 copy_attr(s, ss)
306                 setattr(ss, 'PACKAGING_INSTALL_LOCATION', s.get_path())
307
308     return (target, n_source)
309
310 # Local Variables:
311 # tab-width:4
312 # indent-tabs-mode:nil
313 # End:
314 # vim: set expandtab tabstop=4 shiftwidth=4: