Skip to content

Commit

Permalink
add cli commands, fix bugs in viewer
Browse files Browse the repository at this point in the history
  • Loading branch information
gvkhna committed May 29, 2024
1 parent 32ba2be commit 62f08ee
Show file tree
Hide file tree
Showing 26 changed files with 824 additions and 477 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ module.exports = {
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/triple-slash-reference': 'off',
'no-console': ['error', {allow: ['log']}],
'no-console': ['warn'],
'prefer-const': 'off',
'no-shadow': 'off',
'@typescript-eslint/no-shadow': ['error'],
Expand Down
5 changes: 4 additions & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export default defineConfig({
if (filterBases.some((base) => url.pathname.startsWith(`/${base}/`))) {
sitemapAllow = false // Reject the page
}
// eslint-disable-next-line no-undef
// eslint-disable-next-line no-undef, no-console
console.log(`sitemap include?: ${url.pathname} -> ${sitemapAllow}`)
return sitemapAllow // Include? the page
},
Expand All @@ -91,6 +91,9 @@ export default defineConfig({
},
// https://github.com/sveltejs/kit/issues/8140
optimizeDeps: {exclude: ['fsevents']},
esbuild: {
drop: PROD ? ['console', 'debugger'] : []
},
ssr: {
//external: ['node:crypto']
}
Expand Down
15 changes: 15 additions & 0 deletions cli/.goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ archives:
files:
- none*


dockers:
-
ids:
- dive
dockerfile: Dockerfile
# todo: on 1.0 remove 'v' prefix
image_templates:
- "wagoodman/dive:latest"
- "wagoodman/dive:{{ .Tag }}"
- "wagoodman/dive:v{{ .Major }}"
- "wagoodman/dive:v{{ .Major }}.{{ .Minor }}"
build_flag_templates:
- "--build-arg=DOCKER_CLI_VERSION={{.Env.DOCKER_CLI_VERSION}}"

checksum:
name_template: 'checksums.txt'

Expand Down
71 changes: 60 additions & 11 deletions cli/cmd/build.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package cmd

import (
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/gvkhna/warpdive/dive"
"github.com/gvkhna/warpdive/runtime"
)

// buildCmd represents the build command
var buildCmd = &cobra.Command{
Use: "build [any valid `docker build` arguments]",
Short: "Builds and analyzes a docker image from a Dockerfile (this is a thin wrapper for the `docker build` command).",
Use: "build [any args to docker build]",
Short: "Builds and pushes a container image from a Dockerfile to warpdive.xyz",
DisableFlagParsing: true,
Run: doBuildCmd,
}
Expand All @@ -22,17 +23,65 @@ func init() {

// doBuildCmd implements the steps taken for the build command
func doBuildCmd(cmd *cobra.Command, args []string) {
initLogging()
// initLogging()

var remainingArgs []string
var sourceFlagValue string
var foundSource bool
var projectFlagValue string
// var foundProject bool
var exportFlagValue string
var foundExport bool

// Manual parsing to handle help, source, ignore-errors flags
for i := 0; i < len(args); i++ {
switch {
case args[i] == "-h" || args[i] == "--help":
cmd.Help()
os.Exit(0) // Exit after displaying help, no further action required
// case strings.HasPrefix(args[i], "--source="):
// sourceFlagValue = strings.TrimPrefix(args[i], "--source=")
// foundSource = true
case args[i] == "--wd-source" && i+1 < len(args):
sourceFlagValue = args[i+1]
i++ // Skip the next item as it is the value for --source
foundSource = true
// case strings.HasPrefix(args[i], "--project="):
// projectFlagValue = strings.TrimPrefix(args[i], "--project=")
// foundProject = true
case args[i] == "--wd-project" && i+1 < len(args):
projectFlagValue = args[i+1]
i++ // Skip the value next to the flag
// foundProject = true

case args[i] == "--wd-export" && i+1 < len(args):
exportFlagValue = args[i+1]
i++ // Skip the value next to the flag
foundExport = true
default:
remainingArgs = append(remainingArgs, args[i])
}
}

if !foundSource {
sourceFlagValue = defaultSource // Use a default or manage missing source
}

if foundExport {
exportFile = exportFlagValue
}

// there is no cli options allowed, only config can be supplied
// todo: allow for an engine flag to be passed to dive but not the container engine
engine := viper.GetString("container-engine")
// fmt.Printf("Using engine: %s\n", sourceFlagValue)
// fmt.Printf("Passing args to Docker: %v\n", remainingArgs)

runtime.Run(runtime.Options{
Ci: isCi,
Source: dive.ParseImageSource(engine),
BuildArgs: args,
// Ci: isCi,
// CiConfig: ciConfig,
// Source: dive.ParseImageSource(engine),
BuildArgs: remainingArgs,
Engine: runtime.GetPreferredEngine(sourceFlagValue),
ExportFile: exportFile,
CiConfig: ciConfig,
Project: projectFlagValue,
Source: dive.ParseImageSource(sourceFlagValue),
})
}
79 changes: 79 additions & 0 deletions cli/cmd/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package cmd

import (
"fmt"
"net/url"
"os"
"os/user"
"path/filepath"

"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)

var loginCmd = &cobra.Command{
Use: "login",
Short: "Authenticate to the cli with your API Key",
Run: doLoginCmd,
}

func init() {
rootCmd.AddCommand(loginCmd)
}

// doLoginCmd implements the login logic
func doLoginCmd(cmd *cobra.Command, args []string) {
var apiKey string

fmt.Print("Enter your API key: ")
_, err := fmt.Scanln(&apiKey)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading API key: %v\n", err)
os.Exit(1)
}

// Get the user's home directory
usr, err := user.Current()
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot find the user home directory: %v\n", err)
os.Exit(1)
}
configPath := filepath.Join(usr.HomeDir, ".warpdiverc")

// Check if the WARPDIVE_ENDPOINT environment variable is set and is a valid URL
endpoint := os.Getenv("WARPDIVE_ENDPOINT")
if endpoint == "" {
endpoint = "https://www.warpdive.xyz" // Default URL
fmt.Println("Using default API endpoint.")
} else {
_, err := url.ParseRequestURI(endpoint)
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid URL in WARPDIVE_ENDPOINT: %v\n", err)
os.Exit(1)
}
fmt.Printf("Using custom API endpoint: %s\n", endpoint)
}

// Prepare the API key data in YAML format using the endpoint
data := map[string]interface{}{
endpoint: map[string]interface{}{
"api_key": map[string]string{
"value": apiKey,
},
},
}
fileData, err := yaml.Marshal(data)
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshaling API key data: %v\n", err)
os.Exit(1)
}

// Write the data to the .warpdiverc file
err = os.WriteFile(configPath, fileData, 0600) // rw------- permissions
if err != nil {
fmt.Fprintf(os.Stderr, "Error writing API key to file: %v\n", err)
os.Exit(1)
}

fmt.Println("API Key saved successfully to ~/.warpdiverc.")
}
88 changes: 88 additions & 0 deletions cli/cmd/push.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package cmd

import (
"fmt"
"os"

"github.com/gvkhna/warpdive/dive"
"github.com/gvkhna/warpdive/runtime"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var pushCmd = &cobra.Command{
Use: "push [IMAGE ID]",
Short: "Pushes a container image to to warpdive.xyz",
Args: cobra.ExactArgs(1), // Expect exactly one argument: the docker image/tag id
// DisableFlagParsing: true,
Run: doPushCmd,
}

// var outputFilePath string

func init() {
rootCmd.AddCommand(pushCmd)
// exportCmd.Flags().StringVarP(&outputFilePath, "output", "o", "", "Optional: Specify the output file path or directory to place the .warpdive file")
// rootCmd.PersistentFlags().String("source", "docker", "The container engine to fetch the image from. Allowed values: "+strings.Join(dive.ImageSources, ", "))

// exportCmd.Flags().StringVarP(&outputFilePath, "output", "o", "", "Optional: Specify the output file path or directory to place the .warpdive file")
}

// doExportCmd implements the steps taken for the export command
func doPushCmd(cmd *cobra.Command, args []string) {
// initLogging()
// imageID := args[0]

// engine := viper.GetString("source")
// engine := viper.GetString("container-engine")
// fmt.Printf("Using engine %s to export image %s to file %s\n", engine, imageID, outputFilePath)

// fmt.Printf("Exporting image to file %s\n", outputFilePath)

userImage := args[0]
if userImage == "" {
fmt.Println("No image argument given")
os.Exit(1)
}

// initLogging()

// isCi, ciConfig, err := configureCi()

// if err != nil {
// fmt.Printf("ci configuration error: %v\n", err)
// os.Exit(1)
// }

var sourceType dive.ImageSource
var imageStr string

sourceType, imageStr = dive.DeriveImageSource(userImage)

if sourceType == dive.SourceUnknown {
sourceStr := viper.GetString("source")
sourceType = dive.ParseImageSource(sourceStr)
if sourceType == dive.SourceUnknown {
fmt.Printf("unable to determine image source: %v\n", sourceStr)
os.Exit(1)
}

imageStr = userImage
}

// ignoreErrors, err := cmd.PersistentFlags().GetBool("ignore-errors")
// if err != nil {
// logrus.Error("unable to get 'ignore-errors' option:", err)
// }

runtime.Run(runtime.Options{
// Ci: isCi,
Image: imageStr,
Engine: defaultSource,
Source: dive.ParseImageSource(defaultSource),
// Source: dive.ParseImageSource(engine),
PushArgs: args,
// ExportFile: outputFilePath,
// CiConfig: ciConfig,
})
}
Loading

0 comments on commit 62f08ee

Please sign in to comment.