File: cmdproc.py

package info (click to toggle)
palm-doctoolkit 0.99.1-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 152 kB
  • ctags: 130
  • sloc: python: 657; makefile: 40; sh: 19
file content (191 lines) | stat: -rw-r--r-- 5,795 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""
  cmdproc.py - common command-line and option processing stuff
  $Id: cmdproc.py,v 1.1 1998/09/04 08:36:46 rob Exp $

  Copyright 1998 Rob Tillotson <rob@io.com>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2,
  as published by the Free Software Foundation.

  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 the Free Software Foundation,
  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.


"""

__version__ = '$Id: cmdproc.py,v 1.1 1998/09/04 08:36:46 rob Exp $'

import sys, os, getopt, string, urllib, gzip

import DocWriter

#
#  QED hook.  Because the information in the QED module is based on
#  private communication with the author, it is not part of the
#  released package yet and hence the code must work around it if
#  it is not present.
#
try:
    import qed
except:
    qed = None

usage_todoc = """Usage: %s [OPTIONS...] FILES...
Convert %s to PalmPilot e-text.

General Options:
  -h, --help               print this help message
  -t, --title TITLE        set document title
  -b, --backup             set backup bit in database header
  -c, --category NUM       set category number (0-15, 0 = Unfiled)
  --creator ID             set creator ID (default 'REAd')
  --type ID                set database type (default 'TEXt')
  -T                       turn on standard TealDoc options (**)
  
  -I                       install directly onto PalmPilot
  -p PORT                  port to install to (default /dev/pilot)

Common Options: (supported by many, but not all, conversions)
  --teal-headers           use <HEADER> tags **
  --teal-wrap-headers      word-wrap <HEADER> tags **
  --teal-links             use <LINK>/<LABEL> pairs
  --teal-hrules            use <HRULE> tags **
  --teal-bookmarks         use <BOOKMARK> tags instead of real bookmarks
"""

usage_footer = """Each input file may be gzipped and/or a http: or ftp: URL.

Please send bug reports and suggestions to <robt@debian.org>."""

long_options = ['help','title=','creator=','type=','backup','category=',
		'teal-headers','teal-links','teal-hrules','teal-bookmarks']
if qed is not None: long_options = long_options + qed.options_todoc

class GzipFile(gzip.GzipFile):
    """Like an ordinary GzipFile, but doesn't check the CRC; the
    regular GzipFile code requires a seek to do this, which is not
    an option with streams opened by urllib.
    """
    def _read_eof(self):
	pass
    
class CmdLine:
    def __init__(self, conv_type='nothing', extra_options=[]):
	self.conv_type = conv_type
	self.extra_options = extra_options
	self.usage_text = usage_todoc
	if qed is not None: self.usage_text = self.usage_text + qed.usage_todoc
	self.options = {}
	self.argv = []
	self.port = '/dev/pilot'
	self.install_remote = 0
	
    def usage(self):
	print self.usage_text % (sys.argv[0], self.conv_type),
	if self.extra_options:
	    print
	    print "Conversion-Specific Options:"
	for o, d in self.extra_options:
	    if o[-1] == '=':
		print "  --%-21s " % (o[:-1] + ' ARG'),
	    else:
		print "  --%-21s " % o,
	    print d
	print
	print usage_footer

    def process_options(self, argv):
	self.options = {}
	
	try:
	    opts, argv = getopt.getopt(argv[1:], 'hTt:p:Ibc:',
				       long_options +
				       map(lambda x: x[0], self.extra_options))
	except getopt.error, x:
	    self.error_exit(x, 1)

	for k, v in opts:
	    if k == '-h' or k == '--help':
		self.usage()
		sys.exit(0)
	    elif k == '-p':
		self.port = v
	    elif k == '-I':
		self.install_remote = 1
	    elif k == '-T':
		self.options['teal-headers'] = 1
		self.options['teal-wrap-headers'] = 1
		self.options['teal-hrules'] = 1
		self.options['TealDoc'] = 1
		self.options['creator'] = 'TlDc'
	    elif k == '-t' or k == '--title':
		self.options['title'] = v
	    elif k == '-b' or k == '--backup':
		self.options['backup'] = 1
	    elif k == '-c' or k == '--category':
		try:
		    c = string.atoi(v)
		    if c < 0 or c > 15:
			self.error_exit('category must be a number from 0 to 15')
		    self.options['category'] = c
		except:
		    self.error_exit('invalid category')
	    elif k[:2] == '--':
		if k[2:] in self.extra_options or k[2:] in long_options:
		    self.options[k[2:]] = 1
		else: self.options[k[2:]] = v

	self.argv = argv

    def __len__(self): return len(self.argv)
    def __getitem__(self, i): return self.argv[i]

    def process_files(self, callback):
 	if not self.argv:
	    self.error_exit('no files specified (use -h for help).')

	if self.install_remote:
	    from PDA.Palm import DLP
	    try:
		print "Please start HotSync now..."
		target = DLP(self.port)
	    except:
		self.error_exit("error opening HotSync connection.")
	    
	for fn in self.argv:
	    print "Converting %s..." % fn
	    try:
		f = urllib.urlopen(fn)
	    except IOError, msg:
		self.error_exit(msg)

	    n, e = os.path.splitext(os.path.basename(fn))
	    if e == '.gz':  # gzipped
		f = GzipFile(filename="", mode="rb", fileobj=f)
		n, e = os.path.splitext(n)

	    if not self.install_remote:
		target = '%s.pdb' % n

	    w = DocWriter.DocWriter(target, self.options.get('title'),
				    self.options)
	    callback(f, w, self.options.get('title'), self.options,
		     default_title = os.path.basename(fn))

	    if qed is not None: qed.postprocess(w)

	    w.close()
	    
    def error_exit(self, s, show_usage=0):
	sys.stderr.write('%s: %s\n\n' % (sys.argv[0], s))
	if show_usage: self.usage()
	sys.exit(1)