Another batch of updates...
[python/dscho.git] / Mac / Lib / py_resource.py
blob8530b59c260528cd0a68b6e7b8f6c562fac4dd0f
1 """Creation of PYC resources"""
2 import os
3 import Res
4 import __builtin__
6 READ = 1
7 WRITE = 2
8 smAllScripts = -3
10 def Pstring(str):
11 """Return a pascal-style string from a python-style string"""
12 if len(str) > 255:
13 raise ValueError, 'String too large'
14 return chr(len(str))+str
16 def create(dst, creator='Pyth'):
17 """Create output file. Return handle and first id to use."""
19 try:
20 os.unlink(dst)
21 except os.error:
22 pass
23 Res.FSpCreateResFile(dst, creator, 'rsrc', smAllScripts)
24 return open(dst)
26 def open(dst):
27 output = Res.FSpOpenResFile(dst, WRITE)
28 Res.UseResFile(output)
29 return output
31 def writemodule(name, id, data, type='PYC '):
32 """Write pyc code to a PYC resource with given name and id."""
33 # XXXX Check that it doesn't exist
34 res = Res.Resource(data)
35 res.AddResource(type, id, name)
36 res.WriteResource()
37 res.ReleaseResource()
39 def frompycfile(file, name=None):
40 """Copy one pyc file to the open resource file"""
41 if name == None:
42 d, name = os.path.split(file)
43 name = name[:-4]
44 id = findfreeid()
45 writemodule(name, id, __builtin__.open(file, 'rb').read())
46 return id, name
48 def frompyfile(file, name=None):
49 """Compile python source file to pyc file and add to resource file"""
50 import py_compile
52 py_compile.compile(file)
53 file = file +'c'
54 return frompycfile(file, name)
56 # XXXX Note this is incorrect, it only handles one type and one file....
58 _firstfreeid = None
60 def findfreeid(type='PYC '):
61 """Find next free id-number for given resource type"""
62 global _firstfreeid
64 if _firstfreeid == None:
65 Res.SetResLoad(0)
66 highest = 511
67 num = Res.Count1Resources(type)
68 for i in range(1, num+1):
69 r = Res.Get1IndResource(type, i)
70 id, d1, d2 = r.GetResInfo()
71 highest = max(highest, id)
72 Res.SetResLoad(1)
73 _firstfreeid = highest+1
74 id = _firstfreeid
75 _firstfreeid = _firstfreeid+1
76 return id