- int fd, len;
- char buffer[256];
- char *ref_start;
- char *head;
-
- head = fmt("%s/HEAD", repo_path);
- fd = open(head, O_RDONLY);
- if (fd == -1)
- return xstrdup("master");
-
- memset(buffer, 0, sizeof(buffer));
- len = read_in_full(fd, buffer, sizeof(buffer) - 1);
- close(fd);
-
- if(!memcmp(buffer, "ref: refs/heads/", 16))
- return xstrndup(buffer + 16, len - 17);
-
- if(strlen(buffer) == 41) {
- /* probably contains a SHA1 sum */
- memset(buffer, 0, sizeof(buffer));
- if(readlink(head, buffer, sizeof(buffer)-1)) {
- ref_start = memmem(buffer, sizeof(buffer)-1, "refs/heads/", 11);
- if(ref_start)
- return xstrdup(ref_start+11);
+ const char *colon;
+
+ *filename = NULL;
+ *ref = NULL;
+
+ if (!readme || !readme[0])
+ return;
+
+ /* Check if the readme is tracked in the git repo. */
+ colon = strchr(readme, ':');
+ if (colon && strlen(colon) > 1) {
+ /* If it starts with a colon, we want to use
+ * the default branch */
+ if (colon == readme && repo->defbranch)
+ *ref = xstrdup(repo->defbranch);
+ else
+ *ref = xstrndup(readme, colon - readme);
+ readme = colon + 1;
+ }
+
+ /* Prepend repo path to relative readme path unless tracked. */
+ if (!(*ref) && readme[0] != '/')
+ *filename = fmtalloc("%s/%s", repo->path, readme);
+ else
+ *filename = xstrdup(readme);
+}
+static void choose_readme(struct cgit_repo *repo)
+{
+ int found;
+ char *filename, *ref;
+ struct string_list_item *entry;
+
+ if (!repo->readme.nr)
+ return;
+
+ found = 0;
+ for_each_string_list_item(entry, &repo->readme) {
+ parse_readme(entry->string, &filename, &ref, repo);
+ if (!filename) {
+ free(filename);
+ free(ref);
+ continue;