VERSION: Bump version number up to 4.0.4.
[samba.git] / source4 / scripting / python / samba / xattr.py
1 # Utility code for dealing with POSIX extended attributes
2 #
3 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2012
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 from samba.dcerpc import xattr
19 import os
20 import samba.xattr_native
21 import shutil
22
23
24 def copyattrs(frompath, topath):
25     """Copy ACL related attributes from a path to another path."""
26     for attr_name in (xattr.XATTR_NTACL_NAME, "system.posix_acl_access"):
27         # Get the xattr attributes if any
28         try:
29             attribute = samba.xattr_native.wrap_getxattr(frompath,
30                                          xattr.XATTR_NTACL_NAME)
31             samba.xattr_native.wrap_setxattr(topath,
32                                          xattr.XATTR_NTACL_NAME,
33                                          attribute)
34         except Exception:
35             pass
36             # FIXME:Catch a specific exception
37
38
39 def copytree_with_xattrs(src, dst):
40     """Recursively copy a directory tree using shutil.copy2(), preserving xattrs.
41
42     The destination directory must not already exist.
43     If exception(s) occur, an Error is raised with a list of reasons.
44     """
45     names = os.listdir(src)
46
47     os.makedirs(dst)
48     errors = []
49     for name in names:
50         srcname = os.path.join(src, name)
51         dstname = os.path.join(dst, name)
52         if os.path.islink(srcname):
53             linkto = os.readlink(srcname)
54             os.symlink(linkto, dstname)
55         elif os.path.isdir(srcname):
56             copytree_with_xattrs(srcname, dstname)
57         else:
58             # Will raise a SpecialFileError for unsupported file types
59             shutil.copy2(srcname, dstname)
60     shutil.copystat(src, dst)
61     copyattrs(src, dst)