apa 6.93 KB
Newer Older
Anders Blomdell's avatar
Anders Blomdell committed
1
2
3
4
#!/usr/bin/python
"""
Anders Python Archiver

Anders Blomdell's avatar
Anders Blomdell committed
5
Copyright (C) 2004-2009 Anders Blomdell <anders.blomdell@control.lth.se>
Anders Blomdell's avatar
Anders Blomdell committed
6
7
8
9

  A small utility program to join a number of python modules
  into a single executable python program.

Anders Blomdell's avatar
Anders Blomdell committed
10
  http://www.control.lth.se/user/andersb/software/apa
Anders Blomdell's avatar
Anders Blomdell committed
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

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; either version 2
of the License, or (at your option) any later version.

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.
"""

import optparse
import os
import re
import string
import sys

def getModuleName(s):
    m = re.match("^(.*)/__init__\.py$", s)
    if m:
        return string.replace(m.group(1), "/", ".")
    m = re.match("^(.*)\.py$", s)
    if m:
        return string.replace(m.group(1), "/", ".")
    return None

Anders Blomdell's avatar
Anders Blomdell committed
42
43
44
45
46
def emitCode(f, module, filename, code):
    print >> sys.stderr, "EMIT:", module
    print >> f, '"%s" : ( "%s", """%s""")' % (quote(module),
                                                  quote(filename),
                                                  quote(code))
Anders Blomdell's avatar
Anders Blomdell committed
47
48
49
50
51
52
53
54
55
56
57
58
59
    
def quote(s):
    return string.replace(string.replace(s, '\\', '\\\\'), '"', '\\"')

if __name__ == '__main__':
    usage = "%prog [options] <main module> <additional modules>*"
    optParser = optparse.OptionParser(usage=usage)
    optParser.add_option('-d','--documentation',
                         action='store_true', 
                         help='Show documentation')
    optParser.add_option('-o','--output',
                         action='store', 
                         help='Name of archive')
Anders Blomdell's avatar
Anders Blomdell committed
60
61
62
63
    optParser.add_option('-s','--strip',
                         action='append',
                         default=[],
                         help='Strip this part from filenames')
Anders Blomdell's avatar
Anders Blomdell committed
64
65
66
67
68
69
70
71
    (options, args) = optParser.parse_args(sys.argv[1:])

    if options.documentation:
        print __doc__
        sys.exit(0)

    # Read all python files
    code = []
Anders Blomdell's avatar
Anders Blomdell committed
72
    processed = set()
Anders Blomdell's avatar
Anders Blomdell committed
73
    for filename in args:
Anders Blomdell's avatar
Anders Blomdell committed
74
75
76
77
78
79
80
        archivename = filename
        for strip in options.strip:
            m = re.match("^%s/*(.*)" % strip, filename)
            if m:
                archivename = m.group(1)
                break
            
Anders Blomdell's avatar
Anders Blomdell committed
81
82
83
84
        if archivename in processed:
            continue
        processed.add(archivename)

Anders Blomdell's avatar
Anders Blomdell committed
85
        name = getModuleName(archivename)
Anders Blomdell's avatar
Anders Blomdell committed
86
87
        if name:
            f = open(filename)
Anders Blomdell's avatar
Anders Blomdell committed
88
            code.append((name, archivename, f.read()))
Anders Blomdell's avatar
Anders Blomdell committed
89
90
91
92
93
94
95
96
97
            f.close()
        else:
            print "Illegal filename '%s'" % filename
            sys.exit(1)

    if options.output:
        apa = file(options.output, 'w')
    else:
        apa = None
Anders Blomdell's avatar
Anders Blomdell committed
98

Anders Blomdell's avatar
Anders Blomdell committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    # Emit code
    interpreter = code[0][2].splitlines()[0]
    if interpreter.find("python") >= 0:
        # Take interpreter version from main file
        print >> apa, interpreter
    else:
        # Default interpreter
        print >> sys.stderr, "Interpreter defaulting to '#!/usr/bin/python'"
        print >> apa, "#!/usr/bin/python"
    print >> apa, "\"\"\""
    print >> apa, "Executable archive of '%s'" % code[0][0]
    print >> apa, "\nThe following modules are archived:"
    print >> apa, "  %-20s %s" % ('__main__', code[0][1])
    for (n, f, c) in code[1:]:
        print >> apa, "  %-20s %s" % (n, f)
    print >> apa, """
Anders Blomdell's avatar
Anders Blomdell committed
115
Archive created by 'apa' (http://www.control.lth.se/user/andersb/software/apa)
Anders Blomdell's avatar
Anders Blomdell committed
116
117
118
119
120
121
122
123
124
125
126
127

To extract as individual files:

  * Add a .py suffix to the archive (if needed)
  * Start a python interpreter
  * Run the following commands:
       import <archive name>
       <archive name>.extract(<optional destination dir>)
\"\"\"
"""
    print >> apa, "code = {"
    (n, f, c) = code[0]
Anders Blomdell's avatar
Anders Blomdell committed
128
    emitCode(apa, '__main__', f, c)
Anders Blomdell's avatar
Anders Blomdell committed
129
130
    for (n, f, c) in code[1:]:
        print >> apa, ","
Anders Blomdell's avatar
Anders Blomdell committed
131
        emitCode(apa, n, f, c)
Anders Blomdell's avatar
Anders Blomdell committed
132
133
134
    print >> apa, "}"
    print >> apa, """

Anders Blomdell's avatar
Anders Blomdell committed
135
class Importer:
Anders Blomdell's avatar
Anders Blomdell committed
136
137
    \"\"\"Loads modules from local code dictionary
    \"\"\"
Anders Blomdell's avatar
Anders Blomdell committed
138
139
140
141
142
143
144
145
146
147
148
149
    def __init__(self, code):
        self.code = code;
        self.path = "<%s>" % str(self.__class__)
        if not self.path in sys.path:
            sys.path.insert(0, self.path)

    def __call__(self, path):
        if path == self.path:
            return self
        return None
    
    def find_module(self, fullname):
Anders Blomdell's avatar
Anders Blomdell committed
150
        try:
Anders Blomdell's avatar
Anders Blomdell committed
151
152
153
154
155
156
157
158
159
160
161
162
163
            self.code[fullname]
            return self
        except:
            return None
        
    def load_module(self, fullname):
        mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
        (filename, src) = self.code[fullname]
        mod.__file__ = filename
        mod.__loader__ = self
        mod.__path__ = [ self.path ]
        global BAD
        BAD = None
Anders Blomdell's avatar
Anders Blomdell committed
164
        try:
Anders Blomdell's avatar
Anders Blomdell committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
            code = compile(src, "%s/%s" % (self.path, filename), 'exec')
            exec code in mod.__dict__
        except exceptions.SystemExit, e:
            # Silently propagate exit
            raise e
        except Exception, e:
            # Silently propagate other exceptions as well
            BAD = sys.exc_info()
            raise e
        return mod

    def is_package(self, fullname):
        (filename, src) = self.code[fullname]
        return True

    def get_code(self, fullname):
        (filename, src) = self.code[fullname]
        code = compile(src, "%s/%s" % (self.path, filename), 'exec')
        return code

    def get_source(self, fullname):
        (filename, src) = self.code[fullname]
        return src
Anders Blomdell's avatar
Anders Blomdell committed
188
        
Anders Blomdell's avatar
Anders Blomdell committed
189
190
191
192
    def get_filename(self, fullname):
        (filename, src) = self.code[fullname]
        return filename
   
Anders Blomdell's avatar
Anders Blomdell committed
193
194
def extract(dest='.'):
    \"\"\"Extracts archived files in dest directory ('.' is default)\"\"\"
Anders Blomdell's avatar
Anders Blomdell committed
195
196
197
    import os
    import os.path
    for (m, (f, c)) in code.iteritems():
Anders Blomdell's avatar
Anders Blomdell committed
198
199
200
201
202
203
204
205
206
207
208
209
        filepath = '%s/%s' % (dest, f)
        dirpath = os.path.dirname(filepath)
        if os.path.exists(filepath):
            raise Exception('File already exists: %s' % filepath)
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)
        f = file(filepath, 'w')
        f.write(c)
        f.close()
        os.chmod(filepath, 0755)
    
if __name__ == '__main__':
Anders Blomdell's avatar
Anders Blomdell committed
210
211
212
213
214
    import sys
    importer = Importer(code)
    sys.path_hooks.append(importer)
    import exceptions
    import imp
Anders Blomdell's avatar
Anders Blomdell committed
215
    try:
Anders Blomdell's avatar
Anders Blomdell committed
216
217
        # This will start actual execution
        importer.load_module("__main__")
Anders Blomdell's avatar
Anders Blomdell committed
218
219
220
    except exceptions.SystemExit, e:
        raise e
    except:
Anders Blomdell's avatar
Anders Blomdell committed
221
222
223
224
        if BAD:
            import traceback
            traceback.print_exception(*BAD)
            pass
Anders Blomdell's avatar
Anders Blomdell committed
225
226
227
228
        sys.exit(1)
"""
    if apa:
        apa.close()
Anders Blomdell's avatar
Anders Blomdell committed
229
230
231
232
        try:
            os.chmod(options.output, 0755)
        except:
            pass