├── .air.toml
├── .devcontainer
├── devcontainer.json
└── docker-compose.yml
├── .editorconfig
├── .github
└── workflows
│ └── go.yml
├── .gitignore
├── .goreleaser.yaml
├── .pre-commit-config.yaml
├── .tool-versions
├── LICENSE
├── README.md
├── Taskfile.yml
├── cmd
├── install.go
├── list.go
├── purge.go
├── root.go
├── tui
│ ├── installer.go
│ ├── runner.go
│ ├── tui.go
│ └── uninstaller.go
├── uninstall.go
└── utils.go
├── docs
└── gif
│ ├── demo.gif
│ ├── demo.tape
│ ├── install-from-file.gif
│ ├── install-from-file.tape
│ ├── install.gif
│ ├── install.tape
│ ├── list.gif
│ ├── list.tape
│ ├── purge.gif
│ ├── purge.tape
│ ├── uninstall.gif
│ └── uninstall.tape
├── examples
├── 01-basic.yml
└── 02-multi-os-arch.yml
├── go.mod
├── go.sum
├── internal
├── compression
│ └── unzip.go
├── formatter
│ ├── csv.go
│ ├── csv_test.go
│ ├── formatter.go
│ ├── formatter_test.go
│ ├── json.go
│ ├── json_test.go
│ ├── table.go
│ ├── table_test.go
│ ├── text.go
│ └── text_test.go
├── mathutils
│ ├── mathutils.go
│ └── mathutils_test.go
├── parser
│ ├── parser.go
│ ├── parser_test.go
│ ├── yaml.go
│ └── yaml_test.go
├── pathutils
│ ├── pathutils.go
│ └── pathutils_test.go
├── terraform
│ ├── provider.go
│ ├── provider_platform.go
│ ├── provider_platform_test.go
│ ├── provider_test.go
│ ├── provider_version.go
│ ├── provider_version_test.go
│ ├── provider_versions.go
│ ├── provider_versions_test.go
│ ├── registry.go
│ └── registry_test.go
└── tpm
│ ├── base.go
│ ├── install.go
│ ├── list.go
│ ├── purge.go
│ └── uninstall.go
└── main.go
/.air.toml:
--------------------------------------------------------------------------------
1 | [build]
2 | cmd = "task install"
3 | bin = "/usr/bin/true"
4 |
--------------------------------------------------------------------------------
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the
2 | // README at: https://github.com/devcontainers/templates/tree/main/src/go
3 | {
4 | "name": "tpm",
5 | "dockerComposeFile": "docker-compose.yml",
6 | "service": "app",
7 | "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
8 | "features": {
9 | "ghcr.io/devcontainers-extra/features/dasel-asdf:2": {},
10 | "ghcr.io/devcontainers-extra/features/fzf:1": {},
11 | "ghcr.io/devcontainers/features/docker-outside-of-docker:1": {}
12 | },
13 | "postCreateCommand": "(cut -d' ' -f1 .tool-versions | xargs -i asdf plugin add {}) && asdf install",
14 | "customizations": {
15 | "vscode": {
16 | "extensions": [
17 | "EditorConfig.EditorConfig",
18 | "tamasfe.even-better-toml",
19 | "redhat.vscode-yaml"
20 | ]
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/.devcontainer/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | app:
3 | image: mcr.microsoft.com/devcontainers/go:1-1.24-bookworm
4 | container_name: devcontainer_tpm
5 | volumes:
6 | - ../..:/workspaces:cached
7 | command: sleep infinity
8 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | charset = utf-8
7 | end_of_line = lf
8 | indent_size = 2
9 | indent_style = space
10 | insert_final_newline = true
11 | max_line_length = 80
12 | trim_trailing_whitespace = true
13 |
14 | [{Makefile,go.mod,go.sum,*.go,.gitmodules}]
15 | indent_style = tab
16 | indent_size = 4
17 |
18 | [*.md]
19 | max_line_length = 0
20 | trim_trailing_whitespace = false
21 |
--------------------------------------------------------------------------------
/.github/workflows/go.yml:
--------------------------------------------------------------------------------
1 | name: Go
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | pull_request:
7 | branches: [ "main" ]
8 |
9 | jobs:
10 |
11 | build:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v4
15 |
16 | - name: Set up Go
17 | uses: actions/setup-go@v5
18 | with:
19 | go-version-file: go.mod
20 |
21 | - name: Build
22 | run: go build -v ./...
23 |
24 | - name: Test
25 | run: go test -v ./...
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | bin/
3 | dist/
4 | tmp/
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, built with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
17 | # Config files
18 | config.json
19 |
20 | # Log files
21 | *.log
22 |
23 | # Environment Files
24 | .env
25 |
26 | # IDEs
27 | .idea/
28 | .vscode/
29 | *.swp
30 |
31 | # Generated by MacOS
32 | .DS_Store
33 |
--------------------------------------------------------------------------------
/.goreleaser.yaml:
--------------------------------------------------------------------------------
1 | # This is an example .goreleaser.yml file with some sensible defaults.
2 | # Make sure to check the documentation at https://goreleaser.com
3 | before:
4 | hooks:
5 | - go mod tidy
6 | builds:
7 | - env:
8 | - CGO_ENABLED=0
9 | goos:
10 | - linux
11 | - darwin
12 | - windows
13 |
14 | archives:
15 | - format: tar.gz
16 | # this name template makes the OS and Arch compatible with the results of uname.
17 | name_template: >-
18 | {{ .ProjectName }}_
19 | {{- title .Os }}_
20 | {{- if eq .Arch "amd64" }}x86_64
21 | {{- else if eq .Arch "386" }}i386
22 | {{- else }}{{ .Arch }}{{ end }}
23 | {{- if .Arm }}v{{ .Arm }}{{ end }}
24 | # use zip for windows archives
25 | format_overrides:
26 | - goos: windows
27 | format: zip
28 | checksum:
29 | name_template: 'checksums.txt'
30 | snapshot:
31 | name_template: "{{ incpatch .Version }}-next"
32 | changelog:
33 | sort: asc
34 | filters:
35 | exclude:
36 | - '^docs:'
37 | - '^test:'
38 |
39 | brews:
40 | - name: tpm
41 | homepage: "https://github.com/Madh93/tpm"
42 | description: "A package manager for Terraform providers"
43 | license: "MIT"
44 | commit_msg_template: "feat({{ .ProjectName }}): Brew formula update to version {{ .Tag }}"
45 | tap:
46 | owner: Madh93
47 | name: homebrew-tap
48 |
49 | scoops:
50 | - bucket:
51 | owner: Madh93
52 | name: scoop-bucket
53 | homepage: "https://github.com/Madh93/tpm"
54 | description: "A package manager for Terraform providers"
55 | license: "MIT"
56 | commit_msg_template: "feat({{ .ProjectName }}): Scoop update to version {{ .Tag }}"
57 |
58 | release:
59 | github:
60 | owner: Madh93
61 | name: tpm
62 | draft: true
63 |
64 | # The lines beneath this are called `modelines`. See `:help modeline`
65 | # Feel free to remove those if you don't want/use them.
66 | # yaml-language-server: $schema=https://goreleaser.com/static/schema.json
67 | # vim: set ts=2 sw=2 tw=0 fo=cnqoj
68 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/dnephin/pre-commit-golang
3 | rev: v0.5.1
4 | hooks:
5 | - id: go-fmt
6 | - id: go-mod-tidy
7 | - repo: https://github.com/pre-commit/pre-commit-hooks
8 | rev: v4.4.0
9 | hooks:
10 | - id: check-merge-conflict
11 |
--------------------------------------------------------------------------------
/.tool-versions:
--------------------------------------------------------------------------------
1 | air 1.61.5
2 | task 3.40.1
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Miguel Hernández
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Terraform Provider Manager
2 |
3 | [](https://lbesson.mit-license.org/)
4 |
5 | Terraform Provider Manager (`tpm`) is a command-line interface (CLI) tool designed to simplify the management of [Terraform](https://www.terraform.io/) providers in the [plugin cache directory](https://developer.hashicorp.com/terraform/cli/config/config-file#provider-plugin-cache). With `tpm` you can easily **install, uninstall, and list providers**, helping you to streamline your Terraform workflow.
6 |
7 | One of the key benefits of `tpm` is that it **does not require Terraform to be installed**, making it a lightweight and efficient tool for managing your cached providers.
8 |
9 |
10 |
11 |
12 | Installation •
13 | Usage •
14 | Useful Links •
15 | License
16 |
17 |
18 | ## Installation
19 |
20 | ### GNU/Linux
21 |
22 | Arch Linux from [AUR](https://aur.archlinux.org/packages/terraform-tpm-bin) (maintained by [@jonathanio](https://github.com/jonathanio)):
23 |
24 | ```shell
25 | yay -S terraform-tpm-bin
26 | ```
27 |
28 | ### macOS
29 |
30 | Via [Homebrew](https://brew.sh/):
31 |
32 | ```shell
33 | brew install madh93/tap/tpm
34 | ```
35 |
36 | ### Windows
37 |
38 | Via [Scoop](https://scoop.sh/):
39 |
40 | ```shell
41 | scoop bucket add madh93 https://github.com/madh93/scoop-bucket.git
42 | scoop install tpm
43 | ```
44 |
45 | ### From releases
46 |
47 | Stable binaries for all platforms are available on the [releases page](https://github.com/Madh93/tpm/releases). To install, download the binary for your platform from "Assets", extract the downloaded file and place `tpm` into your `PATH`:
48 |
49 | ```shell
50 | curl -L https://github.com/Madh93/tpm/releases/latest/download/tpm_$(uname -s)_$(uname -m).tar.gz | tar -xz -O tpm > /usr/local/bin/tpm
51 | chmod +x /usr/local/bin/tpm
52 | ```
53 |
54 | ### Go
55 |
56 | If you have Go installed:
57 |
58 | ```shell
59 | go install github.com/Madh93/tpm@latest
60 | ```
61 |
62 | ### From source
63 |
64 | Install Go if it is not already installed. You can download it from the official [website](https://golang.org/dl).
65 |
66 | Clone the Terraform Provider Manager repository to build and install the binary:
67 |
68 | ```shell
69 | git clone https://github.com/Madh93/tpm && cd tpm && task install
70 | ```
71 |
72 | ## Usage
73 |
74 | ```shell
75 | Terraform Provider Manager is a simple CLI to manage Terraform providers in the Terraform plugin cache directory
76 |
77 | Usage:
78 | tpm [flags]
79 | tpm [command]
80 |
81 | Available Commands:
82 | completion Generate the autocompletion script for the specified shell
83 | help Help about any command
84 | install Install a provider
85 | list List all installed providers
86 | purge Purge all installed providers
87 | uninstall Uninstall a provider
88 |
89 | Flags:
90 | -c, --config string config file for tpm
91 | -d, --debug enable debug mode
92 | -h, --help help for tpm
93 | -p, --terraform-plugin-cache-dir string the location of the Terraform plugin cache directory (default "/home/user/.terraform.d/plugin-cache")
94 | -r, --terraform-registry string the Terraform registry provider hostname (default "registry.terraform.io")
95 | -v, --version version for tpm
96 |
97 | Use "tpm [command] --help" for more information about a command.
98 | ```
99 |
100 | ### Install a provider
101 |
102 | To install a provider you only need to provide the name. Optionally, you can specify a version by using `@`. By default, if no version is specified, the latest available version, also known as `@latest`, will be installed.
103 |
104 | You can also specify the architecture and operating system. If not specified, the information from the system where tpm is being executed will be used.
105 |
106 |
107 |
108 | In addition, it's possible to install multiple providers at once specifying a `providers.yml` file, making it easier to share and reuse installation requirements. For example:
109 |
110 | ```yaml
111 | providers:
112 | - name: hashicorp/aws@3.64.0
113 | - name: hashicorp/http@3.3.0
114 | os:
115 | - linux
116 | - darwin
117 | arch:
118 | - amd64
119 | - arm64
120 | - name: hashicorp/random
121 | os:
122 | - linux
123 | - darwin
124 | arch:
125 | - amd64
126 | - arm64
127 | ```
128 |
129 |
130 |
131 | The providers are installed in parallel by default. You can adjust the number of parallel jobs by using the `--jobs ` flag.
132 |
133 | ### List installed providers
134 |
135 | This will display on the screen the installed providers. Optionally, you can specify an output format. Valid output formats are:
136 |
137 | - `text` (default)
138 | - `json`
139 | - `csv`
140 | - `table`
141 |
142 |
143 |
144 | ### Uninstall a provider
145 |
146 | Uninstalling a provider is exactly the same as installing it. You can specify both the version, operating system, and architecture.
147 |
148 |
149 |
150 | ### Purge all providers
151 |
152 | This will delete all installed providers from the current registry.
153 |
154 |
155 |
156 | ## Useful Links
157 |
158 | - [Terraform](https://www.terraform.io/)
159 | - [Terraform Registry](https://registry.terraform.io/)
160 | - [Terraform Providers Docs](https://developer.hashicorp.com/terraform/language/providers)
161 | - [Terraform Provider Plugin Cache Docs](https://developer.hashicorp.com/terraform/cli/config/config-file#provider-plugin-cache)
162 | - [Terraform plugin caching](https://www.scalefactory.com/blog/2021/02/25/terraform-plugin-caching/)
163 | - [How to Speed Up Terraform in CI/CD Pipelines](https://infinitelambda.com/speed-up-terraform-cicd-pipeline/)
164 |
165 | ## License
166 |
167 | This project is licensed under the [MIT license](LICENSE).
168 |
--------------------------------------------------------------------------------
/Taskfile.yml:
--------------------------------------------------------------------------------
1 | version: "3"
2 |
3 | vars:
4 | APP_NAME: tpm
5 | APP_VERSION:
6 | sh: git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0"
7 | COMMIT_HASH:
8 | sh: git rev-parse HEAD
9 | LD_FLAG_VERSION: "-X github.com/Madh93/tpm/internal/version.appVersion={{.APP_VERSION}}"
10 | LD_FLAG_COMMIT: "-X github.com/Madh93/tpm/internal/version.commitHash={{.COMMIT_HASH}}"
11 |
12 | env:
13 | GCO_ENABLED: 0
14 |
15 | tasks:
16 | default:
17 | desc: "Build and run"
18 | cmds:
19 | - task update-dependencies
20 | - task build
21 | - task install
22 |
23 | clean:
24 | desc: "Clean build artifacts"
25 | cmds:
26 | - go clean
27 | - rm -rf bin
28 |
29 | install:
30 | desc: "Install the application"
31 | cmds:
32 | - go install -trimpath -ldflags "-s -w {{.LD_FLAG_VERSION}} {{.LD_FLAG_COMMIT}}"
33 |
34 | test:
35 | desc: "Run tests"
36 | cmds:
37 | - go test ./...
38 |
39 | lint:
40 | desc: "Run linters"
41 | cmds:
42 | - golangci-lint run
43 |
44 | update-dependencies:
45 | desc: "Update dependencies"
46 | cmds:
47 | - go get -u all && go mod tidy
48 |
49 | #############
50 | ### BUILD ###
51 | #############
52 |
53 | build:
54 | desc: "Build the application"
55 | cmds:
56 | - go build -trimpath -ldflags "-s -w {{.LD_FLAG_VERSION}} {{.LD_FLAG_COMMIT}}" -o bin/{{.APP_NAME}} main.go
57 |
58 | build:debug:
59 | desc: "Build the application for debug mode"
60 | cmds:
61 | - go build -ldflags "{{.LD_FLAG_VERSION}} {{.LD_FLAG_COMMIT}}" -gcflags=all="-N -l" -o bin/{{.APP_NAME}}-debug main.go
62 |
--------------------------------------------------------------------------------
/cmd/install.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "runtime"
7 |
8 | "github.com/Madh93/tpm/cmd/tui"
9 | "github.com/Madh93/tpm/internal/mathutils"
10 | "github.com/Madh93/tpm/internal/terraform"
11 | "github.com/Madh93/tpm/internal/tpm"
12 | "github.com/spf13/cobra"
13 | "github.com/spf13/viper"
14 | )
15 |
16 | var installCmd = &cobra.Command{
17 | Use: "install [provider]",
18 | Aliases: []string{"i"},
19 | Short: "Install a provider",
20 | Args: func(cmd *cobra.Command, args []string) error {
21 | installFromFile := getStringFlag(cmd, "from-file")
22 | if len(args) != 1 && installFromFile == "" {
23 | return fmt.Errorf("requires 1 arg when '--from-file' flag is not passed, received %d", len(args))
24 | }
25 | if len(args) >= 1 && installFromFile != "" {
26 | return fmt.Errorf("requires 0 arg when '--from-file' flag is passed, received %d", len(args))
27 | }
28 | return nil
29 | },
30 | Run: func(cmd *cobra.Command, args []string) {
31 | viper.Set("force", getBoolFlag(cmd, "force"))
32 | viper.Set("jobs", mathutils.Max(1, getIntFlag(cmd, "jobs")))
33 | var providers []*terraform.Provider
34 | var err error
35 |
36 | // Parse providers to install
37 | if getStringFlag(cmd, "from-file") != "" {
38 | providers, err = tpm.ParseProvidersFromFile(getStringFlag(cmd, "from-file"))
39 | if err != nil {
40 | log.Fatal("Error: ", err)
41 | }
42 | } else {
43 | for _, os := range getStringSliceFlag(cmd, "os") {
44 | for _, arch := range getStringSliceFlag(cmd, "arch") {
45 | providerName, err := terraform.ParseProviderName(args[0])
46 | if err != nil {
47 | log.Fatal("Error: ", err)
48 | }
49 | providers = append(providers, terraform.NewProvider(providerName, os, arch))
50 | }
51 | }
52 | }
53 |
54 | // Install providers
55 | err = tui.RunInstaller(providers)
56 | if err != nil {
57 | log.Fatal("Error: ", err)
58 | }
59 | },
60 | }
61 |
62 | func init() {
63 | rootCmd.AddCommand(installCmd)
64 |
65 | // Local Flags
66 | installCmd.Flags().Bool("force", false, "forces the installation of the provider even if it already exists")
67 | installCmd.Flags().StringP("from-file", "f", "", "installs providers defined in a 'providers.yml' file")
68 | installCmd.Flags().IntP("jobs", "j", 4, "specifies maximum number of concurrent providers to install")
69 | installCmd.Flags().StringSliceP("os", "o", []string{runtime.GOOS}, "terraform provider operating system")
70 | installCmd.Flags().StringSliceP("arch", "a", []string{runtime.GOARCH}, "terraform provider architecture")
71 | }
72 |
--------------------------------------------------------------------------------
/cmd/list.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "log"
5 |
6 | "github.com/Madh93/tpm/internal/tpm"
7 | "github.com/spf13/cobra"
8 | )
9 |
10 | var listCmd = &cobra.Command{
11 | Use: "list",
12 | Aliases: []string{"l"},
13 | Short: "List all installed providers",
14 | Run: func(cmd *cobra.Command, args []string) {
15 | err := tpm.List()
16 | if err != nil {
17 | log.Fatal("Error: ", err)
18 | }
19 | },
20 | }
21 |
22 | func init() {
23 | rootCmd.AddCommand(listCmd)
24 |
25 | // Local Flags
26 | listCmd.Flags().StringP("output", "o", "text", "output in text, json, csv or table format")
27 | listCmd.Flags().VisitAll(bindCustomFlag)
28 | }
29 |
--------------------------------------------------------------------------------
/cmd/purge.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "strings"
7 |
8 | "github.com/Madh93/tpm/internal/tpm"
9 | "github.com/spf13/cobra"
10 | )
11 |
12 | var purgeCmd = &cobra.Command{
13 | Use: "purge",
14 | Aliases: []string{"p"},
15 | Short: "Purge all installed providers",
16 | Run: func(cmd *cobra.Command, args []string) {
17 | skipConfirmation := getBoolFlag(cmd, "yes")
18 |
19 | // Request user confirmation
20 | if !skipConfirmation {
21 | // Read user input
22 | fmt.Print("Are you sure you want to purge ALL installed providers? (yes/no)")
23 | var confirmation string
24 | _, err := fmt.Scanln(&confirmation)
25 | if err != nil {
26 | log.Fatal(err)
27 | }
28 | // Parse user input
29 | if strings.ToLower(confirmation) != "yes" && strings.ToLower(confirmation) != "y" {
30 | fmt.Println("Operation cancelled.")
31 | return
32 | }
33 | }
34 |
35 | // Purge ALL providers
36 | err := tpm.Purge()
37 | if err != nil {
38 | log.Fatal("Error: ", err)
39 | }
40 | },
41 | }
42 |
43 | func init() {
44 | rootCmd.AddCommand(purgeCmd)
45 |
46 | // Local Flags
47 | purgeCmd.Flags().BoolP("yes", "y", false, "skips the confirmation prompt and proceeds with the action")
48 | }
49 |
--------------------------------------------------------------------------------
/cmd/root.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "io/ioutil"
5 | "log"
6 | "os"
7 | "path/filepath"
8 | "strings"
9 |
10 | "github.com/hashicorp/hcl"
11 | "github.com/spf13/cobra"
12 | "github.com/spf13/viper"
13 | )
14 |
15 | var (
16 | cfgFile string
17 | )
18 |
19 | var rootCmd = &cobra.Command{
20 | Use: "tpm",
21 | Version: "0.4.0",
22 | Short: "Terraform Provider Manager",
23 | Long: "Terraform Provider Manager is a simple CLI to manage Terraform providers in the Terraform plugin cache directory",
24 | Run: func(cmd *cobra.Command, args []string) {
25 | cmd.Help()
26 | os.Exit(1)
27 | },
28 | }
29 |
30 | func Execute() {
31 | rootCmd.Execute()
32 | }
33 |
34 | func getCacheDirFromTFConfig() (string, error) {
35 | tfCfgPath, ok := os.LookupEnv("TF_CLI_CONFIG_FILE")
36 | if !ok {
37 | // The file not existing is not an error
38 | return "", nil
39 | }
40 |
41 | data, err := ioutil.ReadFile(tfCfgPath)
42 | if err != nil {
43 | return "", err
44 | }
45 |
46 | var cfg struct {
47 | PluginCacheDir string `hcl:"plugin_cache_dir"`
48 | }
49 | err = hcl.Unmarshal(data, &cfg)
50 | if err != nil {
51 | return "", err
52 | }
53 |
54 | return cfg.PluginCacheDir, nil
55 | }
56 |
57 | func init() {
58 | cobra.OnInitialize(initConfig)
59 |
60 | cacheDir := "$HOME/.terraform.d/plugin-cache"
61 | configuredCacheDir, err := getCacheDirFromTFConfig()
62 | if err != nil {
63 | log.Println("Could not read plugin cache directory from tfrc file, ignoring", err)
64 | }
65 | if configuredCacheDir != "" {
66 | cacheDir = configuredCacheDir
67 | }
68 | cacheDir = filepath.Clean(os.ExpandEnv(cacheDir))
69 |
70 | // Global Flags
71 | rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file for tpm")
72 | rootCmd.PersistentFlags().BoolP("debug", "d", false, "enable debug mode")
73 | rootCmd.PersistentFlags().StringP("terraform-plugin-cache-dir", "p", cacheDir, "the location of the Terraform plugin cache directory")
74 | rootCmd.PersistentFlags().StringP("terraform-registry", "r", "registry.terraform.io", "the Terraform registry provider hostname")
75 | rootCmd.PersistentFlags().VisitAll(bindCustomFlag)
76 | }
77 |
78 | func initConfig() {
79 | if cfgFile != "" {
80 | viper.SetConfigFile(cfgFile)
81 | } else {
82 | // Config name
83 | viper.SetConfigName("config")
84 | viper.SetConfigType("json")
85 |
86 | // Config location
87 | viper.AddConfigPath(".")
88 | viper.AddConfigPath("$HOME/.tpm")
89 | viper.AddConfigPath("/usr/local/etc/tpm")
90 | }
91 |
92 | // Environment variables
93 | viper.SetEnvPrefix("TPM")
94 | viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
95 | viper.AutomaticEnv()
96 |
97 | if err := viper.ReadInConfig(); err == nil {
98 | if viper.GetBool("debug") {
99 | log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
100 | log.Println("Using config file:", viper.ConfigFileUsed())
101 | }
102 | } else {
103 | if viper.GetBool("debug") {
104 | log.Println("Error reading config file,", err)
105 | }
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/cmd/tui/installer.go:
--------------------------------------------------------------------------------
1 | package tui
2 |
3 | import (
4 | "github.com/Madh93/tpm/internal/terraform"
5 | "github.com/Madh93/tpm/internal/tpm"
6 | tea "github.com/charmbracelet/bubbletea"
7 | "github.com/spf13/viper"
8 | )
9 |
10 | type InstallRunner struct{}
11 |
12 | func (r *InstallRunner) RunCmd(job ProviderJob) tea.Cmd {
13 | return func() tea.Msg {
14 | job.err = tpm.Install(job.provider, viper.GetBool("force"))
15 | return processedJobMsg(job)
16 | }
17 | }
18 |
19 | func (r InstallRunner) String() string {
20 | return "Installing"
21 | }
22 |
23 | func RunInstaller(providers []*terraform.Provider) (err error) {
24 | model := NewModel(&InstallRunner{}, providers)
25 | if _, err = tea.NewProgram(model).Run(); err != nil {
26 | return
27 | }
28 | return nil
29 | }
30 |
--------------------------------------------------------------------------------
/cmd/tui/runner.go:
--------------------------------------------------------------------------------
1 | package tui
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | tea "github.com/charmbracelet/bubbletea"
8 | )
9 |
10 | type ProviderJob struct {
11 | id int
12 | provider *terraform.Provider
13 | done bool
14 | err error
15 | }
16 |
17 | type JobRunner interface {
18 | RunCmd(job ProviderJob) tea.Cmd
19 | String() string
20 | }
21 |
22 | func NewRunner(runner string) (JobRunner, error) {
23 | switch runner {
24 | case "install":
25 | return &InstallRunner{}, nil
26 | case "uninstall":
27 | return &UninstallRunner{}, nil
28 | }
29 | return nil, fmt.Errorf("unsupported '%s' job runner", runner)
30 | }
31 |
--------------------------------------------------------------------------------
/cmd/tui/tui.go:
--------------------------------------------------------------------------------
1 | package tui
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/Madh93/tpm/internal/mathutils"
8 | "github.com/Madh93/tpm/internal/terraform"
9 | "github.com/charmbracelet/bubbles/spinner"
10 | tea "github.com/charmbracelet/bubbletea"
11 | "github.com/charmbracelet/lipgloss"
12 | "github.com/spf13/viper"
13 | )
14 |
15 | var (
16 | DefaultSpinner = spinner.New(spinner.WithSpinner(spinner.MiniDot))
17 | CheckMark = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).SetString("✓")
18 | CrossMark = lipgloss.NewStyle().Foreground(lipgloss.Color("160")).SetString("⨯")
19 | )
20 |
21 | type processedJobMsg ProviderJob
22 |
23 | type tearDownMsg bool
24 |
25 | type model struct {
26 | spinner spinner.Model
27 | runner JobRunner
28 | jobs []ProviderJob
29 | maxConcurrentJobs int
30 | doneJobs int
31 | index int
32 | }
33 |
34 | func NewModel(runner JobRunner, providers []*terraform.Provider) *model {
35 | // Setup jobs
36 | jobs := []ProviderJob{}
37 | for i, provider := range providers {
38 | jobs = append(jobs, ProviderJob{id: i, provider: provider, done: false, err: nil})
39 | }
40 |
41 | return &model{
42 | spinner: DefaultSpinner,
43 | runner: runner,
44 | jobs: jobs,
45 | maxConcurrentJobs: viper.GetInt("jobs"),
46 | }
47 | }
48 |
49 | func (m *model) Init() tea.Cmd {
50 | // Setup spinner
51 | cmds := []tea.Cmd{m.spinner.Tick}
52 |
53 | // Add inital jobs
54 | for _, job := range m.jobs[:mathutils.Min(m.maxConcurrentJobs, len(m.jobs))] {
55 | cmds = append(cmds, m.runner.RunCmd(job))
56 | m.index++
57 | }
58 |
59 | return tea.Batch(cmds...)
60 | }
61 |
62 | func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
63 | switch msg := msg.(type) {
64 |
65 | case tea.KeyMsg:
66 | switch msg.String() {
67 | case "ctrl+c":
68 | return m, tea.Quit
69 | }
70 |
71 | case spinner.TickMsg:
72 | var cmd tea.Cmd
73 | m.spinner, cmd = m.spinner.Update(msg)
74 | return m, cmd
75 |
76 | case processedJobMsg:
77 | m.FinishJob(msg)
78 | output := m.GetJobOutput(msg)
79 |
80 | // Latest job! Quitting...
81 | if m.doneJobs >= len(m.jobs) {
82 | return m, tea.Sequence(
83 | tea.Println(output),
84 | tearDownCmd(),
85 | )
86 | }
87 |
88 | // Print result to output
89 | cmds := []tea.Cmd{tea.Println(output)}
90 |
91 | // Adding pending jobs
92 | if m.index <= len(m.jobs) {
93 | cmds = append(cmds, m.runner.RunCmd(m.jobs[m.index-1]))
94 | }
95 |
96 | return m, tea.Batch(cmds...)
97 |
98 | case tearDownMsg:
99 | for {
100 | time.Sleep(time.Millisecond * time.Duration(100))
101 | allDone := true
102 | for _, job := range m.jobs {
103 | if !job.done {
104 | allDone = false
105 | break
106 | }
107 | }
108 |
109 | if allDone {
110 | break
111 | }
112 | }
113 | return m, tea.Quit
114 | }
115 |
116 | return m, nil
117 | }
118 |
119 | func (m model) View() string {
120 | var view string
121 | var currentJobs int
122 |
123 | for _, job := range m.jobs {
124 | // Limit 'Installing' providers to the Max Concurrent Jobs
125 | if currentJobs >= m.maxConcurrentJobs {
126 | break
127 | }
128 | if !job.done {
129 | view += fmt.Sprintf("%s %s %s\n", m.spinner.View(), m.runner, job.provider)
130 | currentJobs++
131 | }
132 | }
133 |
134 | return view
135 | }
136 |
137 | func (m *model) FinishJob(job processedJobMsg) {
138 | m.jobs[job.id].done = true
139 | m.index++
140 | m.doneJobs++
141 | }
142 |
143 | func (m model) GetJobOutput(job processedJobMsg) string {
144 | if job.err != nil {
145 | return fmt.Sprintf("%s %s Reason: %s", CrossMark, job.provider, job.err)
146 | }
147 |
148 | return fmt.Sprintf("%s %s", CheckMark, job.provider)
149 | }
150 |
151 | func tearDownCmd() tea.Cmd {
152 | return func() tea.Msg {
153 | return tearDownMsg(true)
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/cmd/tui/uninstaller.go:
--------------------------------------------------------------------------------
1 | package tui
2 |
3 | import (
4 | "github.com/Madh93/tpm/internal/terraform"
5 | "github.com/Madh93/tpm/internal/tpm"
6 | tea "github.com/charmbracelet/bubbletea"
7 | )
8 |
9 | type UninstallRunner struct{}
10 |
11 | func (r *UninstallRunner) RunCmd(job ProviderJob) tea.Cmd {
12 | return func() tea.Msg {
13 | job.err = tpm.Uninstall(job.provider)
14 | return processedJobMsg(job)
15 | }
16 | }
17 |
18 | func (r UninstallRunner) String() string {
19 | return "Uninstalling"
20 | }
21 |
22 | func RunUninstaller(providers []*terraform.Provider) (err error) {
23 | model := NewModel(&UninstallRunner{}, providers)
24 | if _, err = tea.NewProgram(model).Run(); err != nil {
25 | return
26 | }
27 | return nil
28 | }
29 |
--------------------------------------------------------------------------------
/cmd/uninstall.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "log"
5 | "runtime"
6 |
7 | "github.com/Madh93/tpm/cmd/tui"
8 | "github.com/Madh93/tpm/internal/terraform"
9 | "github.com/spf13/cobra"
10 | "github.com/spf13/viper"
11 | )
12 |
13 | var uninstallCmd = &cobra.Command{
14 | Use: "uninstall [provider]",
15 | Aliases: []string{"u"},
16 | Short: "Uninstall a provider",
17 | Args: cobra.ExactArgs(1),
18 | Run: func(cmd *cobra.Command, args []string) {
19 | var providers []*terraform.Provider
20 | viper.Set("jobs", 1)
21 |
22 | // Get providers to uninstall
23 | for _, os := range getStringSliceFlag(cmd, "os") {
24 | for _, arch := range getStringSliceFlag(cmd, "arch") {
25 | providerName, err := terraform.ParseProviderName(args[0])
26 | if err != nil {
27 | log.Fatal("Error: ", err)
28 | }
29 | providers = append(providers, terraform.NewProvider(providerName, os, arch))
30 | }
31 | }
32 |
33 | // Uninstall providers
34 | err := tui.RunUninstaller(providers)
35 | if err != nil {
36 | log.Fatal("Error: ", err)
37 | }
38 | },
39 | }
40 |
41 | func init() {
42 | rootCmd.AddCommand(uninstallCmd)
43 |
44 | // Local Flags
45 | uninstallCmd.Flags().StringSliceP("os", "o", []string{runtime.GOOS}, "terraform provider operating system (empty to delete all architectures)")
46 | uninstallCmd.Flags().StringSliceP("arch", "a", []string{runtime.GOARCH}, "terraform provider architecture (empty to delete all operating systems)")
47 | }
48 |
--------------------------------------------------------------------------------
/cmd/utils.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "strings"
5 |
6 | "github.com/spf13/cobra"
7 | "github.com/spf13/pflag"
8 | "github.com/spf13/viper"
9 | )
10 |
11 | func bindCustomFlag(flag *pflag.Flag) {
12 | if flag.Name == "config" {
13 | return
14 | }
15 | name := strings.ReplaceAll(flag.Name, "-", "_")
16 | viper.BindPFlag(name, flag)
17 | }
18 |
19 | func getStringFlag(cmd *cobra.Command, flag string) (value string) {
20 | value, _ = cmd.Flags().GetString(flag)
21 | return
22 | }
23 |
24 | func getStringSliceFlag(cmd *cobra.Command, flag string) (value []string) {
25 | value, _ = cmd.Flags().GetStringSlice(flag)
26 | return
27 | }
28 |
29 | func getBoolFlag(cmd *cobra.Command, flag string) (value bool) {
30 | value, _ = cmd.Flags().GetBool(flag)
31 | return
32 | }
33 |
34 | func getIntFlag(cmd *cobra.Command, flag string) (value int) {
35 | value, _ = cmd.Flags().GetInt(flag)
36 | return
37 | }
38 |
--------------------------------------------------------------------------------
/docs/gif/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Madh93/tpm/3f4917045bacdafc5411163cf74b89c23422322b/docs/gif/demo.gif
--------------------------------------------------------------------------------
/docs/gif/demo.tape:
--------------------------------------------------------------------------------
1 | Output demo.gif
2 |
3 | Set FontSize 26
4 | Set Width 1200
5 | Set Height 350
6 |
7 | Type "tpm install hashicorp/aws@4.67.0"
8 | Sleep 500ms
9 | Enter
10 | Sleep 5s
11 |
12 | Ctrl+L
13 | Type "tpm install --from-file providers.yml"
14 | Sleep 500ms
15 | Enter
16 | Sleep 4s
17 |
18 | Ctrl+L
19 | Type "tpm list"
20 | Sleep 500ms
21 | Enter
22 | Sleep 3s
23 |
24 | Ctrl+L
25 | Type "tpm purge --yes"
26 | Sleep 500ms
27 | Enter
28 | Sleep 3s
29 |
--------------------------------------------------------------------------------
/docs/gif/install-from-file.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Madh93/tpm/3f4917045bacdafc5411163cf74b89c23422322b/docs/gif/install-from-file.gif
--------------------------------------------------------------------------------
/docs/gif/install-from-file.tape:
--------------------------------------------------------------------------------
1 | Output install-from-file.gif
2 |
3 | Set FontSize 20
4 | Set Width 1200
5 | Set Height 400
6 |
7 | Type "tpm install --from-file examples/01-basic.yml"
8 | Sleep 500ms
9 | Enter
10 | Sleep 4s
11 |
12 | Ctrl+L
13 | Type "tpm install -f examples/02-multi-os-arch.yml"
14 | Sleep 500ms
15 | Enter
16 | Sleep 6s
17 |
--------------------------------------------------------------------------------
/docs/gif/install.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Madh93/tpm/3f4917045bacdafc5411163cf74b89c23422322b/docs/gif/install.gif
--------------------------------------------------------------------------------
/docs/gif/install.tape:
--------------------------------------------------------------------------------
1 | Output install.gif
2 |
3 | Set FontSize 20
4 | Set Width 1200
5 | Set Height 350
6 |
7 | Type "tpm install hashicorp/aws"
8 | Sleep 500ms
9 | Enter
10 | Sleep 5s
11 |
12 | Ctrl+L
13 | Type "tpm install hashicorp/aws@latest"
14 | Sleep 500ms
15 | Enter
16 | Sleep 3s
17 |
18 | Ctrl+L
19 | Type "tpm install cloudflare/cloudflare@4.4.0"
20 | Sleep 500ms
21 | Enter
22 | Sleep 4s
23 |
24 | Ctrl+L
25 | Type "tpm install hashicorp/random --os linux,darwin --arch amd64,arm64"
26 | Sleep 500ms
27 | Enter
28 | Sleep 6s
29 |
--------------------------------------------------------------------------------
/docs/gif/list.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Madh93/tpm/3f4917045bacdafc5411163cf74b89c23422322b/docs/gif/list.gif
--------------------------------------------------------------------------------
/docs/gif/list.tape:
--------------------------------------------------------------------------------
1 | Output list.gif
2 |
3 | Set FontSize 20
4 | Set Width 1200
5 | Set Height 400
6 |
7 | Type "tpm list"
8 | Sleep 500ms
9 | Enter
10 | Sleep 3s
11 |
12 | Ctrl+L
13 | Type "tpm list --output json"
14 | Sleep 500ms
15 | Enter
16 | Sleep 3s
17 |
18 | Ctrl+L
19 | Type "tpm list --output csv"
20 | Sleep 500ms
21 | Enter
22 | Sleep 3s
23 |
24 | Ctrl+L
25 | Type "tpm list --output table"
26 | Sleep 500ms
27 | Enter
28 | Sleep 3s
29 |
--------------------------------------------------------------------------------
/docs/gif/purge.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Madh93/tpm/3f4917045bacdafc5411163cf74b89c23422322b/docs/gif/purge.gif
--------------------------------------------------------------------------------
/docs/gif/purge.tape:
--------------------------------------------------------------------------------
1 | Output purge.gif
2 |
3 | Set FontSize 20
4 | Set Width 1200
5 | Set Height 400
6 |
7 | Type "tpm purge"
8 | Sleep 500ms
9 | Enter
10 | Type "yes"
11 | Sleep 500ms
12 | Enter
13 | Sleep 3s
14 |
15 | Ctrl+L
16 | Type "tpm purge --yes"
17 | Sleep 500ms
18 | Enter
19 | Sleep 3s
20 |
--------------------------------------------------------------------------------
/docs/gif/uninstall.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Madh93/tpm/3f4917045bacdafc5411163cf74b89c23422322b/docs/gif/uninstall.gif
--------------------------------------------------------------------------------
/docs/gif/uninstall.tape:
--------------------------------------------------------------------------------
1 | Output uninstall.gif
2 |
3 | Set FontSize 20
4 | Set Width 1200
5 | Set Height 300
6 |
7 | Type "tpm uninstall hashicorp/aws"
8 | Sleep 500ms
9 | Enter
10 | Sleep 3s
11 |
12 | Ctrl+L
13 | Type "tpm uninstall hashicorp/aws@latest"
14 | Sleep 500ms
15 | Enter
16 | Sleep 4s
17 |
18 | Ctrl+L
19 | Type "tpm uninstall cloudflare/cloudflare@4.4.0"
20 | Sleep 500ms
21 | Enter
22 | Sleep 3s
23 |
24 | Ctrl+L
25 | Type "tpm uninstall hashicorp/random --os linux,darwin --arch amd64,arm64"
26 | Sleep 500ms
27 | Enter
28 | Sleep 4s
29 |
--------------------------------------------------------------------------------
/examples/01-basic.yml:
--------------------------------------------------------------------------------
1 | providers:
2 | - name: hashicorp/http@3.2.1
3 | - name: hashicorp/null@latest
4 | - name: hashicorp/random
5 |
--------------------------------------------------------------------------------
/examples/02-multi-os-arch.yml:
--------------------------------------------------------------------------------
1 | providers:
2 | - name: hashicorp/null@latest
3 | os:
4 | - windows
5 | arch:
6 | - amd64
7 | - name: hashicorp/http@3.3.0
8 | os:
9 | - linux
10 | - darwin
11 | arch:
12 | - amd64
13 | - arm64
14 | - name: hashicorp/random
15 | os:
16 | - linux
17 | - darwin
18 | arch:
19 | - amd64
20 | - arm64
21 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/Madh93/tpm
2 |
3 | go 1.24.1
4 |
5 | require (
6 | github.com/Masterminds/semver/v3 v3.3.1
7 | github.com/charmbracelet/bubbles v0.20.0
8 | github.com/charmbracelet/bubbletea v1.3.4
9 | github.com/charmbracelet/lipgloss v1.1.0
10 | github.com/hashicorp/hcl v1.0.0
11 | github.com/olekukonko/tablewriter v0.0.5
12 | github.com/spf13/cobra v1.9.1
13 | github.com/spf13/pflag v1.0.6
14 | github.com/spf13/viper v1.20.0
15 | github.com/stretchr/testify v1.10.0
16 | gopkg.in/yaml.v3 v3.0.1
17 | )
18 |
19 | require (
20 | github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
21 | github.com/charmbracelet/x/ansi v0.8.0 // indirect
22 | github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
23 | github.com/charmbracelet/x/term v0.2.1 // indirect
24 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
25 | github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
26 | github.com/sagikazarmark/locafero v0.8.0 // indirect
27 | github.com/sourcegraph/conc v0.3.0 // indirect
28 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
29 | go.uber.org/multierr v1.11.0 // indirect
30 | )
31 |
32 | require (
33 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
34 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
35 | github.com/fsnotify/fsnotify v1.8.0 // indirect
36 | github.com/inconshreveable/mousetrap v1.1.0 // indirect
37 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
38 | github.com/mattn/go-isatty v0.0.20 // indirect
39 | github.com/mattn/go-localereader v0.0.1 // indirect
40 | github.com/mattn/go-runewidth v0.0.16 // indirect
41 | github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
42 | github.com/muesli/cancelreader v0.2.2 // indirect
43 | github.com/muesli/termenv v0.16.0 // indirect
44 | github.com/pelletier/go-toml/v2 v2.2.3 // indirect
45 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
46 | github.com/rivo/uniseg v0.4.7 // indirect
47 | github.com/spf13/afero v1.14.0 // indirect
48 | github.com/spf13/cast v1.7.1 // indirect
49 | github.com/subosito/gotenv v1.6.0 // indirect
50 | golang.org/x/exp v0.0.0-20250305212735-054e65f0b394
51 | golang.org/x/sync v0.12.0 // indirect
52 | golang.org/x/sys v0.31.0 // indirect
53 | golang.org/x/text v0.23.0 // indirect
54 | )
55 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4=
2 | github.com/Masterminds/semver/v3 v3.3.1/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
3 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
4 | github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
5 | github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE=
6 | github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU=
7 | github.com/charmbracelet/bubbletea v1.3.4 h1:kCg7B+jSCFPLYRA52SDZjr51kG/fMUEoPoZrkaDHyoI=
8 | github.com/charmbracelet/bubbletea v1.3.4/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo=
9 | github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
10 | github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
11 | github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
12 | github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
13 | github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
14 | github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
15 | github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=
16 | github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
17 | github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
18 | github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
19 | github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
20 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
21 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
22 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
23 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
24 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
25 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
26 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
27 | github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
28 | github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
29 | github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
30 | github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
31 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
32 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
33 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
34 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
35 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
36 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
37 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
38 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
39 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
40 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
41 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
42 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
43 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
44 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
45 | github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
46 | github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
47 | github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
48 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
49 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
50 | github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
51 | github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
52 | github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
53 | github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
54 | github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
55 | github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
56 | github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
57 | github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
58 | github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
59 | github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
60 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
61 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
62 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
63 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
64 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
65 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
66 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
67 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
68 | github.com/sagikazarmark/locafero v0.8.0 h1:mXaMVw7IqxNBxfv3LdWt9MDmcWDQ1fagDH918lOdVaQ=
69 | github.com/sagikazarmark/locafero v0.8.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk=
70 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
71 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
72 | github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
73 | github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
74 | github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
75 | github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
76 | github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
77 | github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
78 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
79 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
80 | github.com/spf13/viper v1.20.0 h1:zrxIyR3RQIOsarIrgL8+sAvALXul9jeEPa06Y0Ph6vY=
81 | github.com/spf13/viper v1.20.0/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
82 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
83 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
84 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
85 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
86 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
87 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
88 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
89 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
90 | golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
91 | golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
92 | golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
93 | golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
94 | golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
95 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
96 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
97 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
98 | golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
99 | golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
100 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
101 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
102 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
103 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
104 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
105 |
--------------------------------------------------------------------------------
/internal/compression/unzip.go:
--------------------------------------------------------------------------------
1 | package compression
2 |
3 | import (
4 | "archive/zip"
5 | "fmt"
6 | "io"
7 | "os"
8 | "path/filepath"
9 | "strings"
10 | )
11 |
12 | func Unzip(src, dest string) (err error) {
13 | // Open zip
14 | r, err := zip.OpenReader(src)
15 | if err != nil {
16 | return
17 | }
18 | defer func() {
19 | if err := r.Close(); err != nil {
20 | return
21 | }
22 | }()
23 |
24 | // Ensure destination exists
25 | err = os.MkdirAll(dest, 0755)
26 | if err != nil {
27 | return
28 | }
29 |
30 | // Closure to address file descriptors issue with all the deferred .Close() methods
31 | extractAndWriteFile := func(f *zip.File) error {
32 | // Open file in zip
33 | rc, err := f.Open()
34 | if err != nil {
35 | return err
36 | }
37 | defer func() {
38 | if err := rc.Close(); err != nil {
39 | panic(err)
40 | }
41 | }()
42 |
43 | path := filepath.Join(dest, f.Name)
44 |
45 | // Check for ZipSlip (Directory traversal)
46 | if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) {
47 | return fmt.Errorf("illegal file path: %s", path)
48 | }
49 |
50 | if f.FileInfo().IsDir() {
51 | os.MkdirAll(path, f.Mode())
52 | } else {
53 | os.MkdirAll(filepath.Dir(path), f.Mode())
54 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
55 | if err != nil {
56 | return err
57 | }
58 | defer func() {
59 | if err := f.Close(); err != nil {
60 | panic(err)
61 | }
62 | }()
63 |
64 | _, err = io.Copy(f, rc)
65 | if err != nil {
66 | return err
67 | }
68 | }
69 | return nil
70 | }
71 |
72 | // Extract every file in the zip
73 | for _, f := range r.File {
74 | err = extractAndWriteFile(f)
75 | if err != nil {
76 | return
77 | }
78 | }
79 |
80 | return nil
81 | }
82 |
--------------------------------------------------------------------------------
/internal/formatter/csv.go:
--------------------------------------------------------------------------------
1 | package formatter
2 |
3 | import (
4 | "bytes"
5 | "encoding/csv"
6 |
7 | "github.com/Madh93/tpm/internal/terraform"
8 | )
9 |
10 | type CSVFormatter struct{}
11 |
12 | func (f *CSVFormatter) Format(providers []*terraform.Provider) ([]byte, error) {
13 | var output bytes.Buffer
14 | writer := csv.NewWriter(&output)
15 |
16 | err := writer.Write(ProviderHeader)
17 | if err != nil {
18 | return nil, err
19 | }
20 |
21 | for _, provider := range providers {
22 | err := writer.Write(provider.ToOutputRow())
23 | if err != nil {
24 | return nil, err
25 | }
26 | }
27 |
28 | writer.Flush()
29 | return output.Bytes(), nil
30 | }
31 |
--------------------------------------------------------------------------------
/internal/formatter/csv_test.go:
--------------------------------------------------------------------------------
1 | package formatter_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/formatter"
7 | "github.com/Madh93/tpm/internal/terraform"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestCSVFormatterFormat(t *testing.T) {
12 | tests := []struct {
13 | name string
14 | providers []*terraform.Provider
15 | expected string
16 | }{
17 | {
18 | name: "no installed provider",
19 | providers: nil,
20 | expected: "namespace,name,version,os,arch\n",
21 | },
22 | {
23 | name: "one installed provider",
24 | providers: []*terraform.Provider{terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "linux", "amd64")},
25 | expected: "namespace,name,version,os,arch\n" +
26 | "hashicorp,http,3.2.1,linux,amd64\n",
27 | },
28 | {
29 | name: "multiple installed providers",
30 | providers: []*terraform.Provider{
31 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), "windows", "amd64"),
32 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), "darwin", "arm64"),
33 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "linux", "amd64"),
34 | },
35 | expected: "namespace,name,version,os,arch\n" +
36 | "cloudflare,cloudflare,4.4.0,windows,amd64\n" +
37 | "digitalocean,digitalocean,2.28.0,darwin,arm64\n" +
38 | "hashicorp,aws,4.64.0,linux,amd64\n",
39 | },
40 | }
41 |
42 | for _, tt := range tests {
43 | t.Run(tt.name, func(t *testing.T) {
44 | csvFormatter := &formatter.CSVFormatter{}
45 | output, err := csvFormatter.Format(tt.providers)
46 |
47 | assert.NoError(t, err)
48 | assert.Equal(t, tt.expected, string(output))
49 | })
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/internal/formatter/formatter.go:
--------------------------------------------------------------------------------
1 | package formatter
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | )
8 |
9 | var (
10 | ProviderHeader = []string{"namespace", "name", "version", "os", "arch"}
11 | )
12 |
13 | type OutputFormatter interface {
14 | Format(providers []*terraform.Provider) ([]byte, error)
15 | }
16 |
17 | func NewFormatter(outputFormat string) (OutputFormatter, error) {
18 | switch outputFormat {
19 | case "text":
20 | return &TextFormatter{}, nil
21 | case "csv":
22 | return &CSVFormatter{}, nil
23 | case "json":
24 | return &JSONFormatter{}, nil
25 | case "table":
26 | return &TableFormatter{}, nil
27 | }
28 | return nil, fmt.Errorf("unsupported '%s' output format", outputFormat)
29 | }
30 |
--------------------------------------------------------------------------------
/internal/formatter/formatter_test.go:
--------------------------------------------------------------------------------
1 | package formatter_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/formatter"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestNewFormatter(t *testing.T) {
11 | tests := []struct {
12 | name string
13 | outputFormat string
14 | wantErr bool
15 | }{
16 | {
17 | name: "valid 'text' output format",
18 | outputFormat: "text",
19 | wantErr: false,
20 | },
21 | {
22 | name: "valid 'csv' output format",
23 | outputFormat: "csv",
24 | wantErr: false,
25 | },
26 | {
27 | name: "valid 'json' output format",
28 | outputFormat: "json",
29 | wantErr: false,
30 | },
31 | {
32 | name: "valid 'table' output format",
33 | outputFormat: "table",
34 | wantErr: false,
35 | },
36 | {
37 | name: "invalid output format",
38 | outputFormat: "unknown",
39 | wantErr: true,
40 | },
41 | }
42 |
43 | for _, tt := range tests {
44 | t.Run(tt.name, func(t *testing.T) {
45 | output, err := formatter.NewFormatter(tt.outputFormat)
46 |
47 | if tt.wantErr {
48 | assert.Error(t, err)
49 | assert.Nil(t, output)
50 | } else {
51 | assert.NoError(t, err)
52 | assert.NotZero(t, output)
53 | }
54 | })
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/internal/formatter/json.go:
--------------------------------------------------------------------------------
1 | package formatter
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | )
8 |
9 | type JSONFormatter struct{}
10 |
11 | func (f *JSONFormatter) Format(providers []*terraform.Provider) ([]byte, error) {
12 | output, err := json.MarshalIndent(providers, "", " ")
13 | if err != nil {
14 | return nil, err
15 | }
16 |
17 | return output, nil
18 | }
19 |
--------------------------------------------------------------------------------
/internal/formatter/json_test.go:
--------------------------------------------------------------------------------
1 | package formatter_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/formatter"
7 | "github.com/Madh93/tpm/internal/terraform"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestJSONFormatterFormat(t *testing.T) {
12 | tests := []struct {
13 | name string
14 | providers []*terraform.Provider
15 | expected string
16 | }{
17 | {
18 | name: "no installed provider",
19 | providers: nil,
20 | expected: "null",
21 | },
22 | {
23 | name: "one installed provider",
24 | providers: []*terraform.Provider{terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "linux", "amd64")},
25 | expected: `[
26 | {
27 | "namespace": "hashicorp",
28 | "name": "http",
29 | "version": "3.2.1",
30 | "os": "linux",
31 | "arch": "amd64"
32 | }
33 | ]`,
34 | },
35 | {
36 | name: "multiple installed providers",
37 | providers: []*terraform.Provider{
38 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), "windows", "amd64"),
39 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), "darwin", "arm64"),
40 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "linux", "amd64"),
41 | },
42 | expected: `[
43 | {
44 | "namespace": "cloudflare",
45 | "name": "cloudflare",
46 | "version": "4.4.0",
47 | "os": "windows",
48 | "arch": "amd64"
49 | },
50 | {
51 | "namespace": "digitalocean",
52 | "name": "digitalocean",
53 | "version": "2.28.0",
54 | "os": "darwin",
55 | "arch": "arm64"
56 | },
57 | {
58 | "namespace": "hashicorp",
59 | "name": "aws",
60 | "version": "4.64.0",
61 | "os": "linux",
62 | "arch": "amd64"
63 | }
64 | ]`,
65 | },
66 | }
67 |
68 | for _, tt := range tests {
69 | t.Run(tt.name, func(t *testing.T) {
70 | jsonFormatter := &formatter.JSONFormatter{}
71 | output, err := jsonFormatter.Format(tt.providers)
72 |
73 | assert.NoError(t, err)
74 | assert.Equal(t, tt.expected, string(output))
75 | })
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/internal/formatter/table.go:
--------------------------------------------------------------------------------
1 | package formatter
2 |
3 | import (
4 | "bytes"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | "github.com/olekukonko/tablewriter"
8 | )
9 |
10 | type TableFormatter struct{}
11 |
12 | func (f *TableFormatter) Format(providers []*terraform.Provider) ([]byte, error) {
13 | var output bytes.Buffer
14 | table := tablewriter.NewWriter(&output)
15 |
16 | table.SetHeader(ProviderHeader)
17 |
18 | for _, provider := range providers {
19 | table.Append(provider.ToOutputRow())
20 | }
21 |
22 | table.Render()
23 | return output.Bytes(), nil
24 | }
25 |
--------------------------------------------------------------------------------
/internal/formatter/table_test.go:
--------------------------------------------------------------------------------
1 | package formatter_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/formatter"
7 | "github.com/Madh93/tpm/internal/terraform"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestTableFormatterFormat(t *testing.T) {
12 | tests := []struct {
13 | name string
14 | providers []*terraform.Provider
15 | expected string
16 | }{
17 | {
18 | name: "no installed provider",
19 | providers: nil,
20 | expected: "+-----------+------+---------+----+------+\n" +
21 | "| NAMESPACE | NAME | VERSION | OS | ARCH |\n" +
22 | "+-----------+------+---------+----+------+\n" +
23 | "+-----------+------+---------+----+------+\n",
24 | },
25 | {
26 | name: "one installed provider",
27 | providers: []*terraform.Provider{terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "linux", "amd64")},
28 | expected: "+-----------+------+---------+-------+-------+\n" +
29 | "| NAMESPACE | NAME | VERSION | OS | ARCH |\n" +
30 | "+-----------+------+---------+-------+-------+\n" +
31 | "| hashicorp | http | 3.2.1 | linux | amd64 |\n" +
32 | "+-----------+------+---------+-------+-------+\n",
33 | },
34 | {
35 | name: "multiple installed providers",
36 | providers: []*terraform.Provider{
37 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), "windows", "amd64"),
38 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), "darwin", "arm64"),
39 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "linux", "amd64"),
40 | },
41 | expected: "+--------------+--------------+---------+---------+-------+\n" +
42 | "| NAMESPACE | NAME | VERSION | OS | ARCH |\n" +
43 | "+--------------+--------------+---------+---------+-------+\n" +
44 | "| cloudflare | cloudflare | 4.4.0 | windows | amd64 |\n" +
45 | "| digitalocean | digitalocean | 2.28.0 | darwin | arm64 |\n" +
46 | "| hashicorp | aws | 4.64.0 | linux | amd64 |\n" +
47 | "+--------------+--------------+---------+---------+-------+\n",
48 | },
49 | }
50 |
51 | for _, tt := range tests {
52 | t.Run(tt.name, func(t *testing.T) {
53 | tableFormatter := &formatter.TableFormatter{}
54 | output, err := tableFormatter.Format(tt.providers)
55 |
56 | assert.NoError(t, err)
57 | assert.Equal(t, tt.expected, string(output))
58 | })
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/internal/formatter/text.go:
--------------------------------------------------------------------------------
1 | package formatter
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | )
8 |
9 | type TextFormatter struct{}
10 |
11 | func (f *TextFormatter) Format(providers []*terraform.Provider) ([]byte, error) {
12 | var output string
13 |
14 | if providers != nil {
15 | for _, provider := range providers {
16 | output += fmt.Sprintf("%s\n", provider.String())
17 | }
18 | } else {
19 | output = "No packages found.\n"
20 | }
21 |
22 | return []byte(output), nil
23 | }
24 |
--------------------------------------------------------------------------------
/internal/formatter/text_test.go:
--------------------------------------------------------------------------------
1 | package formatter_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/formatter"
7 | "github.com/Madh93/tpm/internal/terraform"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestTextFormatterFormat(t *testing.T) {
12 | tests := []struct {
13 | name string
14 | providers []*terraform.Provider
15 | expected string
16 | }{
17 | {
18 | name: "no installed provider",
19 | providers: nil,
20 | expected: "No packages found.\n",
21 | },
22 | {
23 | name: "one installed provider",
24 | providers: []*terraform.Provider{terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "linux", "amd64")},
25 | expected: "'hashicorp/http@3.2.1' (linux/amd64)\n",
26 | },
27 | {
28 | name: "multiple installed providers",
29 | providers: []*terraform.Provider{
30 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), "windows", "amd64"),
31 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), "darwin", "arm64"),
32 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "linux", "amd64"),
33 | },
34 | expected: "'cloudflare/cloudflare@4.4.0' (windows/amd64)\n" +
35 | "'digitalocean/digitalocean@2.28.0' (darwin/arm64)\n" +
36 | "'hashicorp/aws@4.64.0' (linux/amd64)\n",
37 | },
38 | }
39 |
40 | for _, tt := range tests {
41 | t.Run(tt.name, func(t *testing.T) {
42 | textFormatter := &formatter.TextFormatter{}
43 | output, err := textFormatter.Format(tt.providers)
44 |
45 | assert.NoError(t, err)
46 | assert.Equal(t, tt.expected, string(output))
47 | })
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/internal/mathutils/mathutils.go:
--------------------------------------------------------------------------------
1 | package mathutils
2 |
3 | import (
4 | "golang.org/x/exp/constraints"
5 | )
6 |
7 | func Max[T constraints.Ordered](a, b T) T {
8 | if a > b {
9 | return a
10 | }
11 | return b
12 | }
13 |
14 | func Min[T constraints.Ordered](a, b T) T {
15 | if a < b {
16 | return a
17 | }
18 | return b
19 | }
20 |
--------------------------------------------------------------------------------
/internal/mathutils/mathutils_test.go:
--------------------------------------------------------------------------------
1 | package mathutils_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/mathutils"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestMaxWithInt(t *testing.T) {
11 | tests := []struct {
12 | a, b, expected int
13 | }{
14 | {
15 | a: 1,
16 | b: 2,
17 | expected: 2,
18 | },
19 | }
20 |
21 | for _, tc := range tests {
22 | got := mathutils.Max(tc.a, tc.b)
23 | assert.Equal(t, tc.expected, got)
24 | }
25 | }
26 |
27 | func TestMaxWithFloat(t *testing.T) {
28 | tests := []struct {
29 | a, b, expected float32
30 | }{
31 | {
32 | a: 5.5,
33 | b: -2.4,
34 | expected: 5.5,
35 | },
36 | }
37 |
38 | for _, tc := range tests {
39 | got := mathutils.Max(tc.a, tc.b)
40 | assert.Equal(t, tc.expected, got)
41 | }
42 | }
43 |
44 | func TestMaxWithString(t *testing.T) {
45 | tests := []struct {
46 | a, b, expected string
47 | }{
48 | {
49 | a: "foo",
50 | b: "bar",
51 | expected: "foo",
52 | },
53 | }
54 |
55 | for _, tc := range tests {
56 | got := mathutils.Max(tc.a, tc.b)
57 | assert.Equal(t, tc.expected, got)
58 | }
59 | }
60 |
61 | func TestMinWithInt(t *testing.T) {
62 | tests := []struct {
63 | a, b, expected int
64 | }{
65 | {
66 | a: 1,
67 | b: 2,
68 | expected: 1,
69 | },
70 | }
71 |
72 | for _, tc := range tests {
73 | got := mathutils.Min(tc.a, tc.b)
74 | assert.Equal(t, tc.expected, got)
75 | }
76 | }
77 |
78 | func TestMinWithFloat(t *testing.T) {
79 | tests := []struct {
80 | a, b, expected float32
81 | }{
82 | {
83 | a: 5.5,
84 | b: -2.4,
85 | expected: -2.4,
86 | },
87 | }
88 |
89 | for _, tc := range tests {
90 | got := mathutils.Min(tc.a, tc.b)
91 | assert.Equal(t, tc.expected, got)
92 | }
93 | }
94 |
95 | func TestMinWithString(t *testing.T) {
96 | tests := []struct {
97 | a, b, expected string
98 | }{
99 | {
100 | a: "foo",
101 | b: "bar",
102 | expected: "bar",
103 | },
104 | }
105 |
106 | for _, tc := range tests {
107 | got := mathutils.Min(tc.a, tc.b)
108 | assert.Equal(t, tc.expected, got)
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/internal/parser/parser.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 |
7 | "github.com/Madh93/tpm/internal/terraform"
8 | )
9 |
10 | type InputParser interface {
11 | Parse(input []byte) ([]*terraform.Provider, error)
12 | }
13 |
14 | func NewParser(path string) (InputParser, error) {
15 | extension := filepath.Ext(path)
16 |
17 | switch extension {
18 | case ".yml", ".yaml":
19 | return &YAMLParser{}, nil
20 | }
21 |
22 | return nil, fmt.Errorf("unsupported '%s' input format", extension)
23 | }
24 |
--------------------------------------------------------------------------------
/internal/parser/parser_test.go:
--------------------------------------------------------------------------------
1 | package parser_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/Madh93/tpm/internal/parser"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestNewParser(t *testing.T) {
11 | tests := []struct {
12 | name string
13 | path string
14 | wantErr bool
15 | }{
16 | {
17 | name: "valid 'yml' output format",
18 | path: "providers.yml",
19 | wantErr: false,
20 | },
21 | {
22 | name: "valid 'yaml' output format",
23 | path: "whatever.yaml",
24 | wantErr: false,
25 | },
26 | {
27 | name: "invalid input format",
28 | path: "providers.json",
29 | wantErr: true,
30 | },
31 | }
32 |
33 | for _, tt := range tests {
34 | t.Run(tt.name, func(t *testing.T) {
35 | p, err := parser.NewParser(tt.path)
36 |
37 | if tt.wantErr {
38 | assert.Error(t, err)
39 | assert.Nil(t, p)
40 | } else {
41 | assert.NoError(t, err)
42 | assert.NotZero(t, p)
43 | }
44 | })
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/internal/parser/yaml.go:
--------------------------------------------------------------------------------
1 | package parser
2 |
3 | import (
4 | "runtime"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | "gopkg.in/yaml.v3"
8 | )
9 |
10 | type YAMLProvidersFile struct {
11 | Providers []struct {
12 | Name string `yaml:"name"`
13 | OS []string `yaml:"os"`
14 | Arch []string `yaml:"arch"`
15 | } `yaml:"providers"`
16 | }
17 |
18 | type YAMLParser struct{}
19 |
20 | func (f *YAMLParser) Parse(data []byte) (providers []*terraform.Provider, err error) {
21 | // Decode YAML
22 | var config YAMLProvidersFile
23 | err = yaml.Unmarshal(data, &config)
24 | if err != nil {
25 | return nil, err
26 | }
27 |
28 | // Parse providers
29 | for _, provider := range config.Providers {
30 | osList := getListOrDefault(provider.OS, []string{runtime.GOOS})
31 | archList := getListOrDefault(provider.Arch, []string{runtime.GOARCH})
32 | for _, os := range osList {
33 | for _, arch := range archList {
34 | providerName, err := terraform.ParseProviderName(provider.Name)
35 | if err != nil {
36 | return nil, err
37 | }
38 | providers = append(providers, terraform.NewProvider(providerName, os, arch))
39 | }
40 | }
41 | }
42 |
43 | return providers, nil
44 | }
45 |
46 | func getListOrDefault(list, fallback []string) []string {
47 | if len(list) == 0 {
48 | return fallback
49 | }
50 | return list
51 | }
52 |
--------------------------------------------------------------------------------
/internal/parser/yaml_test.go:
--------------------------------------------------------------------------------
1 | package parser_test
2 |
3 | import (
4 | "reflect"
5 | "runtime"
6 | "testing"
7 |
8 | "github.com/Madh93/tpm/internal/parser"
9 | "github.com/Madh93/tpm/internal/terraform"
10 | "github.com/stretchr/testify/assert"
11 | )
12 |
13 | func TestYAMLParserParse(t *testing.T) {
14 | tests := []struct {
15 | name string
16 | input string
17 | expected []*terraform.Provider
18 | }{
19 | {
20 | name: "no providers definition",
21 | input: "",
22 | expected: nil,
23 | },
24 | {
25 | name: "one simple provider definition",
26 | input: `providers:
27 | - name: hashicorp/http@3.2.1`,
28 | expected: []*terraform.Provider{terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), runtime.GOOS, runtime.GOARCH)},
29 | },
30 | {
31 | name: "one provider definition with multiple arch and os",
32 | input: `providers:
33 | - name: hashicorp/http@3.2.1
34 | os:
35 | - linux
36 | - darwin
37 | arch:
38 | - amd64
39 | - arm64`,
40 | expected: []*terraform.Provider{
41 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "linux", "amd64"),
42 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "linux", "arm64"),
43 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "darwin", "amd64"),
44 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "http", "3.2.1"), "darwin", "arm64"),
45 | },
46 | },
47 | {
48 | name: "multiple providers definitions",
49 | input: `providers:
50 | - name: cloudflare/cloudflare@4.4.0
51 | - name: digitalocean/digitalocean@2.28.0
52 | - name: hashicorp/aws@4.64.0`,
53 | expected: []*terraform.Provider{
54 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), runtime.GOOS, runtime.GOARCH),
55 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), runtime.GOOS, runtime.GOARCH),
56 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), runtime.GOOS, runtime.GOARCH),
57 | },
58 | },
59 | {
60 | name: "multiple providers definitions with multiple arch and os",
61 | input: `providers:
62 | - name: cloudflare/cloudflare@4.4.0
63 | os:
64 | - darwin
65 | arch:
66 | - amd64
67 | - arm64
68 | - name: digitalocean/digitalocean@2.28.0
69 | os:
70 | - windows
71 | - linux
72 | arch:
73 | - amd64
74 | - name: hashicorp/aws@4.64.0
75 | os:
76 | - linux
77 | - darwin
78 | arch:
79 | - amd64
80 | - arm64`,
81 | expected: []*terraform.Provider{
82 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), "darwin", "amd64"),
83 | terraform.NewProvider(terraform.NewProviderName("cloudflare", "cloudflare", "4.4.0"), "darwin", "arm64"),
84 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), "windows", "amd64"),
85 | terraform.NewProvider(terraform.NewProviderName("digitalocean", "digitalocean", "2.28.0"), "linux", "amd64"),
86 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "linux", "amd64"),
87 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "linux", "arm64"),
88 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "darwin", "amd64"),
89 | terraform.NewProvider(terraform.NewProviderName("hashicorp", "aws", "4.64.0"), "darwin", "arm64"),
90 | },
91 | },
92 | }
93 |
94 | for _, tt := range tests {
95 | t.Run(tt.name, func(t *testing.T) {
96 | yamlParser := &parser.YAMLParser{}
97 | providers, err := yamlParser.Parse([]byte(tt.input))
98 |
99 | assert.NoError(t, err)
100 | assert.Equal(t, len(tt.expected), len(providers))
101 | if !reflect.DeepEqual(providers, tt.expected) {
102 | t.Errorf("TestYAMLParserParse(%q): expected provider %v, but got %v", tt.input, tt.expected, providers)
103 | }
104 | })
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/internal/pathutils/pathutils.go:
--------------------------------------------------------------------------------
1 | package pathutils
2 |
3 | import (
4 | "path/filepath"
5 | )
6 |
7 | func PathDepth(path string) (depth int) {
8 | for path != filepath.Dir(path) && path != "" {
9 | depth++
10 | path = filepath.Dir(path)
11 | }
12 | return
13 | }
14 |
--------------------------------------------------------------------------------
/internal/pathutils/pathutils_test.go:
--------------------------------------------------------------------------------
1 | package pathutils
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | func TestPathDepth(t *testing.T) {
10 | tests := []struct {
11 | path string
12 | expected int
13 | }{
14 | {
15 | path: "",
16 | expected: 0,
17 | },
18 | {
19 | path: "/",
20 | expected: 0,
21 | },
22 | {
23 | path: "/a",
24 | expected: 1,
25 | },
26 | {
27 | path: "/a/b",
28 | expected: 2,
29 | },
30 | {
31 | path: "/a/b/c",
32 | expected: 3,
33 | },
34 | {
35 | path: "/a/b/c/d",
36 | expected: 4,
37 | },
38 | }
39 |
40 | for _, tc := range tests {
41 | got := PathDepth(tc.path)
42 | assert.Equal(t, tc.expected, got)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/internal/terraform/provider.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | "fmt"
7 | "os"
8 | "path/filepath"
9 | "regexp"
10 | "runtime"
11 | "strings"
12 |
13 | "github.com/spf13/viper"
14 | )
15 |
16 | type ProviderName struct {
17 | namespace string
18 | providerType string
19 | version string
20 | }
21 |
22 | func NewProviderName(namespace, providerType, version string) *ProviderName {
23 | return &ProviderName{
24 | namespace: strings.ToLower(namespace),
25 | providerType: strings.ToLower(providerType),
26 | version: strings.ToLower(version),
27 | }
28 | }
29 |
30 | func ParseProviderName(s string) (*ProviderName, error) {
31 | parts := strings.Split(s, "/")
32 | typeWithVersion := parts[len(parts)-1]
33 | typeWithVersionParts := strings.Split(typeWithVersion, "@")
34 | if len(parts) != 2 || len(typeWithVersionParts) > 2 {
35 | return nil, errors.New("incorrect provider name format, expected '/[@]'")
36 | }
37 |
38 | // Get Namespace
39 | namespace := strings.TrimSpace(parts[0])
40 | if namespace == "" {
41 | return nil, errors.New("invalid provider namespace, expected non-empty value")
42 | }
43 |
44 | // Get Type
45 | providerType := strings.TrimSpace(typeWithVersionParts[0])
46 | if providerType == "" {
47 | return nil, errors.New("invalid provider type, expected non-empty value")
48 | }
49 |
50 | // Get Version
51 | version := "latest"
52 | if len(typeWithVersionParts) > 1 {
53 | version = strings.TrimSpace(typeWithVersionParts[1])
54 |
55 | if version == "" {
56 | return nil, errors.New("invalid provider version, expected non-empty value")
57 | }
58 | }
59 |
60 | return NewProviderName(namespace, providerType, version), nil
61 | }
62 |
63 | type Provider struct {
64 | name *ProviderName
65 | operatingSystem string
66 | architecture string
67 | }
68 |
69 | func NewProvider(name *ProviderName, os, arch string) *Provider {
70 | return &Provider{
71 | name: name,
72 | operatingSystem: strings.ToLower(os),
73 | architecture: strings.ToLower(arch),
74 | }
75 | }
76 |
77 | func ParseProviderFromPath(path string) (*Provider, error) {
78 | // Get parts
79 | parts := strings.Split(path, string(os.PathSeparator))
80 |
81 | // Verify path format
82 | pattern := `^.*\/[^\/]+\/[^\/]+\/[^\/]+\/\d+\.\d+\.\d+\/[^_]+_[^\/]+$`
83 | match, err := regexp.MatchString(pattern, path)
84 | if err != nil {
85 | return nil, err
86 | }
87 | if !match && runtime.GOOS != "windows" {
88 | return nil, errors.New("invalid path format, expected something like '...////_'")
89 | }
90 |
91 | // Get provider data
92 | os := strings.Split(parts[len(parts)-1], "_")[0]
93 | arch := strings.Split(parts[len(parts)-1], "_")[1]
94 | version := parts[len(parts)-2]
95 | providerType := parts[len(parts)-3]
96 | namespace := parts[len(parts)-4]
97 |
98 | providerName := NewProviderName(namespace, providerType, version)
99 | return NewProvider(providerName, os, arch), nil
100 | }
101 |
102 | func (p *Provider) Namespace() string {
103 | return p.name.namespace
104 | }
105 |
106 | func (p *Provider) ProviderType() string {
107 | return p.name.providerType
108 | }
109 |
110 | func (p *Provider) Version() string {
111 | return p.name.version
112 | }
113 |
114 | func (p *Provider) SetVersion(version string) {
115 | p.name.version = version
116 | }
117 |
118 | func (p *Provider) OperatingSystem() string {
119 | return p.operatingSystem
120 | }
121 |
122 | func (p *Provider) Architecture() string {
123 | return p.architecture
124 | }
125 |
126 | func (p Provider) String() string {
127 | return fmt.Sprintf("'%s/%s@%s' (%s/%s)", p.name.namespace, p.name.providerType, p.name.version, p.operatingSystem, p.architecture)
128 | }
129 |
130 | func (p Provider) InstallationPath() string {
131 | return filepath.Join(
132 | viper.GetString("terraform_plugin_cache_dir"),
133 | viper.GetString("terraform_registry"),
134 | p.name.namespace,
135 | p.name.providerType,
136 | p.name.version,
137 | fmt.Sprintf("%s_%s", p.operatingSystem, p.architecture),
138 | )
139 | }
140 |
141 | func (p *Provider) MarshalJSON() ([]byte, error) {
142 | return json.Marshal(struct {
143 | Namespace string `json:"namespace"`
144 | ProviderType string `json:"name"`
145 | Version string `json:"version"`
146 | OperatingSystem string `json:"os"`
147 | Architecture string `json:"arch"`
148 | }{
149 | Namespace: p.Namespace(),
150 | ProviderType: p.ProviderType(),
151 | Version: p.Version(),
152 | OperatingSystem: p.OperatingSystem(),
153 | Architecture: p.Architecture(),
154 | })
155 | }
156 |
157 | func (p *Provider) ToOutputRow() []string {
158 | return []string{p.Namespace(), p.ProviderType(), p.Version(), p.OperatingSystem(), p.Architecture()}
159 | }
160 |
--------------------------------------------------------------------------------
/internal/terraform/provider_platform.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import "fmt"
4 |
5 | type ProviderPlatform struct {
6 | OS string `json:"os"`
7 | Arch string `json:"arch"`
8 | }
9 |
10 | func (p ProviderPlatform) String() string {
11 | return fmt.Sprintf("%s/%s", p.OS, p.Arch)
12 | }
13 |
--------------------------------------------------------------------------------
/internal/terraform/provider_platform_test.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | func TestProviderPlatformString(t *testing.T) {
10 | tests := []struct {
11 | name string
12 | platform ProviderPlatform
13 | expected string
14 | }{
15 | {
16 | name: "linux amd64",
17 | platform: ProviderPlatform{OS: "linux", Arch: "amd64"},
18 | expected: "linux/amd64",
19 | },
20 | {
21 | name: "darwin arm64",
22 | platform: ProviderPlatform{OS: "darwin", Arch: "arm64"},
23 | expected: "darwin/arm64",
24 | },
25 | }
26 |
27 | for _, tt := range tests {
28 | t.Run(tt.name, func(t *testing.T) {
29 | assert.Equal(t, tt.expected, tt.platform.String())
30 | })
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/internal/terraform/provider_test.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestProviderName_Parse(t *testing.T) {
11 | tests := []struct {
12 | name string
13 | input string
14 | wantErr bool
15 | }{
16 | {
17 | name: "valid input",
18 | input: "namespace/type@1.0.0",
19 | wantErr: false,
20 | },
21 | {
22 | name: "valid input with latest version",
23 | input: "namespace/type@latest",
24 | wantErr: false,
25 | },
26 | {
27 | name: "valid input without version",
28 | input: "namespace/type",
29 | wantErr: false,
30 | },
31 | {
32 | name: "invalid input",
33 | input: "example",
34 | wantErr: true,
35 | },
36 | {
37 | name: "invalid namespace",
38 | input: "/type@1.0.0",
39 | wantErr: true,
40 | },
41 | {
42 | name: "invalid multiple namespaces",
43 | input: "namespace1/namespace2/type@1.0.0",
44 | wantErr: true,
45 | },
46 | {
47 | name: "invalid name",
48 | input: "namespace/@1.0.0",
49 | wantErr: true,
50 | },
51 | {
52 | name: "invalid version",
53 | input: "namespace/type@",
54 | wantErr: true,
55 | },
56 | {
57 | name: "invalid multiple versions",
58 | input: "namespace/type@1.0.0@2.0.0",
59 | wantErr: true,
60 | },
61 | }
62 |
63 | for _, tt := range tests {
64 | t.Run(tt.name, func(t *testing.T) {
65 | _, err := ParseProviderName(tt.input)
66 |
67 | if tt.wantErr {
68 | assert.Error(t, err)
69 | } else {
70 | assert.NoError(t, err)
71 | }
72 | })
73 | }
74 | }
75 |
76 | func TestParseProviderFromPath(t *testing.T) {
77 | tests := []struct {
78 | name string
79 | path string
80 | expectedProvider *Provider
81 | wantErr bool
82 | }{
83 | {
84 | name: "valid path",
85 | path: "/home/user/.terraform.d/plugin-cache/namespace/type/1.2.3/os_arch",
86 | expectedProvider: NewProvider(NewProviderName("namespace", "type", "1.2.3"), "os", "arch"),
87 | wantErr: false,
88 | },
89 | {
90 | name: "invalid path",
91 | path: "/home/user/.terraform.d/plugin-cache/namespace/type/version/os/arch",
92 | expectedProvider: nil,
93 | wantErr: true,
94 | },
95 | {
96 | name: "empty path",
97 | path: "",
98 | expectedProvider: nil,
99 | wantErr: true,
100 | },
101 | {
102 | name: "incompleted path",
103 | path: "namespace/type",
104 | expectedProvider: nil,
105 | wantErr: true,
106 | },
107 | }
108 |
109 | for _, tt := range tests {
110 | t.Run(tt.name, func(t *testing.T) {
111 | actualProvider, err := ParseProviderFromPath(tt.path)
112 |
113 | if tt.wantErr {
114 | assert.Error(t, err)
115 | } else {
116 | assert.NoError(t, err)
117 | }
118 |
119 | if !reflect.DeepEqual(actualProvider, tt.expectedProvider) {
120 | t.Errorf("ParseProviderFromPath(%q): expected provider %v, but got %v", tt.path, tt.expectedProvider, actualProvider)
121 | }
122 | })
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/internal/terraform/provider_version.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import "github.com/Masterminds/semver/v3"
4 |
5 | type ProviderVersion struct {
6 | Version string `json:"version"`
7 | Protocols []string `json:"protocols"`
8 | Platforms []ProviderPlatform `json:"platforms"`
9 | }
10 |
11 | func (p ProviderVersion) String() string {
12 | return p.Version
13 | }
14 |
15 | func (p ProviderVersion) SemanticVersion() (version *semver.Version, err error) {
16 | version, err = semver.NewVersion(p.Version)
17 | if err != nil {
18 | return
19 | }
20 | return
21 | }
22 |
--------------------------------------------------------------------------------
/internal/terraform/provider_version_test.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | func TestProviderVersionString(t *testing.T) {
10 | tests := []struct {
11 | name string
12 | version ProviderVersion
13 | expected string
14 | }{
15 | {
16 | name: "1.2.3",
17 | version: ProviderVersion{Version: "1.2.3"},
18 | expected: "1.2.3",
19 | },
20 | {
21 | name: "3.2.1",
22 | version: ProviderVersion{Version: "3.2.1"},
23 | expected: "3.2.1",
24 | },
25 | }
26 |
27 | for _, tt := range tests {
28 | t.Run(tt.name, func(t *testing.T) {
29 | assert.Equal(t, tt.expected, tt.version.String())
30 | })
31 | }
32 | }
33 |
34 | func TestProviderVersionSemanticVersion(t *testing.T) {
35 | tests := []struct {
36 | name string
37 | version ProviderVersion
38 | expected string
39 | wantErr bool
40 | }{
41 | {
42 | name: "valid semantic version",
43 | version: ProviderVersion{Version: "1.2.3"},
44 | expected: "1.2.3",
45 | wantErr: false,
46 | },
47 | {
48 | name: "invalid semantic version",
49 | version: ProviderVersion{Version: "a.b.c"},
50 | expected: "",
51 | wantErr: true,
52 | },
53 | }
54 |
55 | for _, tt := range tests {
56 | t.Run(tt.name, func(t *testing.T) {
57 | version, err := tt.version.SemanticVersion()
58 |
59 | if tt.wantErr {
60 | assert.Error(t, err)
61 | assert.Nil(t, version)
62 | } else {
63 | assert.NoError(t, err)
64 | assert.NotEmpty(t, version)
65 | assert.Equal(t, tt.expected, version.String())
66 | }
67 | })
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/internal/terraform/provider_versions.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | type ProviderVersions []*ProviderVersion
4 |
5 | func (p ProviderVersions) Last() *ProviderVersion {
6 | return p[len(p)-1]
7 | }
8 |
9 | // Implementing sort.Interface based on the Version field
10 |
11 | func (p ProviderVersions) Len() int {
12 | return len(p)
13 | }
14 |
15 | func (p ProviderVersions) Less(i, j int) bool {
16 | pi, _ := p[i].SemanticVersion()
17 | pj, _ := p[j].SemanticVersion()
18 | return pi.LessThan(pj)
19 | }
20 |
21 | func (p ProviderVersions) Swap(i, j int) {
22 | p[i], p[j] = p[j], p[i]
23 | }
24 |
--------------------------------------------------------------------------------
/internal/terraform/provider_versions_test.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "sort"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestProviderVersionsLast(t *testing.T) {
11 | tests := []struct {
12 | name string
13 | versions ProviderVersions
14 | expected *ProviderVersion
15 | }{
16 | {
17 | name: "valid version",
18 | versions: ProviderVersions{{Version: "1.0.0"}, {Version: "1.1.0"}, {Version: "1.2.0"}},
19 | expected: &ProviderVersion{Version: "1.2.0"},
20 | },
21 | {
22 | name: "another valid version",
23 | versions: ProviderVersions{{Version: "2.0.0"}, {Version: "1.5.0"}, {Version: "1.7.0"}},
24 | expected: &ProviderVersion{Version: "1.7.0"},
25 | },
26 | }
27 | for _, tt := range tests {
28 | t.Run(tt.name, func(t *testing.T) {
29 | assert.Equal(t, tt.expected, tt.versions.Last())
30 | })
31 | }
32 | }
33 |
34 | func TestProviderVersionsSort(t *testing.T) {
35 | tests := []struct {
36 | name string
37 | versions ProviderVersions
38 | expected ProviderVersions
39 | }{
40 | {
41 | name: "valid versions",
42 | versions: ProviderVersions{{Version: "1.2.0"}, {Version: "1.0.0"}, {Version: "1.1.0"}},
43 | expected: ProviderVersions{{Version: "1.0.0"}, {Version: "1.1.0"}, {Version: "1.2.0"}},
44 | },
45 | {
46 | name: "more valid versions",
47 | versions: ProviderVersions{{Version: "2.4.0"}, {Version: "3.0.1"}, {Version: "1.2.0"}},
48 | expected: ProviderVersions{{Version: "1.2.0"}, {Version: "2.4.0"}, {Version: "3.0.1"}},
49 | },
50 | }
51 | for _, tt := range tests {
52 | t.Run(tt.name, func(t *testing.T) {
53 | sort.Sort(tt.versions)
54 | for i, version := range tt.versions {
55 | assert.Equal(t, tt.expected[i], version)
56 |
57 | }
58 | })
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/internal/terraform/registry.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "log"
7 | "net/http"
8 |
9 | "github.com/spf13/viper"
10 | )
11 |
12 | type Registry struct {
13 | baseURL string
14 | }
15 |
16 | func NewRegistry(hostname string) *Registry {
17 | return &Registry{
18 | baseURL: fmt.Sprintf("https://%s/v1/providers", hostname),
19 | }
20 | }
21 |
22 | func (r Registry) String() string {
23 | return fmt.Sprintf("'%s'", r.baseURL)
24 | }
25 |
26 | type GetVersionsResponse struct {
27 | Versions ProviderVersions `json:"versions"`
28 | }
29 |
30 | func (r *Registry) GetVersions(provider *Provider) (ProviderVersions, error) {
31 | url := fmt.Sprintf("%s/%s/%s/versions", r.baseURL, provider.Namespace(), provider.ProviderType())
32 |
33 | if viper.GetBool("debug") {
34 | log.Printf("Requesting the next url: '%s' \n", url)
35 | }
36 |
37 | // Get request
38 | resp, err := http.Get(url)
39 | if err != nil {
40 | return nil, err
41 | }
42 | defer resp.Body.Close()
43 |
44 | switch resp.StatusCode {
45 | case 200:
46 | break
47 | case 404:
48 | return nil, fmt.Errorf("provider not found")
49 | default:
50 | return nil, fmt.Errorf("unable to get provider versions: %q", resp.Status)
51 | }
52 |
53 | // Parse response
54 | var versionsResp GetVersionsResponse
55 | err = json.NewDecoder(resp.Body).Decode(&versionsResp)
56 | if err != nil {
57 | return nil, err
58 | }
59 |
60 | return versionsResp.Versions, nil
61 | }
62 |
63 | type GetPackageResponse struct {
64 | Protocols []string `json:"protocols"`
65 | OS string `json:"os"`
66 | Arch string `json:"arch"`
67 | Filename string `json:"filename"`
68 | DownloadURL string `json:"download_url"`
69 | SHASumsURL string `json:"shasums_url"`
70 | SHASumsSignatureURL string `json:"shasums_signature_url"`
71 | SHASum string `json:"shasum"`
72 | SigningKeys struct {
73 | GPGPublicKeys []struct {
74 | KeyID string `json:"key_id"`
75 | ASCIIArmor string `json:"ascii_armor"`
76 | TrustSignature string `json:"trust_signature"`
77 | Source string `json:"source"`
78 | SourceURL string `json:"source_url"`
79 | } `json:"gpg_public_keys"`
80 | } `json:"signing_keys"`
81 | }
82 |
83 | func (r *Registry) GetPackage(provider *Provider) (*GetPackageResponse, error) {
84 | url := fmt.Sprintf("%s/%s/%s/%s/download/%s/%s", r.baseURL, provider.Namespace(), provider.ProviderType(), provider.Version(), provider.OperatingSystem(), provider.Architecture())
85 |
86 | if viper.GetBool("debug") {
87 | log.Printf("Requesting the next url: '%s' \n", url)
88 | }
89 |
90 | // Get request
91 | resp, err := http.Get(url)
92 | if err != nil {
93 | return nil, err
94 | }
95 | defer resp.Body.Close()
96 |
97 | switch resp.StatusCode {
98 | case 200:
99 | break
100 | case 404:
101 | return nil, fmt.Errorf("provider not found")
102 | default:
103 | return nil, fmt.Errorf("unable to download provider: %q", resp.Status)
104 | }
105 |
106 | // Parse response
107 | var packageResp GetPackageResponse
108 | err = json.NewDecoder(resp.Body).Decode(&packageResp)
109 | if err != nil {
110 | return nil, err
111 | }
112 |
113 | return &packageResp, nil
114 | }
115 |
--------------------------------------------------------------------------------
/internal/terraform/registry_test.go:
--------------------------------------------------------------------------------
1 | package terraform
2 |
3 | import (
4 | "net/http"
5 | "net/http/httptest"
6 | "testing"
7 |
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestGetVersions(t *testing.T) {
12 | tests := []struct {
13 | name string
14 | mockServer *httptest.Server
15 | provider *Provider
16 | wantErr bool
17 | }{
18 | {
19 | name: "valid versions",
20 | mockServer: makeValidVersionsServer(),
21 | provider: NewProvider(NewProviderName("hashicorp", "null", "3.2.1"), "linux", "amd64"),
22 | wantErr: false,
23 | },
24 | {
25 | name: "package not found",
26 | mockServer: makeNotFoundServer(),
27 | provider: NewProvider(NewProviderName("hashiwhat", "idontexist", "0.0.0"), "linux", "amd64"),
28 | wantErr: true,
29 | },
30 | }
31 |
32 | for _, tt := range tests {
33 | t.Run(tt.name, func(t *testing.T) {
34 | server := tt.mockServer
35 | defer server.Close()
36 |
37 | registry := Registry{baseURL: server.URL}
38 | versions, err := registry.GetVersions(tt.provider)
39 |
40 | if tt.wantErr {
41 | assert.Error(t, err)
42 | assert.Nil(t, versions)
43 | } else {
44 | assert.NoError(t, err)
45 | assert.NotZero(t, len(versions))
46 | }
47 | })
48 | }
49 | }
50 |
51 | func TestGetPackage(t *testing.T) {
52 | tests := []struct {
53 | name string
54 | mockServer *httptest.Server
55 | provider *Provider
56 | wantErr bool
57 | }{
58 | {
59 | name: "valid package",
60 | mockServer: makeValidServer(),
61 | provider: NewProvider(NewProviderName("hashicorp", "null", "3.2.1"), "linux", "amd64"),
62 | wantErr: false,
63 | },
64 | {
65 | name: "package not found",
66 | mockServer: makeNotFoundServer(),
67 | provider: NewProvider(NewProviderName("hashicorp", "whatever", "0.0.0"), "linux", "amd64"),
68 | wantErr: true,
69 | },
70 | }
71 |
72 | for _, tt := range tests {
73 | t.Run(tt.name, func(t *testing.T) {
74 | server := tt.mockServer
75 | defer server.Close()
76 |
77 | registry := Registry{baseURL: server.URL}
78 | pkg, err := registry.GetPackage(tt.provider)
79 |
80 | if tt.wantErr {
81 | assert.Error(t, err)
82 | assert.Nil(t, pkg)
83 | } else {
84 | assert.NoError(t, err)
85 | assert.NotEmpty(t, pkg.DownloadURL)
86 | }
87 | })
88 | }
89 | }
90 |
91 | func makeValidVersionsServer() *httptest.Server {
92 | return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
93 | w.WriteHeader(http.StatusOK)
94 | w.Write([]byte(`{
95 | "id": "hashicorp/null",
96 | "versions": [
97 | {
98 | "version": "3.2.1",
99 | "protocols": [
100 | "5.0"
101 | ],
102 | "platforms": [
103 | {
104 | "os": "linux",
105 | "arch": "amd64"
106 | }
107 | ]
108 | }
109 | ],
110 | "warnings": null
111 | }`))
112 | }))
113 | }
114 |
115 | func makeValidServer() *httptest.Server {
116 | return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
117 | w.WriteHeader(http.StatusOK)
118 | w.Write([]byte(`{
119 | "protocols": [
120 | "5.0"
121 | ],
122 | "os": "linux",
123 | "arch": "amd64",
124 | "filename": "terraform-provider-null_3.2.1_linux_amd64.zip",
125 | "download_url": "https://releases.hashicorp.com/terraform-provider-null/3.2.1/terraform-provider-null_3.2.1_linux_amd64.zip",
126 | "shasums_url": "https://releases.hashicorp.com/terraform-provider-null/3.2.1/terraform-provider-null_3.2.1_SHA256SUMS",
127 | "shasums_signature_url": "https://releases.hashicorp.com/terraform-provider-null/3.2.1/terraform-provider-null_3.2.1_SHA256SUMS.72D7468F.sig",
128 | "shasum": "74cb22c6700e48486b7cabefa10b33b801dfcab56f1a6ac9b6624531f3d36ea3",
129 | "signing_keys": {
130 | "gpg_public_keys": [
131 | {
132 | "key_id": "34365D9472D7468F",
133 | "ascii_armor": "-----BEGIN PGP PUBLIC KEY BLOCK-----",
134 | "trust_signature": "",
135 | "source": "HashiCorp",
136 | "source_url": "https://www.hashicorp.com/security.html"
137 | }
138 | ]
139 | }
140 | }`))
141 | }))
142 | }
143 |
144 | func makeNotFoundServer() *httptest.Server {
145 | return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
146 | w.WriteHeader(http.StatusNotFound)
147 | w.Write([]byte(`{
148 | "errors": [
149 | "Not Found"
150 | ]
151 | }`))
152 | }))
153 | }
154 |
--------------------------------------------------------------------------------
/internal/tpm/base.go:
--------------------------------------------------------------------------------
1 | package tpm
2 |
3 | import (
4 | "sort"
5 |
6 | "github.com/Madh93/tpm/internal/terraform"
7 | )
8 |
9 | var registry *terraform.Registry
10 |
11 | func setLatestProviderVersion(provider *terraform.Provider) (err error) {
12 | versions, err := registry.GetVersions(provider)
13 | if err != nil {
14 | return
15 | }
16 |
17 | sort.Sort(versions)
18 |
19 | provider.SetVersion(versions.Last().String())
20 |
21 | return nil
22 | }
23 |
24 | func removeDuplicatedProviders(providers []*terraform.Provider) []*terraform.Provider {
25 | found := map[string]bool{}
26 | result := []*terraform.Provider{}
27 |
28 | for _, provider := range providers {
29 | if !found[provider.String()] {
30 | found[provider.String()] = true
31 | result = append(result, provider)
32 | }
33 | }
34 |
35 | return result
36 | }
37 |
--------------------------------------------------------------------------------
/internal/tpm/install.go:
--------------------------------------------------------------------------------
1 | package tpm
2 |
3 | import (
4 | "io"
5 | "log"
6 | "net/http"
7 | "os"
8 |
9 | "github.com/Madh93/tpm/internal/compression"
10 | "github.com/Madh93/tpm/internal/parser"
11 | "github.com/Madh93/tpm/internal/terraform"
12 | "github.com/spf13/viper"
13 | )
14 |
15 | func ParseProvidersFromFile(filename string) (providers []*terraform.Provider, err error) {
16 | if viper.GetBool("debug") {
17 | log.Printf("Reading '%s' providers file \n", filename)
18 | }
19 |
20 | // Setup input parser
21 | parser, err := parser.NewParser(filename)
22 | if err != nil {
23 | return
24 | }
25 |
26 | // Read file
27 | data, err := os.ReadFile(filename)
28 | if err != nil {
29 | return
30 | }
31 |
32 | // Parse providers
33 | providers, err = parser.Parse(data)
34 | if err != nil {
35 | return
36 | }
37 |
38 | // Remove duplicates
39 | providers = removeDuplicatedProviders(providers)
40 |
41 | return
42 | }
43 |
44 | func Install(provider *terraform.Provider, force bool) (err error) {
45 | if viper.GetBool("debug") {
46 | log.Printf("Installing %s...\n", provider)
47 | }
48 |
49 | // Setup registry
50 | registry = terraform.NewRegistry(viper.GetString("terraform_registry"))
51 |
52 | // Set latest version
53 | if provider.Version() == "latest" {
54 | err := setLatestProviderVersion(provider)
55 | if err != nil {
56 | return err
57 | }
58 | }
59 |
60 | // Check provider already exists
61 | if !force {
62 | if _, err = os.Stat(provider.InstallationPath()); !os.IsNotExist(err) {
63 | if viper.GetBool("debug") {
64 | log.Printf("Provider already installed in '%s' directory. Use '--force' to reinstall\n", provider.InstallationPath())
65 | }
66 | return nil
67 | }
68 | }
69 |
70 | // Download
71 | filename, err := downloadProvider(provider)
72 | if err != nil {
73 | return
74 | }
75 |
76 | // Extract
77 | err = extractProvider(provider, filename)
78 | if err != nil {
79 | return
80 | }
81 |
82 | return nil
83 | }
84 |
85 | func downloadProvider(provider *terraform.Provider) (filename string, err error) {
86 | // Create Temporary file
87 | file, err := os.CreateTemp("", "")
88 | if err != nil {
89 | return
90 | }
91 |
92 | if viper.GetBool("debug") {
93 | log.Printf("Created tpm file under '%s' \n", file.Name())
94 | }
95 |
96 | // Get Download URL
97 | pkg, err := registry.GetPackage(provider)
98 | if err != nil {
99 | return
100 | }
101 |
102 | if viper.GetBool("debug") {
103 | log.Printf("Downloading provider from '%s'\n", pkg.DownloadURL)
104 | }
105 |
106 | // Download
107 | resp, err := http.Get(pkg.DownloadURL)
108 | if err != nil {
109 | return
110 | }
111 | defer resp.Body.Close()
112 |
113 | // Save to file
114 | _, err = io.Copy(file, resp.Body)
115 | if err != nil {
116 | return
117 | }
118 |
119 | if viper.GetBool("debug") {
120 | log.Println("The download has finished sucessfully!")
121 | }
122 |
123 | return file.Name(), nil
124 | }
125 |
126 | func extractProvider(provider *terraform.Provider, filename string) (err error) {
127 | destinationDir := provider.InstallationPath()
128 |
129 | if viper.GetBool("debug") {
130 | log.Printf("Provider will be extracted under '%s'\n", destinationDir)
131 | }
132 |
133 | // Extract
134 | err = compression.Unzip(filename, destinationDir)
135 | if err != nil {
136 | return
137 | }
138 |
139 | // Delete Temporary file
140 | err = os.Remove(filename)
141 | if err != nil {
142 | return
143 | }
144 |
145 | if viper.GetBool("debug") {
146 | log.Println("The provider has been extracted sucessfully!")
147 | }
148 |
149 | return nil
150 | }
151 |
--------------------------------------------------------------------------------
/internal/tpm/list.go:
--------------------------------------------------------------------------------
1 | package tpm
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | "path/filepath"
8 |
9 | "github.com/Madh93/tpm/internal/formatter"
10 | "github.com/Madh93/tpm/internal/pathutils"
11 | "github.com/Madh93/tpm/internal/terraform"
12 | "github.com/spf13/viper"
13 | )
14 |
15 | func List() (err error) {
16 | if viper.GetBool("debug") {
17 | log.Printf("Listing providers installed from '%s' registry\n", viper.GetString("terraform_registry"))
18 | }
19 |
20 | // Find providers
21 | providers, err := findProviders()
22 | if err != nil {
23 | return
24 | }
25 |
26 | // Setup output formatter
27 | formatter, err := formatter.NewFormatter(viper.GetString("output"))
28 | if err != nil {
29 | return
30 | }
31 |
32 | // Show output
33 | output, err := formatter.Format(providers)
34 | if err != nil {
35 | return
36 | }
37 |
38 | fmt.Print(string(output))
39 |
40 | return nil
41 | }
42 |
43 | func findProviders() (providers []*terraform.Provider, err error) {
44 | registryPath := filepath.Join(
45 | viper.GetString("terraform_plugin_cache_dir"),
46 | viper.GetString("terraform_registry"),
47 | )
48 |
49 | // Check registry path exists
50 | if _, err = os.Stat(registryPath); os.IsNotExist(err) {
51 | return nil, nil
52 | }
53 |
54 | registryDepth := pathutils.PathDepth(registryPath)
55 |
56 | // Find providers in registry path
57 | err = filepath.Walk(registryPath, func(path string, info os.FileInfo, errf error) error {
58 | if err != nil {
59 | return err
60 | }
61 | if info.IsDir() && pathutils.PathDepth(path) == registryDepth+4 {
62 | provider, err := terraform.ParseProviderFromPath(path)
63 | if err != nil {
64 | return err
65 | }
66 | providers = append(providers, provider)
67 | }
68 | return nil
69 | })
70 |
71 | return providers, nil
72 | }
73 |
--------------------------------------------------------------------------------
/internal/tpm/purge.go:
--------------------------------------------------------------------------------
1 | package tpm
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | "path/filepath"
8 |
9 | "github.com/spf13/viper"
10 | )
11 |
12 | func Purge() (err error) {
13 | fmt.Println("Removing all providers...")
14 |
15 | registryPath := filepath.Join(
16 | viper.GetString("terraform_plugin_cache_dir"),
17 | viper.GetString("terraform_registry"),
18 | )
19 |
20 | if viper.GetBool("debug") {
21 | log.Printf("Providers should be located in '%s' directory\n", registryPath)
22 | }
23 |
24 | // Check provider already exists
25 | if _, err = os.Stat(registryPath); os.IsNotExist(err) {
26 | if viper.GetBool("debug") {
27 | log.Printf("Registry path under '%s' does not exist! Ignoring...\n", registryPath)
28 | }
29 | fmt.Printf("No installed providers from '%s' registry! Ignoring...\n", viper.GetString("terraform_registry"))
30 | return nil
31 | }
32 |
33 | // Remove provider
34 | err = os.RemoveAll(registryPath)
35 | if err != nil {
36 | return
37 | }
38 |
39 | fmt.Println("All providers were removed sucessfully!")
40 |
41 | return nil
42 | }
43 |
--------------------------------------------------------------------------------
/internal/tpm/uninstall.go:
--------------------------------------------------------------------------------
1 | package tpm
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 |
8 | "github.com/Madh93/tpm/internal/terraform"
9 | "github.com/spf13/viper"
10 | )
11 |
12 | func Uninstall(provider *terraform.Provider) (err error) {
13 | if viper.GetBool("debug") {
14 | log.Printf("Uninstalling %s...\n", provider)
15 | }
16 |
17 | // Setup registry
18 | registry = terraform.NewRegistry(viper.GetString("terraform_registry"))
19 |
20 | // Set latest version
21 | if provider.Version() == "latest" {
22 | err := setLatestProviderVersion(provider)
23 | if err != nil {
24 | return err
25 | }
26 | }
27 |
28 | var installationPath = provider.InstallationPath()
29 | if viper.GetBool("debug") {
30 | log.Printf("Provider should be located in '%s' directory\n", installationPath)
31 | }
32 |
33 | // Check provider already exists
34 | if _, err = os.Stat(installationPath); os.IsNotExist(err) {
35 | return fmt.Errorf("provider is not installed")
36 | }
37 |
38 | // Remove provider
39 | err = os.RemoveAll(installationPath)
40 | if err != nil {
41 | return
42 | }
43 |
44 | if viper.GetBool("debug") {
45 | log.Printf("%s has been uninstalled sucessfully!\n", provider)
46 | }
47 |
48 | return nil
49 | }
50 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 |
6 | "github.com/Madh93/tpm/cmd"
7 | )
8 |
9 | func main() {
10 | log.SetFlags(log.Default().Flags())
11 | cmd.Execute()
12 | }
13 |
--------------------------------------------------------------------------------