util: add a tmpdir helper

With the __attribute__(cleanup) helper this makes it simple
enough to provide a tempdir inside a function that is (recursively)
automatically deleted when the variable is deleted.

Part-of: <https://gitlab.freedesktop.org/libinput/libinput/-/merge_requests/1204>
This commit is contained in:
Peter Hutterer 2025-05-06 17:22:41 +10:00 committed by Marge Bot
parent 91d4f9e58e
commit e91e1c3111
2 changed files with 46 additions and 0 deletions

View file

@ -113,3 +113,31 @@ char **
list_files(const char **directories,
const char *suffix,
size_t *nfiles);
struct tmpdir {
char *path;
};
static inline void
tmpdir_destroy(struct tmpdir *tmpdir)
{
/* String check so we can't accidentally rm -rf */
if (tmpdir->path && strstr(tmpdir->path, "tmpdir-")) {
rmdir_r(tmpdir->path);
free(tmpdir->path);
}
free(tmpdir);
}
DEFINE_DESTROY_CLEANUP_FUNC(tmpdir);
static inline struct tmpdir *
tmpdir_create(const char *basedir)
{
_destroy_(tmpdir) *tmpdir = zalloc(sizeof(*tmpdir));
tmpdir->path = strdup_printf("%s/tmpdir-XXXXXX", basedir ? basedir : "/tmp");
if (!mkdtemp(tmpdir->path))
return NULL;
return steal(&tmpdir);
}

View file

@ -113,6 +113,23 @@ START_TEST(rmdir_r_test)
}
END_TEST
START_TEST(tmpdir_test)
{
_autofree_ char *tmpdir_path = NULL;
{
_destroy_(tmpdir) *tmpdir = tmpdir_create(NULL);
tmpdir_path = safe_strdup(tmpdir->path);
_autofree_ char *f1 = strdup_printf("%s/wipeme", tmpdir_path);
litest_assert_errno_success(close(open(f1, O_WRONLY | O_CREAT, 0644)));
}
struct stat st;
int rc = stat(tmpdir_path, &st) < 0 ? -errno : 0;
litest_assert_int_eq(rc, -ENOENT);
}
END_TEST
START_TEST(find_files_test)
{
_autofree_ char *dirname = strdup("/tmp/litest_find_files_test.XXXXXX");
@ -2445,6 +2462,7 @@ int main(void)
ADD_TEST(auto_test);
ADD_TEST(mkdir_p_test);
ADD_TEST(rmdir_r_test);
ADD_TEST(tmpdir_test);
ADD_TEST(find_files_test);
ADD_TEST(array_for_each);