~dvshkn/planfile

ref: 34ce4118513c1048ed016eed0bde9d14435c1ad5 planfile/utils/metadata.go -rw-r--r-- 1.0 KiB
34ce4118David Knight first post 10 months ago
                                                                                
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
package utils

import (
	"os"
	"path/filepath"
	"regexp"
	"time"
)

var filenamePattern = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}\.plan$`)
var filenameDateFormat = "2006-01-02"

func FindLatestPlanfile() string {
	var latest time.Time
	var result string
	var today, _ = ParsePlanfileName(GetPlanfileName(time.Now()))
	filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// no subdirectories
		if info.IsDir() && info.Name() != "." {
			return filepath.SkipDir
		}

		if IsPlanfile(path) {
			t, _ := ParsePlanfileName(path)
			if (latest.IsZero() || t.After(latest)) && !t.After(today) {
				latest = t
				result = path
			}
		}

		return nil
	})
	return result
}

func ParsePlanfileName(filename string) (time.Time, error) {
	return time.Parse(filenameDateFormat, filename[:10])
}

func GetPlanfileName(t time.Time) string {
	return t.Format(filenameDateFormat) + ".plan"
}

func IsPlanfile(filename string) bool {
	return filenamePattern.MatchString(filename)
}