diff mbox series

[1/4] path.c: introduce strbuf_interpolate_path

Message ID eb40f012-e910-49a3-9e3f-2dbab2b169a6@gmail.com (mailing list archive)
State New, archived
Headers show
Series fix a leak with excludes_file | expand

Commit Message

Rubén Justo April 6, 2024, 2:31 p.m. UTC
Factorize interpolate_path to have a similar function that uses a
strbuf, instead of allocating a new string, to return the interpolated
path.

It will allow us to avoid some allocs and also some frees, which we will
take advantage of in the next commits.

Signed-off-by: Rubén Justo <rjusto@gmail.com>
---
 path.c | 20 ++++++++++++++------
 path.h |  1 +
 2 files changed, 15 insertions(+), 6 deletions(-)
diff mbox series

Patch

diff --git a/path.c b/path.c
index 8bb223c92c..7a1a1a9bc0 100644
--- a/path.c
+++ b/path.c
@@ -737,8 +737,16 @@  static struct passwd *getpw_str(const char *username, size_t len)
 char *interpolate_path(const char *path, int real_home)
 {
 	struct strbuf user_path = STRBUF_INIT;
+
+	return strbuf_interpolate_path(path, real_home, &user_path);
+}
+
+char *strbuf_interpolate_path(const char *path, int real_home, struct strbuf* dst)
+{
 	const char *to_copy = path;
 
+	strbuf_reset(dst);
+
 	if (!path)
 		goto return_null;
 
@@ -754,9 +762,9 @@  char *interpolate_path(const char *path, int real_home)
 			if (!home)
 				goto return_null;
 			if (real_home)
-				strbuf_add_real_path(&user_path, home);
+				strbuf_add_real_path(dst, home);
 			else
-				strbuf_addstr(&user_path, home);
+				strbuf_addstr(dst, home);
 #ifdef GIT_WINDOWS_NATIVE
 			convert_slashes(user_path.buf);
 #endif
@@ -764,14 +772,14 @@  char *interpolate_path(const char *path, int real_home)
 			struct passwd *pw = getpw_str(username, username_len);
 			if (!pw)
 				goto return_null;
-			strbuf_addstr(&user_path, pw->pw_dir);
+			strbuf_addstr(dst, pw->pw_dir);
 		}
 		to_copy = first_slash;
 	}
-	strbuf_addstr(&user_path, to_copy);
-	return strbuf_detach(&user_path, NULL);
+	strbuf_addstr(dst, to_copy);
+	return dst->buf;
 return_null:
-	strbuf_release(&user_path);
+	strbuf_release(dst);
 	return NULL;
 }
 
diff --git a/path.h b/path.h
index e053effef2..da7e5384a3 100644
--- a/path.h
+++ b/path.h
@@ -185,6 +185,7 @@  int calc_shared_perm(int mode);
 int adjust_shared_perm(const char *path);
 
 char *interpolate_path(const char *path, int real_home);
+char *strbuf_interpolate_path(const char *path, int real_home, struct strbuf *dst);
 const char *enter_repo(const char *path, int strict);
 const char *remove_leading_path(const char *in, const char *prefix);
 const char *relative_path(const char *in, const char *prefix, struct strbuf *sb);