+/* The caller must free filename and ref after calling this. */
+static inline void parse_readme(const char *readme, char **filename, char **ref, struct cgit_repo *repo)
+{
+ 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;
+ }
+ /* If there's only one item, we skip the possibly expensive
+ * selection process. */
+ if (repo->readme.nr == 1) {
+ found = 1;
+ break;
+ }
+ if (ref) {
+ if (cgit_ref_path_exists(filename, ref, 1)) {
+ found = 1;
+ break;
+ }
+ }
+ else if (!access(filename, R_OK)) {
+ found = 1;
+ break;
+ }
+ free(filename);
+ free(ref);
+ }
+ repo->readme.strdup_strings = 1;
+ string_list_clear(&repo->readme, 0);
+ repo->readme.strdup_strings = 0;
+ if (found)
+ string_list_append(&repo->readme, filename)->util = ref;
+}