arns-lt-tree-push-service/server.go
Arnas Udovicius 18d8a03e09
All checks were successful
continuous-integration/drone/push Build is passing
add rebuild gprc command
2022-08-22 22:53:27 +03:00

127 lines
2.3 KiB
Go

package main
import (
"context"
"google.golang.org/grpc"
"log"
"net"
"os"
"path/filepath"
zordTree "g.arns.lt/zordsdavini/zord-tree"
)
type server struct {
UnimplementedTreeManagerServer
}
func (TreeManagerServer *server) GetSummery(_ context.Context, in *TreeRequest) (*Tree, error) {
log.Println(in)
tree, err := zordTree.BuildTree(dest, meta)
if err != nil {
log.Fatal(err)
return nil, err
}
if *in.Path != "" {
ntree, err := tree.Slice(dest + *in.Path)
if err != nil {
log.Fatal(err)
return &Tree{}, err
}
tree = ntree
}
if len(in.Filter) != 0 {
ntree, found := tree.Filter(simplifyFilter(in.Filter))
if !found {
return &Tree{}, err
}
tree = ntree
}
formattedTree := FormatTreeSummery(tree)
return &formattedTree, nil
}
func (TreeManagerServer *server) GetFile(_ context.Context, in *FileRequest) (*FileContent, error) {
log.Println(in)
tree, err := zordTree.BuildTree(dest, meta)
if err != nil {
log.Fatal(err)
return nil, err
}
file, err := tree.FileById(in.Id)
if err != nil {
return nil, err
}
fileContent := GetContent(file)
return &fileContent, nil
}
func (TreeManagerServer *server) RebuildTree(ctx context.Context, in *TreeSecret) (*RebuildResponse, error) {
success := false
if in.Key == key {
err := removeContents(dest)
if err == nil {
Collect()
success = true
}
}
response := RebuildResponse{Success: success}
return &response, nil
}
func removeContents(dir string) error {
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
}
return nil
}
func simplifyFilter(filter []*TreeRequest_Filter) map[string]string {
simpleFilter := make(map[string]string)
for _, f := range filter {
simpleFilter[f.Key] = f.Value
}
return simpleFilter
}
func Run() {
if _, err := os.Stat(dest); os.IsNotExist(err) {
log.Fatalf("Destination directory does not exist.")
}
ln, err := net.Listen("tcp", ":8301")
if err != nil {
log.Fatalf("Failed to listen: " + err.Error())
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
RegisterTreeManagerServer(grpcServer, &server{})
err = grpcServer.Serve(ln)
if err != nil {
log.Fatalf("failed to serve: %v", err)
}
}