<?php
+$limit = 10;
$path = ' '.escapeshellarg('*.html');
+
$cmd = "git grep -li -- ".escapeshellarg($Page).$path;
-$cmd .= ' |sort -R |head -n 10'; # random selection
exec($cmd, $results);
+if (count($results) > $limit) {
+ shuffle($results);
+ array_splice($results, $limit);
+}
+
+$cmd = "git ls-files -- $path";
+exec($cmd, $ls);
+if ($ls) {
+ # order files by similarity to query
+ $ls = array_combine($ls, array_map(function ($row) use ($Page) {
+ $row = preg_replace('{(?:^|/)index\.html$}', '', $row);
+ return similar_text($row, $Page) - strlen($row) / 8;
+ }, $ls));
+ arsort($ls);
+
+ # prepend best match, replace unless duplicate
+ array_unshift($results, key($ls));
+ $results = array_unique($results);
+ array_splice($results, $limit);
+}
-if (!$results) {
+elseif (!$results) {
$results = ['index.html'];
}