aboutsummaryrefslogtreecommitdiff
path: root/internal/commands/add.go
blob: 4ee15ec1b4d120ab57662f6a685fd45c637d13b8 (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
package commands

import (
	"fmt"
	"strings"

	"github.com/Fuwn/yae/internal/yae"
	"github.com/urfave/cli/v2"
)

func Add(sources *yae.Sources) func(c *cli.Context) error {
	return func(c *cli.Context) error {
		if c.Args().Len() != 2 {
			return fmt.Errorf("invalid number of arguments")
		}

		if sources.Exists(c.Args().Get(0)) {
			return fmt.Errorf("source already exists")
		}

		source := yae.Source{
			Unpack: c.Bool("unpack"),
			Type:   c.String("type"),
		}
		version := c.String("version")

		if version != "" {
			source.URLTemplate = c.Args().Get(1)
			source.Version = c.String("version")

			if strings.Contains(source.URLTemplate, "{version}") {
				source.URL = strings.ReplaceAll(source.URLTemplate, "{version}", source.Version)
			}
		} else {
			source.URL = c.Args().Get(1)
		}

		if source.Type == "git" && c.String("tag-predicate") != "" {
			source.TagPredicate = c.String("tag-predicate")
		}

		if c.String("trim-tag-prefix") != "" {
			source.TrimTagPrefix = c.String("trim-tag-prefix")
		}

		if c.Bool("pin") {
			source.Pinned = true
		}

		if c.Bool("force") {
			if source.Pinned {
				return fmt.Errorf("cannot set a source to be statically forced and pinned at the same time")
			}

			source.Force = true
		}

		if sha256, err := yae.FetchSHA256(source.URL, c.Bool("unpack")); err != nil {
			return err
		} else {
			source.SHA256 = sha256
		}

		if err := sources.Add(c.Args().Get(0), source); err != nil {
			return err
		}

		return sources.Save(c.String("sources"))
	}
}