112 lines
2.4 KiB
Go
112 lines
2.4 KiB
Go
// Copyright 2022 Ariadne Conill
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/docker/cli/cli/config"
|
|
"github.com/docker/cli/cli/config/types"
|
|
"github.com/google/go-containerregistry/pkg/authn"
|
|
"github.com/google/go-containerregistry/pkg/name"
|
|
"github.com/joho/godotenv"
|
|
"github.com/urfave/cli"
|
|
)
|
|
|
|
const version = "unknown"
|
|
|
|
func main() {
|
|
if env := os.Getenv("PLUGIN_ENV_FILE"); env != "" {
|
|
godotenv.Load(env)
|
|
}
|
|
|
|
app := cli.NewApp()
|
|
app.Name = "crane-login plugin"
|
|
app.Usage = "crane-login"
|
|
app.Action = run
|
|
app.Version = version
|
|
app.Flags = []cli.Flag{
|
|
cli.StringFlag{
|
|
Name: "registry",
|
|
Usage: "docker registry for login",
|
|
EnvVar: "PLUGIN_REGISTRY",
|
|
},
|
|
cli.StringFlag{
|
|
Name: "username",
|
|
Usage: "username for login",
|
|
EnvVar: "PLUGIN_USERNAME",
|
|
},
|
|
cli.StringFlag{
|
|
Name: "password",
|
|
Usage: "password for login",
|
|
EnvVar: "PLUGIN_PASSWORD",
|
|
},
|
|
}
|
|
|
|
if err := app.Run(os.Args); err != nil {
|
|
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(c *cli.Context) error {
|
|
user := c.String("username")
|
|
if user == "" {
|
|
return errors.New("username required")
|
|
}
|
|
|
|
pass := c.String("password")
|
|
if pass == "" {
|
|
return errors.New("password required")
|
|
}
|
|
|
|
reg, err := name.NewRegistry(c.String("registry"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
workspaceConfig := filepath.Join(os.Getenv("CI_WORKSPACE"), ".docker.json")
|
|
cf, err := config.Load(workspaceConfig)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
regName := reg.Name()
|
|
creds := cf.GetCredentialsStore(regName)
|
|
|
|
if regName == name.DefaultRegistry {
|
|
regName = authn.DefaultAuthKey
|
|
}
|
|
|
|
if err := creds.Store(types.AuthConfig{
|
|
ServerAddress: regName,
|
|
Username: user,
|
|
Password: pass,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := cf.Save(); err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("Logged in via %s.\n", cf.Filename)
|
|
|
|
return nil
|
|
}
|