Files
mark/pkg/mark/ancestry.go

148 lines
2.6 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"
"github.com/reconquest/karma-go"
2020-11-03 17:12:51 +03:00
"github.com/reconquest/pkg/log"
2019-04-08 22:44:27 +03:00
)
func EnsureAncestry(
dryRun bool,
2019-04-08 22:44:27 +03:00
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(
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, ` > `),
)
if !dryRun {
for _, title := range rest {
page, err := api.CreatePage(space, parent, title, ``)
if err != nil {
return nil, karma.Format(
err,
`error during creating parent page with title %q`,
title,
)
}
parent = page
2019-04-08 22:44:27 +03:00
}
} else {
log.Infof(
nil,
"skipping page creation due to enabled dry-run mode, "+
"need to create %d pages: %v",
len(rest),
rest,
)
2019-04-08 22:44:27 +03:00
}
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, ` > `),
)
}
for _, parent := range ancestry[:len(ancestry)-1] {
found := false
// skipping root article title
for _, ancestor := range page.Ancestors[1:] {
if ancestor.Title == parent {
found = true
break
}
}
if !found {
list := []string{}
for _, ancestor := range page.Ancestors[1:] {
list = append(list, ancestor.Title)
}
return nil, karma.Describe("expected parent", parent).
Describe("list", strings.Join(list, "; ")).
Format(
nil,
"unexpected ancestry tree, did not find expected parent page in the tree",
)
2019-04-08 22:44:27 +03:00
}
}
return page, nil
}