]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
hardlink: simplify file_link()
authorKarel Zak <kzak@redhat.com>
Wed, 1 Dec 2021 14:38:50 +0000 (15:38 +0100)
committerKarel Zak <kzak@redhat.com>
Wed, 1 Dec 2021 14:38:50 +0000 (15:38 +0100)
Signed-off-by: Karel Zak <kzak@redhat.com>
misc-utils/hardlink.c

index 2aca5ad603c3d45c2a6966493dbc4417d5f78279..f363ce766feff5c0f7cc7ece9425d11cb4681afb 100644 (file)
@@ -634,26 +634,23 @@ static int file_link(struct file *a, struct file *b)
        free(ssz);
 
        if (!opts.dry_run) {
-               size_t len =
-                   strlen(b->links->path) + strlen(".hardlink-temporary") + 1;
-               char *new_path = xmalloc(len);
+               char *new_path;
+               int failed = 1;
 
-               snprintf(new_path, len, "%s.hardlink-temporary",
-                        b->links->path);
+               xasprintf(&new_path, "%s.hardlink-temporary", b->links->path);
+
+               if (link(a->links->path, new_path) != 0)
+                       warn(_("cannot link %s to %s"), a->links->path, new_path);
+
+               else if (rename(new_path, b->links->path) != 0) {
+                       warn(_("cannot rename %s to %s"), a->links->path, new_path);
+                       unlink(new_path);
+               } else
+                       failed = 0;
 
-               if (link(a->links->path, new_path) != 0) {
-                       warn(_("cannot link %s to %s"), a->links->path,
-                            new_path);
-                       free(new_path);
-                       return FALSE;
-               } else if (rename(new_path, b->links->path) != 0) {
-                       warn(_("cannot rename %s to %s"), a->links->path,
-                            new_path);
-                       unlink(new_path);       /* cleanup failed rename */
-                       free(new_path);
-                       return FALSE;
-               }
                free(new_path);
+               if (failed)
+                       return FALSE;
        }
 
        /* Update statistics */