diff --git a/src/pyinfra/facts/files.py b/src/pyinfra/facts/files.py index f58648c7a..058127a8e 100644 --- a/src/pyinfra/facts/files.py +++ b/src/pyinfra/facts/files.py @@ -398,7 +398,7 @@ def process(self, output) -> Optional[str]: class Sha1File(HashFileFactBase, digits=40, cmds=["sha1sum", "shasum", "sha1"]): """ Returns a SHA1 hash of a file. Works with both sha1sum and sha1. Returns - ``None`` if the file doest not exist. + ``None`` if the file does not exist. """ @@ -664,14 +664,16 @@ def process(self, output): class FileContents(FactBase): """ - Returns the contents of a file as a list of lines. Works with both sha1sum and sha1. Returns - ``None`` if the file doest not exist. + Returns the contents of a file as a list of lines. Returns + ``None`` if the file does not exist. """ @override def command(self, path): - return make_formatted_string_command("cat {0}", QuoteString(path)) + return make_formatted_string_command("test -e {0} && cat {0} || true", QuoteString(path)) @override def process(self, output): + if not output: + return self.default() return output diff --git a/tests/facts/files.FileContents/file.json b/tests/facts/files.FileContents/file.json index 8b71de1c1..8f4c1a988 100644 --- a/tests/facts/files.FileContents/file.json +++ b/tests/facts/files.FileContents/file.json @@ -1,6 +1,6 @@ { "arg": "myfile", - "command": "cat myfile", + "command": "test -e myfile && cat myfile || true", "output": ["line1", "line2"], "fact": ["line1", "line2"] } diff --git a/tests/facts/files.FileContents/no_file.json b/tests/facts/files.FileContents/no_file.json index cab556293..97cdf593d 100644 --- a/tests/facts/files.FileContents/no_file.json +++ b/tests/facts/files.FileContents/no_file.json @@ -1,6 +1,6 @@ { "arg": ["test"], - "command": "cat test", - "output": null, + "command": "test -e test && cat test || true", + "output": [], "fact": null }