# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-## Copyright 2019-2023 Canonical Ltd.## This program is free software; you can redistribute it and/or# modify it under the terms of the GNU Lesser General Public# License version 3 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# Lesser General Public License for more details.## You should have received a copy of the GNU Lesser General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>."""Helpers to read and write filesystem extended attributes."""importloggingimportosimportsysfromcraft_partsimporterrorslogger=logging.getLogger(__name__)
[docs]defread_xattr(path:str,key:str)->str|None:"""Get extended attribute metadata from a file. :param path: The file to get metadata from. :param key: The attribute key. :return: The attribute value. """ifsys.platform!="linux":raiseRuntimeError("xattr support only available for Linux")# Extended attributes do not apply to symlinks.ifos.path.islink(path):returnNonekey=f"user.craft_parts.{key}"try:value=os.getxattr(path,key)exceptFileNotFoundError:raiseexceptOSErroraserror:# No label present with:# OSError: [Errno 61] No data available: b'<path>'iferror.errno==61:# noqa: PLR2004returnNone# Chain unknown variants of OSError.raiseerrors.XAttributeError(key=key,path=path)fromerrorreturnvalue.decode().strip()
[docs]defwrite_xattr(path:str,key:str,value:str)->None:"""Add extended attribute metadata to a file. :param path: The file to add metadata to. :param key: The attribute key. :param value: The attribute value. """ifsys.platform!="linux":raiseRuntimeError("xattr support only available for Linux")# Extended attributes do not apply to symlinks.ifos.path.islink(path):returnkey=f"user.craft_parts.{key}"try:os.setxattr(path,key,value.encode())exceptOSErroraserror:# Label is too long for filesystem:# OSError: [Errno 7] Argument list too long: b'<path>'iferror.errno==7:# noqa: PLR2004raiseerrors.XAttributeTooLong(path=path,key=key,value=value)fromerror# Chain unknown variants of OSError.raiseerrors.XAttributeError(key=key,path=path,is_write=True)fromerror