]> www.infradead.org Git - users/sagi/nvme-cli.git/commitdiff
util/types: Add generic spinner
authorWei Hou <wei.hou@scaleflux.com>
Thu, 1 Jun 2023 18:15:33 +0000 (20:15 +0200)
committerDaniel Wagner <wagi@monom.org>
Fri, 2 Jun 2023 11:45:51 +0000 (13:45 +0200)
Signed-off-by: Wei Hou <wei.hou@scaleflux.com>
util/types.c
util/types.h

index 2278252255545690bced47f730b59683d8425045..044391d4a4d09c7ee3d4a72f94a2df046748e914 100644 (file)
@@ -169,3 +169,35 @@ int convert_ts(time_t time, char *ts_buf)
 
        return 0;
 }
+
+void util_spinner(const char *disp_name, float percent)
+{
+       static const char dash[51] = {[0 ... 49] = '=', '\0'};
+       static const char space[51] = {[0 ... 49] = ' ', '\0'};
+       static const char spin[] = {'-', '\\', '|', '/' };
+       static int progress;
+       static int i;
+       const char *dn = disp_name ? disp_name : "";
+
+       if (percent < 0)
+               percent = 0;
+       else if (percent > 1)
+               percent = 1;
+
+       progress = (int)(percent * 100.0);
+       if (progress < 2)
+               printf("\r%s [%c%.*s] %3d%%", dn,
+                      spin[i % 4], 49,
+                      space, progress);
+       else if (progress < 100)
+               printf("\r%s [%.*s%c%.*s] %3d%%", dn,
+                      progress / 2 - 1, dash,
+                      spin[i % 4], 50 - progress / 2,
+                      space, progress);
+       else
+               printf("\r%s [%.*s] %3d%%\n", dn,
+                      50, dash, 100);
+       i++;
+
+       fflush(stdout);
+}
index 6bb67c513188e54cd926e667fd8fc5a32ce3cd09..595958bb7c01572863a5fe9bd35ff32530cf1a0a 100644 (file)
@@ -45,4 +45,16 @@ const char *util_fw_to_string(char *c);
  */
 int convert_ts(time_t time, char *ts_buf);
 
+/**
+ * @brief print once a progress of spinner to stdout
+ *        the output will be looks like if disp_name is "LogDump" and percent is 0.5
+ *        LogDump [========================-                         ]  50%
+
+ *
+ * @param disp_name, const string displayed before spiner
+ * @param percent [0, 1.0] about the progress
+ *
+ */
+void util_spinner(const char *disp_name, float percent);
+
 #endif /* _MISC_H */