strbuf: add strbuf_getcwd()
Add strbuf_getcwd(), which puts the current working directory into a strbuf. Because it doesn't use a fixed-size buffer it supports arbitrarily long paths, provided the platform's getcwd() does as well. At least on Linux and FreeBSD it handles paths longer than PATH_MAX just fine. Suggested-by: Karsten Blees <karsten.blees@gmail.com> Helped-by: Duy Nguyen <pclouds@gmail.com> Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
René Scharfe committed
Jul 28, 2014 at 20:24 UTC
f22a76e9110e8e31efa3781b1a3cf2b4565d9e8a
3 files changed
+26
Documentation/technical/api-strbuf.txt
+4
@@ -289,6 +289,10 @@ same behaviour as well.
289
use it unless you need the correct position in the file
290
descriptor.
291
292
+`strbuf_getcwd`::
293
+
294
+ Set the buffer to the path of the current working directory.
295
+
296
`stripspace`::
297
298
Strip whitespace from a buffer. The second parameter controls if
strbuf.c
+21
@@ -398,6 +398,27 @@ int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
398
return -1;
399
}
400
401
+int strbuf_getcwd(struct strbuf *sb)
402
+{
403
+ size_t oldalloc = sb->alloc;
404
+ size_t guessed_len = 128;
405
+
406
+ for (;; guessed_len *= 2) {
407
+ strbuf_grow(sb, guessed_len);
408
+ if (getcwd(sb->buf, sb->alloc)) {
409
+ strbuf_setlen(sb, strlen(sb->buf));
410
+ return 0;
411
+ }
412
+ if (errno != ERANGE)
413
+ break;
414
+ }
415
+ if (oldalloc == 0)
416
+ strbuf_release(sb);
417
+ else
418
+ strbuf_reset(sb);
419
+ return -1;
420
+}
421
+
422
int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
423
{
424
int ch;
strbuf.h
+1
@@ -163,6 +163,7 @@ extern size_t strbuf_fread(struct strbuf *, size_t, FILE *);
163
extern ssize_t strbuf_read(struct strbuf *, int fd, size_t hint);
164
extern int strbuf_read_file(struct strbuf *sb, const char *path, size_t hint);
165
extern int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint);
166
+extern int strbuf_getcwd(struct strbuf *sb);
167
168
extern int strbuf_getwholeline(struct strbuf *, FILE *, int);
169
extern int strbuf_getline(struct strbuf *, FILE *, int);