summaryrefslogtreecommitdiff
path: root/unix.go
blob: 601015ddeb6c75972090c57676cf38e545ccfae8 (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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package repostatus

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/go-cmd/cmd"
	"go.wit.com/lib/gui/shell"
	"go.wit.com/log"
)

func run(path string, thing string, cmdline string) string {
	parts := strings.Split(cmdline, " ")
	// Create the command
	cmd := exec.Command(thing, parts...)

	// Set the working directory
	cmd.Dir = path

	// Execute the command
	output, err := cmd.CombinedOutput()
	tmp := string(output)
	tmp = strings.TrimSpace(tmp)

	if err != nil {
		log.Log(WARN, "run()", path, thing, cmdline, "=", tmp)
		log.Error(err, "cmd error'd out", parts)
		return ""
	}

	// Print the output
	log.Log(INFO, "run()", path, thing, cmdline, "=", tmp)
	return tmp
}

// goes in one directory so it gets remote branch names
func listFiles(directory string) []string {
	var files []string
	fileInfo, err := os.ReadDir(directory)
	if err != nil {
		log.Error(err)
		return nil
	}

	for _, file := range fileInfo {
		if file.IsDir() {
			dirname := file.Name()
			newdir, _ := os.ReadDir(directory + "/" + dirname)
			for _, file := range newdir {
				if !file.IsDir() {
					files = append(files, dirname+"/"+file.Name())
				}
			}
		} else {
			files = append(files, file.Name())
		}
	}

	return files
}

/*
// string handling examples that might be helpful for normalizeInt()
isAlpha := regexp.MustCompile(`^[A-Za-z]+$`).MatchString

for _, username := range []string{"userone", "user2", "user-three"} {
    if !isAlpha(username) {
        log.Log(GUI, "%q is not valid\n", username)
    }
}

const alpha = "abcdefghijklmnopqrstuvwxyz"

func alphaOnly(s string) bool {
   for _, char := range s {
      if !strings.Contains(alpha, strings.ToLower(string(char))) {
         return false
      }
   }
   return true
}
*/

func normalizeVersion(s string) string {
	// reg, err := regexp.Compile("[^a-zA-Z0-9]+")
	parts := strings.Split(s, "-")
	if len(parts) == 0 {
		return ""
	}
	reg, err := regexp.Compile("[^0-9.]+")
	if err != nil {
		log.Log(WARN, "normalizeVersion() regexp.Compile() ERROR =", err)
		return parts[0]
	}
	clean := reg.ReplaceAllString(parts[0], "")
	log.Log(INFO, "normalizeVersion() s =", clean)
	return clean
}

func splitVersion(version string) (a, b, c string) {
	tmp := normalizeVersion(version)
	parts := strings.Split(tmp, ".")
	switch len(parts) {
	case 1:
		return parts[0], "", ""
	case 2:
		return parts[0], parts[1], ""
	default:
		return parts[0], parts[1], parts[2]
	}
}

func (rs *RepoStatus) Run(cmd []string) cmd.Status {
	path := rs.realPath.String()
	r := shell.PathRun(path, cmd)
	output := strings.Join(r.Stdout, "\n")
	if r.Error != nil {
		log.Log(WARN, "cmd:", cmd)
		log.Log(WARN, "ouptput:", output)
		log.Log(WARN, "failed with error:", r.Error)
	}
	return r
}

// Set the path to the package
func getfiles(pathToPackage string) {
	// List files in the directory
	err := filepath.Walk(pathToPackage, nil) // compiles but crashes
	if err == nil {
		log.Log(INFO, "directory ok", pathToPackage)
	} else {
		log.Warn("directory wrong", pathToPackage)
	}
}

func IsDirectory(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}
	return info.IsDir()
}

func (rs *RepoStatus) Exists(filename string) bool {
	if rs == nil {
		log.Warn("rs == nil for Exists()")
		panic(-1)
	}
	testf := filepath.Join(rs.Path(), filename)
	if Exists(testf) {
		return true
	}
	return false
}

func (rs *RepoStatus) mtime(filename string) (time.Time, error) {
	pathf := filepath.Join(rs.Path(), filename)
	statf, err := os.Stat(pathf)
	if err == nil {
		return statf.ModTime(), nil
	}
	log.Log(REPOWARN, "mtime() error", pathf, err)
	return time.Now(), err
}

// returns true if the file exists
func Exists(file string) bool {
	_, err := os.Stat(file)
	if err != nil {
		return false
	}
	return true
}

func readFileToString(filename string) (string, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(data)), nil
}

// converts a git for-each-ref date. "Wed Feb 7 10:13:38 2024 -0600"
func getGitDateStamp(gitdefault string) (time.Time, string, string) {
	// now := time.Now().Format("Wed Feb 7 10:13:38 2024 -0600")
	const gitLayout = "Mon Jan 2 15:04:05 2006 -0700"
	tagTime, err := time.Parse(gitLayout, gitdefault)
	if err != nil {
		log.Warn("GOT THIS IN PARSE AAA." + gitdefault + ".AAA")
		log.Warn(err)
		return time.Now(), "Feb 1 12:34:56 1978 -0600", ""
	}
	return tagTime, gitdefault, getDurationStamp(tagTime)
}
func getRawDateStamp(raw string) (time.Time, string, string) {
	parts := strings.Split(raw, " ")
	if len(parts) == 0 {
		// raw was blank here
		// return "Jan 4 1977", "40y" // eh, why not. it'll be easy to grep for this
		return time.Now(), "Jan 4 1977", "40y" // eh, why not. it'll be easy to grep for this
	}
	i, err := strconv.ParseInt(parts[0], 10, 64) // base 10 string, return int64
	if err != nil {
		log.Warn("Error converting timestamp:", raw)
		log.Warn("Error converting timestamp err =", err)
		return time.Now(), "", ""
	}

	// Parse the Unix timestamp into a time.Time object
	gitTagDate := time.Unix(i, 0)
	return gitTagDate, gitTagDate.UTC().Format("2006/01/02 15:04:05 UTC"), getDurationStamp(gitTagDate)
}

func getDurationStamp(t time.Time) string {

	// Get the current time
	currentTime := time.Now()

	// Calculate the duration between t current time
	duration := currentTime.Sub(t)

	return formatDuration(duration)
}

func formatDuration(d time.Duration) string {
	seconds := int(d.Seconds()) % 60
	minutes := int(d.Minutes()) % 60
	hours := int(d.Hours()) % 24
	days := int(d.Hours()) / 24
	years := int(d.Hours()) / (24 * 365)

	result := ""
	if years > 0 {
		result += fmt.Sprintf("%dy ", years)
		return result
	}
	if days > 0 {
		result += fmt.Sprintf("%dd ", days)
		return result
	}
	if hours > 0 {
		result += fmt.Sprintf("%dh ", hours)
		return result
	}
	if minutes > 0 {
		result += fmt.Sprintf("%dm ", minutes)
		return result
	}
	if seconds > 0 {
		result += fmt.Sprintf("%ds", seconds)
	}
	return result
}

func (rs *RepoStatus) XtermNohup(cmdline string) {
	shell.XtermCmd(rs.Path(), []string{cmdline})
}
func (rs *RepoStatus) Xterm(cmdline string) {
	shell.XtermCmd(rs.Path(), []string{cmdline})
}
func (rs *RepoStatus) XtermWait(cmdline string) {
	shell.XtermCmdWait(rs.Path(), []string{cmdline})
}

/*
func (rs *RepoStatus) XtermNohup(args []string) {
	var argsX = []string{"xterm", "-geometry", "120x40"}
	argsX = append(argsX, "-e", "bash", "-c")
	argsX = append(argsX, args...)
	log.Info("xterm cmd=", argsX)
	// set less to not exit on small diff's
	os.Setenv("LESS", "-+F -+X -R")
	cmd := exec.Command("nohup", argsX...)
	path := rs.realPath.String()
	cmd.Dir = path
	log.Info("path =", path)
	log.Info("cmd =", strings.Join(args, " "))
	if err := cmd.Run(); err != nil {
		log.Info("xterm.Run() failed")
		log.Info("path =", path)
		log.Info("cmd =", argsX)
	} else {
		log.Info("xterm.Run() worked")
		log.Info("path =", path)
		log.Info("cmd =", argsX)
	}
}
*/

/*
func (rs *RepoStatus) Xterm(args []string) {
	var argsX = []string{"-geometry", "120x40"}
	argsX = append(argsX, "-e", "bash", "-c")
	argsX = append(argsX, args...)
	log.Info("xterm cmd=", argsX)
	// set less to not exit on small diff's
	os.Setenv("LESS", "-+F -+X -R")
	cmd := exec.Command("xterm", argsX...)
	path := rs.realPath.String()
	cmd.Dir = path
	if err := cmd.Run(); err != nil {
		log.Info("xterm.Run() failed")
		log.Info("path =", path)
		log.Info("cmd = xterm", argsX)
	} else {
		log.Info("xterm.Run() worked")
		log.Info("path =", path)
		log.Info("cmd = xterm", argsX)
	}
}
*/

/*
func (rs *RepoStatus) XtermHold(args []string) {
	var argsX = []string{"-hold", "-geometry", "120x40"}
	tmp := strings.Join(args, " ") + ";bash"
	argsX = append(argsX, "-e", "bash", "-c", tmp)
	argsX = append(argsX, args...)
	log.Info("xterm cmd=", argsX)
	// set less to not exit on small diff's
	os.Setenv("LESS", "-+F -+X -R")
	cmd := exec.Command("xterm", argsX...)
	path := rs.realPath.String()
	cmd.Dir = path
	if err := cmd.Run(); err != nil {
		log.Info("xterm.Run() failed")
		log.Info("path =", path)
		log.Info("cmd = xterm", argsX)
	} else {
		log.Info("xterm.Run() worked")
		log.Info("path =", path)
		log.Info("cmd = xterm", argsX)
	}
}
*/

func (rs *RepoStatus) XtermBash(args []string) {
	var argsX = []string{"-geometry", "120x40"}
	tmp := strings.Join(args, " ") + ";bash"
	argsX = append(argsX, "-e", "bash", "-c", tmp)
	argsX = append(argsX, args...)
	log.Info("xterm cmd=", argsX)
	// set less to not exit on small diff's
	os.Setenv("LESS", "-+F -+X -R")
	cmd := exec.Command("xterm", argsX...)
	path := rs.realPath.String()
	cmd.Dir = path
	if err := cmd.Run(); err != nil {
		log.Log(WARN, "xterm.Run() failed")
		log.Log(WARN, "path =", path)
		log.Log(WARN, "cmd = xterm", argsX)
	} else {
		log.Log(WARN, "xterm.Run() worked")
		log.Log(WARN, "path =", path)
		log.Log(WARN, "cmd = xterm", argsX)
	}
}

func (rs *RepoStatus) DoAll(all [][]string) bool {
	for _, cmd := range all {
		log.Log(WARN, "doAll() RUNNING: cmd =", cmd)
		r := rs.Run(cmd)
		if r.Error != nil {
			log.Log(WARN, "doAll() err =", r.Error)
			log.Log(WARN, "doAll() out =", r.Stdout)
			return false
		}
	}
	return true
}

func ScanGitDirectories(srcDir string) []string {
	var all []string
	err := filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			log.Log(REPOWARN, "Error accessing path:", path, err)
			return nil
		}

		// Check if the path is a directory and has a .git subdirectory
		if info.IsDir() && IsGitDir(path) {
			all = append(all, path)
		}

		return nil
	})

	if err != nil {
		log.Log(REPOWARN, "Error walking the path:", srcDir, err)
	}

	return all
}