summaryrefslogtreecommitdiff
path: root/main.go
blob: 8b905d8a5dabc427fafa370f68063b8c1626f675 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package main

import (
	_ "embed"
	"errors"
	"fmt"
	"github.com/ewy1/pik/cache"
	"github.com/ewy1/pik/crawl"
	"github.com/ewy1/pik/flags"
	"github.com/ewy1/pik/git"
	"github.com/ewy1/pik/indexers/pikdex"
	"github.com/ewy1/pik/menu"
	"github.com/ewy1/pik/model"
	"github.com/ewy1/pik/paths"
	"github.com/ewy1/pik/run"
	"github.com/ewy1/pik/runner/exc"
	"github.com/ewy1/pik/runner/gnumake"
	"github.com/ewy1/pik/runner/js"
	"github.com/ewy1/pik/runner/just"
	"github.com/ewy1/pik/runner/python"
	"github.com/ewy1/pik/runner/shell"
	"github.com/ewy1/pik/search"
	"github.com/ewy1/pik/spool"
	"github.com/spf13/pflag"
	"os"
	"runtime/pprof"
)

// syncInitializers are ran before the initializers.
// useful for initializing stuff like paths, preparing directories, and reading the environment
var syncInitializers = ComponentList[model.Initializer]{
	paths.Component,
	cache.Init,
}

// initializers are ran before indexing with the indexers,
// data from the syncInitializers can be accessed at this time.
var initializers = ComponentList[model.Initializer]{
	pikdex.Indexer,
	python.Python,
	git.Git,
	js.Js,
}

// indexers are methods which scan a directory and return a number of targets.
var indexers = ComponentList[model.Indexer]{
	pikdex.Indexer,
	just.Indexer,
	gnumake.Indexer,
	js.Js,
}

// runners are modules which know how to turn a file into an exec.Cmd
// all indexers have access to these but only pikdex uses it
var runners = ComponentList[model.Runner]{
	shell.Runner,
	python.Python,
	exc.Exc,
	js.Js,
}

// hydrators are ran when the menu is required
// for example adding git info, descriptions, icons...
var hydrators = ComponentList[model.Modder]{
	pikdex.Indexer,
	git.Git,
}

// ForceConfirm means we will have to ask for confirmation before running no matter what
var ForceConfirm = false

// SourcesWithoutResults is a failed cache from the previous iteration
// used for stripping out results to prevent double-index
var SourcesWithoutResults *cache.Cache

//go:embed version.txt
var version string

func main() {
	result := pik()
	if profileFd != nil {
		pprof.StopCPUProfile()
		err := profileFd.Close()
		if err != nil {
			_, _ = spool.Warn("%v\n", err)
		}
	}
	if result != 0 {
		os.Exit(result)
	}
}

func mode[T any](list ModeMap[T], fire func(mode T) error) *int {
	err := list.Traverse(func(in T) error {
		return fire(in)
	})
	if errors.Is(err, Success) {
		zero := 0
		return &zero
	} else if err != nil {
		_, _ = spool.Warn("%v\n", err)
		one := 1
		return &one
	}
	return nil
}

func pik() int {
	pflag.Parse()

	syncInitializers.RunSync(func(initializer model.Initializer) error {
		return initializer.Init()
	})

	code := mode(statelessModes, func(mode func() error) error {
		return mode()
	})
	if code != nil {
		return *code
	}

	initializers.RunAsync(func(initializer model.Initializer) error {
		return initializer.Init()
	})

	here, err := os.Getwd()
	if err != nil {
		_, _ = spool.Warn("%v\n", err)
		return 1
	}
	locs := append(crawl.RichLocations(here), paths.System.String())
	root, err := os.OpenRoot("/")
	defer root.Close()
	if root == nil {
		_, _ = spool.Warn("%v\n", err)
		return 1
	}
	fs := root.FS()
	if err != nil {
		_, _ = spool.Warn("%v\n", err)
		return 1
	}
	var st *model.State
	var stateErrors []error

	var c *cache.Cache
	if !*flags.All {
		st, stateErrors = model.NewState(fs, locs, indexers, runners)
		go func() {
			if len(stateErrors) > 0 {
				return
			}
			err := cache.MergeAndSave(st)
			if err != nil {
				_, _ = spool.Warn("%v\n", err)
			}

		}()
	} else {
		c, err = cache.LoadFile(fs, paths.ContextsFile.String()[1:])
		if err != nil {
			_, _ = spool.Warn("%v\n", err)
			return 1
		}
		st, stateErrors = cache.LoadState(fs, c, indexers, runners)
	}
	if stateErrors != nil {
		_, _ = spool.Warn("%v\n", stateErrors)
	}

	code = mode(statefulModes, func(mode func(st *model.State) error) error {
		return mode(st)
	})
	if code != nil {
		return *code
	}

	args := pflag.Args()

	var result *search.Result
	cancelled := false

	if len(args) == 0 {
		md, err := menu.Show(st, hydrators)
		if err != nil {
			_, _ = spool.Warn("%v\n", err)
			return 1
		}
		cancelled = md.Cancel
		source, target := md.Result()
		if target != nil {
			t := target.Target()
			result = &search.Result{
				Target:            t,
				Source:            source.Source,
				NeedsConfirmation: false,
				Overridden:        t.Tags().Has(model.Override),
				Sub:               t.Sub(),
			}
		}
	}

	if result == nil {
		result = search.Search(st, args...)
	}

	// TODO: Move auto-all logic into Search?
	if !*flags.All && result.Target == nil && len(result.Args) > 0 && SourcesWithoutResults == nil && !ForceConfirm {
		ForceConfirm = true
		if err != nil {
			_, _ = spool.Warn("%v\n", err)
			return 1
		}
		SourcesWithoutResults = c
		return pik()
	}

	if cancelled {
		_, _ = spool.Warn("no target selected\n")
		return 0
	}

	if result.Target == nil {
		_, _ = spool.Warn("target not found\n")
		return 1
	}

	if result.NeedsConfirmation || ForceConfirm {
		_, _ = fmt.Fprintf(os.Stderr, "this target is out of tree.\n")
		if !menu.Confirm(os.Stdin, result.Source, result.Target, args...) {
			return 0
		}
	}
	if result.Overridden {
		_, _ = fmt.Fprintln(os.Stderr, menu.OverrideWarning(result.Target))
	}

	code = mode(selectionModes, func(mode func(st *model.State, src *model.Source, t model.Target) error) error {
		return mode(st, result.Source, result.Target)
	})
	if code != nil {
		return *code
	}

	err = run.Run(result.Source, result.Target, result.Args...)

	if err != nil {
		_, _ = spool.Warn("%v\n", err)
		return 1
	}

	return 0
}