repos/stagit

fork of stagit, a static git page generator
Commits Files Refs README LICENSE
commit 78ea8debfc82f0c0c0123ceb8d357db26a64f614
parent 84c8fcef4fd1c96cc6c20696d7bbcc8bc0066ea3
Author: Martin Kloeckner <mjkloeckner@gmail.com>
Date:   Fri,  4 Sep 2026 21:11:58 -0300

Show sizes in human readable format (instead of just bytes)

Diffstat:
Mstagit.c | 25++++++++++++++++++++++---
1 file changed, 22 insertions(+), 3 deletions(-)
diff --git a/stagit.c b/stagit.c
@@ -1075,6 +1075,25 @@ writeblobmd(FILE *fp, const git_blob *blob, const char *rawprefix)
             "</script>\n", fp);
 }
 
+const char *
+formatsize(size_t size)
+{
+    static const char *units[] = { "B", "KiB", "MiB", "GiB", "TiB" };
+    static char buf[32];
+    double sz = size;
+    size_t i;
+
+    for (i = 0; sz >= 1024 && i < LEN(units) - 1; i++)
+        sz /= 1024;
+
+    if (i == 0)
+        snprintf(buf, sizeof(buf), "%zuB", size);
+    else
+        snprintf(buf, sizeof(buf), "%.1f%s", sz, units[i]);
+
+    return buf;
+}
+
 size_t
 writeblob(git_object *obj, const char *fpath, const char *rpath, const char *filename, const char *path, size_t filesize)
 {
@@ -1151,7 +1170,7 @@ writeblob(git_object *obj, const char *fpath, const char *rpath, const char *fil
     xmlencode(fp, path, strlen(path));
     fprintf(fp, "</a>%s", strlen(path) == 0 ? "" : "/");
     xmlencode(fp, filename, strlen(filename));
-    fprintf(fp, " (%zuB)</div>\n\n", filesize);
+    fprintf(fp, " (%s)</div>\n\n", formatsize(filesize));
 
     if (!isbin) {
         fputs("<div id=\"line-checkbox-div\"><input type=\"checkbox\""
@@ -1401,7 +1420,7 @@ writefilestree(FILE *fp, git_tree *tree, const char *path)
                     fprintf(fp, "<a href=\"%s", relpath);
                     percentencode(fp, filepath, strlen(filepath));
                     fputs("\">", fp);
-                    fprintf(fp, "%zuB", filesize);
+                    fputs(formatsize(filesize), fp);
                 }
                 else if (is_obj_tree) {
                     fputs("<td id=\"dir-size\">", fp);
@@ -1483,7 +1502,7 @@ writefilestree(FILE *fp, git_tree *tree, const char *path)
                 fprintf(fp, "<a href=\"%s", relpath);
                 percentencode(fp, filepath, strlen(filepath));
                 fputs("\">", fp);
-                fprintf(fp, "%zuB", filesize);
+                fputs(formatsize(filesize), fp);
             }
             else if (is_obj_tree) {
                 fputs("<td id=\"dir-size\">", fp);