func SplitToDocumentSections()

in pkg/document/generator/splitter.go [49:113]


func SplitToDocumentSections(text string) ([]*DocumentSection, error) {
	lines := strings.Split(text, "\n")
	var sections []*DocumentSection
	var currentSection *DocumentSection

	for lineIndex, line := range lines {
		lineWithoutSpace := strings.TrimSpace(line)
		if strings.HasPrefix(lineWithoutSpace, beginGeneratedSectionPrefix) && strings.HasSuffix(lineWithoutSpace, generatedSectionSuffix) {
			if currentSection != nil {
				if currentSection.Type == SectionTypeGenerated {
					return nil, fmt.Errorf("invalid begin of section. section began twice. line %d", lineIndex+1)
				}
				sections = append(sections, currentSection)
			}
			id := readIdFromGeneratedSectionComment(lineWithoutSpace)
			currentSection = &DocumentSection{
				Type: SectionTypeGenerated,
				ID:   id,
				Body: line,
			}
			continue
		}
		if strings.HasPrefix(lineWithoutSpace, endGeneratedSectionPrefix) && strings.HasSuffix(lineWithoutSpace, generatedSectionSuffix) {
			id := readIdFromGeneratedSectionComment(lineWithoutSpace)
			if currentSection == nil {
				return nil, fmt.Errorf("invalid end of section. section id %s ended but not began. line %d", id, lineIndex+1)
			}
			if currentSection.ID != id {
				return nil, fmt.Errorf("invalid end of section. section id %s ended but the id is not matching with the previous section id %s. line %d", id, currentSection.ID, lineIndex+1)
			}
			currentSection.Body += "\n" + line
			sections = append(sections, currentSection)
			currentSection = nil
			continue
		}

		if currentSection == nil {
			currentSection = &DocumentSection{
				Type: SectionTypeAmend,
				ID:   "",
				Body: line,
			}
			continue
		}

		currentSection.Body += "\n" + line
	}

	if currentSection != nil {
		if currentSection.Type == SectionTypeGenerated {
			return nil, fmt.Errorf("invalid end of section. section id %s began but not ended", currentSection.ID)
		}
		if currentSection.Body != "" {
			sections = append(sections, currentSection)
		}
	}

	for _, section := range sections {
		// generate section id for amended section. This uses hash just because I don't want to use random string to improve testability.
		if section.ID == "" {
			section.ID = getHashFromText(section.Body)
		}
	}
	return sections, nil
}