go-projecttxt/project.go
2022-06-07 13:50:33 -05:00

116 lines
2.9 KiB
Go

package projecttxt
import (
"fmt"
"sort"
"strings"
)
type Project struct {
Id int // Internal project id
Original string // Original raw project text
Name string // The name of the project
Directory string // The directory part of the project text
Contexts []string
ProjectTags []string
AdditionalTags map[string]string
}
// ParseProject parses the input text string into a Project struct
func ParseProject(text string) (*Project, error) {
var err error
project := Project{
AdditionalTags: make(map[string]string),
}
project.Original = strings.Trim(text, "\t\n\r ")
parts := strings.Fields(project.Original)
project.Name, parts = parts[0], parts[1:]
if parts[1][0] == '^' {
project.Directory, parts = parts[0], parts[1:]
}
for _, v := range parts {
switch v[0] {
case '@': // Contexts
project.Contexts = append(project.Contexts, v[1:])
case '+': // ProjectTags
project.ProjectTags = append(project.ProjectTags, v[1:])
default:
if strings.Contains(v, ":") {
// Additional Tags
tagPts := strings.Split(v, ":")
if tagPts[0] != "" && tagPts[1] != "" {
project.AdditionalTags[tagPts[0]] = tagPts[1]
}
}
}
}
return &project, err
}
// String returns a complete project string in project.txt format.
//
// Contexts, ProjectTags, and Additional Tags are alphabetically sorted,
// and appended at the end in the following order:
// Contexts, ProjectTags, Tags
//
// For example:
// Project.txt ^/home/user/projects/projecttxt @personal +projectxt contact:"Frank Workman" "Address 1":"1234 Work Place"
func (project Project) String() string {
text := fmt.Sprintf("%s ", project.Name)
text += fmt.Sprintf("%s ", project.Directory)
if len(project.Contexts) > 0 {
sort.Strings(project.Contexts)
for _, context := range project.Contexts {
text += fmt.Sprintf("@%s ", context)
}
}
if len(project.ProjectTags) > 0 {
sort.Strings(project.ProjectTags)
for _, pTag := range project.ProjectTags {
text += fmt.Sprintf("+%s ", pTag)
}
}
if len(project.AdditionalTags) > 0 {
keys := make([]string, 0, len(project.AdditionalTags))
for key := range project.AdditionalTags {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
text += fmt.Sprintf("%s:%s ", key, project.AdditionalTags[key])
}
}
return text
}
func (project *Project) HasContext(context string) bool {
for _, v := range project.Contexts {
if v == context {
return true
}
}
return false
}
func (project *Project) HasProjectTag(projectTag string) bool {
for _, v := range project.ProjectTags {
if v == projectTag {
return true
}
}
return false
}
func (project *Project) SetTag(name, val string) {
project.AdditionalTags[name] = val
}
func (project *Project) HasTag(name string) bool {
_, ok := project.AdditionalTags[name]
return ok
}
func (project *Project) GetTag(name string) string {
return project.AdditionalTags[name]
}