Files
mark/pkg/mark/ancestry.go

123 lines
2.2 KiB
Go
Raw Normal View History

2019-04-08 22:44:27 +03:00
package mark
import (
"fmt"
"strings"
"github.com/kovetskiy/mark/pkg/confluence"
2019-08-02 22:58:08 +03:00
"github.com/kovetskiy/mark/pkg/log"
2019-04-08 22:44:27 +03:00
"github.com/reconquest/karma-go"
)
func EnsureAncestry(
api *confluence.API,
space string,
ancestry []string,
) (*confluence.PageInfo, error) {
var parent *confluence.PageInfo
rest := ancestry
for i, title := range ancestry {
page, err := api.FindPage(space, title)
if err != nil {
return nil, karma.Format(
err,
2019-04-19 10:31:41 +03:00
`error during finding parent page with title %q`,
2019-04-08 22:44:27 +03:00
title,
)
}
if page == nil {
break
}
2019-04-20 10:24:30 +03:00
log.Debugf(nil, "parent page %q exists: %s", title, page.Links.Full)
2019-04-08 22:44:27 +03:00
rest = ancestry[i:]
parent = page
}
if parent != nil {
rest = rest[1:]
} else {
page, err := api.FindRootPage(space)
if err != nil {
return nil, karma.Format(
err,
2019-04-19 10:31:41 +03:00
"can't find root page for space %q",
space,
2019-04-08 22:44:27 +03:00
)
}
parent = page
}
if len(rest) == 0 {
return parent, nil
}
2019-08-02 22:58:08 +03:00
log.Debugf(
2019-08-20 19:05:37 +03:00
nil,
2019-04-19 10:31:41 +03:00
"empty pages under %q to be created: %s",
2019-04-08 22:44:27 +03:00
parent.Title,
strings.Join(rest, ` > `),
)
for _, title := range rest {
page, err := api.CreatePage(space, parent, title, ``)
if err != nil {
return nil, karma.Format(
err,
2019-04-19 10:31:41 +03:00
`error during creating parent page with title %q`,
2019-04-08 22:44:27 +03:00
title,
)
}
parent = page
}
return parent, nil
}
func ValidateAncestry(
api *confluence.API,
space string,
ancestry []string,
) (*confluence.PageInfo, error) {
page, err := api.FindPage(space, ancestry[len(ancestry)-1])
if err != nil {
return nil, err
}
if page == nil {
return nil, nil
}
if len(page.Ancestors) < 1 {
2019-04-19 10:31:41 +03:00
return nil, fmt.Errorf(`page %q has no parents`, page.Title)
2019-04-08 22:44:27 +03:00
}
if len(page.Ancestors) < len(ancestry) {
return nil, fmt.Errorf(
2019-04-19 10:31:41 +03:00
"page %q has fewer parents than specified: %s",
2019-04-08 22:44:27 +03:00
page.Title,
strings.Join(ancestry, ` > `),
)
}
// skipping root article title
for i, ancestor := range page.Ancestors[1:len(ancestry)] {
if ancestor.Title != ancestry[i] {
return nil, fmt.Errorf(
"broken ancestry tree; expected tree: %s; "+
2019-04-19 10:31:41 +03:00
"encountered %q at position of %q",
2019-04-08 22:44:27 +03:00
strings.Join(ancestry, ` > `),
ancestor.Title,
ancestry[i],
)
}
}
return page, nil
}