| 1 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
# |
| 3 |
# This file is formatted with Python Black |
| 4 |
|
| 5 |
import os |
| 6 |
from pathlib import Path |
| 7 |
from gi.repository import GLib, Gio |
| 8 |
|
| 9 |
|
| 10 |
EXPORT_FILES_FLAG_EXPORT_DIR = 8 |
| 11 |
|
| 12 |
|
| 13 |
def path_from_null_term_bytes(bytes): |
| 14 |
path_bytes, rest = bytes.split(b"\x00") |
| 15 |
assert rest == b"" |
| 16 |
return Path(os.fsdecode(path_bytes)) |
| 17 |
|
| 18 |
|
| 19 |
def get_mountpoint(documents_intf): |
| 20 |
mountpoint = documents_intf.GetMountPoint(byte_arrays=True) |
| 21 |
mountpoint = path_from_null_term_bytes(mountpoint) |
| 22 |
assert mountpoint.exists() |
| 23 |
return mountpoint |
| 24 |
|
| 25 |
|
| 26 |
def export_file(documents_intf, file_path, unique=False): |
| 27 |
assert file_path.exists() |
| 28 |
|
| 29 |
with open(file_path.absolute().as_posix(), "r") as file: |
| 30 |
doc_id = documents_intf.Add(file.fileno(), not unique, False) |
| 31 |
assert doc_id |
| 32 |
|
| 33 |
return doc_id |
| 34 |
|
| 35 |
|
| 36 |
def export_file_named(documents_intf, folder_path, name, unique=False): |
| 37 |
assert folder_path.exists() |
| 38 |
|
| 39 |
# bytestring convention is zero terminated |
| 40 |
name_nt = os.fsencode(name) + b"\x00" |
| 41 |
|
| 42 |
try: |
| 43 |
fd = os.open(folder_path.absolute().as_posix(), os.O_PATH | os.O_CLOEXEC) |
| 44 |
doc_id = documents_intf.AddNamed(fd, name_nt, not unique, False) |
| 45 |
assert doc_id |
| 46 |
finally: |
| 47 |
os.close(fd) |
| 48 |
|
| 49 |
return doc_id |
| 50 |
|
| 51 |
|
| 52 |
def export_files(documents_intf, file_paths, perms, flags=0, app_id=""): |
| 53 |
fds = [] |
| 54 |
try: |
| 55 |
for file_path in file_paths: |
| 56 |
fds.append( |
| 57 |
os.open(file_path.absolute().as_posix(), os.O_PATH | os.O_CLOEXEC) |
| 58 |
) |
| 59 |
|
| 60 |
result = documents_intf.AddFull( |
| 61 |
fds, |
| 62 |
flags, |
| 63 |
app_id, |
| 64 |
perms, |
| 65 |
byte_arrays=True, |
| 66 |
) |
| 67 |
finally: |
| 68 |
for fd in fds: |
| 69 |
os.close(fd) |
| 70 |
|
| 71 |
assert result |
| 72 |
return result |
| 73 |
|
| 74 |
|
| 75 |
def write_bytes_atomic(file_path, bytes): |
| 76 |
GLib.file_set_contents(file_path.absolute().as_posix(), bytes) |
| 77 |
|
| 78 |
|
| 79 |
def write_bytes_trunc(file_path, bytes): |
| 80 |
try: |
| 81 |
fd = os.open( |
| 82 |
file_path.absolute().as_posix(), os.O_RDWR | os.O_TRUNC | os.O_CREAT |
| 83 |
) |
| 84 |
os.write(fd, bytes) |
| 85 |
finally: |
| 86 |
os.close(fd) |
| 87 |
|
| 88 |
|
| 89 |
def get_host_path_attr(path): |
| 90 |
xattr = "xattr::document-portal.host-path" |
| 91 |
file = Gio.file_new_for_path(path.absolute().as_posix()) |
| 92 |
info = file.query_info(xattr, Gio.FileQueryInfoFlags.NONE) |
| 93 |
host_path = info.get_attribute_as_string(xattr) |
| 94 |
if not host_path: |
| 95 |
return None |
| 96 |
return Path(os.fsdecode(host_path)) |