package cop import ( "encoding/json" "errors" "fmt" "io/fs" "log" "os" "path" "path/filepath" "strings" "github.com/go-git/go-git/v5" "gitea.mmo.to/ppForge/ppforge/globals" "gitea.mmo.to/ppForge/ppforge/protocol" ) // GlobalCOP is the global variable holding the protocol collections, var GlobalCOP *ProtocolCollectionList = &ProtocolCollectionList{[]COP{}} // ProtocolCollectionList is a list of all databases, with the most simple interface type ProtocolCollectionList struct { PCs []COP } // WriteCache updates the cache file of the available protocols func (pcl *ProtocolCollectionList) WriteCache() error { // [impl->dsn~protocol-collection-cache~0>>utest] data, err := json.MarshalIndent(pcl, "", " ") if err != nil { return err } err = os.WriteFile(path.Join(globals.CollectionOfProtocolsDir, globals.COPCacheFileName), data, 0644) return err } // ReadCache reads the cache for display func (pcl *ProtocolCollectionList) ReadCache() error { // [impl->dsn~protocol-collection-cache~0>>utest] // TODO: Think about if it makes sense to have this function as a member of PCL, // or if it makes more sense to make this function standalone and return a new PCL? data, err := os.ReadFile(path.Join(globals.CollectionOfProtocolsDir, globals.COPCacheFileName)) if err != nil { return err } //fmt.Println(string(data)) err = json.Unmarshal(data, pcl) data, err = json.MarshalIndent(pcl, "", " ") fmt.Println(string(data)) return err } // ProtocolCollectionEntry is a single entry in the file database, additionally to the meta data the path is required type ProtocolCollectionEntry struct { Path string Protocol protocol.ProtocolMeta } // Init initializes the databases, opens the default one and checks for others if available func init() { Init() } // Init the global COP func Init() { // initialize default db fdb := FileCOP{COP{map[string]ProtocolCollectionEntry{}, false}, globals.CollectionOfProtocolsDir} err := fdb.Open(globals.CollectionOfProtocolsDir) if err != nil { log.Printf("Error opening global COP dir: %v", err) return } err = fdb.Sync() if err != nil { log.Printf("Error on initial syncing of the global COP dir: %v", err) return } GlobalCOP.PCs = append(GlobalCOP.PCs, fdb.COP) log.Printf("Amount of databases available %d", len(GlobalCOP.PCs)) } // GetCOP returns the global collection of Protocols func GetCOP() *ProtocolCollectionList { return GlobalCOP } // COP represents a Collection of Protocols type COP struct { Protocols map[string]ProtocolCollectionEntry closed bool } // COPer interface defines the functions a CollectionOfProtocols should have at least. type COPer interface { Open(string) error Close() error GetProtocols() ([]ProtocolCollectionEntry, error) Add(*protocol.Protocol) error Sync() error Update(*protocol.Protocol) error Get(string) (*protocol.Protocol, error) } // FileCOP implements type FileCOP struct { COP Path string } // FileCOPFromGitRemote implements retrieving the latest stuff from an external git remote additionally to the FileDatabase functionality type FileCOPFromGitRemote struct { FileCOP RemoteGitRepository string gitRepo git.Repository } // NewFileCOP returns a new FileCOP instance from a given path func NewFileCOP(path string) (*FileCOP, error) { fCOP := &FileCOP{} err := fCOP.Open(path) if err != nil { log.Printf("Error opening file COP at %s: %v", path, err) return nil, err } err = fCOP.Sync() return fCOP, err } // Open the database func (fd *FileCOP) Open(path string) error { fileinfo, err := os.Stat(path) if err == os.ErrNotExist { return err } if fileinfo == nil || !fileinfo.IsDir() { return fmt.Errorf("Path %s is not a directory or does not exist", path) } fd.Path = path fd.closed = false return nil } // Close the database and free the data func (fd *FileCOP) Close() error { fd.closed = true return nil } // GetProtocols returns the map of protocols or an error if the first read failed func (fd *FileCOP) GetProtocols() ([]ProtocolCollectionEntry, error) { if fd.closed { return nil, errors.New("COP closed, no protocols to deliver") } entries := []ProtocolCollectionEntry{} if !fd.closed && len(fd.Protocols) == 0 { fd.Protocols = map[string]ProtocolCollectionEntry{} err := fd.Sync() if err != nil { return nil, err } } if entries == nil || len(entries) == 0 { entries = make([]ProtocolCollectionEntry, 0) for _, v := range fd.Protocols { entries = append(entries, v) } } return entries, nil } // Add puts a new protocol into the path of the file database func (fd *FileCOP) Add(prot *protocol.Protocol) error { if fd.closed { return errors.New("Cannot add, FileCOP is closed") } p := path.Join(fd.Path, prot.Metadata.Name, ".protocoljson") err := prot.Save(p) if err == nil { fd.Protocols[prot.Metadata.Name] = ProtocolCollectionEntry{p, prot.Metadata} } return err } // Update updates an existing entry through saving the contents of the protocol to the file, or just adding it anew func (fd *FileCOP) Update(prot *protocol.Protocol) error { if fd.closed { return errors.New("Cannot update, FileCOP is closed") } if v, ok := fd.Protocols[prot.Metadata.Name]; ok { v.Protocol = prot.Metadata return prot.Save(v.Path) } return fd.Add(prot) } // Sync just rereads all files func (fd *FileCOP) Sync() error { if fd.closed { return errors.New("Cannot sync, FileCOP is closed") } // recurse recursively through the path if fd.Protocols == nil { fd.Protocols = make(map[string]ProtocolCollectionEntry) } err := filepath.Walk(fd.Path, func(path string, info fs.FileInfo, err error) error { if !info.IsDir() && strings.HasSuffix(info.Name(), ".protocoljson") { prot, err := protocol.LoadNew(path) if err == nil { // add to map // add to map entry := ProtocolCollectionEntry{path, prot.Metadata} fd.Protocols[prot.Metadata.Name] = entry } return err } return nil }) return err } // Get a protocol by name func (fd *FileCOP) Get(prot string) (*protocol.Protocol, error) { entry := fd.Protocols[prot] return protocol.LoadNew(entry.Path) }