]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
glob: add glob_first(), returns first match
authorLuca Boccassi <bluca@debian.org>
Wed, 3 Aug 2022 13:20:41 +0000 (14:20 +0100)
committerLuca Boccassi <bluca@debian.org>
Tue, 23 Aug 2022 19:04:41 +0000 (20:04 +0100)
Note that which match is returned depends on the system and is
not guaranteed to be stable

src/basic/glob-util.c
src/basic/glob-util.h
src/test/test-glob-util.c

index e026b29478e2fae333040429743711d426a98aa5..fd60a6eda2d085c298ed4d11d7cf75426f09f292 100644 (file)
@@ -47,17 +47,28 @@ int safe_glob(const char *path, int flags, glob_t *pglob) {
         return 0;
 }
 
-int glob_exists(const char *path) {
+int glob_first(const char *path, char **ret_first) {
         _cleanup_globfree_ glob_t g = {};
         int k;
 
         assert(path);
 
         k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE, &g);
-        if (k == -ENOENT)
+        if (k == -ENOENT) {
+                if (ret_first)
+                        *ret_first = NULL;
                 return false;
+        }
         if (k < 0)
                 return k;
+
+        if (ret_first) {
+                char *first = strdup(g.gl_pathv[0]);
+                if (!first)
+                        return log_oom_debug();
+                *ret_first = first;
+        }
+
         return true;
 }
 
index fc86e990dd74979014a2b353311f1e8fec9f3554..7ca26cc27f73903e6661e902f704f363347310c1 100644 (file)
@@ -10,7 +10,9 @@
 /* Note: this function modifies pglob to set various functions. */
 int safe_glob(const char *path, int flags, glob_t *pglob);
 
-int glob_exists(const char *path);
+/* Note: which match is returned depends on the implementation/system and not guaranteed to be stable */
+int glob_first(const char *path, char **ret_first);
+#define glob_exists(path) glob_first(path, NULL)
 int glob_extend(char ***strv, const char *path, int flags);
 
 int glob_non_glob_prefix(const char *path, char **ret);
index ec8b74f48f3481ed1a3e92b6573176becb5d7000..566b68b5892dd652db250337155455518e0b7fa7 100644 (file)
 #include "tests.h"
 #include "tmpfile-util.h"
 
+TEST(glob_first) {
+        char *first, name[] = "/tmp/test-glob_first.XXXXXX";
+        int fd = -1;
+        int r;
+
+        fd = mkostemp_safe(name);
+        assert_se(fd >= 0);
+        close(fd);
+
+        r = glob_first("/tmp/test-glob_first*", &first);
+        assert_se(r == 1);
+        assert_se(streq(name, first));
+        first = mfree(first);
+
+        r = unlink(name);
+        assert_se(r == 0);
+        r = glob_first("/tmp/test-glob_first*", &first);
+        assert_se(r == 0);
+        assert_se(first == NULL);
+}
+
 TEST(glob_exists) {
         char name[] = "/tmp/test-glob_exists.XXXXXX";
         int fd = -1;