[pacman-dev] [PATCH] Add helper function to copy files and preserve associated times

Allan McRae allan at archlinux.org
Wed Jan 8 12:29:53 UTC 2020


It is useful to be able to copy files, particularly sync databases,
while preserving mtimes.  Also preserve atmine while we are at it.
---
 lib/libalpm/util.c | 30 ++++++++++++++++++++++++++++++
 lib/libalpm/util.h |  1 +
 2 files changed, 31 insertions(+)

diff --git a/lib/libalpm/util.c b/lib/libalpm/util.c
index dacabdad..9d3f3914 100644
--- a/lib/libalpm/util.c
+++ b/lib/libalpm/util.c
@@ -33,6 +33,7 @@
 #include <sys/socket.h>
 #include <fnmatch.h>
 #include <poll.h>
+#include <utime.h>
 
 /* libarchive */
 #include <archive.h>
@@ -228,6 +229,35 @@ cleanup:
 	return ret;
 }
 
+
+/** Copies a file while preserving associated times.
+ * @param src file path to copy from
+ * @param dest file path to copy to
+ * @return 0 on success, 1 on error
+ */
+int _alpm_copyfile_with_time(const char *src, const char *dest)
+{
+	struct stat st;
+	struct utimbuf times;
+
+	if(_alpm_copyfile(src, dest) != 0) {
+		return 1;
+	};
+
+	if(stat(src, &st) != 0) {
+		return 1;
+	}
+
+	times.modtime = st.st_mtime;
+	times.actime = st.st_atime;
+
+	if(utime(dest, &times) != 0) {
+		return 1;
+	}
+
+	return 0;
+}
+
 /** Trim trailing newlines from a string (if any exist).
  * @param str a single line of text
  * @param len size of str, if known, else 0
diff --git a/lib/libalpm/util.h b/lib/libalpm/util.h
index 12c7fbc7..24cd1214 100644
--- a/lib/libalpm/util.h
+++ b/lib/libalpm/util.h
@@ -113,6 +113,7 @@ int _alpm_makepath(const char *path);
 int _alpm_makepath_mode(const char *path, mode_t mode);
 int _alpm_mkdtemp(alpm_handle_t *handle, char **tmpdir);
 int _alpm_copyfile(const char *src, const char *dest);
+int _alpm_copyfile_with_time(const char *src, const char *dest);
 size_t _alpm_strip_newline(char *str, size_t len);
 
 int _alpm_open_archive(alpm_handle_t *handle, const char *path,
-- 
2.24.1


More information about the pacman-dev mailing list