-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
236 lines (190 loc) · 8.73 KB
/
cli.py
File metadata and controls
236 lines (190 loc) · 8.73 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
"""
Command-line interface for unoconvert.
This module provides the command-line interface for unoconvert.
"""
import os
import sys
import argparse
from . import __version__, convert, listen, get_formats
from .config import Config
from .formats import fmts, doctypes
def parse_args(args=None):
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description='Convert between office document formats using LibreOffice/OpenOffice'
)
# Connection options
connection_group = parser.add_argument_group('Connection Options')
connection_group.add_argument('-c', '--connection', help='use a custom connection string')
connection_group.add_argument('--pipe', help='alternative method of connection using a pipe')
connection_group.add_argument('-s', '--server', default='127.0.0.1', help='specify the server address')
connection_group.add_argument('-p', '--port', default='2002', help='specify the port')
connection_group.add_argument('-T', '--timeout', type=int, default=60, help='timeout after seconds if connection fails')
# Document options
document_group = parser.add_argument_group('Document Options')
document_group.add_argument('-d', '--doctype', help='specify document type')
document_group.add_argument('-f', '--format', default='pdf', help='specify the output format')
document_group.add_argument('-o', '--output', help='output basename, filename or directory')
document_group.add_argument('-t', '--template', help='import the styles from template')
document_group.add_argument('--password', help='provide a password to decrypt the document')
# Filter options
filter_group = parser.add_argument_group('Filter Options')
filter_group.add_argument('-i', '--import', dest='importfilteroptions', help='set import filter option string')
filter_group.add_argument('-I', '--import-filter-name', dest='importfiltername', help='set import filter name')
filter_group.add_argument('-e', '--export', dest='exportfilteroptions', help='set export filter option string')
# I/O options
io_group = parser.add_argument_group('I/O Options')
io_group.add_argument('--stdin', action='store_true', help='read from stdin')
io_group.add_argument('--stdout', action='store_true', help='write output to stdout')
io_group.add_argument('--preserve', action='store_true', help='keep timestamp and permissions of the original document')
# Metadata options
meta_group = parser.add_argument_group('Metadata Options')
meta_group.add_argument('-F', '--field', dest='fields', action='append', help='replace user-defined text field with value')
meta_group.add_argument('-M', '--meta', dest='metadata', action='append', help='set metadata')
# Process options
process_group = parser.add_argument_group('Process Options')
process_group.add_argument('-l', '--listener', action='store_true', help='start a permanent listener')
process_group.add_argument('-n', '--no-launch', action='store_true', help='fail if no listener is found')
process_group.add_argument('--debug', action='store_true', help='enable debug output')
process_group.add_argument('-v', '--verbose', action='count', default=0, help='be more verbose')
process_group.add_argument('--show', dest='showlist', action='store_true', help='list the available output formats')
# Update options
update_group = parser.add_argument_group('Update Options')
update_group.add_argument('--unsafe-quiet-update', action='store_true',
help='allow rendered document to fetch external resources')
update_group.add_argument('--disable-html-update-links', action='store_false', dest='updatehtmllinks',
help='disables the recheck for updating links missed by libreoffice')
update_group.add_argument('--user-profile', help='use a custom user profile path')
# Printer options
printer_group = parser.add_argument_group('Printer Options')
printer_group.add_argument('-P', '--printer', action='append', help='printer options')
# Version information
parser.add_argument('-V', '--version', action='store_true', help='display version number')
# Input files
parser.add_argument('files', nargs='*', help='input files to convert')
# Parse arguments
args = parser.parse_args(args)
return args
def process_args(args):
"""Process command-line arguments and convert options to config dictionary."""
config_dict = vars(args).copy()
# Process fields
fields = {}
if args.fields:
for field in args.fields:
parts = field.split('=', 1)
if len(parts) == 2:
fields[parts[0]] = parts[1]
config_dict['fields'] = fields
# Process metadata
metadata = {}
if args.metadata:
for meta in args.metadata:
parts = meta.split('=', 1)
if len(parts) == 2:
metadata[parts[0]] = parts[1]
config_dict['metadata'] = metadata
# Process printer options
setprinter = False
paperformat = None
paperorientation = None
papersize = None
if args.printer:
for opt in args.printer:
parts = opt.split('=', 1)
if len(parts) == 2:
key, value = parts
if key == 'PaperFormat':
paperformat = value
setprinter = True
elif key == 'PaperOrientation':
paperorientation = value.upper()
setprinter = True
elif key == 'PaperSize':
try:
dimensions = list(map(int, value.split('x')))
if len(dimensions) == 2:
papersize = dimensions
setprinter = True
except ValueError:
pass
config_dict.update({
'setprinter': setprinter,
'paperformat': paperformat,
'paperorientation': paperorientation,
'papersize': papersize,
})
# Handle updateDocMode
if args.unsafe_quiet_update:
from .config import QUIET_UPDATE
config_dict['updateDocMode'] = QUIET_UPDATE
# Remove 'files' entry from config
if 'files' in config_dict:
del config_dict['files']
return config_dict
def show_formats(doctype=None):
"""Show available formats."""
if doctype:
doctypes_to_show = [doctype]
else:
doctypes_to_show = doctypes
for dt in doctypes_to_show:
print(f"The following list of {dt} formats are currently available:\n", file=sys.stderr)
formats = [fmt for fmt in fmts.list if fmt.doctype == dt]
for fmt in sorted(formats, key=lambda f: f.name):
print(f" {fmt.name:<8} - {fmt}", file=sys.stderr)
print(file=sys.stderr)
def show_version():
"""Show version information."""
print(f'unoconv {__version__}')
print('Written by Dag Wieers <dag@wieers.com>')
print('Homepage at http://dag.wieers.com/home-made/unoconv/')
print()
print(f'platform {os.name}/{sys.platform}')
print(f'python {sys.version}')
def main():
"""Main entry point for the command-line interface."""
args = parse_args()
# Version information
if args.version:
show_version()
return 0
# Show available formats
if args.showlist:
show_formats(args.doctype)
return 0
# Process arguments to config
config_dict = process_args(args)
try:
# Start a listener
if args.listener:
if listen(**config_dict):
return 0
else:
return 1
# Convert documents
if args.stdin:
# Read from stdin
if sys.version_info.major > 2:
input_data = sys.stdin.buffer.read()
else:
input_data = sys.stdin.read()
convert(input_data, format=args.format, **config_dict)
elif args.files:
# Convert each file
for input_file in args.files:
try:
convert(input_file, format=args.format, **config_dict)
except Exception as e:
print(f"Error converting {input_file}: {str(e)}", file=sys.stderr)
return 1
else:
print("unoconvert: you have to provide a filename or url as argument", file=sys.stderr)
print("Try `unoconvert -h' for more information.", file=sys.stderr)
return 255
return 0
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())