38 Commits

Author SHA1 Message Date
Alex Schroeder
761a5f16dd Use full text search 2023-09-10 23:41:11 +02:00
Alex Schroeder
4e5aa70529 Add language detection 2023-09-10 15:58:31 +02:00
Alex Schroeder
b7048bd5a9 Pass regular expression to highlighter 2023-09-10 15:57:50 +02:00
Alex Schroeder
41be47dc03 Scoring
Improved description in the README. Score the raw body of the page and
not the plain text (so that invisible text such as URLs are part of
the score). Page sorting is such that with equal score pages that
start with a number get sorted descending (in the hopes of putting
newer pages at the top, if ISO dates are part of page names).
2023-09-10 11:31:18 +02:00
Alex Schroeder
44b92cc3e0 Add CSS for header to search.html 2023-09-10 10:56:54 +02:00
Alex Schroeder
025d993eb7 Add search box to search itself for iteration 2023-09-10 10:45:00 +02:00
Alex Schroeder
1209c2b209 Moved a score test to the right file 2023-09-10 10:34:10 +02:00
Alex Schroeder
5d3aa45ddb Split score and highlight into 2 files 2023-09-10 10:31:01 +02:00
Alex Schroeder
f93177def5 Split highlighting and scoring 2023-09-10 00:51:20 +02:00
Alex Schroeder
aeb53148e7 Consider using a full text search engine 2023-09-09 22:11:35 +02:00
Alex Schroeder
4bce6fcb38 Split search phrase into words
Trigrams are then merged but word boundaries don't get their own
trigrams. The result is that the word order no longer matters.
2023-09-09 21:46:33 +02:00
Alex Schroeder
92cc1ad883 Document scoring of the search results 2023-09-09 21:46:22 +02:00
Alex Schroeder
378330cbce Add case-insensitive indexing 2023-09-09 20:45:36 +02:00
Alex Schroeder
ad472f9db1 Thoughts on multi-lingual wikis. 2023-09-09 20:07:36 +02:00
Alex Schroeder
b4f861a24e Add todo list. 2023-09-09 20:01:08 +02:00
Alex Schroeder
e97e5c7e6c Add back the missing rocket link translation 2023-08-25 21:23:22 +02:00
Alex Schroeder
0a4eabee3d New intro 2023-08-25 21:19:56 +02:00
Alex Schroeder
fcd4d9136d Move sanitization into separate functions
Add score for title matches but discard the markup.
2023-08-25 19:08:47 +02:00
Alex Schroeder
103007be48 Fix regexp quoting and title searching 2023-08-25 18:32:15 +02:00
Alex Schroeder
4afffbc409 Add hyphenation to the templates 2023-08-25 18:15:31 +02:00
Alex Schroeder
9e6d59cefa Run go fmt 2023-08-25 00:29:43 +02:00
Alex Schroeder
2a4902b1b4 Add footer and add note change its email address 2023-08-25 00:28:37 +02:00
Alex Schroeder
efc54f1524 Add title 2023-08-24 18:24:25 +02:00
Alex Schroeder
8fc5bd30e3 Link Home 2023-08-24 18:24:17 +02:00
Alex Schroeder
40855ea442 More documentation 2023-08-24 18:24:09 +02:00
Alex Schroeder
29af9a4cfa Add cleanup to tests 2023-08-24 14:34:03 +02:00
Alex Schroeder
146f4c9f57 Allow creation of subdirectories 2023-08-24 14:30:19 +02:00
Alex Schroeder
6f61dde12a Test search and fix bugs 2023-08-24 14:14:33 +02:00
Alex Schroeder
5b29e6433a Add page tests 2023-08-24 13:06:02 +02:00
Alex Schroeder
2bd20432e2 More snippet and highlight testing and fixing 2023-08-24 12:42:50 +02:00
Alex Schroeder
49d62a7979 Split highlight.go from snippets.go 2023-08-24 10:33:32 +02:00
Alex Schroeder
071e807886 Add snippets test 2023-08-24 10:32:07 +02:00
Alex Schroeder
df1fdf4373 Add indexing limitation 2023-08-24 10:12:54 +02:00
Alex Schroeder
08b63ae84b Add scoring 2023-08-24 10:00:39 +02:00
Alex Schroeder
645a87e5c8 Split page.go 2023-08-24 08:57:36 +02:00
Alex Schroeder
c54e41da28 Comments. handleTitle takes arg.
handleTitle now takes an argument so that the edit page can show the
page title and still have an untouched Page.Body for editing.
2023-08-24 08:51:51 +02:00
Alex Schroeder
6a4e014d1c Split search.go and snippets.go 2023-08-24 08:29:53 +02:00
Alex Schroeder
2142144b0c Add search 2023-08-23 23:27:34 +02:00
26 changed files with 1713 additions and 122 deletions

2
.gitignore vendored
View File

@@ -1 +1,3 @@
/oddmu
test.md
/testdata/

201
LICENSE-2.0 Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

241
README.md
View File

@@ -1,20 +1,75 @@
# Oddµ: A minimal wiki
This program runs a wiki. It serves all the Markdown files (ending in
`.md`) into web pages and allows you to edit them.
`.md`) into web pages and allows you to edit them. If your files don't
provide their own title (`# title`), the file name (without `.md`) is
used for the title. Subdirectories are created as necessary.
This is a minimal wiki. There is no version history. It probably makes
sense to only use it as one person or in very small groups.
This is a minimal wiki. There is no version history. It's well suited
as a *secondary* medium: collaboration and conversation happens
elsewhere, in chat, on social media. The wiki serves as the text
repository that results from these discussions.
This wiki only uses Markdown. There is no additional wiki markup, most
The wiki lists no recent changes. The expectation is that the people
that care were involved in the discussions beforehand.
The wiki also produces no feed. The assumption is that announcements
are made on social media: blogs, news aggregators, discussion forums,
the fediverse, but humans. There is no need for bots.
As you'll see below, the idea is that the webserver handles as many
tasks as possible. It logs requests, does rate limiting, handles
encryption, gets the certificates, and so on. The web server acts as a
reverse proxy and the wiki ends up being a content management system
with almost no structure or endless malleability, depending on your
point of view.
And last but not least: µ is the letter mu, so Oddµ is usually written
Oddmu. 🙃
## Markdown
This wiki uses Markdown. There is no additional wiki markup, most
importantly double square brackets are not a link. If you're used to
that, it'll be strange as you need to repeat the name: `[like
this](like this)`.
this](like this)`. The Markdown processor comes with a few extensions,
some of which are enable by default:
If your files don't provide their own title (`# title`), the file name
is used for the title.
* emphasis markers inside words are ignored
* tables are supported
* fenced code blocks are supported
* autolinking of "naked" URLs are supported
* strikethrough using two tildes is supported (`~~like this~~`)
* it is strict about prefix heading rules
* you can specify an id for headings (`{#id}`)
* trailing backslashes turn into line breaks
* definition lists are supported
* MathJax is supported (but needs a separte setup)
µ is the letter mu, so Oddµ is usually written Oddmu. 🙃
See the section on
[extensions](https://github.com/gomarkdown/markdown#extensions) in the
Markdown library for information on the various extensions.
A table with footers and a columnspan:
```text
Name | Age
--------|------
Bob ||
Alice | 23
========|======
Total | 23
```
A definition list:
```text
Cat
: Fluffy animal everyone likes
Internet
: Vector of transmission for pictures of cats
```
## Templates
@@ -22,6 +77,9 @@ Feel free to change the templates `view.html` and `edit.html` and
restart the server. Modifying the styles in the templates would be a
good start to get a feel for it.
The first change you should make is to replace the email address in
`view.html`. 😄
The templates can refer to the following properties of a page:
`{{.Title}}` is the page title. If the page doesn't provide its own
@@ -35,6 +93,30 @@ extension.
`{{printf "%s" .Body}}` is the Markdown, as a string (the data itself
is a byte array and that's why we need to call `printf`).
When calling the `save` action, the page name is take from the URL and
the page content is taken from the `body` form parameter. To
illustrate, here's how to edit a page using `curl`:
```sh
curl --form body="Did you bring a towel?" \
http://localhost:8080/save/welcome
```
## Non-English hyphenation
Automatic hyphenation by the browser requires two things: The style
sheet must indicate `hyphen: auto` for an HTML element such as `body`,
and that element must have a `lang` set (usually a two letter language
code such as `de` for German). This happens in the template files,
such as `view.html` and `search.html`.
If have pages in different languages, the problem is that they all use
the same template and that's not good. In such cases, it might be
better to not specificy the `lang` attribute in the template. This
also disables hyphenation by the browser, unfortunately. It might
still be better than using English hyphenation patterns for
non-English languages.
## Building
```sh
@@ -68,9 +150,11 @@ As root, on your server:
adduser --system --home /home/oddmu oddmu
```
Copy all the files into `/home/oddmu` to your server: `oddmu`, `oddmu.service`, `view.html` and `edit.html`.
Copy all the files into `/home/oddmu` to your server: `oddmu`,
`oddmu.service`, `view.html` and `edit.html`.
Edit the `oddmu.service` file. These are the three lines you most likely have to take care of:
Edit the `oddmu.service` file. These are the three lines you most
likely have to take care of:
```
ExecStart=/home/oddmu/oddmu
@@ -126,15 +210,15 @@ MDCertificateAgreement accepted
RewriteEngine on
RewriteRule ^/$ http://%{HTTP_HOST}:8080/view/index [redirect]
RewriteRule ^/(view|edit|save)/(.*) http://%{HTTP_HOST}:8080/$1/$2 [proxy]
RewriteRule ^/(view|edit|save|search)/(.*) http://%{HTTP_HOST}:8080/$1/$2 [proxy]
</VirtualHost>
```
First, it manages the domain, getting the necessary certificates. It
redirects regular HTTP traffic from port 80 to port 443. It turns on
the SSL engine for port 443. It redirects `/` to `/view/index` and any
path that starts with `/view/`, `/edit/` or `/save/` is proxied to
port 8080 where the Oddmu program can handle it.
path that starts with `/view/`, `/edit/`, `/save/` or `/search/` is
proxied to port 8080 where the Oddmu program can handle it.
Thus, this is what happens:
@@ -208,9 +292,13 @@ DocumentRoot /home/oddmu/static
Create this directory, making sure to give it a permission that your
webserver can read (world readable file, world readable and executable
directory). Populate it with files. For example, create a file called
`robots.txt` containing the following, tellin all robots that they're
not welcome.
directory). Populate it with files.
Make sure that none of the static files look like the wiki paths
`/view/`, `/edit/`, `/save/` or `/search/`.
For example, create a file called `robots.txt` containing the
following, tellin all robots that they're not welcome.
```text
User-agent: *
@@ -223,8 +311,37 @@ and without needing a wiki page.
[Wikipedia](https://en.wikipedia.org/wiki/Robot_exclusion_standard)
has more information.
All you have make sure is that none of the static files look like the
wiki paths `/view/`, `/edit/` or `/save/`.
## Different logins for different access rights
What if you have a site with various subdirectories and each
subdirectory is for a different group of friends? You can set this up
using your webserver. One way to do this is to require specific
usernames (which must have a password in the password file mentioned
above.
This requires a valid login by the user "alex" or "berta":
```apache
<LocationMatch "^/(edit|save)/intetebi/">
Require user alex berta
</LocationMatch>
```
## Private wikis
Based on the above, you can prevent people from reading the wiki, too.
The `LocationMatch` must cover the `/view/` URLs. In order to protect
*everything*, use a [Location directive](https://httpd.apache.org/docs/current/mod/core.html#location)
that matches everything:
```apache
<Location />
AuthType Basic
AuthName "Password Required"
AuthUserFile /home/oddmu/.htpasswd
Require valid-user
</Location>
```
## Customization (with recompilation)
@@ -242,70 +359,86 @@ rocket links (`=>`). Here's how to modify the `loadPage` so that a
translated into Markdown:
```go
func loadPage(title string) (*Page, error) {
filename := title + ".md"
func loadPage(name string) (*Page, error) {
filename := name + ".md"
body, err := os.ReadFile(filename)
if err == nil {
return &Page{Title: title, Name: title, Body: body}, nil
return &Page{Title: name, Name: name, Body: body}, nil
}
filename = title + ".gmi"
filename = name + ".gmi"
body, err = os.ReadFile(filename)
if err == nil {
return &Page{Title: title, Name: title, Body: body}, nil
re := regexp.MustCompile(`(?m)^=>\s*(\S+)\s+(.+)`)
body = []byte(re.ReplaceAllString(string(body), `* [$2]($1)`))
return &Page{Title: name, Name: name, Body: body}, nil
}
return nil, err
}
```
There is a small problem, however: By default, Markdown expects an
empty line before a list begins. The following change to `viewHandler`
empty line before a list begins. The following change to `renderHtml`
uses the `NoEmptyLineBeforeBlock` extension for the parser:
```go
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
// Short cut for text files
if (strings.HasSuffix(title, ".txt")) {
body, err := os.ReadFile(title)
if err == nil {
w.Write(body)
return
}
}
// Attempt to load Markdown or Gemini page; edit it if this fails
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
// Render the Markdown to HTML, extracting a title and
// possibly sanitizing it
s := string(p.Body)
m := titleRegexp.FindStringSubmatch(s)
if m != nil {
p.Title = m[1]
p.Body = []byte(strings.Replace(s, m[0], "", 1))
}
func (p* Page) renderHtml() {
// Here is where a new extension is added!
extensions := parser.CommonExtensions | parser.NoEmptyLineBeforeBlock
markdownParser := parser.NewWithExtensions(extensions)
flags := html.CommonFlags
opts := html.RendererOptions{
Flags: flags,
}
htmlRenderer := html.NewRenderer(opts)
maybeUnsafeHTML := markdown.ToHTML(p.Body, markdownParser, htmlRenderer)
maybeUnsafeHTML := markdown.ToHTML(p.Body, markdownParser, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)
p.Html = template.HTML(html);
renderTemplate(w, "view", p)
}
```
## Understanding search
The index indexes trigrams. Each group of three characters is a
trigram. A document with content "This is a test" is turned to lower
case and indexed under the trigrams "thi", "his", "is ", "s i", " is",
"is ", "s a", " a ", "a t", " te", "tes", "est".
Each query is split into words and then processed the same way. A
query with the words "this test" is turned to lower case and produces
the trigrams "thi", "his", "tes", "est". This means that the word
order is not considered when searching for documents.
This also means that there is no stemming. Searching for "testing"
won't find "This is a test" because there are no matches for the
trigrams "sti", "tin", "ing".
These trigrams are looked up in the index, resulting in the list of
documents. Each document found is then scored. Each of the following
increases the score by one point:
- the entire phrase matches
- a word matches
- a word matches at the beginning of a word
- a word matches at the end of a word
- a word matches as a whole word
A document with content "This is a test" when searched with the phrase
"this test" therefore gets a score of 8: the entire phrase does not
match but each word gets four points.
Trigrams are sometimes strange: In a text containing the words
"software" and "#socialmedia", a search for "#software" returns a
result because the trigram "#so" is part of "#socialmedia".
## Limitations
Page titles are filenames with `.md` appended. If your filesystem
cannot handle it, it can't be a page title. Specifically, *no slashes*
in filenames.
The pages are indexed as the server starts and the index is kept in
memory. If you have a ton of pages, this surely wastes a lot of
memory.
## Bugs
If you spot any, [contact](https://alexschroeder.ch/wiki/Contact) me.
## References
[Writing Web Applications](https://golang.org/doc/articles/wiki/)

23
TODO.md Normal file
View File

@@ -0,0 +1,23 @@
Easily prepend or append text for use with a mobile browser. Like
comments.
Upload files.
Automatically scale or process files.
Post by Delta Chat? That is, allow certain encrypted emails to post.
Convert the existing wiki.
Investigate how to run a multi-lingual wiki where an appropriate
template is used based on the language of the page. This is important
because the template needs to use the appropriate `lang` attribute for
hyphenation to work.
Investigate how to run a multi-linugual wiki where an appropriate
version of a page is served based on language preferences of the user.
This is a low priority issue since it's probably only of interest for
corporate or governmental sites.
Switch from trigram search to a simple full text search engine?
https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/

32
filter.go Normal file
View File

@@ -0,0 +1,32 @@
// Copyright 2020 Artem Krylysov
// Copyright 2023 Alex Schroeder
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This code was originally copied from
// https://github.com/akrylysov/simplefts
// https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/
package main
import (
"strings"
)
// lowercaseFilter returns a slice of tokens normalized to lower case.
func lowercaseFilter(tokens []string) []string {
r := make([]string, len(tokens))
for i, token := range tokens {
r[i] = strings.ToLower(token)
}
return r
}

33
filter_test.go Normal file
View File

@@ -0,0 +1,33 @@
// Copyright 2020 Artem Krylysov
// Copyright 2023 Alex Schroeder
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This code was originally copied from
// https://github.com/akrylysov/simplefts
// https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestLowercaseFilter(t *testing.T) {
var (
in = []string{"Cat", "DOG", "fish"}
out = []string{"cat", "dog", "fish"}
)
assert.Equal(t, out, lowercaseFilter(in))
}

9
go.mod
View File

@@ -3,12 +3,21 @@ module alexschroeder.ch/cgit/oddmu
go 1.21.0
require (
github.com/dgryski/go-trigram v0.0.0-20160407183937-79ec494e1ad0
github.com/gomarkdown/markdown v0.0.0-20230716120725-531d2d74bc12
github.com/microcosm-cc/bluemonday v1.0.25
github.com/pemistahl/lingua-go v1.4.0
github.com/stretchr/testify v1.8.4
)
require (
github.com/aymerick/douceur v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/shopspring/decimal v1.3.1 // indirect
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect
golang.org/x/net v0.12.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

23
go.sum
View File

@@ -1,10 +1,33 @@
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-trigram v0.0.0-20160407183937-79ec494e1ad0 h1:b+7JSiBM+hnLQjP/lXztks5hnLt1PS46hktG9VOJgzo=
github.com/dgryski/go-trigram v0.0.0-20160407183937-79ec494e1ad0/go.mod h1:qzKC/DpcxK67zaSHdCmIv3L9WJViHVinYXN2S7l3RM8=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/gomarkdown/markdown v0.0.0-20230716120725-531d2d74bc12 h1:uK3X/2mt4tbSGoHvbLBHUny7CKiuwUip3MArtukol4E=
github.com/gomarkdown/markdown v0.0.0-20230716120725-531d2d74bc12/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
github.com/microcosm-cc/bluemonday v1.0.25 h1:4NEwSfiJ+Wva0VxN5B8OwMicaJvD8r9tlJWm9rtloEg=
github.com/microcosm-cc/bluemonday v1.0.25/go.mod h1:ZIOjCQp1OrzBBPIJmfX4qDYFuhU02nx4bn030ixfHLE=
github.com/pemistahl/lingua-go v1.4.0 h1:ifYhthrlW7iO4icdubwlduYnmwU37V1sbNrwhKBR4rM=
github.com/pemistahl/lingua-go v1.4.0/go.mod h1:ECuM1Hp/3hvyh7k8aWSqNCPlTxLemFZsRjocUf3KgME=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 h1:Fq7F/w7MAa1KJ5bt2aJ62ihqp9HDcRuyILskkpIAurw=
golang.org/x/exp v0.0.0-20221106115401-f9659909a136/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

13
highlight.go Normal file
View File

@@ -0,0 +1,13 @@
package main
import (
"regexp"
)
// highlight splits the query string q into terms and highlights them
// using the bold tag. Return the highlighted string.
// This assumes that q already has all its meta characters quoted.
func highlight(q string, re *regexp.Regexp, s string) string {
s = re.ReplaceAllString(s, "<b>$1</b>")
return s
}

43
highlight_test.go Normal file
View File

@@ -0,0 +1,43 @@
package main
import (
"testing"
)
func TestHighlight(t *testing.T) {
s := `The windows opens
A wave of car noise hits me
No birds to be heard.`
h := `The <b>window</b>s opens
A wave of car noise hits me
No birds to be heard.`
q := "window"
re, _ := re(q)
r := highlight(q, re, s)
if r != h {
t.Logf("The highlighting is wrong in 「%s」", r)
t.Fail()
}
}
func TestOverlap(t *testing.T) {
s := `Sit with me my love
Kids shout and so do parents
I hear the fountain`
h := `Sit with me my love
Kids <b>shout</b> and so do parents
I hear the fountain`
q := "shout out"
re, _ := re(q)
r := highlight(q, re, s)
if r != h {
t.Logf("The highlighting is wrong in 「%s」", r)
t.Fail()
}
}

121
index.go Normal file
View File

@@ -0,0 +1,121 @@
// Copyright 2020 Artem Krylysov
// Copyright 2023 Alex Schroeder
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This code was originally copied from
// https://github.com/akrylysov/simplefts
// https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/
package main
import(
"log"
"sort"
)
type docid uint
// next_id is the number of the next document added to the index
var next_id docid = 0
// index is an inverted index. It maps tokens to document ids. Use add
// to add a document to the index. Use remove to remove a document
// from the index. Remove the old document and add the new document to
// update the index.
type index map[string][]docid
// add adds a document to the index and returns the new document id.
// This limits the number of documents and updates that can happen
// during a particular run.
func (idx index) add(text string) docid {
id := next_id; next_id++
for _, token := range analyze(text) {
ids := idx[token]
if ids != nil && ids[len(ids)-1] == id {
// Don't add same ID twice.
continue
}
idx[token] = append(ids, id)
}
return id
}
// delete removes a document from the index by removing all the words.
func (idx index) delete(text string, id docid) {
for _, token := range analyze(text) {
ids := idx[token]
// If the token doesn't show up, that's strange. This
// shouldn't happen.
if ids == nil {
log.Printf("Token %s is not indexed", token)
continue
}
// If the token appears only in this document, remove
// the whole entry.
if len(ids) == 1 && ids[0] == id {
delete(idx, token)
continue
}
// Otherwise, remove the token from the index.
i := sort.Search(len(ids), func(i int) bool { return ids[i] >= id })
if i != -1 && i < len(ids) && ids[i] == id {
copy(ids[i:], ids[i+1:])
idx[token] = ids[:len(ids)-1]
continue
}
// If none of the above, then our docid wasn't
// indexed. This shouldn't happen, either.
log.Printf("The index for token %s does not contain doc id %d", token, id)
}
}
// intersection returns the set intersection between a and b.
// a and b have to be sorted in ascending order and contain no duplicates.
func intersection(a []docid, b []docid) []docid {
maxLen := len(a)
if len(b) > maxLen {
maxLen = len(b)
}
r := make([]docid, 0, maxLen)
var i, j int
for i < len(a) && j < len(b) {
if a[i] < b[j] {
i++
} else if a[i] > b[j] {
j++
} else {
r = append(r, a[i])
i++
j++
}
}
return r
}
// search queries the index for the given text.
func (idx index) search(text string) []docid {
var r []docid
for _, token := range analyze(text) {
if ids, ok := idx[token]; ok {
if r == nil {
r = ids
} else {
r = intersection(r, ids)
}
} else {
// Token doesn't exist.
return nil
}
}
return r
}

View File

@@ -1,3 +1,5 @@
# Welcome to Oddµ
Hello! 🙃
Check out the [README](README).

41
index_test.go Normal file
View File

@@ -0,0 +1,41 @@
// Copyright 2020 Artem Krylysov
// Copyright 2023 Alex Schroeder
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This code was originally copied from
// https://github.com/akrylysov/simplefts
// https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIndex(t *testing.T) {
idx := make(index)
assert.Nil(t, idx.search("foo"))
assert.Nil(t, idx.search("donut"))
id1 := idx.add("A donut on a glass plate. Only the donuts.")
assert.Equal(t, idx.search("donut"), []docid{id1})
assert.Equal(t, idx.search("DoNuts"), []docid{id1})
assert.Equal(t, idx.search("glass"), []docid{id1})
id2 := idx.add("donut is a donut")
assert.Equal(t, idx.search("donut"), []docid{id1, id2})
assert.Equal(t, idx.search("DoNuts"), []docid{id1})
assert.Equal(t, idx.search("glass"), []docid{id1})
}

157
page.go Normal file
View File

@@ -0,0 +1,157 @@
package main
import (
"bytes"
"fmt"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/parser"
"github.com/microcosm-cc/bluemonday"
"github.com/pemistahl/lingua-go"
"html/template"
"os"
"path/filepath"
"strings"
)
// languages is the list of languages the wiki understands. This is
// passed along to the template so that it can be added to the
// template which allows browsers to (maybe) do hyphenation correctly.
var languages = []lingua.Language{
lingua.English,
lingua.German,
}
// detector is built once based on the list languages.
var detector = lingua.NewLanguageDetectorBuilder().
FromLanguages(languages...).
WithPreloadedLanguageModels().
WithLowAccuracyMode().
Build()
// Page is a struct containing information about a single page. Title
// is the title extracted from the page content using titleRegexp.
// Name is the filename without extension (so a filename of "foo.md"
// results in the Name "foo"). Body is the Markdown content of the
// page and Html is the rendered HTML for that Markdown. Score is a
// number indicating how well the page matched for a search query.
type Page struct {
Title string
Name string
Language string
Body []byte
Html template.HTML
Score int
}
func sanitize(s string) template.HTML {
return template.HTML(bluemonday.UGCPolicy().Sanitize(s))
}
func sanitizeBytes(bytes []byte) template.HTML {
return template.HTML(bluemonday.UGCPolicy().SanitizeBytes(bytes))
}
// save saves a Page. The filename is based on the Page.Name and gets
// the ".md" extension. Page.Body is saved, without any carriage
// return characters ("\r"). The file permissions used are readable
// and writeable for the current user, i.e. u+rw or 0600. Page.Title
// and Page.Html are not saved no caching. There is no caching.
func (p *Page) save() error {
filename := p.Name + ".md"
s := bytes.ReplaceAll(p.Body, []byte{'\r'}, []byte{})
p.Body = s
p.updateIndex()
d := filepath.Dir(filename)
if d != "." {
err := os.MkdirAll(d, 0700)
if err != nil {
fmt.Printf("Creating directory %s failed", d)
return err
}
}
return os.WriteFile(filename, s, 0600)
}
// loadPage loads a Page given a name. The filename loaded is that
// Page.Name with the ".md" extension. The Page.Title is set to the
// Page.Name (and possibly changed, later). The Page.Body is set to
// the file content. The Page.Html remains undefined (there is no
// caching).
func loadPage(name string) (*Page, error) {
filename := name + ".md"
body, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: name, Name: name, Body: body, Language: ""}, nil
}
// handleTitle extracts the title from a Page and sets Page.Title, if
// any. If replace is true, the page title is also removed from
// Page.Body. Make sure not to save this! This is only for rendering.
func (p *Page) handleTitle(replace bool) {
s := string(p.Body)
m := titleRegexp.FindStringSubmatch(s)
if m != nil {
p.Title = m[1]
if replace {
p.Body = []byte(strings.Replace(s, m[0], "", 1))
}
}
}
// renderHtml renders the Page.Body to HTML and sets Page.Html.
func (p *Page) renderHtml() {
maybeUnsafeHTML := markdown.ToHTML(p.Body, nil, nil)
p.Html = sanitizeBytes(maybeUnsafeHTML)
p.Language = p.language(p.plainText())
}
// plainText renders the Page.Body to plain text and returns it,
// ignoring all the Markdown and all the newlines. The result is one
// long single line of text.
func (p *Page) plainText() string {
parser := parser.New()
doc := markdown.Parse(p.Body, parser)
text := []byte("")
ast.WalkFunc(doc, func(node ast.Node, entering bool) ast.WalkStatus {
if entering && node.AsLeaf() != nil {
text = append(text, node.AsLeaf().Literal...)
text = append(text, []byte(" ")...)
}
return ast.GoToNext
})
// Some Markdown still contains newlines
for i, c := range text {
if c == '\n' {
text[i] = ' '
}
}
// Remove trailing space
for len(text) > 0 && text[len(text)-1] == ' ' {
text = text[0 : len(text)-1]
}
return string(text)
}
// summarize for query string q sets Page.Html to an extract.
func (p *Page) summarize(q string) {
p.handleTitle(true)
p.Score = score(q, string(p.Body)) + score(q, p.Title)
t := p.plainText()
p.Html = sanitize(snippets(q, t))
p.Language = p.language(t)
}
func (p *Page) language(s string) string {
if language, ok := detector.DetectLanguageOf(s); ok {
switch language {
case lingua.English:
return "en"
case lingua.German:
return "de"
}
}
return ""
}

78
page_test.go Normal file
View File

@@ -0,0 +1,78 @@
package main
import (
"os"
"strings"
"testing"
)
func TestPageTitle(t *testing.T) {
p := &Page{Body: []byte(`# Ache
My back aches for you
I sit, stare and type for hours
But yearn for blue sky`)}
p.handleTitle(false)
if p.Title != "Ache" {
t.Logf("The page title was not extracted correctly: %s", p.Title)
t.Fail()
}
if !strings.HasPrefix(string(p.Body), "# Ache") {
t.Logf("The page title was removed: %s", p.Body)
t.Fail()
}
p.handleTitle(true)
if !strings.HasPrefix(string(p.Body), "My back") {
t.Logf("The page title was not removed: %s", p.Body)
t.Fail()
}
}
func TestPagePlainText(t *testing.T) {
p := &Page{Body: []byte(`# Water
The air will not come
To inhale is an effort
The summer heat kills`)}
s := p.plainText()
r := "Water The air will not come To inhale is an effort The summer heat kills"
if s != r {
t.Logf("The plain text version is wrong: %s", s)
t.Fail()
}
}
func TestPageHtml(t *testing.T) {
p := &Page{Body: []byte(`# Sun
Silver leaves shine bright
They droop, boneless, weak and sad
A cruel sun stares down`)}
p.renderHtml()
s := string(p.Html)
r := `<h1>Sun</h1>
<p>Silver leaves shine bright
They droop, boneless, weak and sad
A cruel sun stares down</p>
`
if s != r {
t.Logf("The HTML is wrong: %s", s)
t.Fail()
}
}
func TestPageDir(t *testing.T) {
_ = os.RemoveAll("testdata")
loadIndex()
p := &Page{Name: "testdata/moon", Body: []byte(`# Moon
From bed to bathroom
A slow shuffle in the dark
Moonlight floods the aisle`)}
p.save()
o, err := loadPage("testdata/moon")
if err != nil || string(o.Body) != string(p.Body) {
t.Logf("File in subdirectory not loaded: %s", p.Name)
t.Fail()
}
t.Cleanup(func() {
_ = os.RemoveAll("testdata")
})
}

47
score.go Normal file
View File

@@ -0,0 +1,47 @@
package main
import (
"regexp"
"strings"
)
// score splits the query string q into terms and scores the text
// based on those terms. This assumes that q already has all its meta
// characters quoted.
func score(q string, s string) int {
score := 0
re, err := regexp.Compile("(?i)" + q)
if err == nil {
m := re.FindAllString(s, -1)
if m != nil {
// Score increases for each full match of q.
score += len(m)
}
}
for _, v := range strings.Split(q, " ") {
if len(v) == 0 {
continue
}
re, err := regexp.Compile(`(?is)(\pL?)(` + v + `)(\pL?)`)
if err != nil {
continue
}
for _, m := range re.FindAllStringSubmatch(s, -1) {
// Term matched increases the score.
score++
// Terms matching at the beginning and
// end of words and matching entire
// words increase the score further.
if len(m[1]) == 0 {
score++
}
if len(m[3]) == 0 {
score++
}
if len(m[1]) == 0 && len(m[3]) == 0 {
score++
}
}
}
return score
}

104
score_test.go Normal file
View File

@@ -0,0 +1,104 @@
package main
import (
"testing"
)
func TestScore(t *testing.T) {
s := `The windows opens
A wave of car noise hits me
No birds to be heard.`
q := "window"
// Score:
// - q itself
// - the single token
// - the beginning of a word
c := score(q, s)
if c != 3 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
q = "windows"
c = score(q, s)
// Score:
// - q itself
// - the single token
// - the beginning of a word
// - the end of a word
// - the whole word
if c != 5 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
q = "car noise"
c = score(q, s)
// Score:
// - car noise (+1)
// - car, with beginning, end, whole word (+4)
// - noise, with beginning, end, whole word (+4)
if c != 9 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
q = "noise car"
c = score(q, s)
// Score:
// - the car token
// - the noise token
// - each with beginning, end and whole token (3 each)
if c != 8 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
}
func TestScoreLong(t *testing.T) {
s := `We are immersed in a sea of dead people. All the dead that have gone before us, silent now, just staring, gaping. As we move and talk and fret, never once stopping to ask ourselves or them! what it was all about. Instead we drown ourselves in noise. Incessantly we babble, surrounded by false friends claiming that all is well. And look at us! Yes, we are well. Patting our backs and expecting a pat and we do! we smugly do enjoy.`
q := "all is well"
c := score(q, s)
// Score:
// - all is well (1)
// - all, beginning, end, whole word (+4 × 3 = 12)
// - is, beginning, end, whole word (+4 × 1 = 4), and as a substring (1)
// - well, beginning, end, whole word (+4 × 2 = 8)
if c != 26 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
}
func TestScoreSubstring(t *testing.T) {
s := `The loneliness of space means that receiving messages means knowledge that other people are out there. Not satellites pinging forever. Not bots searching and probing. Instead, humans. People who care. Curious and cautious.`
q := "search probe"
c := score(q, s)
// Score:
// - search, beginning (2)
// - probe (0)
if c != 2 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
q = "ear"
c = score(q, s)
// Score:
// - ear, all (2)
if c != 2 {
t.Logf("%s score is %d", q, c)
t.Fail()
}
}
func TestScorePageAndMarkup(t *testing.T) {
s := `The Transjovian Council accepts new members. If you think we'd be a good fit, apply for an account. Contact [Alex Schroeder](https://alexschroeder.ch/wiki/Contact). Mail is best. Encrypted mail is best. [Delta Chat](https://delta.chat/de/) is a messenger app that uses encrypted mail. It's the bestest best.`
p := &Page{Title: "Test", Name: "Test", Body: []byte(s)}
q := "wiki"
p.summarize(q)
// "wiki" is not visible in the plain text but the score is no affected:
// - wiki, all, whole, beginning, end (5)
if p.Score != 5 {
t.Logf("%s score is %d", q, p.Score)
t.Fail()
}
}

131
search.go Normal file
View File

@@ -0,0 +1,131 @@
package main
import (
"log"
"io/fs"
"path/filepath"
"slices"
"strings"
"unicode"
"unicode/utf8"
)
// idx is the global full text search index mapping tokens to docids
var idx index
// documents is an index of document names, i.e. it maps docids to file names in our case
var docs map[docid]string
// Search is a struct containing the result of a search. Query is the
// query string and Items is the array of pages with the result.
// Currently there is no pagination of results! When a page is part of
// a search result, Body and Html are simple extracts.
type Search struct {
Query string
Items []Page
Results bool
}
func indexAdd(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
filename := path
if info.IsDir() || strings.HasPrefix(filename, ".") || !strings.HasSuffix(filename, ".md") {
return nil
}
name := strings.TrimSuffix(filename, ".md")
p, err := loadPage(name)
if err != nil {
return err
}
id := idx.add(string(p.Body))
docs[id] = p.Name
return nil
}
func loadIndex() error {
idx = make(index)
docs = make(map[docid]string)
err := filepath.Walk(".", indexAdd)
if err != nil {
log.Print("Indexing failed")
idx = nil
docs = nil
}
return err
}
// updateIndex deletes the old page from the index before adding the
// new page, if an old page exists.
func (p *Page) updateIndex() {
var id docid
for docId, name := range docs {
if name == p.Name {
id = docId
break
}
}
if id == 0 {
id = idx.add(string(p.Body))
docs[id] = p.Name
} else {
o, err := loadPage(p.Name)
if err == nil {
idx.delete(string(o.Body), id)
}
id = idx.add(string(p.Body))
docs[id] = p.Name
}
}
// search returns a sorted []Page where each page contains an extract
// of the actual Page.Body in its Page.Html.
func search(q string) []Page {
if len(q) == 0 {
return make([]Page, 0)
}
ids := idx.search(q)
items := make([]Page, len(ids))
for i, id := range ids {
name := docs[id]
p, err := loadPage(name)
if err != nil {
log.Printf("Error loading %s", name)
} else {
p.summarize(q)
items[i] = *p
}
}
fn := func(a, b Page) int {
// Sort by score
if a.Score < b.Score {
return 1
} else if a.Score > b.Score {
return -1
}
// If the score is the same and both page names start
// with a number (like an ISO date), sort descending.
ra, _ := utf8.DecodeRuneInString(a.Title)
rb, _ := utf8.DecodeRuneInString(b.Title)
if unicode.IsNumber(ra) && unicode.IsNumber(rb) {
if a.Title < b.Title {
return 1
} else if a.Title > b.Title {
return -1
} else {
return 0
}
}
// Otherwise sort ascending.
if a.Title < b.Title {
return -1
} else if a.Title > b.Title {
return 1
} else {
return 0
}
}
slices.SortFunc(items, fn)
return items
}

42
search.html Normal file
View File

@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width">
<title>Search for {{.Query}}</title>
<style>
html { max-width: 65ch; padding: 2ch; margin: auto; color: #111; background: #ffe; }
body { hyphens: auto; }
header a { margin-right: 1ch; }
form { display: inline-block; }
img { max-width: 20%; }
.result { font-size: larger }
.score { font-size: smaller; opacity: 0.8; }
</style>
</head>
<body lang="en">
<header>
<a href="#main">Skip navigation</a>
<a href="/view/index">Home</a>
<form role="search" action="/search" method="GET">
<input type="text" value="{{.Query}}" spellcheck="false" name="q" required>
<button>Search</button>
</form>
</header>
<main id="main">
<h1>Search for {{.Query}}</h1>
{{if .Results}}
{{range .Items}}
<article lang="{{.Language}}">
<p><a class="result" href="/view/{{.Name}}">{{.Title}}</a>
<span class="score">{{.Score}}</span></p>
<blockquote>{{.Html}}</blockquote>
</article>
{{end}}
{{else}}
<p>No results.</p>
{{end}}
</main>
</body>
</html>

102
search_test.go Normal file
View File

@@ -0,0 +1,102 @@
package main
import (
"os"
"strings"
"testing"
)
var name string = "test"
// TestIndex relies on README.md being indexed
func TestSearch(t *testing.T) {
_ = os.Remove(name + ".md")
loadIndex()
q := "Oddµ"
pages := search(q)
if len(pages) == 0 {
t.Log("Search found no result")
t.Fail()
}
for _, p := range pages {
if strings.Contains(p.Title, "<b>") {
t.Logf("Page %s contains <b>", p.Name)
t.Fail()
}
if !strings.Contains(string(p.Body), q) && !strings.Contains(string(p.Title), q) {
t.Logf("Page %s does not contain %s", p.Name, q)
t.Fail()
}
if p.Score == 0 {
t.Logf("Page %s has no score", p.Name)
t.Fail()
}
}
p := &Page{Name: name, Body: []byte("This is a test.")}
p.save()
pages = search("This is a test")
found := false
for _, p := range pages {
if p.Name == name {
found = true
break
}
}
if !found {
t.Logf("Page '%s' was not found", name)
t.Fail()
}
pages = search("this is a test")
found = false
for _, p := range pages {
if p.Name == name {
found = true
break
}
}
if !found {
t.Logf("Page '%s' was not found using the lower case text", name)
t.Fail()
}
pages = search("this test")
found = false
for _, p := range pages {
if p.Name == name {
found = true
break
}
}
if !found {
t.Logf("Page '%s' was not found using a query missing some words", name)
t.Fail()
}
p = &Page{Name: name, Body: []byte("Guvf vf n grfg.")}
p.save()
pages = search("This is a test")
found = false
for _, p := range pages {
if p.Name == name {
found = true
break
}
}
if found {
t.Logf("Page '%s' was still found using the old content: %s", name, p.Body)
t.Fail()
}
pages = search("Guvf")
found = false
for _, p := range pages {
if p.Name == name {
found = true
break
}
}
if !found {
t.Logf("Page '%s' not found using the new content: %s", name, p.Body)
t.Fail()
}
t.Cleanup(func() {
_ = os.Remove(name + ".md")
})
}

93
snippets.go Normal file
View File

@@ -0,0 +1,93 @@
package main
import (
"regexp"
"strings"
)
// re returns a regular expression matching any word in q.
func re(q string) (*regexp.Regexp, error) {
q = regexp.QuoteMeta(q)
re, err := regexp.Compile(`\s+`)
if err != nil {
return nil, err
}
words := re.ReplaceAllString(q, "|")
re, err = regexp.Compile(`(?i)(` + words + `)`)
if err != nil {
return nil, err
}
return re, nil
}
func snippets(q string, s string) string {
// Look for Snippets
snippetlen := 100
maxsnippets := 4
re, err := re(q)
// If the compilation didn't work, truncate and return
if err != nil || len(s) <= snippetlen {
if len(s) > 400 {
s = s[0:400] + " …"
}
return s
}
// show a snippet from the beginning of the document
j := strings.LastIndex(s[:snippetlen], " ")
if j == -1 {
// OK, look for a longer word
j = strings.Index(s, " ")
if j == -1 {
// Or just truncate the body.
if len(s) > 400 {
s = s[0:400] + " …"
}
return highlight(q, re, s)
}
}
t := s[0:j]
res := t + " …"
s = s[j:] // avoid rematching
jsnippet := 0
for jsnippet < maxsnippets {
m := re.FindStringSubmatch(s)
if m == nil {
break
}
jsnippet++
j = strings.Index(s, m[1])
if j > -1 {
// get the substring containing the start of
// the match, ending on word boundaries
from := j - snippetlen/2
if from < 0 {
from = 0
}
start := strings.Index(s[from:], " ")
if start == -1 {
start = 0
} else {
start += from
}
to := j + snippetlen/2
if to > len(s) {
to = len(s)
}
end := strings.LastIndex(s[:to], " ")
if end == -1 {
// OK, look for a longer word
end = strings.Index(s[to:], " ")
if end == -1 {
end = len(s)
} else {
end += to
}
}
t = s[start:end]
res = res + t + " …"
// truncate text to avoid rematching the same string.
s = s[end:]
}
}
return highlight(q, re, res)
}

18
snippets_test.go Normal file
View File

@@ -0,0 +1,18 @@
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSnippets(t *testing.T) {
s := `We are immersed in a sea of dead people. All the dead that have gone before us, silent now, just staring, gaping. As we move and talk and fret, never once stopping to ask ourselves or them! what it was all about. Instead we drown ourselves in noise. Incessantly we babble, surrounded by false friends claiming that all is well. And look at us! Yes, we are well. Patting our backs and expecting a pat and we do! we smugly do enjoy.`
h1 := `We are immersed in a sea of dead people. <b>All</b> the dead that have gone before us, silent now, just … to ask ourselves or them! what it was <b>all</b> about. Instead we drown ourselves in no<b>is</b>e. … surrounded by false friends claiming that <b>all</b> <b>is</b> <b>well</b>. And look at us! Yes, we are <b>well</b>. …`
assert.Equal(t, h1, snippets("all is well", s))
h2 := `We are immersed in a sea of dead people. All the dead that have gone before us, silent now, just … And look at us! Yes, we are well. Patting our backs and expecting a pat and we do! we smugly do <b>enjoy</b>.`
assert.Equal(t, h2, snippets("enjoy", s))
}

41
tokenizer.go Normal file
View File

@@ -0,0 +1,41 @@
// Copyright 2020 Artem Krylysov
// Copyright 2023 Alex Schroeder
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This code was originally copied from
// https://github.com/akrylysov/simplefts
// https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/
//
// This file no longer does stemming and stop words.
package main
import (
"strings"
"unicode"
)
// tokenize returns a slice of tokens for the given text.
func tokenize(text string) []string {
return strings.FieldsFunc(text, func(r rune) bool {
// Split on any character that is not a letter or a number.
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})
}
// analyze analyzes the text and returns a slice of tokens.
func analyze(text string) []string {
tokens := tokenize(text)
tokens = lowercaseFilter(tokens)
return tokens
}

52
tokenizer_test.go Normal file
View File

@@ -0,0 +1,52 @@
// Copyright 2020 Artem Krylysov
// Copyright 2023 Alex Schroeder
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This code was originally copied from
// https://github.com/akrylysov/simplefts
// https://artem.krylysov.com/blog/2020/07/28/lets-build-a-full-text-search-engine/
//
// This file no longer does stemming and stop words.
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTokenizer(t *testing.T) {
testCases := []struct {
text string
tokens []string
}{
{
text: "",
tokens: []string{},
},
{
text: "a",
tokens: []string{"a"},
},
{
text: "small wild,cat!",
tokens: []string{"small", "wild", "cat"},
},
}
for _, tc := range testCases {
t.Run(tc.text, func(st *testing.T) {
assert.EqualValues(st, tc.tokens, tokenize(tc.text))
})
}
}

View File

@@ -6,15 +6,32 @@
<meta name="viewport" content="width=device-width">
<title>{{.Title}}</title>
<style>
html { max-width: 70ch; padding: 2ch; margin: auto; color: #111; background: #ffe; }
html { max-width: 65ch; padding: 1ch; margin: auto; color: #111; background: #ffe; }
body { hyphens: auto; }
header a { margin-right: 1ch; }
form { display: inline-block; }
footer { border-top: 1px solid #888 }
img { max-width: 100%; }
</style>
</head>
<body>
<h1>{{.Title}}</h1>
<p><a href="/edit/{{.Name}}">Edit this page</a></p>
<div>
{{.Html}}
</div>
<body lang="{{.Language}}">
<header>
<a href="#main">Skip navigation</a>
<a href="/view/index">Home</a>
<a href="/edit/{{.Name}}">Edit this page</a>
<form role="search" action="/search" method="GET">
<input type="text" spellcheck="false" name="q" required>
<button>Search</button>
</form>
</header>
<main id="main">
<h1>{{.Title}}</h1>
{{.Html}}
</main>
<footer>
<address>
Comments? Send mail to Alex Schroeder <<a href="mailto:alex@alexschroeder.ch">alex@alexschroeder.ch</a>>
</address>
</footer>
</body>
</html>

155
wiki.go
View File

@@ -1,113 +1,136 @@
package main
import (
"github.com/microcosm-cc/bluemonday"
"github.com/gomarkdown/markdown"
"fmt"
"html/template"
"net/http"
"strings"
"regexp"
"bytes"
"fmt"
"os"
"regexp"
"strings"
)
var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
// Templates are parsed at startup.
var templates = template.Must(template.ParseFiles("edit.html", "view.html", "search.html"))
var validPath = regexp.MustCompile("^/(edit|save|view)/(([a-z]+/)?[^/]+)$")
// validPath is a regular expression where the second group matches a
// page, so when the handler for "/edit/" is called, a URL path of
// "/edit/foo" results in the editHandler being called with title
// "foo". The regular expression doesn't define the handlers (this
// happens in the main function).
var validPath = regexp.MustCompile("^/([^/]+)/(.+)$")
// titleRegexp is a regular expression matching a level 1 header line
// in a Markdown document. The first group matches the actual text and
// is used to provide an title for pages. If no title exists in the
// document, the page name is used instead.
var titleRegexp = regexp.MustCompile("(?m)^#\\s*(.*)\n+")
type Page struct {
Title string
Name string
Body []byte
Html template.HTML
}
func (p *Page) save() error {
filename := p.Name + ".md"
return os.WriteFile(filename, bytes.ReplaceAll(p.Body, []byte{'\r'}, []byte{}), 0600)
}
func loadPage(title string) (*Page, error) {
filename := title + ".md"
body, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Name: title, Body: body}, nil
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
err := templates.ExecuteTemplate(w, tmpl+".html", p)
// renderTemplate is the helper that is used render the templates with
// data.
func renderTemplate(w http.ResponseWriter, tmpl string, data any) {
err := templates.ExecuteTemplate(w, tmpl+".html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// rootHandler just redirects to /view/index.
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/view/index", http.StatusFound)
}
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
// viewHandler renders a text file, if the name ends in ".txt" and
// such a file exists. Otherwise, it loads the page. If this didn't
// work, the browser is redirected to an edit page. Otherwise, the
// "view.html" template is used to show the rendered HTML.
func viewHandler(w http.ResponseWriter, r *http.Request, name string) {
// Short cut for text files
if (strings.HasSuffix(title, ".txt")) {
body, err := os.ReadFile(title)
if strings.HasSuffix(name, ".txt") {
body, err := os.ReadFile(name)
if err == nil {
w.Write(body)
return
}
}
// Attempt to load Markdown page; edit it if this fails
p, err := loadPage(title)
p, err := loadPage(name)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
http.Redirect(w, r, "/edit/"+name, http.StatusFound)
return
}
// Render the Markdown to HTML, extracting a title and
// possibly sanitizing it
s := string(p.Body)
m := titleRegexp.FindStringSubmatch(s)
if m != nil {
p.Title = m[1]
p.Body = []byte(strings.Replace(s, m[0], "", 1))
}
maybeUnsafeHTML := markdown.ToHTML(p.Body, nil, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)
p.Html = template.HTML(html);
p.handleTitle(true)
p.renderHtml()
renderTemplate(w, "view", p)
}
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
// editHandler uses the "edit.html" template to present an edit page.
// When editing, the page title is not overriden by a title in the
// text. Instead, the page name is used.
func editHandler(w http.ResponseWriter, r *http.Request, name string) {
p, err := loadPage(name)
if err != nil {
p = &Page{Title: title, Name: title}
p = &Page{Title: name, Name: name}
} else {
p.handleTitle(false)
}
renderTemplate(w, "edit", p)
}
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
// saveHandler takes the "body" form parameter and saves it. The
// browser is redirected to the page view.
func saveHandler(w http.ResponseWriter, r *http.Request, name string) {
body := r.FormValue("body")
p := &Page{Title: title, Name: title, Body: []byte(body)}
p := &Page{Name: name, Body: []byte(body)}
err := p.save()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
http.Redirect(w, r, "/view/"+name, http.StatusFound)
}
func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
// makeHandler returns a handler that uses the URL path without the
// first path element as its argument, e.g. if the URL path is
// /edit/foo/bar, the editHandler is called with "foo/bar" as its
// argument. This uses the second group from the validPath regular
// expression.
func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
if m != nil {
fn(w, r, m[2])
} else {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}
// searchHandler presents a search result. It uses the query string in
// the form parameter "q" and the template "search.html". For each
// page found, the HTML is just an extract of the actual body.
func searchHandler(w http.ResponseWriter, r *http.Request) {
q := r.FormValue("q")
items := search(q)
s := &Search{Query: q, Items: items, Results: len(items) > 0}
renderTemplate(w, "search", s)
}
// searchCommand prints a search result to the command line.
func searchCommand() {
q := strings.Join(os.Args[1:], " ")
fmt.Println("Indexing all pages")
loadIndex()
fmt.Printf("Searching for %s\n", q)
for _, p := range search(q) {
t := strings.ReplaceAll(string(p.Html), "<b>", "\033[31;1m")
t = strings.ReplaceAll(t, "</b>", "\033[0m")
fmt.Printf("%s.md\n" + "\033[1;4m%s\033[0m (%d)\n" + "%s\n\n",
p.Name, p.Title, p.Score, t)
}
}
// getPort returns the environment variable ODDMU_PORT or the default
// port, "8080".
func getPort() string {
port := os.Getenv("ODDMU_PORT")
if port == "" {
@@ -116,13 +139,23 @@ func getPort() string {
return port
}
func main() {
func serve() {
http.HandleFunc("/", rootHandler)
http.HandleFunc("/view/", makeHandler(viewHandler))
http.HandleFunc("/edit/", makeHandler(editHandler))
http.HandleFunc("/save/", makeHandler(saveHandler))
http.HandleFunc("/search", searchHandler)
fmt.Println("Indexing all pages")
loadIndex()
port := getPort()
fmt.Println("Serving a wiki on port " + port)
http.ListenAndServe(":" + port, nil)
fmt.Printf("Serving a wiki on port %s\n", port)
http.ListenAndServe(":"+port, nil)
}
func main() {
if len(os.Args) > 1 {
searchCommand()
} else {
serve()
}
}