Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions src/pyinfra/facts/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,19 @@
from pyinfra.api.util import try_int
from pyinfra.facts.util.units import parse_size

LINUX_STAT_COMMAND = "stat -c 'user=%U group=%G mode=%A atime=%X mtime=%Y ctime=%Z size=%s %N'"
BSD_STAT_COMMAND = "stat -f 'user=%Su group=%Sg mode=%Sp atime=%a mtime=%m ctime=%c size=%z %N%SY'"
LINUX_STAT_COMMAND = (
"stat -c 'user=%U group=%G mode=%A atime=%X mtime=%Y ctime=%Z size=%s uid=%u gid=%g %N'"
)
BSD_STAT_COMMAND = (
"stat -f 'user=%Su group=%Sg mode=%Sp atime=%a mtime=%m ctime=%c size=%z uid=%u gid=%g %N%SY'"
)
LS_COMMAND = "ls -ld"
LS_ID_COMMAND = "ls -ldn"

STAT_REGEX = (
r"user=(.*) group=(.*) mode=(.*) "
r"atime=(-?[0-9]*) mtime=(-?[0-9]*) ctime=(-?[0-9]*) "
r"size=([0-9]*) (.*)"
r"size=([0-9]*) uid=([0-9]+) gid=([0-9]+) (.*)"
)

# ls -ld output: permissions links user group size month day year/time path
Expand Down Expand Up @@ -217,6 +222,8 @@ class FileDict(TypedDict):
ctime: datetime | None
user: str
group: str
uid: NotRequired[int]
gid: NotRequired[int]
link_target: NotRequired[str]


Expand All @@ -229,6 +236,8 @@ class File(FactBase[FileDict | Literal[False] | None]):
{
"user": "pyinfra",
"group": "pyinfra",
"uid": 1000,
"gid": 1000,
"mode": 644,
"size": 3928,
}
Expand All @@ -255,12 +264,14 @@ def command(self, path):
# only stat if the path exists (file or symlink)
"! (test -e {0} || test -L {0} ) || "
"( {linux_stat_command} {0} 2> /dev/null || "
"{bsd_stat_command} {0} || {ls_command} {0} )"
"{bsd_stat_command} {0} || "
"( {ls_command} {0} && {ls_id_command} {0} ) )"
),
path,
linux_stat_command=LINUX_STAT_COMMAND,
bsd_stat_command=BSD_STAT_COMMAND,
ls_command=LS_COMMAND,
ls_id_command=LS_ID_COMMAND,
)

@override
Expand All @@ -274,6 +285,8 @@ def process(self, output) -> FileDict | Literal[False] | None:
data: FileDict = {
"user": match.group(1),
"group": match.group(2),
"uid": int(match.group(8)),
"gid": int(match.group(9)),
"mode": _parse_mode(mode[1:]),
"atime": _parse_datetime(match.group(4)),
"mtime": _parse_datetime(match.group(5)),
Expand All @@ -285,7 +298,7 @@ def process(self, output) -> FileDict | Literal[False] | None:
return False

if path_type == "link":
filename = match.group(8)
filename = match.group(10)
filename, target = filename.split(" -> ")
data["link_target"] = _unquote_stat_name(target)

Expand All @@ -299,6 +312,16 @@ def process(self, output) -> FileDict | Literal[False] | None:
if path_type != self.type:
return False

if len(output) > 1:
numeric_ls_result = _parse_ls_output(output[1])
if numeric_ls_result is not None:
numeric_data, _ = numeric_ls_result
numeric_user = numeric_data["user"]
numeric_group = numeric_data["group"]
if numeric_user.isdigit() and numeric_group.isdigit():
data["uid"] = int(numeric_user)
data["gid"] = int(numeric_group)

return data

return None
Expand All @@ -313,6 +336,8 @@ class Link(File):
{
"user": "pyinfra",
"group": "pyinfra",
"uid": 1000,
"gid": 1000,
"link_target": "/path/to/link/target"
}

Expand All @@ -335,6 +360,8 @@ class Directory(File):
{
"user": "pyinfra",
"group": "pyinfra",
"uid": 1000,
"gid": 1000,
"mode": 644,
}

Expand All @@ -357,6 +384,8 @@ class Socket(File):
{
"user": "pyinfra",
"group": "pyinfra",
"uid": 1000,
"gid": 1000,
}

If the path does not exist:
Expand Down
90 changes: 55 additions & 35 deletions src/pyinfra/operations/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
Directory,
File,
FileContents,
FileDict,
FindFiles,
FindInFile,
FindLinks,
Expand Down Expand Up @@ -76,12 +77,30 @@
)


def _get_ownership_changes(
info: FileDict,
user: str | int | None,
group: str | int | None,
) -> tuple[bool, bool]:
user_changed = (
info.get("uid") != user
if isinstance(user, int)
else user is not None and info["user"] != user
)
group_changed = (
info.get("gid") != group
if isinstance(group, int)
else group is not None and info["group"] != group
)
return user_changed, group_changed


@operation()
def download(
src: str,
dest: str,
user: str | None = None,
group: str | None = None,
user: str | int | None = None,
group: str | int | None = None,
mode: int | str | None = None,
cache_time: int | None = None,
force=False,
Expand All @@ -102,8 +121,8 @@ def download(

+ src: source URL of the file
+ dest: where to save the file
+ user: user to own the files
+ group: group to own the files
+ user: username or UID to own the files
+ group: group name or GID to own the files
+ mode: permissions of the files
+ cache_time: if the file exists already, re-download after this time (in seconds)
+ force: always download the file, even if it already exists
Expand Down Expand Up @@ -240,7 +259,7 @@ def download(

yield StringCommand("mv", QuoteString(temp_file), QuoteString(dest))

if user or group:
if user is not None or group is not None:
yield file_utils.chown(dest, user, group)

if mode:
Expand Down Expand Up @@ -293,7 +312,7 @@ def download(
assert info is not None # narrowed: download=True covers info is None
changed = False

if (user and info["user"] != user) or (group and info["group"] != group):
if any(_get_ownership_changes(info, user, group)):
yield file_utils.chown(dest, user, group)
changed = True

Expand Down Expand Up @@ -1015,8 +1034,8 @@ def _times_differ_in_s(ref, cand):
def put(
src: str | IO[Any],
dest: str,
user: str | None = None,
group: str | None = None,
user: str | int | None = None,
group: str | int | None = None,
mode: int | str | bool | None = None,
add_deploy_dir=True,
create_remote_dir=True,
Expand All @@ -1030,8 +1049,8 @@ def put(

+ src: filename or IO-like object to upload
+ dest: remote filename to upload to
+ user: user to own the files
+ group: group to own the files
+ user: username or UID to own the files
+ group: group name or GID to own the files
+ mode: permissions of the files, use ``True`` to copy the local file
+ add_deploy_dir: src is relative to the deploy directory
+ create_remote_dir: create the remote directory if it doesn't exist
Expand Down Expand Up @@ -1182,7 +1201,7 @@ def put(
remote_temp_filename=host.get_temp_filename(dest, temp_directory=temp_dir),
)

if user or group:
if user is not None or group is not None:
yield file_utils.chown(dest, user, group)

if mode:
Expand Down Expand Up @@ -1233,7 +1252,7 @@ def put(
remote_temp_filename=host.get_temp_filename(dest, temp_directory=temp_dir),
)

if user or group:
if user is not None or group is not None:
yield file_utils.chown(dest, user, group)

if mode:
Expand Down Expand Up @@ -1265,16 +1284,17 @@ def put(
changed = True

# Check user/group
if (user and remote_file["user"] != user) or (group and remote_file["group"] != group):
user_changed, group_changed = _get_ownership_changes(remote_file, user, group)
if user_changed or group_changed:
if state.config.DIFF:
old_status = [remote_file["user"], remote_file["group"]]
new_status = [user, group]
if user and remote_file["user"] != user:
if user_changed:
old_status[0] = format_text(remote_file["user"], "red")
new_status[0] = format_text(user, "green")
if group and remote_file["group"] != group:
new_status[0] = format_text(str(user), "green")
if group_changed:
old_status[1] = format_text(remote_file["group"], "red")
new_status[1] = format_text(group, "green")
new_status[1] = format_text(str(group), "green")

logger.info("chown %s:%s", *old_status)
logger.info("chown %s:%s", *new_status)
Expand Down Expand Up @@ -1614,8 +1634,8 @@ def link(
path: str,
target: str | None = None,
present=True,
user: str | None = None,
group: str | None = None,
user: str | int | None = None,
group: str | int | None = None,
symbolic=True,
create_remote_dir=True,
force=False,
Expand All @@ -1628,8 +1648,8 @@ def link(
+ path: the name of the link
+ target: the file/directory the link points to
+ present: whether the link should exist
+ user: user to own the link
+ group: group to own the link
+ user: username or UID to own the link
+ group: group name or GID to own the link
+ symbolic: whether to make a symbolic link (vs hard link)
+ create_remote_dir: create the remote directory if it doesn't exist
+ force: if the target exists and is not a file, move or remove it and continue
Expand Down Expand Up @@ -1702,7 +1722,7 @@ def link(

yield add_cmd

if user or group:
if user is not None or group is not None:
yield file_utils.chown(path, user, group, dereference=False)

else: # edit
Expand All @@ -1715,7 +1735,7 @@ def link(
yield add_cmd

# Check user/group
if (user and info["user"] != user) or (group and info["group"] != group):
if any(_get_ownership_changes(info, user, group)):
yield file_utils.chown(path, user, group, dereference=False)
changed = True

Expand All @@ -1727,8 +1747,8 @@ def link(
def file(
path: str,
present=True,
user: str | None = None,
group: str | None = None,
user: str | int | None = None,
group: str | int | None = None,
mode: int | str | None = None,
touch=False,
create_remote_dir=True,
Expand All @@ -1741,8 +1761,8 @@ def file(

+ path: name/path of the remote file
+ present: whether the file should exist
+ user: user to own the files
+ group: group to own the files
+ user: username or UID to own the files
+ group: group name or GID to own the files
+ mode: permissions of the files as an integer, eg: 755
+ touch: whether to touch the file
+ create_remote_dir: create the remote directory if it doesn't exist
Expand Down Expand Up @@ -1801,7 +1821,7 @@ def file(

if mode:
yield file_utils.chmod(path, mode)
if user or group:
if user is not None or group is not None:
yield file_utils.chown(path, user, group)

else: # update
Expand All @@ -1817,7 +1837,7 @@ def file(
changed = True

# Check user/group
if (user and info["user"] != user) or (group and info["group"] != group):
if any(_get_ownership_changes(info, user, group)):
yield file_utils.chown(path, user, group)
changed = True

Expand All @@ -1829,8 +1849,8 @@ def file(
def directory(
path: str,
present=True,
user: str | None = None,
group: str | None = None,
user: str | int | None = None,
group: str | int | None = None,
mode: int | str | None = None,
recursive=False,
force=False,
Expand All @@ -1844,8 +1864,8 @@ def directory(

+ path: path of the remote folder
+ present: whether the folder should exist
+ user: user to own the folder
+ group: group to own the folder
+ user: username or UID to own the folder
+ group: group name or GID to own the folder
+ mode: permissions of the folder
+ recursive: recursively apply user/group/mode
+ force: if the target exists and is not a file, move or remove it and continue
Expand Down Expand Up @@ -1913,7 +1933,7 @@ def directory(
yield StringCommand("mkdir", "-p", QuoteString(path))
if mode:
yield file_utils.chmod(path, mode, recursive=recursive)
if user or group:
if user is not None or group is not None:
yield file_utils.chown(path, user, group, recursive=recursive)

else: # update
Expand All @@ -1926,7 +1946,7 @@ def directory(
yield file_utils.chmod(path, mode, recursive=recursive)
changed = True

if (user and info["user"] != user) or (group and info["group"] != group):
if any(_get_ownership_changes(info, user, group)):
yield file_utils.chown(path, user, group, recursive=recursive)
changed = True

Expand Down
Loading
Loading