0
# Command Line and Configuration
1
2
Integrated command line argument processing and FUSE option management for filesystem mounting, configuration, and runtime behavior control.
3
4
## Capabilities
5
6
### Main Filesystem Class
7
8
The primary class for implementing FUSE filesystems with integrated command line processing.
9
10
```python { .api }
11
class Fuse:
12
"""
13
Main FUSE filesystem class.
14
15
Base class for implementing filesystems with built-in command line
16
argument processing and FUSE integration.
17
"""
18
19
fuse_args: FuseArgs # Command line arguments
20
parser: FuseOptParse # Option parser
21
multithreaded: bool # Enable multithreading
22
23
def __init__(self, *args, **kwargs):
24
"""
25
Initialize FUSE filesystem.
26
27
Args:
28
version (str, optional): Version string for --version output
29
usage (str, optional): Usage string for help output
30
dash_s_do (str, optional): Single-threading behavior
31
parser_class (class, optional): Custom parser class
32
fuse_args (FuseArgs, optional): Pre-configured arguments
33
**kwargs: Additional initialization parameters
34
"""
35
36
def parse(self, *args, **kwargs):
37
"""
38
Parse command line arguments.
39
40
Args:
41
*args: Arguments to parse (default: sys.argv)
42
errex (int): Exit code on error (default: don't exit)
43
values (object): Object to store parsed values
44
45
Returns:
46
Parsed arguments and options
47
"""
48
49
def main(self):
50
"""
51
Enter filesystem service loop.
52
53
This method starts the FUSE main loop and handles filesystem
54
operations until unmount or termination.
55
56
Returns:
57
int: Exit status (normally doesn't return)
58
"""
59
60
@classmethod
61
def fuseoptref(cls):
62
"""
63
Get FUSE library supported options reference.
64
65
Returns:
66
FuseArgs: Reference args containing all supported FUSE options
67
"""
68
```
69
70
**Usage Example:**
71
72
```python
73
class MyFS(Fuse):
74
def __init__(self, *args, **kwargs):
75
super().__init__(*args, **kwargs)
76
self.multithreaded = False # Single-threaded filesystem
77
78
def getattr(self, path):
79
# ... implement filesystem methods
80
pass
81
82
# Create and run filesystem
83
fs = MyFS(
84
version="MyFS 1.0",
85
usage="MyFS filesystem\n\n" + Fuse.fusage
86
)
87
fs.parse(errex=1) # Exit on parse errors
88
fs.main() # Start filesystem loop
89
```
90
91
### Command Line Arguments
92
93
Structure for managing FUSE command line arguments and mount options.
94
95
```python { .api }
96
class FuseArgs(SubOptsHive):
97
"""
98
FUSE command line arguments container.
99
100
Manages FUSE-specific command line options and mount arguments.
101
"""
102
103
mountpoint: str # Mount point path
104
modifiers: dict # Boolean option modifiers
105
fuse_modifiers: dict # FUSE option mappings
106
107
def getmod(self, opt):
108
"""
109
Get modifier value.
110
111
Args:
112
opt (str): Modifier name
113
114
Returns:
115
bool: Modifier value
116
"""
117
118
def setmod(self, opt):
119
"""
120
Set modifier to True.
121
122
Args:
123
opt (str): Modifier name
124
"""
125
126
def unsetmod(self, opt):
127
"""
128
Set modifier to False.
129
130
Args:
131
opt (str): Modifier name
132
"""
133
134
def assemble(self):
135
"""
136
Assemble arguments for FUSE.
137
138
Returns:
139
list: Arguments suitable for FUSE main()
140
"""
141
142
def filter(self, other=None):
143
"""
144
Filter arguments against option reference.
145
146
Args:
147
other (FuseArgs, optional): Reference args to filter against.
148
If None, uses fuseoptref() result.
149
"""
150
```
151
152
**Usage Example:**
153
154
```python
155
def custom_parse(self):
156
# Access parsed arguments
157
args = self.fuse_args
158
159
# Check for specific modifiers
160
if args.getmod('foreground'):
161
print("Running in foreground mode")
162
163
if args.getmod('showhelp'):
164
self.parser.print_help()
165
sys.exit(0)
166
167
# Get mount point
168
if args.mountpoint:
169
print(f"Mounting at: {args.mountpoint}")
170
else:
171
print("No mount point specified")
172
sys.exit(1)
173
```
174
175
### Option Parser
176
177
Enhanced option parser with FUSE-specific extensions and sub-option support.
178
179
```python { .api }
180
class FuseOptParse(SubbedOptParse):
181
"""
182
FUSE option parser.
183
184
Enhanced OptionParser with FUSE integration and sub-option support.
185
"""
186
187
fuse_args: FuseArgs # Associated FuseArgs instance
188
189
def parse_args(self, args=None, values=None):
190
"""
191
Parse command line arguments.
192
193
Args:
194
args (list): Arguments to parse
195
values (object): Object to store values
196
197
Returns:
198
tuple: (options, args) tuple
199
"""
200
201
def add_option(self, *args, **kwargs):
202
"""
203
Add command line option.
204
205
Args:
206
*args: Option names (-f, --foreground)
207
**kwargs: Option configuration
208
209
Returns:
210
Option: Created option object
211
"""
212
213
def print_help(self, file=None):
214
"""
215
Print help message including FUSE options.
216
217
Args:
218
file: Output file (default: sys.stdout)
219
"""
220
221
def print_version(self, file=None):
222
"""
223
Print version information.
224
225
Args:
226
file: Output file (default: sys.stdout)
227
"""
228
```
229
230
**Usage Example:**
231
232
```python
233
class MyFS(Fuse):
234
def __init__(self, *args, **kwargs):
235
super().__init__(*args, **kwargs)
236
237
# Add custom options
238
self.parser.add_option(
239
'-d', '--debug',
240
action='store_true',
241
help='Enable debug mode'
242
)
243
244
self.parser.add_option(
245
'--cache-size',
246
type='int',
247
default=1024,
248
help='Cache size in MB'
249
)
250
251
def parse(self, *args, **kwargs):
252
options, args = super().parse(*args, **kwargs)
253
254
# Access custom options
255
if hasattr(options, 'debug') and options.debug:
256
self.enable_debug()
257
258
if hasattr(options, 'cache_size'):
259
self.set_cache_size(options.cache_size)
260
261
return options, args
262
```
263
264
### Help Formatter
265
266
Specialized help formatter for FUSE option output.
267
268
```python { .api }
269
class FuseFormatter(SubbedOptIndentedFormatter):
270
"""
271
FUSE help formatter.
272
273
Formats help output for FUSE-specific options and sub-options.
274
"""
275
```
276
277
### API Version Control
278
279
Control FUSE Python API version for compatibility.
280
281
```python { .api }
282
fuse_python_api: tuple # Global API version (0, 2)
283
284
def get_fuse_python_api():
285
"""
286
Get current FUSE Python API version.
287
288
Returns:
289
tuple: API version tuple (major, minor)
290
"""
291
292
def get_compat_0_1():
293
"""
294
Check if using legacy 0.1 API compatibility.
295
296
Returns:
297
bool: True if using 0.1 compatibility mode
298
"""
299
```
300
301
**Usage Example:**
302
303
```python
304
# Set API version before importing/using FUSE
305
import fuse
306
fuse.fuse_python_api = (0, 2)
307
308
# Or set via environment variable
309
# export FUSE_PYTHON_API=0.2
310
311
class MyFS(Fuse):
312
def __init__(self, *args, **kwargs):
313
super().__init__(*args, **kwargs)
314
315
# Check API version
316
if fuse.get_compat_0_1():
317
print("Warning: Using legacy 0.1 API")
318
else:
319
print(f"Using API version: {fuse.get_fuse_python_api()}")
320
```
321
322
## FUSE Mount Options
323
324
Common FUSE mount options that can be set via command line:
325
326
### Basic Options
327
- `-f, --foreground`: Run in foreground (don't daemonize)
328
- `-d, --debug`: Enable debug output
329
- `-s`: Single-threaded operation
330
- `-o opt[,opt...]`: Mount options
331
332
### Mount Options (`-o` parameter)
333
- `allow_other`: Allow access by other users
334
- `allow_root`: Allow access by root
335
- `default_permissions`: Enable permission checking
336
- `ro`: Read-only filesystem
337
- `rw`: Read-write filesystem
338
- `suid`: Allow suid/sgid bits
339
- `nosuid`: Disallow suid/sgid bits
340
- `dev`: Allow device files
341
- `nodev`: Disallow device files
342
- `exec`: Allow program execution
343
- `noexec`: Disallow program execution
344
345
**Usage Example:**
346
347
```python
348
# Command line usage:
349
# python myfs.py /mnt/point -f -o allow_other,default_permissions
350
351
class MyFS(Fuse):
352
def __init__(self, *args, **kwargs):
353
super().__init__(*args, **kwargs)
354
355
# Add filesystem-specific options
356
self.parser.add_option(
357
'-o',
358
dest='mount_options',
359
help='Mount options'
360
)
361
362
def parse(self, *args, **kwargs):
363
options, args = super().parse(*args, **kwargs)
364
365
# Process mount options
366
if hasattr(options, 'mount_options'):
367
opts = options.mount_options.split(',')
368
for opt in opts:
369
if opt == 'ro':
370
self.read_only = True
371
elif opt == 'allow_other':
372
self.allow_other = True
373
```
374
375
## Error Handling
376
377
Command line parsing can encounter various errors:
378
379
- **OptParseError**: Invalid command line options
380
- **Missing mount point**: No mount point specified
381
- **Permission errors**: Cannot access mount point
382
- **FUSE initialization errors**: FUSE library problems
383
384
**Usage Example:**
385
386
```python
387
def main():
388
fs = MyFS(version="MyFS 1.0")
389
390
try:
391
fs.parse(errex=1) # Exit on parse errors
392
fs.main()
393
except OptParseError as e:
394
print(f"Command line error: {e}")
395
sys.exit(1)
396
except Exception as e:
397
print(f"Filesystem error: {e}")
398
sys.exit(1)
399
```
400
401
## Best Practices
402
403
- Always set API version at the beginning of your program
404
- Use `errex=1` in `parse()` to exit on command line errors
405
- Provide meaningful help text and version information
406
- Handle both foreground and daemon modes appropriately
407
- Validate mount point accessibility before starting main loop
408
- Support standard FUSE options for compatibility
409
- Test with various command line option combinations