notes: handle multiple worktrees
[gitweb.git] / wrapper.c
index 5b77d2a1aecd494ea4bb5eb1e6f31afc9c96f82e..a2dff8e5be019f0aca58f3858d7a880f290b69e1 100644 (file)
--- a/wrapper.c
+++ b/wrapper.c
@@ -466,17 +466,29 @@ int xmkstemp_mode(char *template, int mode)
 
 static int warn_if_unremovable(const char *op, const char *file, int rc)
 {
-       if (rc < 0) {
-               int err = errno;
-               if (ENOENT != err) {
-                       warning("unable to %s %s: %s",
-                               op, file, strerror(errno));
-                       errno = err;
-               }
-       }
+       int err;
+       if (!rc || errno == ENOENT)
+               return 0;
+       err = errno;
+       warning("unable to %s %s: %s", op, file, strerror(errno));
+       errno = err;
        return rc;
 }
 
+int unlink_or_msg(const char *file, struct strbuf *err)
+{
+       int rc = unlink(file);
+
+       assert(err);
+
+       if (!rc || errno == ENOENT)
+               return 0;
+
+       strbuf_addf(err, "unable to unlink %s: %s",
+                   file, strerror(errno));
+       return -1;
+}
+
 int unlink_or_warn(const char *file)
 {
        return warn_if_unremovable("unlink", file, unlink(file));
@@ -538,3 +550,34 @@ char *xgetcwd(void)
                die_errno(_("unable to get current working directory"));
        return strbuf_detach(&sb, NULL);
 }
+
+int write_file(const char *path, int fatal, const char *fmt, ...)
+{
+       struct strbuf sb = STRBUF_INIT;
+       va_list params;
+       int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
+       if (fd < 0) {
+               if (fatal)
+                       die_errno(_("could not open %s for writing"), path);
+               return -1;
+       }
+       va_start(params, fmt);
+       strbuf_vaddf(&sb, fmt, params);
+       va_end(params);
+       if (write_in_full(fd, sb.buf, sb.len) != sb.len) {
+               int err = errno;
+               close(fd);
+               strbuf_release(&sb);
+               errno = err;
+               if (fatal)
+                       die_errno(_("could not write to %s"), path);
+               return -1;
+       }
+       strbuf_release(&sb);
+       if (close(fd)) {
+               if (fatal)
+                       die_errno(_("could not close %s"), path);
+               return -1;
+       }
+       return 0;
+}