Skip to content

Commit

Permalink
strbuf: add strbuf_getcwd()
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
René Scharfe authored and Junio C Hamano committed Jul 28, 2014
1 parent ebc5da3 commit f22a76e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Documentation/technical/api-strbuf.txt
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,10 @@ same behaviour as well.
use it unless you need the correct position in the file
descriptor.

`strbuf_getcwd`::

Set the buffer to the path of the current working directory.

`stripspace`::

Strip whitespace from a buffer. The second parameter controls if
Expand Down
21 changes: 21 additions & 0 deletions strbuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,27 @@ int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
return -1;
}

int strbuf_getcwd(struct strbuf *sb)
{
size_t oldalloc = sb->alloc;
size_t guessed_len = 128;

for (;; guessed_len *= 2) {
strbuf_grow(sb, guessed_len);
if (getcwd(sb->buf, sb->alloc)) {
strbuf_setlen(sb, strlen(sb->buf));
return 0;
}
if (errno != ERANGE)
break;
}
if (oldalloc == 0)
strbuf_release(sb);
else
strbuf_reset(sb);
return -1;
}

int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
{
int ch;
Expand Down
1 change: 1 addition & 0 deletions strbuf.h
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ extern size_t strbuf_fread(struct strbuf *, size_t, FILE *);
extern ssize_t strbuf_read(struct strbuf *, int fd, size_t hint);
extern int strbuf_read_file(struct strbuf *sb, const char *path, size_t hint);
extern int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint);
extern int strbuf_getcwd(struct strbuf *sb);

extern int strbuf_getwholeline(struct strbuf *, FILE *, int);
extern int strbuf_getline(struct strbuf *, FILE *, int);
Expand Down

0 comments on commit f22a76e

Please sign in to comment.