summaryrefslogtreecommitdiff
path: root/model/new.go
blob: cddb404a28ed9ee5c394fe5c9a33784ff9f48534 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package model

import (
	"errors"
	"io/fs"
	"path/filepath"
	"pik/identity"
	"strings"
	"sync"
)

func NewState(f fs.FS, locations []string, indexers []Indexer, runners []Runner) (*State, []error) {
	var errs []error
	st := &State{}
	wg := sync.WaitGroup{}
	var sources = make([]*Source, len(locations), len(locations))
	for i, loc := range locations {
		wg.Go(func() {
			_, dirName := filepath.Split(strings.TrimSuffix(loc, "/"))
			src := &Source{
				Path:     loc,
				Identity: identity.New(dirName),
			}
			sources[i] = src
			loc = strings.TrimSuffix(loc, "/")
			loc = strings.TrimPrefix(loc, "/")

			if loc == "" {
				return
			}

			myWg := sync.WaitGroup{}
			var targets = make([][]Target, len(indexers), len(indexers))
			for ti, indexer := range indexers {
				myWg.Go(func() {
					s, err := fs.Sub(f, loc)
					if err != nil && !errors.Is(err, fs.ErrNotExist) {
						errs = append(errs, err)
						return
					}
					result, err := indexer.Index("/"+loc, s, runners)
					if err != nil && !errors.Is(err, fs.ErrNotExist) {
						errs = append(errs, err)
						return
					}
					targets[ti] = result
				})
			}
			myWg.Wait()

			for _, t := range targets {
				if t == nil {
					continue
				}
				sources[i].Targets = append(sources[i].Targets, t...)
			}

		})

	}
	wg.Wait()

	for _, s := range sources {
		if s == nil || s.Targets == nil {
			continue
		}
		st.Sources = append(st.Sources, s)
	}

	return st, errs
}