Skip to content

Commit

Permalink
libotutil: add utility functions for calculating directory size
Browse files Browse the repository at this point in the history
Prep for future patch.
  • Loading branch information
jlebon committed Apr 14, 2023
1 parent a0681cd commit 462d413
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/libotutil/ot-fs-utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,47 @@ ot_parse_file_by_line (const char *path,

return TRUE;
}

/* Calculate the size of the files contained in a directory. Symlinks are not
* followed. */
gboolean
ot_get_dir_size (int dfd,
const char *path,
guint64 *out_size,
GCancellable *cancellable,
GError **error)
{
g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
if (!glnx_dirfd_iterator_init_at (dfd, path, FALSE, &dfd_iter, error))
return FALSE;

*out_size = 0;
while (TRUE)
{
struct dirent *dent;
if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, cancellable, error))
return FALSE;

if (dent == NULL)
break;

if (dent->d_type == DT_REG)
{
struct stat stbuf;
if (!glnx_fstatat (dfd_iter.fd, dent->d_name, &stbuf, AT_SYMLINK_NOFOLLOW, error))
return FALSE;

*out_size += stbuf.st_size;
}
else if (dent->d_type == DT_DIR)
{
guint64 subdir_size;
if (!ot_get_dir_size (dfd_iter.fd, dent->d_name, &subdir_size, cancellable, error))
return FALSE;

*out_size += subdir_size;
}
}

return TRUE;
}
7 changes: 7 additions & 0 deletions src/libotutil/ot-fs-utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,11 @@ ot_parse_file_by_line (const char *path,
GCancellable *cancellable,
GError **error);

gboolean
ot_get_dir_size (int dfd,
const char *path,
guint64 *out_size,
GCancellable *cancellable,
GError **error);

G_END_DECLS

0 comments on commit 462d413

Please sign in to comment.