Collect aliases

This commit is contained in:
Niko Abeler 2022-08-06 19:38:13 +02:00
parent 5739a9348c
commit f07a913129
4 changed files with 86 additions and 0 deletions

13
post.go
View File

@ -69,3 +69,16 @@ func (post Post) MarkdownData() (bytes.Buffer, map[string]interface{}) {
return buf, metaData
}
func (post Post) Aliases() []string {
_, metaData := post.MarkdownData()
if metaData["aliases"] != nil {
alias_data := metaData["aliases"].([]interface{})
aliases := make([]string, 0)
for _, alias := range alias_data {
aliases = append(aliases, alias.(string))
}
return aliases
}
return []string{}
}

View File

@ -161,3 +161,21 @@ func (repo Repository) GetUser(name string) (User, error) {
}
return user, nil
}
func (repo Repository) PostAliases() (map[string]*Post, error) {
users, err := repo.Users()
if err != nil {
return nil, err
}
aliases := make(map[string]*Post)
for _, user := range users {
user_aliases, err := user.PostAliases()
if err != nil {
return nil, err
}
for alias, post := range user_aliases {
aliases[alias] = post
}
}
return aliases, nil
}

View File

@ -237,3 +237,40 @@ func TestSingleUserRepoUserUrlPathIsSimple(t *testing.T) {
t.Error("User url is not '/'. Got: ", user.UrlPath())
}
}
func TestCanGetMapWithAllPostAliases(t *testing.T) {
repo, _ := owl.CreateRepository(testRepoName())
user, _ := repo.CreateUser(randomUserName())
post, _ := user.CreateNewPost("test-1")
content := "---\n"
content += "title: Test\n"
content += "aliases: \n"
content += " - /foo/bar\n"
content += " - /foo/baz\n"
content += "---\n"
content += "This is a test"
os.WriteFile(post.ContentFile(), []byte(content), 0644)
posts, _ := user.Posts()
if len(posts) != 1 {
t.Error("Wrong number of posts returned, expected 1, got ", len(posts))
}
var aliases map[string]*owl.Post
aliases, err := repo.PostAliases()
if err != nil {
t.Error("Error getting post aliases: ", err.Error())
}
if len(aliases) != 2 {
t.Error("Wrong number of aliases returned, expected 2, got ", len(aliases))
t.Error("Aliases: ", aliases)
}
if aliases["/foo/bar"] == nil {
t.Error("Alias '/foo/bar' not found")
}
if aliases["/foo/baz"] == nil {
t.Error("Alias '/foo/baz' not found")
}
}

18
user.go
View File

@ -137,3 +137,21 @@ func (user User) SetConfig(new_config UserConfig) error {
}
return nil
}
func (user User) PostAliases() (map[string]*Post, error) {
post_aliases := make(map[string]*Post)
posts, err := user.Posts()
if err != nil {
return post_aliases, err
}
for _, id := range posts {
post, err := user.GetPost(id)
if err != nil {
return post_aliases, err
}
for _, alias := range post.Aliases() {
post_aliases[alias] = &post
}
}
return post_aliases, nil
}