Python bindings for FUSE (Filesystem in USErspace) enabling custom userspace filesystems
—
FUSE data structures for representing file attributes, directory entries, filesystem statistics, and other metadata used in filesystem operations.
All FUSE data structures inherit from a common base class that provides initialization and representation functionality.
class FuseStruct:
"""
Base class for FUSE data structures.
Provides keyword argument initialization and string representation.
"""
def __init__(self, **kwargs):
"""
Initialize structure with keyword arguments.
Args:
**kwargs: Attribute values to set
"""
def __repr__(self):
"""Return string representation of structure."""Usage Example:
# Initialize with keyword arguments
st = fuse.Stat(st_mode=0o644, st_size=1024)
# Access attributes directly
st.st_nlink = 1
st.st_uid = 1000Structure representing file and directory attributes, similar to the result of stat() system call.
class Stat(FuseStruct):
"""
File/directory attributes structure.
Contains all standard POSIX file attributes.
"""
st_mode: int # File type and permissions (default: None)
st_ino: int # Inode number (default: 0)
st_dev: int # Device ID (default: 0)
st_nlink: int # Number of hard links (default: 0)
st_uid: int # User ID of owner (default: 0)
st_gid: int # Group ID of owner (default: 0)
st_size: int # Size in bytes (default: 0)
st_atime: int # Last access time (default: 0)
st_mtime: int # Last modification time (default: 0)
st_ctime: int # Last status change time (default: 0)Usage Example:
import stat
import time
def getattr(self, path):
st = fuse.Stat()
if path == '/':
# Directory attributes
st.st_mode = stat.S_IFDIR | 0o755
st.st_nlink = 2
st.st_size = 4096
else:
# File attributes
st.st_mode = stat.S_IFREG | 0o644
st.st_nlink = 1
st.st_size = len(self.get_file_content(path))
# Common attributes
current_time = int(time.time())
st.st_atime = current_time
st.st_mtime = current_time
st.st_ctime = current_time
st.st_uid = os.getuid()
st.st_gid = os.getgid()
return stStructure for filesystem-wide statistics, similar to the result of statvfs() system call.
class StatVfs(FuseStruct):
"""
Filesystem statistics structure.
Contains information about filesystem capacity and usage.
"""
f_bsize: int # Filesystem block size
f_frsize: int # Fragment size
f_blocks: int # Total number of blocks
f_bfree: int # Number of free blocks
f_bavail: int # Number of available blocks for unprivileged users
f_files: int # Total number of file nodes (inodes)
f_ffree: int # Number of free file nodes
f_favail: int # Number of available file nodes for unprivileged users
f_flag: int # Filesystem flags
f_namemax: int # Maximum filename lengthUsage Example:
def statfs(self, path):
stv = fuse.StatVfs()
# Block information
stv.f_bsize = 4096 # 4KB blocks
stv.f_frsize = 4096 # Fragment size same as block size
stv.f_blocks = 1000000 # 1M total blocks (~4GB)
stv.f_bfree = 500000 # 500K free blocks
stv.f_bavail = 450000 # 450K available (some reserved)
# Inode information
stv.f_files = 100000 # 100K total inodes
stv.f_ffree = 80000 # 80K free inodes
stv.f_favail = 80000 # Same as free for unprivileged
# Filesystem properties
stv.f_flag = 0 # No special flags
stv.f_namemax = 255 # Maximum 255 character filenames
return stvStructure representing individual entries in directory listings.
class Direntry(FuseStruct):
"""
Directory entry structure.
Represents a single item in a directory listing.
"""
def __init__(self, name, **kwargs):
"""
Initialize directory entry.
Args:
name (str): Entry name (required)
**kwargs: Additional attributes (type, ino, offset)
"""
name: str # Entry name (required)
type: int # File type (optional, from stat module, default: None)
ino: int # Inode number (optional, default: None)
offset: int # Offset for next entry (optional, default: None)Usage Example:
def readdir(self, path, offset):
# Standard entries
yield fuse.Direntry('.')
yield fuse.Direntry('..')
# File entries with type information
for filename, content in self.files.items():
if filename.startswith(path.rstrip('/') + '/'):
basename = filename[len(path.rstrip('/') + '/'):]
if '/' not in basename: # Direct child only
yield fuse.Direntry(
name=basename,
type=stat.S_IFREG,
ino=hash(filename) % 2**32
)
# Directory entries
for dirname in self.dirs:
if dirname.startswith(path.rstrip('/') + '/'):
basename = dirname[len(path.rstrip('/') + '/'):]
if '/' not in basename: # Direct child only
yield fuse.Direntry(
name=basename,
type=stat.S_IFDIR,
ino=hash(dirname) % 2**32
)Structure for file locking operations, similar to struct flock.
class Flock(FuseStruct):
"""
File locking structure.
Used for advisory file locking operations.
"""
l_type: int # Lock type (F_RDLCK, F_WRLCK, F_UNLCK)
l_start: int # Starting offset for lock
l_len: int # Number of bytes to lock (0 = to EOF)
l_pid: int # Process ID of lock ownerUsage Example:
def lock(self, path, fip, cmd, lock):
"""Handle file locking operations."""
if cmd == fcntl.F_GETLK:
# Check if lock would block
if self.would_block_lock(path, lock):
# Return conflicting lock info
conflicting_lock = fuse.Flock()
conflicting_lock.l_type = fcntl.F_WRLCK
conflicting_lock.l_start = 0
conflicting_lock.l_len = 0
conflicting_lock.l_pid = 1234
return conflicting_lock
else:
# No conflict
lock.l_type = fcntl.F_UNLCK
return 0
elif cmd == fcntl.F_SETLK:
# Set lock (non-blocking)
return self.set_lock(path, lock, blocking=False)
elif cmd == fcntl.F_SETLKW:
# Set lock (blocking)
return self.set_lock(path, lock, blocking=True)High-precision time structure for nanosecond-accurate timestamps.
class Timespec(FuseStruct):
"""
Time specification with nanosecond precision.
Used for high-precision timestamp operations.
"""
tv_sec: int # Seconds since epoch
tv_nsec: int # Nanoseconds (0-999999999)Usage Example:
def utimens(self, path, ts_acc, ts_mod):
"""Set file timestamps with nanosecond precision."""
if path not in self.files:
return -errno.ENOENT
# Convert Timespec to float seconds
atime = ts_acc.tv_sec + ts_acc.tv_nsec / 1e9
mtime = ts_mod.tv_sec + ts_mod.tv_nsec / 1e9
# Store timestamps (implementation dependent)
self.file_times[path] = {
'atime': atime,
'mtime': mtime,
'ctime': time.time() # Change time is now
}
return 0Structure containing file operation context and flags.
class FuseFileInfo(FuseStruct):
"""
File information structure.
Provides context for file operations.
"""
keep: bool # Whether to keep cached data
direct_io: bool # Whether to use direct I/OUsage Example:
def open(self, path, flags):
"""Open file with specific flags."""
if path not in self.files:
return -errno.ENOENT
# Check access permissions
if flags & os.O_WRONLY and self.is_readonly(path):
return -errno.EACCES
# Create file info for this open
fip = fuse.FuseFileInfo()
fip.keep = True # Enable caching
fip.direct_io = False # Use buffered I/O
return 0Common constants used with data structures, primarily from the stat module:
stat.S_IFREG: Regular filestat.S_IFDIR: Directorystat.S_IFLNK: Symbolic linkstat.S_IFCHR: Character devicestat.S_IFBLK: Block devicestat.S_IFIFO: Named pipe (FIFO)stat.S_IFSOCK: Socketstat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR: User read/write/executestat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP: Group read/write/executestat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH: Other read/write/executeos.R_OK: Test for read permissionos.W_OK: Test for write permissionos.X_OK: Test for execute permissionos.F_OK: Test for file existencestat and os modulesInstall with Tessl CLI
npx tessl i tessl/pypi-fuse-python