Skip to content

Commit 462d413

Browse files
committed
libotutil: add utility functions for calculating directory size
Prep for future patch.
1 parent a0681cd commit 462d413

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/libotutil/ot-fs-utils.c

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,47 @@ ot_parse_file_by_line (const char *path,
245245

246246
return TRUE;
247247
}
248+
249+
/* Calculate the size of the files contained in a directory. Symlinks are not
250+
* followed. */
251+
gboolean
252+
ot_get_dir_size (int dfd,
253+
const char *path,
254+
guint64 *out_size,
255+
GCancellable *cancellable,
256+
GError **error)
257+
{
258+
g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
259+
if (!glnx_dirfd_iterator_init_at (dfd, path, FALSE, &dfd_iter, error))
260+
return FALSE;
261+
262+
*out_size = 0;
263+
while (TRUE)
264+
{
265+
struct dirent *dent;
266+
if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, cancellable, error))
267+
return FALSE;
268+
269+
if (dent == NULL)
270+
break;
271+
272+
if (dent->d_type == DT_REG)
273+
{
274+
struct stat stbuf;
275+
if (!glnx_fstatat (dfd_iter.fd, dent->d_name, &stbuf, AT_SYMLINK_NOFOLLOW, error))
276+
return FALSE;
277+
278+
*out_size += stbuf.st_size;
279+
}
280+
else if (dent->d_type == DT_DIR)
281+
{
282+
guint64 subdir_size;
283+
if (!ot_get_dir_size (dfd_iter.fd, dent->d_name, &subdir_size, cancellable, error))
284+
return FALSE;
285+
286+
*out_size += subdir_size;
287+
}
288+
}
289+
290+
return TRUE;
291+
}

src/libotutil/ot-fs-utils.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,11 @@ ot_parse_file_by_line (const char *path,
9595
GCancellable *cancellable,
9696
GError **error);
9797

98+
gboolean
99+
ot_get_dir_size (int dfd,
100+
const char *path,
101+
guint64 *out_size,
102+
GCancellable *cancellable,
103+
GError **error);
104+
98105
G_END_DECLS

0 commit comments

Comments
 (0)