search: prepend fuzzy filename matches
authorMischa POSLAWSKY <perl@shiar.org>
Tue, 16 Oct 2018 16:59:36 +0000 (18:59 +0200)
committerMischa POSLAWSKY <perl@shiar.org>
Mon, 22 Oct 2018 22:59:20 +0000 (00:59 +0200)
Prefer similar url over contents.

search.php

index e1da846057329535512477e3148d85b9da6c554e..5bd03bb3d464f882e8e6b908157fe5ab4b843672 100644 (file)
@@ -1,10 +1,31 @@
 <?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'];
 }