Signed-off-by: Nguyễn Thái Ngọc Duy <pclo...@gmail.com>
---
 setup.c | 44 ++++++++++++++++++++++++--------------------
 1 file changed, 24 insertions(+), 20 deletions(-)

diff --git a/setup.c b/setup.c
index 5432a31..c040981 100644
--- a/setup.c
+++ b/setup.c
@@ -278,15 +278,31 @@ static int check_repository_format_gently(const char 
*gitdir, int *nongit_ok)
        return 0;
 }
 
+static char *path_from_gitfile(const char *path, const char *buf, int len)
+{
+       const char *slash;
+       if (len < 1)
+               die("No path in gitfile: %s", path);
+
+       if (!is_absolute_path(buf) && (slash = strrchr(path, '/'))) {
+               size_t pathlen = slash+1 - path;
+               size_t dirlen = pathlen + len;
+               char *p = xmalloc(dirlen + 1);
+               strncpy(p, path, pathlen);
+               strncpy(p + pathlen, buf, len);
+               p[dirlen] = '\0';
+               return p;
+       } else
+               return xmemdupz(buf, len);
+}
+
 /*
  * Try to read the location of the git directory from the .git file,
  * return path to git directory if found.
  */
 const char *read_gitfile(const char *path)
 {
-       char *buf;
-       char *dir;
-       const char *slash;
+       char *buf, *dir;
        struct stat st;
        int fd;
        ssize_t len;
@@ -303,31 +319,19 @@ const char *read_gitfile(const char *path)
        close(fd);
        if (len != st.st_size)
                die("Error reading %s", path);
-       buf[len] = '\0';
-       if (prefixcmp(buf, "gitdir: "))
-               die("Invalid gitfile format: %s", path);
-       while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
+       while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r'))
                len--;
-       if (len < 9)
-               die("No path in gitfile: %s", path);
        buf[len] = '\0';
-       dir = buf + 8;
 
-       if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
-               size_t pathlen = slash+1 - path;
-               size_t dirlen = pathlen + len - 8;
-               dir = xmalloc(dirlen + 1);
-               strncpy(dir, path, pathlen);
-               strncpy(dir + pathlen, buf + 8, len - 8);
-               dir[dirlen] = '\0';
-               free(buf);
-               buf = dir;
-       }
+       if (prefixcmp(buf, "gitdir: "))
+               die("Invalid gitfile format: %s", path);
+       dir = path_from_gitfile(path, buf + 8, len - 8);
 
        if (!is_git_directory(dir))
                die("Not a git repository: %s", dir);
        path = real_path(dir);
 
+       free(dir);
        free(buf);
        return path;
 }
-- 
1.8.5.1.77.g42c48fa

--
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