Signed-off-by: Nguyễn Thái Ngọc Duy <pclo...@gmail.com>
---
 cache.h   |  2 ++
 wrapper.c | 31 +++++++++++++++++++++++++++++++
 2 files changed, 33 insertions(+)

diff --git a/cache.h b/cache.h
index e3ff7dc..bf4d15e 100644
--- a/cache.h
+++ b/cache.h
@@ -1359,6 +1359,8 @@ static inline ssize_t write_str_in_full(int fd, const 
char *str)
 {
        return write_in_full(fd, str, strlen(str));
 }
+__attribute__((format (printf,3,4)))
+extern int write_file(const char *path, int fatal, const char *fmt, ...);
 
 /* pager.c */
 extern void setup_pager(void);
diff --git a/wrapper.c b/wrapper.c
index bc1bfb8..9d7b9ac 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -493,3 +493,34 @@ struct passwd *xgetpwuid_self(void)
                    errno ? strerror(errno) : _("no such user"));
        return pw;
 }
+
+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;
+}
-- 
1.9.1.346.ga2b5940

--
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majord...@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Reply via email to