summaryrefslogtreecommitdiff
path: root/search/search.go
blob: 5b227b2f9346a9ed968afc3e081c560449589d83 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package search

import (
	"pik/model"
	"slices"
)

func Search(s *model.State, args ...string) (model.Target, *model.Source, bool, []string, []string) {
	var target model.Target
	var suspect model.Target
	var suspectSource *model.Source
	var targetSource *model.Source
	var forward []string
	var subdir []string
	confirm := false

args_loop:
	for _, a := range args {
		for _, src := range s.Sources {

			if targetSource == nil {
				if src.Is(a) {
					targetSource = src
					for _, t := range targetSource.Targets {
						if t.Matches(a) {
							target = t
							continue args_loop
						}
					}
					continue args_loop
				}
			}

			if target == nil && targetSource == nil {
				for _, t := range src.Targets {
					if t.Matches(a) {
						target = t
						targetSource = src
						continue args_loop
					}
				}
			} else if target == nil { // && targetSource == nil (but it is always true)
				for _, t := range targetSource.Targets {
					if t.Matches(a) {
						target = t
						continue args_loop
					}
				}
				// if we find the right target
				for _, t := range src.Targets {
					if t.Matches(a) {
						confirm = true
						suspect = t
						suspectSource = src
						continue args_loop
					}
				}
			}

		}

		if target == nil {
			subdir = append(subdir, a)
			continue args_loop
		} else if targetSource != nil {
			forward = append(forward, a)
			continue args_loop
		}
	}

	if suspect != nil && target == nil {
		target = suspect
		targetSource = suspectSource
		confirm = true
	}

	if target != nil && target.Sub() != nil && subdir != nil && !slices.Equal(target.Sub(), subdir) {
		confirm = true
	}

	if target == nil {
		forward = args
	}

	return target, targetSource, confirm, subdir, forward
}