diff --git a/libfwupdplugin/fu-common.c b/libfwupdplugin/fu-common.c index 19acec92f..39293b36f 100644 --- a/libfwupdplugin/fu-common.c +++ b/libfwupdplugin/fu-common.c @@ -1678,6 +1678,49 @@ fu_common_fnmatch (const gchar *pattern, const gchar *str) #endif } +static gint +fu_common_filename_glob_sort_cb (gconstpointer a, gconstpointer b) +{ + return g_strcmp0 (*(const gchar **)a, *(const gchar **)b); +} + +/** + * fu_common_filename_glob: + * @directory: a directory path + * @pattern: a glob pattern, e.g. `*foo*` + * @error: A #GError or %NULL + * + * Returns all the filenames that match a specific glob pattern. + * Any results are sorted. No matching files will set @error. + * + * Return value: (element-type utf8) (transfer container): matching files, or %NULL + * + * Since: 1.5.0 + **/ +GPtrArray * +fu_common_filename_glob (const gchar *directory, const gchar *pattern, GError **error) +{ + const gchar *basename; + g_autoptr(GDir) dir = g_dir_open (directory, 0, error); + g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free); + if (dir == NULL) + return NULL; + while ((basename = g_dir_read_name (dir)) != NULL) { + if (!fu_common_fnmatch (pattern, basename)) + continue; + g_ptr_array_add (files, g_build_filename (directory, basename, NULL)); + } + if (files->len == 0) { + g_set_error_literal (error, + G_IO_ERROR, + G_IO_ERROR_NOT_FOUND, + "no files matched pattern"); + return NULL; + } + g_ptr_array_sort (files, fu_common_filename_glob_sort_cb); + return g_steal_pointer (&files); +} + /** * fu_common_strnsplit: * @str: a string to split diff --git a/libfwupdplugin/fu-common.h b/libfwupdplugin/fu-common.h index c61627285..50681202e 100644 --- a/libfwupdplugin/fu-common.h +++ b/libfwupdplugin/fu-common.h @@ -93,6 +93,9 @@ gboolean fu_common_spawn_sync (const gchar * const *argv, gchar *fu_common_get_path (FuPathKind path_kind); gchar *fu_common_realpath (const gchar *filename, GError **error); +GPtrArray *fu_common_filename_glob (const gchar *directory, + const gchar *pattern, + GError **error); gboolean fu_common_fnmatch (const gchar *pattern, const gchar *str); gboolean fu_common_rmtree (const gchar *directory, diff --git a/libfwupdplugin/fwupdplugin.map b/libfwupdplugin/fwupdplugin.map index b3ac35435..5d1db3e44 100644 --- a/libfwupdplugin/fwupdplugin.map +++ b/libfwupdplugin/fwupdplugin.map @@ -583,6 +583,7 @@ LIBFWUPDPLUGIN_1.4.1 { LIBFWUPDPLUGIN_1.5.0 { global: + fu_common_filename_glob; fu_udev_device_get_parent_name; fu_udev_device_get_sysfs_attr; local: *;