blob: ec14f2ebfdf57fece2c85b0cc101e57ccda8ef8a [file] [log] [blame]
Guido van Rossumd4d77281994-08-19 10:51:31 +00001# Extract files from a SHAR archive.
2# Run this on the Mac.
3# Usage:
4# >>> import unshar
5# >>> f = open('SHAR')
6# >>> unshar.unshar(f)
7
8import string
Jack Jansenb340acf2003-01-26 21:40:00 +00009import EasyDialogs
Guido van Rossumd4d77281994-08-19 10:51:31 +000010
11def unshar(fp, verbose=0, overwrite=0):
12 ofp = None
13 file = None
14 while 1:
15 line = fp.readline()
16 if verbose > 3: print 'Got:', `line`
17 if line[:1] == 'X':
18 # Most common case first
19 if ofp: ofp.write(line[1:])
20 continue
21 if not line:
22 if verbose: print 'EOF'
23 if ofp:
24 print 'Unterminated file -- closing'
25 ofp.close()
26 ofp = None
27 break
28 if line[0] == '#':
29 if verbose: print line,
30 continue
31 if line[:14] == 'sed "s/^X//" >':
32 if verbose: print "!!!", `line`
33 i = string.find(line, "'")
34 j = string.find(line, "'", i+1)
35 if i >= 0 and j > i:
36 file = line[i+1:j]
37 if '/' in file:
38 words = string.splitfields(file, '/')
39 for funny in '', '.':
40 while funny in words: words.remove(funny)
41 for i in range(len(words)):
42 if words[i] == '..': words[i] = ''
43 words.insert(0, '')
44 file = string.joinfields(words, ':')
45 try:
46 ofp = open(file, 'r')
47 ofp.close()
48 ofp = None
49 over = 1
50 except IOError:
51 over = 0
52 if over and not overwrite:
53 print 'Skipping', file, '(already exists) ...'
54 continue
55 ofp = open(file, 'w')
56 if over:
57 print 'Overwriting', file, '...'
58 else:
59 print 'Writing', file, '...'
60 continue
61 if line == 'END_OF_FILE\n':
62 if not file:
63 print 'Unexpected END_OF_FILE marker'
64 if ofp:
65 print 'done'
66 ofp.close()
67 ofp = None
68 else:
69 print 'done skipping'
70 file = None
71 continue
72 if verbose: print "...", `line`
Jack Jansen8bd7c561996-12-23 16:54:51 +000073
74def main():
75 import sys
76 import os
77 if len(sys.argv) > 1:
78 for fname in sys.argv[1:]:
79 fp = open(fname, 'r')
80 dir, fn = os.path.split(fname)
81 if dir:
82 os.chdir(dir)
83 unshar(fp)
84 else:
85 import macfs
Jack Jansenb340acf2003-01-26 21:40:00 +000086 fname = EasyDialogs.AskFileForOpen()
87 if not fname:
Jack Jansen8bd7c561996-12-23 16:54:51 +000088 sys.exit(0)
Jack Jansen8bd7c561996-12-23 16:54:51 +000089 fp = open(fname, 'r')
Jack Jansenb340acf2003-01-26 21:40:00 +000090 dirname = EasyDialogs.AskFolder(message='Folder to save files in:')
91 if not dirname:
Jack Jansen8bd7c561996-12-23 16:54:51 +000092 sys.exit(0)
Jack Jansenb340acf2003-01-26 21:40:00 +000093 os.chdir(dirname)
Jack Jansen8bd7c561996-12-23 16:54:51 +000094 unshar(fp)
95
96if __name__ == '__main__':
97 main()