diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 0000000000..e4a95ad23d
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: [skevetter]
diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md
deleted file mode 100644
index fdcb83f378..0000000000
--- a/.github/ISSUE_TEMPLATE/bug-report.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-name: Bug report
-about: Create a report to help us reproduce and fix a bug
-labels:
-- kind/bug
----
-
-
-
-**What happened?**
-
-
-**What did you expect to happen instead?**
-
-
-**How can we reproduce the bug?** (as minimally and precisely as possible)
-
-My *`devcontainer.json`*:
-```
-{
- "name": "...",
- ...
-}
-```
-
-**Local Environment:**
-- DevPod Version: [use `devpod version`]
-- Operating System: windows | linux | mac
-- ARCH of the OS: AMD64 | ARM64 | i386
-
-**DevPod Provider:**
-- Cloud Provider: google | aws | azure | digitalOcean
-- Kubernetes Provider: [use `kubectl version`]
-- Local/remote provider: docker | ssh
-- Custom provider: provide imported `provider.yaml` config file
-
-
-**Anything else we need to know?**
diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml
new file mode 100644
index 0000000000..1199fda482
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug-report.yml
@@ -0,0 +1,162 @@
+name: Bug Report
+description: Report a bug to help fix your issue
+title: "[Bug]: "
+labels:
+ - kind/bug
+body:
+ - type: checkboxes
+ id: preflight
+ attributes:
+ label: Before submitting
+ options:
+ - label: I have searched existing issues to confirm this is not a duplicate
+ required: true
+ - label: I am running the latest version of DevPod
+ required: false
+
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: What happened?
+ description: A clear description of the bug.
+ validations:
+ required: true
+
+ - type: textarea
+ id: expected
+ attributes:
+ label: What did you expect to happen instead?
+ validations:
+ required: true
+
+ - type: textarea
+ id: repro
+ attributes:
+ label: Steps to reproduce
+ description: Minimal steps to reproduce. The more precise, the faster the issue can be investigated.
+ placeholder: |
+ 1. Run `devpod up ...`
+ 2. Click on ...
+ 3. See error ...
+ validations:
+ required: true
+
+ - type: textarea
+ id: devcontainer
+ attributes:
+ label: devcontainer.json
+ description: Paste your devcontainer.json if applicable.
+ render: json
+ validations:
+ required: false
+
+ - type: textarea
+ id: logs
+ attributes:
+ label: Error output / logs
+ description: Paste relevant error messages, CLI output, or logs. Use `devpod provider logs` for provider logs.
+ render: shell
+ validations:
+ required: false
+
+ - type: dropdown
+ id: reproducibility
+ attributes:
+ label: How often does this happen?
+ options:
+ - Every time
+ - Sometimes
+ - Only once
+ validations:
+ required: true
+
+ - type: dropdown
+ id: os
+ attributes:
+ label: Operating system
+ options:
+ - macOS
+ - Linux
+ - Windows
+ validations:
+ required: true
+
+ - type: input
+ id: distro
+ attributes:
+ label: Linux distribution (if applicable)
+ description: e.g. Ubuntu 24.04, Fedora 41, Arch, Debian 13, NixOS
+ placeholder: Ubuntu 24.04
+ validations:
+ required: false
+
+ - type: dropdown
+ id: arch
+ attributes:
+ label: Architecture
+ options:
+ - ARM64
+ - AMD64
+ validations:
+ required: true
+
+ - type: dropdown
+ id: interface
+ attributes:
+ label: Desktop app or CLI?
+ options:
+ - Desktop app
+ - CLI only
+ - Both
+ validations:
+ required: true
+
+ - type: input
+ id: version
+ attributes:
+ label: DevPod version
+ description: Output of `devpod version`
+ placeholder: v0.6.0
+ validations:
+ required: true
+
+ - type: dropdown
+ id: provider
+ attributes:
+ label: DevPod provider
+ options:
+ - Docker
+ - SSH
+ - Kubernetes
+ - AWS
+ - Google Cloud
+ - Azure
+ - DigitalOcean
+ - Other / Custom
+ validations:
+ required: true
+
+ - type: input
+ id: provider-version
+ attributes:
+ label: Provider version
+ description: Output of `devpod provider list` for the relevant provider
+ placeholder: v0.1.0
+ validations:
+ required: false
+
+ - type: textarea
+ id: screenshots
+ attributes:
+ label: Screenshots
+ description: If this is a UI bug, please include screenshots or a screen recording.
+ validations:
+ required: false
+
+ - type: textarea
+ id: additional
+ attributes:
+ label: Anything else?
+ description: Additional context, workarounds you have tried, links to related issues.
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md
deleted file mode 100644
index f3f2fe61a3..0000000000
--- a/.github/ISSUE_TEMPLATE/feature-request.md
+++ /dev/null
@@ -1,17 +0,0 @@
----
-name: Feature request
-about: Suggest an idea for this project
-labels:
-- kind/feature
----
-
-**Is your feature request related to a problem?**
-
-
-**Which solution do you suggest?**
-
-
-**Which alternative solutions exist?**
-
-
-**Additional context**
diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml
new file mode 100644
index 0000000000..eb8706d043
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature-request.yml
@@ -0,0 +1,75 @@
+name: Feature Request
+description: Suggest an idea or improvement
+title: "[Feature]: "
+labels:
+ - kind/feature
+body:
+ - type: checkboxes
+ id: preflight
+ attributes:
+ label: Before submitting
+ options:
+ - label: I have searched existing issues and discussions to confirm this hasn't been requested
+ required: true
+
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem or motivation
+ description: What problem does this solve? Who benefits from it?
+ placeholder: "I want [goal] because [reason]..."
+ validations:
+ required: true
+
+ - type: textarea
+ id: solution
+ attributes:
+ label: Proposed solution
+ description: Describe the solution you'd like. Be as specific as possible.
+ validations:
+ required: true
+
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: Alternatives considered
+ description: What other approaches have you considered? How do other tools handle this?
+ validations:
+ required: false
+
+ - type: dropdown
+ id: area
+ attributes:
+ label: Area
+ description: Which part of DevPod does this affect?
+ multiple: true
+ options:
+ - CLI
+ - Desktop app
+ - Providers
+ - Dev containers
+ - SSH / tunneling
+ - Documentation
+ - Other
+ validations:
+ required: true
+
+ - type: textarea
+ id: acceptance
+ attributes:
+ label: Acceptance criteria
+ description: When is this feature complete? What should it do?
+ placeholder: |
+ - [ ] User can ...
+ - [ ] CLI command `devpod ...` supports ...
+ - [ ] Desktop UI shows ...
+ validations:
+ required: false
+
+ - type: textarea
+ id: context
+ attributes:
+ label: Additional context
+ description: Screenshots, mockups, links to related issues or discussions.
+ validations:
+ required: false
diff --git a/.golangci.yaml b/.golangci.yaml
index 207544f91c..0964bacd04 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -2,6 +2,12 @@ version: "2"
run:
timeout: 5m
concurrency: 8
+formatters:
+ enable:
+ - gci
+ - gofumpt
+ - goimports
+ - golines
linters:
enable:
- cyclop
@@ -27,7 +33,7 @@ linters:
- whitespace
settings:
cyclop:
- max-complexity: 7
+ max-complexity: 8
revive:
rules:
- name: argument-limit
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 294463fbc1..99fabd7960 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -33,31 +33,28 @@ repos:
- id: shfmt
args: ["-i", "4", "-ci", "-w"]
- repo: https://github.com/rhysd/actionlint
- rev: v1.7.11
+ rev: v1.7.12
hooks:
- id: actionlint
files: '^\.github/workflows/'
- repo: https://github.com/biomejs/pre-commit
- rev: v2.4.2
+ rev: v2.4.12
hooks:
- id: biome-format
exclude: '^(\.github/actions/|\.vscode/|desktop/|docs/|examples/)'
- id: biome-ci
exclude: '^(\.github/actions/|\.vscode/|desktop/|docs/|examples/)'
- repo: https://github.com/gitleaks/gitleaks
- rev: v8.30.0
+ rev: v8.30.1
hooks:
- id: gitleaks
- repo: https://github.com/commitizen-tools/commitizen
- rev: v4.13.7
+ rev: v4.13.10
hooks:
- id: commitizen
stages: [commit-msg]
- - repo: https://github.com/TekWizely/pre-commit-golang
- rev: v1.0.0-rc.4
+ - repo: https://github.com/golangci/golangci-lint
+ rev: v2.11.4
hooks:
- - id: go-fmt
- - id: go-imports
- id: golangci-lint
- pass_filenames: false
- args: [--new-from-rev=HEAD]
+ - id: golangci-lint-fmt
diff --git a/README.md b/README.md
index 76bf8ba29f..b2d6c45f4f 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,8 @@
+> [!IMPORTANT]
+> I am working on a new project called [Devsy](https://devsy.sh/) at [https://github.com/devsy-org/devsy](https://github.com/devsy-org/devsy). Devsy is a continuation of the changes that I have worked on here to build a better devcontainer experience for developers. I have written more details about Devsy in this linked [issue](https://github.com/skevetter/devpod/issues/773).
+
+---
+
diff --git a/Taskfile.yml b/Taskfile.yml
index 9b632a94ff..6fd7885181 100644
--- a/Taskfile.yml
+++ b/Taskfile.yml
@@ -6,8 +6,24 @@ tasks:
cmd: go mod tidy
cli:lint:
- desc: run devpod linters
- cmd: golangci-lint run
+ desc: lint go code using golangci-lint
+ cmd: golangci-lint run ./...
+
+ cli:lint:new:
+ desc: lint go code changed since origin/main using golangci-lint
+ cmd: golangci-lint run --new-from-rev="$(git merge-base HEAD origin/main)" ./... # or use --new-from-rev=HEAD~1 for changes since last push or --new for changes since last commit
+
+ cli:lint:fix:
+ desc: fix lint issues using golangci-lint
+ cmd: golangci-lint run --fix ./...
+
+ cli:format:
+ desc: format go code using golangci-lint formatters
+ cmd: golangci-lint fmt ./...
+
+ cli:act:lint:
+ desc: run devpod linters using act
+ cmd: act workflow_dispatch -W .github/workflows/lint.yml
cli:build:
desc: build devpod CLI
@@ -50,8 +66,8 @@ tasks:
dir: pkg/agent/tunnel
cmd: |
# sudo apt install protobuf-compiler
- go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
- go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
+ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.5.1
+ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.4
protoc -I . tunnel.proto --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative
cli:test:
diff --git a/cmd/agent/agent.go b/cmd/agent/agent.go
index 8791e8fdbe..669e84e9fa 100644
--- a/cmd/agent/agent.go
+++ b/cmd/agent/agent.go
@@ -7,7 +7,6 @@ import (
"github.com/skevetter/devpod/cmd/agent/container"
"github.com/skevetter/devpod/cmd/agent/workspace"
"github.com/skevetter/devpod/cmd/flags"
- "github.com/skevetter/devpod/pkg/client/clientimplementation"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/envfile"
"github.com/skevetter/log"
@@ -16,7 +15,7 @@ import (
var AgentExecutedAnnotation = "loft.sh/agent-executed"
-// NewAgentCmd returns a new root command
+// NewAgentCmd returns a new root command.
func NewAgentCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
agentCmd := &cobra.Command{
Use: "agent",
@@ -38,7 +37,11 @@ func NewAgentCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return agentCmd
}
-func AgentPersistentPreRunE(cobraCmd *cobra.Command, args []string, globalFlags *flags.GlobalFlags) error {
+func AgentPersistentPreRunE(
+ cobraCmd *cobra.Command,
+ args []string,
+ globalFlags *flags.GlobalFlags,
+) error {
// get top level parent
parent := cobraCmd
for parent.Parent() != nil {
@@ -59,12 +62,12 @@ func AgentPersistentPreRunE(cobraCmd *cobra.Command, args []string, globalFlags
log.Default.SetLevel(logrus.FatalLevel)
} else if globalFlags.Debug {
log.Default.SetLevel(logrus.DebugLevel)
- } else if os.Getenv(clientimplementation.DevPodDebug) == "true" {
+ } else if os.Getenv(config.EnvDebug) == config.BoolTrue {
log.Default.SetLevel(logrus.DebugLevel)
}
if globalFlags.DevPodHome != "" {
- _ = os.Setenv(config.DEVPOD_HOME, globalFlags.DevPodHome)
+ _ = os.Setenv(config.EnvHome, globalFlags.DevPodHome)
}
// apply environment
diff --git a/cmd/agent/container/codeserver_async.go b/cmd/agent/container/codeserver_async.go
new file mode 100644
index 0000000000..6e302770be
--- /dev/null
+++ b/cmd/agent/container/codeserver_async.go
@@ -0,0 +1,54 @@
+//nolint:dupl // CodeServerAsyncCmd is intentionally parallel to VSCodeWebAsyncCmd but uses a distinct IDE package
+package container
+
+import (
+ "encoding/json"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/compress"
+ "github.com/skevetter/devpod/pkg/devcontainer/config"
+ "github.com/skevetter/devpod/pkg/ide/codeserver"
+ "github.com/skevetter/log"
+ "github.com/spf13/cobra"
+)
+
+// CodeServerAsyncCmd holds the cmd flags.
+type CodeServerAsyncCmd struct {
+ *flags.GlobalFlags
+
+ SetupInfo string
+}
+
+// NewCodeServerAsyncCmd creates a new command.
+func NewCodeServerAsyncCmd() *cobra.Command {
+ cmd := &CodeServerAsyncCmd{}
+ asyncCmd := &cobra.Command{
+ Use: "codeserver-async",
+ Short: "Installs code-server extensions",
+ Args: cobra.NoArgs,
+ RunE: cmd.Run,
+ }
+ asyncCmd.Flags().StringVar(&cmd.SetupInfo, "setup-info", "", "The container setup info")
+ _ = asyncCmd.MarkFlagRequired("setup-info")
+ return asyncCmd
+}
+
+// Run runs the command logic.
+func (cmd *CodeServerAsyncCmd) Run(_ *cobra.Command, _ []string) error {
+ log.Default.Debugf("Start setting up container...")
+ decompressed, err := compress.Decompress(cmd.SetupInfo)
+ if err != nil {
+ return err
+ }
+
+ setupInfo := &config.Result{}
+ err = json.Unmarshal([]byte(decompressed), setupInfo)
+ if err != nil {
+ return err
+ }
+
+ vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
+ user := config.GetRemoteUser(setupInfo)
+ return codeserver.NewCodeServerServer(vsCodeConfiguration.Extensions, "", user, "", "", nil, log.Default).
+ InstallExtensions()
+}
diff --git a/cmd/agent/container/container.go b/cmd/agent/container/container.go
index 6796730eda..5f33eb865c 100644
--- a/cmd/agent/container/container.go
+++ b/cmd/agent/container/container.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewContainerCmd returns a new command
+// NewContainerCmd returns a new command.
func NewContainerCmd(flags *flags.GlobalFlags) *cobra.Command {
containerCmd := &cobra.Command{
Use: "container",
@@ -13,9 +13,12 @@ func NewContainerCmd(flags *flags.GlobalFlags) *cobra.Command {
}
containerCmd.AddCommand(NewSetupContainerCmd(flags))
+ containerCmd.AddCommand(NewPostAttachCmd(flags))
containerCmd.AddCommand(NewDaemonCmd())
containerCmd.AddCommand(NewVSCodeAsyncCmd())
containerCmd.AddCommand(NewOpenVSCodeAsyncCmd())
+ containerCmd.AddCommand(NewVSCodeWebAsyncCmd())
+ containerCmd.AddCommand(NewCodeServerAsyncCmd())
containerCmd.AddCommand(NewCredentialsServerCmd(flags))
containerCmd.AddCommand(NewSetupLoftPlatformAccessCmd(flags))
containerCmd.AddCommand(NewSSHServerCmd(flags))
diff --git a/cmd/agent/container/credentials_server.go b/cmd/agent/container/credentials_server.go
index 1f86d6902b..5416034d23 100644
--- a/cmd/agent/container/credentials_server.go
+++ b/cmd/agent/container/credentials_server.go
@@ -24,7 +24,7 @@ import (
const ExitCodeIO int = 64
-// CredentialsServerCmd holds the cmd flags
+// CredentialsServerCmd holds the cmd flags.
type CredentialsServerCmd struct {
*flags.GlobalFlags
@@ -37,7 +37,7 @@ type CredentialsServerCmd struct {
GitUserSigningKey string
}
-// NewCredentialsServerCmd creates a new command
+// NewCredentialsServerCmd creates a new command.
func NewCredentialsServerCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &CredentialsServerCmd{
GlobalFlags: flags,
@@ -55,9 +55,13 @@ func NewCredentialsServerCmd(flags *flags.GlobalFlags) *cobra.Command {
return cmd.Run(c.Context(), port)
},
}
- credentialsServerCmd.Flags().BoolVar(&cmd.ConfigureGitHelper, "configure-git-helper", false, "If true will configure git helper")
- credentialsServerCmd.Flags().BoolVar(&cmd.ConfigureDockerHelper, "configure-docker-helper", false, "If true will configure docker helper")
- credentialsServerCmd.Flags().BoolVar(&cmd.ForwardPorts, "forward-ports", false, "If true will automatically try to forward open ports within the container")
+ credentialsServerCmd.Flags().
+ BoolVar(&cmd.ConfigureGitHelper, "configure-git-helper", false, "If true will configure git helper")
+ credentialsServerCmd.Flags().
+ BoolVar(&cmd.ConfigureDockerHelper, "configure-docker-helper", false, "If true will configure docker helper")
+ credentialsServerCmd.Flags().
+ BoolVar(&cmd.ForwardPorts, "forward-ports", false,
+ "If true will automatically try to forward open ports within the container")
credentialsServerCmd.Flags().StringVar(&cmd.GitUserSigningKey, "git-user-signing-key", "", "")
credentialsServerCmd.Flags().StringVar(&cmd.User, "user", "", "The user to use")
_ = credentialsServerCmd.MarkFlagRequired("user")
@@ -65,7 +69,7 @@ func NewCredentialsServerCmd(flags *flags.GlobalFlags) *cobra.Command {
return credentialsServerCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *CredentialsServerCmd) Run(ctx context.Context, port int) error {
// create a grpc client
tunnelClient, err := tunnelserver.NewTunnelClient(os.Stdin, os.Stdout, true, ExitCodeIO)
@@ -131,29 +135,38 @@ func (cmd *CredentialsServerCmd) Run(ctx context.Context, port int) error {
}(cmd.User)
}
- // configure git ssh signature helper
+ // configure git ssh signature helper — non-fatal so that a signing
+ // setup failure does not take down the entire credentials server
+ // (git/docker credential forwarding, port forwarding, etc.)
if cmd.GitUserSigningKey != "" {
decodedKey, err := base64.StdEncoding.DecodeString(cmd.GitUserSigningKey)
if err != nil {
- return fmt.Errorf("decode git ssh signature key: %w", err)
- }
- err = gitsshsigning.ConfigureHelper(cmd.User, string(decodedKey), log)
- if err != nil {
- return fmt.Errorf("configure git ssh signature helper: %w", err)
+ log.Errorf("Failed to decode git SSH signing key, signing will be unavailable: %v", err)
+ } else {
+ err = gitsshsigning.ConfigureHelper(cmd.User, string(decodedKey), log)
+ if err != nil {
+ log.Errorf(
+ "Failed to configure git SSH signature helper, signing will be unavailable: %v",
+ err,
+ )
+ } else {
+ defer func(userName string) {
+ _ = gitsshsigning.RemoveHelper(userName)
+ }(cmd.User)
+ }
}
-
- // cleanup when we are done
- defer func(userName string) {
- _ = gitsshsigning.RemoveHelper(userName)
- }(cmd.User)
}
return credentials.RunCredentialsServer(ctx, port, tunnelClient, log)
}
-func configureGitUserLocally(ctx context.Context, userName string, client tunnel.TunnelClient) error {
+func configureGitUserLocally(
+ ctx context.Context,
+ userName string,
+ client tunnel.TunnelClient,
+) error {
// get local credentials
- localGitUser, err := gitcredentials.GetUser(userName)
+ localGitUser, err := gitcredentials.GetUser(userName, "")
if err != nil {
return err
} else if localGitUser.Name != "" && localGitUser.Email != "" {
diff --git a/cmd/agent/container/daemon.go b/cmd/agent/container/daemon.go
index 31bee43e5a..86f5e128fc 100644
--- a/cmd/agent/container/daemon.go
+++ b/cmd/agent/container/daemon.go
@@ -4,30 +4,29 @@ import (
"context"
"encoding/base64"
"encoding/json"
+ "errors"
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
- "sync"
"syscall"
"time"
- "errors"
-
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/pkg/agent"
+ config2 "github.com/skevetter/devpod/pkg/config"
agentd "github.com/skevetter/devpod/pkg/daemon/agent"
- "github.com/skevetter/devpod/pkg/devcontainer/config"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/ts"
"github.com/skevetter/log"
"github.com/spf13/cobra"
+ "golang.org/x/sync/errgroup"
)
const (
- RootDir = "/var/devpod"
- DaemonConfigPath = "/var/run/secrets/devpod/daemon_config"
+ RootDir = agent.ContainerDataDir
+ DaemonConfigPath = "/var/run/secrets/" + config2.BinaryName + "/daemon_config"
)
type DaemonCmd struct {
@@ -47,20 +46,16 @@ func NewDaemonCmd() *cobra.Command {
Args: cobra.NoArgs,
RunE: cmd.Run,
}
- daemonCmd.Flags().StringVar(&cmd.Config.Timeout, "timeout", "", "The timeout to stop the container after")
+ daemonCmd.Flags().
+ StringVar(&cmd.Config.Timeout, "timeout", "", "The timeout to stop the container after")
return daemonCmd
}
func (cmd *DaemonCmd) Run(c *cobra.Command, args []string) error {
- ctx := c.Context()
- errChan := make(chan error, 4)
- var wg sync.WaitGroup
-
if err := cmd.loadConfig(); err != nil {
return err
}
- // Prepare timeout if specified.
var timeoutDuration time.Duration
if cmd.Config.Timeout != "" {
var err error
@@ -69,61 +64,68 @@ func (cmd *DaemonCmd) Run(c *cobra.Command, args []string) error {
return fmt.Errorf("failed to parse timeout duration: %w", err)
}
if timeoutDuration > 0 {
- if err := setupActivityFile(); err != nil {
- return err
+ if err := os.WriteFile(
+ agent.ContainerActivityFile,
+ nil,
+ 0o666,
+ ); err != nil { // #nosec G306
+ return fmt.Errorf("failed to create activity file: %w", err)
+ }
+ if err := os.Chmod(agent.ContainerActivityFile, 0o666); err != nil { // #nosec G302
+ return fmt.Errorf("failed to set activity file permissions: %w", err)
}
}
}
- ctx, cancel := context.WithCancel(ctx)
- defer cancel()
+ ctx, stop := signal.NotifyContext(c.Context(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ g, ctx := errgroup.WithContext(ctx)
var tasksStarted bool
// Start process reaper.
if os.Getpid() == 1 {
- wg.Add(1)
- go runReaper(ctx, errChan, &wg)
+ g.Go(func() error {
+ agentd.RunProcessReaper(ctx)
+ return nil
+ })
}
// Start Tailscale networking server.
if cmd.shouldRunNetworkServer() {
tasksStarted = true
- wg.Add(1)
- go runNetworkServer(ctx, cmd, errChan, &wg)
+ g.Go(func() error {
+ return runNetworkServer(ctx, cmd)
+ })
}
// Start timeout monitor.
if timeoutDuration > 0 {
tasksStarted = true
- wg.Add(1)
- go runTimeoutMonitor(ctx, timeoutDuration, errChan, &wg)
+ g.Go(func() error {
+ return runTimeoutMonitor(ctx, timeoutDuration)
+ })
}
// Start ssh server.
if cmd.shouldRunSsh() {
tasksStarted = true
- wg.Add(1)
- go runSshServer(ctx, cmd, errChan, &wg)
+ g.Go(func() error {
+ return runSshServer(ctx, cmd)
+ })
}
// In case no task is configured, just wait indefinitely.
if !tasksStarted {
- wg.Go(func() {
+ g.Go(func() error {
<-ctx.Done()
+ return nil
})
}
- // Listen for OS termination signals.
- go handleSignals(ctx, errChan)
-
- // Wait until an error (or termination signal) occurs.
- err := <-errChan
- cancel()
- wg.Wait()
-
+ err := g.Wait()
if err != nil {
- cmd.Log.Errorf("Daemon error: %v", err)
+ cmd.Log.Errorf("daemon error: %v", err)
os.Exit(1)
}
os.Exit(0)
@@ -139,7 +141,7 @@ func (cmd *DaemonCmd) loadConfig() error {
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// check environment variable
- encodedCfg = os.Getenv(config.WorkspaceDaemonConfigExtraEnvVar)
+ encodedCfg = os.Getenv(config2.EnvWorkspaceDaemonConfig)
} else {
return fmt.Errorf("get daemon config file %s: %w", DaemonConfigPath, err)
}
@@ -177,49 +179,36 @@ func (cmd *DaemonCmd) shouldRunSsh() bool {
return cmd.Config.Ssh.Workdir != "" || cmd.Config.Ssh.User != ""
}
-// setupActivityFile creates and sets permissions on the container activity file.
-func setupActivityFile() error {
- if err := os.WriteFile(agent.ContainerActivityFile, nil, 0777); err != nil {
- return err
- }
- return os.Chmod(agent.ContainerActivityFile, 0777)
-}
-
-// runReaper starts the process reaper and waits for context cancellation.
-func runReaper(ctx context.Context, errChan chan<- error, wg *sync.WaitGroup) {
- defer wg.Done()
- agentd.RunProcessReaper()
- <-ctx.Done()
-}
-
// runTimeoutMonitor monitors the activity file and signals an error if the timeout is exceeded.
-func runTimeoutMonitor(ctx context.Context, duration time.Duration, errChan chan<- error, wg *sync.WaitGroup) {
- defer wg.Done()
+func runTimeoutMonitor(
+ ctx context.Context,
+ duration time.Duration,
+) error {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
- return
+ return nil
case <-ticker.C:
stat, err := os.Stat(agent.ContainerActivityFile)
if err != nil {
continue
}
if !stat.ModTime().Add(duration).After(time.Now()) {
- errChan <- errors.New("timeout reached, terminating daemon")
- return
+ return errors.New("timeout reached, terminating daemon")
}
}
}
}
// runNetworkServer starts the network server.
-func runNetworkServer(ctx context.Context, cmd *DaemonCmd, errChan chan<- error, wg *sync.WaitGroup) {
- defer wg.Done()
+func runNetworkServer(
+ ctx context.Context,
+ cmd *DaemonCmd,
+) error {
if err := os.MkdirAll(RootDir, os.ModePerm); err != nil {
- errChan <- err
- return
+ return err
}
logger := initLogging()
config := client.NewConfig()
@@ -228,8 +217,7 @@ func runNetworkServer(ctx context.Context, cmd *DaemonCmd, errChan chan<- error,
config.Insecure = true
baseClient := client.NewClientFromConfig(config)
if err := baseClient.RefreshSelf(ctx); err != nil {
- errChan <- fmt.Errorf("failed to refresh client: %w", err)
- return
+ return fmt.Errorf("failed to refresh client: %w", err)
}
tsServer := ts.NewWorkspaceServer(&ts.WorkspaceServerConfig{
AccessKey: cmd.Config.Platform.AccessKey,
@@ -242,17 +230,17 @@ func runNetworkServer(ctx context.Context, cmd *DaemonCmd, errChan chan<- error,
},
}, logger)
if err := tsServer.Start(ctx); err != nil {
- errChan <- fmt.Errorf("network server: %w", err)
+ return fmt.Errorf("network server: %w", err)
}
+ return nil
}
-// runSshServer starts the SSH server.
-func runSshServer(ctx context.Context, cmd *DaemonCmd, errChan chan<- error, wg *sync.WaitGroup) {
- defer wg.Done()
+// runSshServer starts the SSH server, sending SIGTERM on context cancellation
+// with a grace period before force-killing.
+func runSshServer(ctx context.Context, cmd *DaemonCmd) error {
binaryPath, err := os.Executable()
if err != nil {
- errChan <- err
- return
+ return err
}
args := []string{"agent", "container", "ssh-server"}
@@ -263,45 +251,18 @@ func runSshServer(ctx context.Context, cmd *DaemonCmd, errChan chan<- error, wg
args = append(args, "--remote-user", cmd.Config.Ssh.User)
}
- sshCmd := exec.Command(binaryPath, args...)
+ sshCmd := exec.CommandContext(ctx, binaryPath, args...) // #nosec G204
sshCmd.Stdout = os.Stdout
sshCmd.Stderr = os.Stderr
-
- if err := sshCmd.Start(); err != nil {
- errChan <- fmt.Errorf("failed to start SSH server: %w", err)
- return
+ sshCmd.Cancel = func() error {
+ return sshCmd.Process.Signal(syscall.SIGTERM)
}
+ sshCmd.WaitDelay = 5 * time.Second // Graceful shutdown before force-killing.
- done := make(chan struct{})
- go func() {
- select {
- case <-ctx.Done():
- if sshCmd.Process != nil {
- if err := sshCmd.Process.Signal(syscall.SIGTERM); err != nil {
- errChan <- fmt.Errorf("failed to send SIGTERM to SSH server: %w", err)
- }
- }
- case <-done:
- }
- }()
-
- if err := sshCmd.Wait(); err != nil {
- errChan <- fmt.Errorf("SSH server exited abnormally: %w", err)
- close(done)
- return
- }
- close(done)
-}
-
-// handleSignals listens for OS termination signals and sends an error through errChan.
-func handleSignals(ctx context.Context, errChan chan<- error) {
- sigChan := make(chan os.Signal, 1)
- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
- select {
- case sig := <-sigChan:
- errChan <- fmt.Errorf("received signal: %v", sig)
- case <-ctx.Done():
+ if err := sshCmd.Run(); err != nil && ctx.Err() == nil {
+ return fmt.Errorf("SSH server exited abnormally: %w", err)
}
+ return nil
}
// initLogging initializes logging and returns a combined logger.
diff --git a/cmd/agent/container/openvscode_async.go b/cmd/agent/container/openvscode_async.go
index 5d2f436ae9..03a4e6fad1 100644
--- a/cmd/agent/container/openvscode_async.go
+++ b/cmd/agent/container/openvscode_async.go
@@ -11,14 +11,14 @@ import (
"github.com/spf13/cobra"
)
-// OpenVSCodeAsyncCmd holds the cmd flags
+// OpenVSCodeAsyncCmd holds the cmd flags.
type OpenVSCodeAsyncCmd struct {
*flags.GlobalFlags
SetupInfo string
}
-// NewOpenVSCodeAsyncCmd creates a new command
+// NewOpenVSCodeAsyncCmd creates a new command.
func NewOpenVSCodeAsyncCmd() *cobra.Command {
cmd := &OpenVSCodeAsyncCmd{}
vsCodeAsyncCmd := &cobra.Command{
@@ -32,7 +32,7 @@ func NewOpenVSCodeAsyncCmd() *cobra.Command {
return vsCodeAsyncCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *OpenVSCodeAsyncCmd) Run(_ *cobra.Command, _ []string) error {
log.Default.Debugf("Start setting up container...")
decompressed, err := compress.Decompress(cmd.SetupInfo)
@@ -58,5 +58,6 @@ func (cmd *OpenVSCodeAsyncCmd) Run(_ *cobra.Command, _ []string) error {
func setupOpenVSCodeExtensions(setupInfo *config.Result, log log.Logger) error {
vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
user := config.GetRemoteUser(setupInfo)
- return openvscode.NewOpenVSCodeServer(vsCodeConfiguration.Extensions, "", user, "", "", nil, log).InstallExtensions()
+ return openvscode.NewOpenVSCodeServer(vsCodeConfiguration.Extensions, "", user, "", "", nil, log).
+ InstallExtensions()
}
diff --git a/cmd/agent/container/post_attach.go b/cmd/agent/container/post_attach.go
new file mode 100644
index 0000000000..f162ac7f2a
--- /dev/null
+++ b/cmd/agent/container/post_attach.go
@@ -0,0 +1,61 @@
+//go:build !windows
+
+package container
+
+import (
+ "context"
+ "encoding/json"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/compress"
+ "github.com/skevetter/devpod/pkg/devcontainer/config"
+ "github.com/skevetter/devpod/pkg/devcontainer/setup"
+ "github.com/skevetter/log"
+ "github.com/spf13/cobra"
+)
+
+// PostAttachCmd runs postAttachCommand hooks as a detached background process.
+type PostAttachCmd struct {
+ *flags.GlobalFlags
+ SetupInfo string
+}
+
+// NewPostAttachCmd creates a new command.
+func NewPostAttachCmd(flags *flags.GlobalFlags) *cobra.Command {
+ cmd := &PostAttachCmd{
+ GlobalFlags: flags,
+ }
+ postAttachCmd := &cobra.Command{
+ Use: "post-attach",
+ Short: "Runs postAttachCommand lifecycle hooks",
+ Args: cobra.NoArgs,
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
+ },
+ }
+ postAttachCmd.Flags().StringVar(&cmd.SetupInfo, "setup-info", "", "The container setup info")
+ _ = postAttachCmd.MarkFlagRequired("setup-info")
+ return postAttachCmd
+}
+
+// Run runs the postAttachCommand lifecycle hooks.
+func (cmd *PostAttachCmd) Run(ctx context.Context) error {
+ logger := log.Default
+
+ decompressed, err := compress.Decompress(cmd.SetupInfo)
+ if err != nil {
+ return err
+ }
+
+ setupInfo := &config.Result{}
+ if err := json.Unmarshal([]byte(decompressed), setupInfo); err != nil {
+ return err
+ }
+
+ logger.Debugf("running postAttachCommand hooks")
+ if err := setup.RunPostAttachHooks(ctx, setupInfo, logger); err != nil {
+ logger.Errorf("postAttachCommand failed: %v", err)
+ }
+
+ return nil
+}
diff --git a/cmd/agent/container/post_attach_windows.go b/cmd/agent/container/post_attach_windows.go
new file mode 100644
index 0000000000..61b7718292
--- /dev/null
+++ b/cmd/agent/container/post_attach_windows.go
@@ -0,0 +1,21 @@
+//go:build windows
+
+package container
+
+import (
+ "fmt"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/spf13/cobra"
+)
+
+func NewPostAttachCmd(flags *flags.GlobalFlags) *cobra.Command {
+ return &cobra.Command{
+ Use: "post-attach",
+ Short: "Runs postAttachCommand lifecycle hooks",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return fmt.Errorf("Windows Containers are not supported")
+ },
+ }
+}
diff --git a/cmd/agent/container/setup.go b/cmd/agent/container/setup.go
index 71db5cc58b..0fc232e967 100644
--- a/cmd/agent/container/setup.go
+++ b/cmd/agent/container/setup.go
@@ -31,20 +31,21 @@ import (
"github.com/skevetter/devpod/pkg/dockercredentials"
"github.com/skevetter/devpod/pkg/extract"
"github.com/skevetter/devpod/pkg/git"
+ "github.com/skevetter/devpod/pkg/ide/codeserver"
"github.com/skevetter/devpod/pkg/ide/fleet"
"github.com/skevetter/devpod/pkg/ide/jetbrains"
"github.com/skevetter/devpod/pkg/ide/jupyter"
"github.com/skevetter/devpod/pkg/ide/openvscode"
"github.com/skevetter/devpod/pkg/ide/rstudio"
"github.com/skevetter/devpod/pkg/ide/vscode"
+ "github.com/skevetter/devpod/pkg/ide/vscodeweb"
provider2 "github.com/skevetter/devpod/pkg/provider"
- "github.com/skevetter/devpod/pkg/single"
"github.com/skevetter/devpod/pkg/ts"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-// SetupContainerCmd holds the cmd flags
+// SetupContainerCmd holds the cmd flags.
type SetupContainerCmd struct {
*flags.GlobalFlags
@@ -58,7 +59,7 @@ type SetupContainerCmd struct {
WorkspaceHost string
}
-// NewSetupContainerCmd creates a new command
+// NewSetupContainerCmd creates a new command.
func NewSetupContainerCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SetupContainerCmd{
GlobalFlags: flags,
@@ -67,17 +68,24 @@ func NewSetupContainerCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "setup",
Short: "Sets up a container",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- setupContainerCmd.Flags().BoolVar(&cmd.StreamMounts, "stream-mounts", false, "If true, will try to stream the bind mounts from the host")
- setupContainerCmd.Flags().BoolVar(&cmd.ChownWorkspace, "chown-workspace", false, "If DevPod should chown the workspace to the remote user")
- setupContainerCmd.Flags().BoolVar(&cmd.InjectGitCredentials, "inject-git-credentials", false, "If DevPod should inject git credentials during setup")
- setupContainerCmd.Flags().StringVar(&cmd.ContainerWorkspaceInfo, "container-workspace-info", "", "The container workspace info")
- setupContainerCmd.Flags().StringVar(&cmd.SetupInfo, "setup-info", "", "The container setup info")
+ setupContainerCmd.Flags().
+ BoolVar(&cmd.StreamMounts, "stream-mounts", false, "If true, will try to stream the bind mounts from the host")
+ setupContainerCmd.Flags().
+ BoolVar(&cmd.ChownWorkspace, "chown-workspace", false, "If DevPod should chown the workspace to the remote user")
+ setupContainerCmd.Flags().
+ BoolVar(&cmd.InjectGitCredentials, "inject-git-credentials", false,
+ "If DevPod should inject git credentials during setup")
+ setupContainerCmd.Flags().
+ StringVar(&cmd.ContainerWorkspaceInfo, "container-workspace-info", "", "The container workspace info")
+ setupContainerCmd.Flags().
+ StringVar(&cmd.SetupInfo, "setup-info", "", "The container setup info")
setupContainerCmd.Flags().StringVar(&cmd.AccessKey, "access-key", "", "Access Key to use")
- setupContainerCmd.Flags().StringVar(&cmd.WorkspaceHost, "workspace-host", "", "Workspace hostname to use")
+ setupContainerCmd.Flags().
+ StringVar(&cmd.WorkspaceHost, "workspace-host", "", "Workspace hostname to use")
setupContainerCmd.Flags().StringVar(&cmd.PlatformHost, "platform-host", "", "Platform host")
_ = setupContainerCmd.MarkFlagRequired("setup-info")
return setupContainerCmd
@@ -91,13 +99,21 @@ type setupContext struct {
logger log.Logger
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SetupContainerCmd) Run(ctx context.Context) error {
tunnelClient, logger, err := cmd.initializeTunnelClient(ctx)
if err != nil {
return err
}
+ // The tunnel logger forwards messages over the tunnel asynchronously, so
+ // flush before returning to make sure the final log lines (e.g. the last
+ // stderr output of a failing lifecycle hook) reach the client before the
+ // connection is torn down. ctx is still alive while this defer runs.
+ if f, ok := logger.(tunnelserver.Flusher); ok {
+ defer f.Flush()
+ }
+
workspaceInfo, setupInfo, err := cmd.parseWorkspaceAndSetupInfo(logger)
if err != nil {
return err
@@ -115,11 +131,7 @@ func (cmd *SetupContainerCmd) Run(ctx context.Context) error {
return err
}
- if err := cmd.finalizeSetup(sctx); err != nil {
- return err
- }
-
- return cmd.sendSetupResult(ctx, setupInfo, tunnelClient)
+ return cmd.finalizeSetup(sctx)
}
func (cmd *SetupContainerCmd) prepareWorkspace(sctx *setupContext) error {
@@ -135,11 +147,19 @@ func (cmd *SetupContainerCmd) prepareWorkspace(sctx *setupContext) error {
Debug: cmd.Debug,
Log: sctx.logger,
ConfigureCredentialsFunc: func(ctx context.Context) (string, error) {
- serverPort, err := credentials.StartCredentialsServer(ctx, sctx.tunnelClient, sctx.logger)
+ serverPort, err := credentials.StartCredentialsServer(
+ ctx,
+ sctx.tunnelClient,
+ sctx.logger,
+ )
if err != nil {
return "", err
}
- return dockercredentials.ConfigureCredentialsDockerless(agent.DockerlessCredentialsPath, serverPort, sctx.logger)
+ return dockercredentials.ConfigureCredentialsDockerless(
+ agent.DockerlessCredentialsPath,
+ serverPort,
+ sctx.logger,
+ )
},
}); err != nil {
return fmt.Errorf("dockerless build: %w", err)
@@ -156,7 +176,12 @@ func (cmd *SetupContainerCmd) prepareWorkspace(sctx *setupContext) error {
)
// Clone repository before cleaning up git credentials
- cloneErr := cmd.cloneRepositoryIfNeeded(sctx.ctx, sctx.workspaceInfo, sctx.setupInfo, sctx.logger)
+ cloneErr := cmd.cloneRepositoryIfNeeded(
+ sctx.ctx,
+ sctx.workspaceInfo,
+ sctx.setupInfo,
+ sctx.logger,
+ )
// Clean up git credentials after cloning
if cleanupFunc != nil {
@@ -167,16 +192,16 @@ func (cmd *SetupContainerCmd) prepareWorkspace(sctx *setupContext) error {
}
func (cmd *SetupContainerCmd) finalizeSetup(sctx *setupContext) error {
- err := setup.SetupContainer(
- sctx.ctx,
- sctx.setupInfo,
- sctx.workspaceInfo.CLIOptions.WorkspaceEnv,
- cmd.ChownWorkspace,
- &sctx.workspaceInfo.CLIOptions.Platform,
- sctx.tunnelClient,
- sctx.logger,
- )
- if err != nil {
+ cfg := &setup.ContainerSetupConfig{
+ SetupInfo: sctx.setupInfo,
+ ExtraWorkspaceEnv: sctx.workspaceInfo.CLIOptions.WorkspaceEnv,
+ ChownProjects: cmd.ChownWorkspace,
+ PlatformOptions: &sctx.workspaceInfo.CLIOptions.Platform,
+ TunnelClient: sctx.tunnelClient,
+ Log: sctx.logger,
+ }
+
+ if err := setup.SetupContainerPreAttach(sctx.ctx, cfg); err != nil {
return err
}
@@ -184,10 +209,24 @@ func (cmd *SetupContainerCmd) finalizeSetup(sctx *setupContext) error {
return err
}
- return cmd.startContainerDaemon(sctx.workspaceInfo, sctx.logger)
+ if err := cmd.startContainerDaemon(sctx.workspaceInfo, sctx.logger); err != nil {
+ return err
+ }
+
+ // Launch postAttachCommand as a detached background process before sending
+ // the result. Once sendSetupResult returns, the client tears down the SSH
+ // tunnel which kills this process, so postAttach must already be running
+ // independently.
+ if err := cmd.startPostAttachHooks(sctx); err != nil {
+ sctx.logger.Errorf("failed to start postAttachCommand: %v", err)
+ }
+
+ return cmd.sendSetupResult(sctx.ctx, sctx.setupInfo, sctx.tunnelClient)
}
-func (cmd *SetupContainerCmd) initializeTunnelClient(ctx context.Context) (tunnel.TunnelClient, log.Logger, error) {
+func (cmd *SetupContainerCmd) initializeTunnelClient(
+ ctx context.Context,
+) (tunnel.TunnelClient, log.Logger, error) {
tunnelClient, err := tunnelserver.NewTunnelClient(os.Stdin, os.Stdout, true, 0)
if err != nil {
return nil, nil, fmt.Errorf("initializing tunnel client: %w", err)
@@ -241,7 +280,13 @@ func (cmd *SetupContainerCmd) syncMounts(sctx *setupContext) error {
}
}
- if err := streamMount(sctx.ctx, sctx.workspaceInfo, m, sctx.tunnelClient, sctx.logger); err != nil {
+ if err := streamMount(
+ sctx.ctx,
+ sctx.workspaceInfo,
+ m,
+ sctx.tunnelClient,
+ sctx.logger,
+ ); err != nil {
return err
}
}
@@ -321,15 +366,50 @@ func (cmd *SetupContainerCmd) startContainerDaemon(
return nil
}
- return single.Single("devpod.daemon.pid", func() (*exec.Cmd, error) {
- logger.Debugf("start devpod container daemon with inactivity timeout %s", workspaceInfo.ContainerTimeout)
+ return command.StartBackgroundOnce(config2.BinaryName+".daemon", func() (*exec.Cmd, error) {
+ logger.Debugf(
+ "start %s container daemon with inactivity timeout %s",
+ config2.BinaryName,
+ workspaceInfo.ContainerTimeout,
+ )
+ binaryPath, err := os.Executable()
+ if err != nil {
+ return nil, err
+ }
+
+ //nolint:gosec // binaryPath is from os.Executable(), not user input
+ return exec.Command(
+ binaryPath,
+ "agent",
+ "container",
+ "daemon",
+ "--timeout",
+ workspaceInfo.ContainerTimeout,
+ ), nil
+ })
+}
+
+func (cmd *SetupContainerCmd) startPostAttachHooks(sctx *setupContext) error {
+ if len(sctx.setupInfo.MergedConfig.PostAttachCommands) == 0 {
+ return nil
+ }
+
+ return command.StartBackgroundOnce("devpod.post-attach", func() (*exec.Cmd, error) {
+ sctx.logger.Debugf("starting postAttachCommand as background process")
binaryPath, err := os.Executable()
if err != nil {
return nil, err
}
//nolint:gosec // binaryPath is from os.Executable(), not user input
- return exec.Command(binaryPath, "agent", "container", "daemon", "--timeout", workspaceInfo.ContainerTimeout), nil
+ return exec.Command(
+ binaryPath,
+ "agent",
+ "container",
+ "post-attach",
+ "--setup-info",
+ cmd.SetupInfo,
+ ), nil
})
}
@@ -362,7 +442,11 @@ func fillContainerEnv(setupInfo *config.Result) error {
// merge config
newMergedConfig := &config.MergedDevContainerConfig{}
- err := config.SubstituteContainerEnv(config.ListToObject(os.Environ()), setupInfo.MergedConfig, newMergedConfig)
+ err := config.SubstituteContainerEnv(
+ config.ListToObject(os.Environ()),
+ setupInfo.MergedConfig,
+ newMergedConfig,
+ )
if err != nil {
return fmt.Errorf("substitute container env: %w", err)
}
@@ -370,7 +454,11 @@ func fillContainerEnv(setupInfo *config.Result) error {
return nil
}
-func (cmd *SetupContainerCmd) installIDE(setupInfo *config.Result, ide *provider2.WorkspaceIDEConfig, log log.Logger) error {
+func (cmd *SetupContainerCmd) installIDE(
+ setupInfo *config.Result,
+ ide *provider2.WorkspaceIDEConfig,
+ log log.Logger,
+) error {
switch ide.Name {
case string(config2.IDENone):
return nil
@@ -388,43 +476,68 @@ func (cmd *SetupContainerCmd) installIDE(setupInfo *config.Result, ide *provider
return cmd.setupVSCode(setupInfo, ide.Options, vscode.FlavorWindsurf, log)
case string(config2.IDEAntigravity):
return cmd.setupVSCode(setupInfo, ide.Options, vscode.FlavorAntigravity, log)
+ case string(config2.IDEBob):
+ return cmd.setupVSCode(setupInfo, ide.Options, vscode.FlavorBob, log)
case string(config2.IDEOpenVSCode):
return cmd.setupOpenVSCode(setupInfo, ide.Options, log)
+ case string(config2.IDEVSCodeWeb):
+ return cmd.setupVSCodeWeb(setupInfo, ide.Options, log)
+ case string(config2.IDECodeServer):
+ return cmd.setupCodeServer(setupInfo, ide.Options, log)
case string(config2.IDEGoland):
- return jetbrains.NewGolandServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewGolandServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDERustRover):
- return jetbrains.NewRustRoverServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewRustRoverServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDEPyCharm):
- return jetbrains.NewPyCharmServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewPyCharmServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDEPhpStorm):
- return jetbrains.NewPhpStorm(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewPhpStorm(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDEIntellij):
- return jetbrains.NewIntellij(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewIntellij(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDECLion):
- return jetbrains.NewCLionServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewCLionServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDERider):
- return jetbrains.NewRiderServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewRiderServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDERubyMine):
- return jetbrains.NewRubyMineServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewRubyMineServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDEWebStorm):
- return jetbrains.NewWebStormServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewWebStormServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDEDataSpell):
- return jetbrains.NewDataSpellServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo)
+ return jetbrains.NewDataSpellServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo)
case string(config2.IDEFleet):
- return fleet.NewFleetServer(config.GetRemoteUser(setupInfo), ide.Options, log).Install(setupInfo.SubstitutionContext.ContainerWorkspaceFolder)
+ return fleet.NewFleetServer(config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install(setupInfo.SubstitutionContext.ContainerWorkspaceFolder)
case string(config2.IDEJupyterNotebook):
- return jupyter.NewJupyterNotebookServer(setupInfo.SubstitutionContext.ContainerWorkspaceFolder, config.GetRemoteUser(setupInfo), ide.Options, log).Install()
+ return jupyter.NewJupyterNotebookServer(
+ setupInfo.SubstitutionContext.ContainerWorkspaceFolder,
+ config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install()
case string(config2.IDERStudio):
- err := rstudio.NewRStudioServer(setupInfo.SubstitutionContext.ContainerWorkspaceFolder, config.GetRemoteUser(setupInfo), ide.Options, log).Install()
- if err != nil {
- log.Errorf("could not install rstudio with error: %w", err)
- }
+ return rstudio.NewRStudioServer(
+ setupInfo.SubstitutionContext.ContainerWorkspaceFolder,
+ config.GetRemoteUser(setupInfo), ide.Options, log).
+ Install()
}
return nil
}
-func (cmd *SetupContainerCmd) setupVSCode(setupInfo *config.Result, ideOptions map[string]config2.OptionValue, flavor vscode.Flavor, log log.Logger) error {
+func (cmd *SetupContainerCmd) setupVSCode(
+ setupInfo *config.Result,
+ ideOptions map[string]config2.OptionValue,
+ flavor vscode.Flavor,
+ log log.Logger,
+) error {
log.Debugf("setup %s", flavor.DisplayName())
vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
log.Debugf("vscode settings: %v", vsCodeConfiguration.Settings)
@@ -460,24 +573,34 @@ func (cmd *SetupContainerCmd) setupVSCode(setupInfo *config.Result, ideOptions m
return nil
}
- return single.Single(fmt.Sprintf("%s-async.pid", flavor), func() (*exec.Cmd, error) {
- log.Infof("installing extensions in the background: %s", strings.Join(vsCodeConfiguration.Extensions, ","))
- binaryPath, err := os.Executable()
- if err != nil {
- return nil, err
- }
+ return command.StartBackgroundOnce(
+ fmt.Sprintf("%s-async", flavor),
+ func() (*exec.Cmd, error) {
+ log.Infof(
+ "installing extensions in the background: %s",
+ strings.Join(vsCodeConfiguration.Extensions, ","),
+ )
+ binaryPath, err := os.Executable()
+ if err != nil {
+ return nil, err
+ }
- args := []string{
- "agent", "container", "vscode-async",
- "--setup-info", cmd.SetupInfo,
- "--flavor", string(flavor),
- }
+ args := []string{
+ "agent", "container", "vscode-async",
+ "--setup-info", cmd.SetupInfo,
+ "--flavor", string(flavor),
+ }
- return exec.Command(binaryPath, args...), nil
- })
+ //nolint:gosec // binaryPath is from os.Executable(), not user input
+ return exec.Command(binaryPath, args...), nil
+ })
}
-func (cmd *SetupContainerCmd) setupOpenVSCode(setupInfo *config.Result, ideOptions map[string]config2.OptionValue, log log.Logger) error {
+func (cmd *SetupContainerCmd) setupOpenVSCode(
+ setupInfo *config.Result,
+ ideOptions map[string]config2.OptionValue,
+ log log.Logger,
+) error {
log.Debugf("setup openvscode")
vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
settings := ""
@@ -491,7 +614,15 @@ func (cmd *SetupContainerCmd) setupOpenVSCode(setupInfo *config.Result, ideOptio
}
user := config.GetRemoteUser(setupInfo)
- openVSCode := openvscode.NewOpenVSCodeServer(vsCodeConfiguration.Extensions, settings, user, "0.0.0.0", strconv.Itoa(openvscode.DefaultVSCodePort), ideOptions, log)
+ openVSCode := openvscode.NewOpenVSCodeServer(
+ vsCodeConfiguration.Extensions,
+ settings,
+ user,
+ "0.0.0.0",
+ strconv.Itoa(openvscode.DefaultVSCodePort),
+ ideOptions,
+ log,
+ )
// install open vscode
err := openVSCode.Install()
@@ -501,14 +632,24 @@ func (cmd *SetupContainerCmd) setupOpenVSCode(setupInfo *config.Result, ideOptio
// install extensions in background
if len(vsCodeConfiguration.Extensions) > 0 {
- err = single.Single("openvscode-async.pid", func() (*exec.Cmd, error) {
- log.Infof("installing extensions in the background: %s", strings.Join(vsCodeConfiguration.Extensions, ","))
+ err = command.StartBackgroundOnce("openvscode-async", func() (*exec.Cmd, error) {
+ log.Infof(
+ "installing extensions in the background: %s",
+ strings.Join(vsCodeConfiguration.Extensions, ","),
+ )
binaryPath, err := os.Executable()
if err != nil {
return nil, err
}
- return exec.Command(binaryPath, "agent", "container", "openvscode-async", "--setup-info", cmd.SetupInfo), nil
+ return exec.Command(
+ binaryPath,
+ "agent",
+ "container",
+ "openvscode-async",
+ "--setup-info",
+ cmd.SetupInfo,
+ ), nil
})
if err != nil {
return fmt.Errorf("install extensions: %w", err)
@@ -519,7 +660,128 @@ func (cmd *SetupContainerCmd) setupOpenVSCode(setupInfo *config.Result, ideOptio
return openVSCode.Start()
}
-func configureSystemGitCredentials(ctx context.Context, client tunnel.TunnelClient, log log.Logger) (func(), error) {
+//nolint:dupl // setupVSCodeWeb and setupCodeServer are intentionally parallel but use distinct IDE packages
+func (cmd *SetupContainerCmd) setupVSCodeWeb(
+ setupInfo *config.Result,
+ ideOptions map[string]config2.OptionValue,
+ log log.Logger,
+) error {
+ log.Debugf("setup vscode-web")
+ vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
+ settings := ""
+ if len(vsCodeConfiguration.Settings) > 0 {
+ out, err := json.Marshal(vsCodeConfiguration.Settings)
+ if err != nil {
+ return err
+ }
+ settings = string(out)
+ }
+
+ user := config.GetRemoteUser(setupInfo)
+ // Bind to loopback: DevPod's tunnel dials localhost inside the container,
+ // so there's no need to expose the IDE on all container interfaces.
+ server := vscodeweb.NewVSCodeWebServer(
+ vsCodeConfiguration.Extensions,
+ settings,
+ user,
+ "127.0.0.1",
+ strconv.Itoa(vscodeweb.DefaultVSCodePort),
+ ideOptions,
+ log,
+ )
+
+ if err := server.Install(); err != nil {
+ return err
+ }
+
+ if len(vsCodeConfiguration.Extensions) > 0 {
+ err := command.StartBackgroundOnce("vscode-web-async", func() (*exec.Cmd, error) {
+ log.Infof(
+ "installing extensions in the background: %s",
+ strings.Join(vsCodeConfiguration.Extensions, ","),
+ )
+ binaryPath, err := os.Executable()
+ if err != nil {
+ return nil, err
+ }
+ //nolint:gosec // binaryPath is from os.Executable(), not user input
+ return exec.Command(
+ binaryPath, "agent", "container", "vscodeweb-async",
+ "--setup-info", cmd.SetupInfo,
+ ), nil
+ })
+ if err != nil {
+ return fmt.Errorf("install extensions: %w", err)
+ }
+ }
+
+ return server.Start()
+}
+
+//nolint:dupl // setupCodeServer and setupVSCodeWeb are intentionally parallel but use distinct IDE packages
+func (cmd *SetupContainerCmd) setupCodeServer(
+ setupInfo *config.Result,
+ ideOptions map[string]config2.OptionValue,
+ log log.Logger,
+) error {
+ log.Debugf("setup code-server")
+ vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
+ settings := ""
+ if len(vsCodeConfiguration.Settings) > 0 {
+ out, err := json.Marshal(vsCodeConfiguration.Settings)
+ if err != nil {
+ return err
+ }
+ settings = string(out)
+ }
+
+ user := config.GetRemoteUser(setupInfo)
+ // Bind to loopback: DevPod's tunnel dials localhost inside the container,
+ // and code-server runs with --auth none, so it must not be exposed on
+ // other container interfaces.
+ server := codeserver.NewCodeServerServer(
+ vsCodeConfiguration.Extensions,
+ settings,
+ user,
+ "127.0.0.1",
+ strconv.Itoa(codeserver.DefaultVSCodePort),
+ ideOptions,
+ log,
+ )
+
+ if err := server.Install(); err != nil {
+ return err
+ }
+
+ if len(vsCodeConfiguration.Extensions) > 0 {
+ err := command.StartBackgroundOnce("code-server-async", func() (*exec.Cmd, error) {
+ log.Infof(
+ "installing extensions in the background: %s",
+ strings.Join(vsCodeConfiguration.Extensions, ","),
+ )
+ binaryPath, err := os.Executable()
+ if err != nil {
+ return nil, err
+ }
+ //nolint:gosec // binaryPath is from os.Executable(), not user input
+ return exec.Command(
+ binaryPath, "agent", "container", "codeserver-async",
+ "--setup-info", cmd.SetupInfo,
+ ), nil
+ })
+ if err != nil {
+ return fmt.Errorf("install extensions: %w", err)
+ }
+ }
+
+ return server.Start()
+}
+
+func configureSystemGitCredentials(
+ ctx context.Context,
+ client tunnel.TunnelClient,
+ log log.Logger,
+) (func(), error) {
if !command.Exists("git") {
return nil, errors.New("git not found")
}
@@ -535,16 +797,19 @@ func configureSystemGitCredentials(ctx context.Context, client tunnel.TunnelClie
}
gitCredentials := fmt.Sprintf("!'%s' agent git-credentials --port %d", binaryPath, serverPort)
- _ = os.Setenv("DEVPOD_GIT_HELPER_PORT", strconv.Itoa(serverPort))
+ _ = os.Setenv(config2.EnvGitHelperPort, strconv.Itoa(serverPort))
- err = git.CommandContext(ctx, git.GetDefaultExtraEnv(false), "config", "--system", "--add", "credential.helper", gitCredentials).Run()
+ err = git.CommandContext(ctx, git.GetDefaultExtraEnv(false), "config", "--system", "--add",
+ "credential.helper", gitCredentials).
+ Run()
if err != nil {
return nil, fmt.Errorf("add git credential helper: %w", err)
}
cleanup := func() {
log.Debug("unset setup system credential helper")
- err = git.CommandContext(ctx, git.GetDefaultExtraEnv(false), "config", "--system", "--unset", "credential.helper").Run()
+ err = git.CommandContext(ctx, git.GetDefaultExtraEnv(false), "config", "--system", "--unset", "credential.helper").
+ Run()
if err != nil {
log.Errorf("unset system credential helper %v", err)
}
@@ -553,7 +818,13 @@ func configureSystemGitCredentials(ctx context.Context, client tunnel.TunnelClie
return cleanup, nil
}
-func streamMount(ctx context.Context, workspaceInfo *provider2.ContainerWorkspaceInfo, m *config.Mount, tunnelClient tunnel.TunnelClient, logger log.Logger) error {
+func streamMount(
+ ctx context.Context,
+ workspaceInfo *provider2.ContainerWorkspaceInfo,
+ m *config.Mount,
+ tunnelClient tunnel.TunnelClient,
+ logger log.Logger,
+) error {
// if we have a platform workspace socket we connect directly to it
if workspaceInfo.CLIOptions.Platform.Enabled {
// check if the runner proxy socket exists
@@ -578,7 +849,10 @@ func streamMount(ctx context.Context, workspaceInfo *provider2.ContainerWorkspac
if err != nil {
return fmt.Errorf("create request: %w", err)
}
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", workspaceInfo.CLIOptions.Platform.AccessKey))
+ req.Header.Set(
+ "Authorization",
+ fmt.Sprintf("Bearer %s", workspaceInfo.CLIOptions.Platform.AccessKey),
+ )
// send the request
resp, err := httpClient.Do(req)
@@ -590,7 +864,11 @@ func streamMount(ctx context.Context, workspaceInfo *provider2.ContainerWorkspac
// check if the response is ok
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("download workspace: body = %s, status = %s", string(body), resp.Status)
+ return fmt.Errorf(
+ "download workspace: body = %s, status = %s",
+ string(body),
+ resp.Status,
+ )
}
// create progress reader
diff --git a/cmd/agent/container/setup_loft_platform_access.go b/cmd/agent/container/setup_loft_platform_access.go
index e8df6efa15..b48bd0b870 100644
--- a/cmd/agent/container/setup_loft_platform_access.go
+++ b/cmd/agent/container/setup_loft_platform_access.go
@@ -7,7 +7,6 @@ import (
"github.com/skevetter/devpod/pkg/credentials"
"github.com/skevetter/devpod/pkg/loftconfig"
"github.com/skevetter/log"
-
"github.com/spf13/cobra"
)
@@ -33,12 +32,15 @@ func NewSetupLoftPlatformAccessCmd(flags *flags.GlobalFlags) *cobra.Command {
}
setupLoftPlatformAccessCmd.Flags().StringVar(&cmd.Context, "context", "", "context to use")
- _ = setupLoftPlatformAccessCmd.Flags().MarkDeprecated("context", "Information should be provided by services server, don't use this flag anymore")
+ _ = setupLoftPlatformAccessCmd.Flags().
+ MarkDeprecated("context", "Information should be provided by services server, don't use this flag anymore")
setupLoftPlatformAccessCmd.Flags().StringVar(&cmd.Provider, "provider", "", "provider to use")
- _ = setupLoftPlatformAccessCmd.Flags().MarkDeprecated("provider", "Information should be provided by services server, don't use this flag anymore")
+ _ = setupLoftPlatformAccessCmd.Flags().
+ MarkDeprecated("provider", "Information should be provided by services server, don't use this flag anymore")
- setupLoftPlatformAccessCmd.Flags().IntVar(&cmd.Port, "port", 0, "If specified, will use the given port")
+ setupLoftPlatformAccessCmd.Flags().
+ IntVar(&cmd.Port, "port", 0, "If specified, will use the given port")
_ = setupLoftPlatformAccessCmd.Flags().MarkDeprecated("port", "")
return setupLoftPlatformAccessCmd
diff --git a/cmd/agent/container/setup_windows.go b/cmd/agent/container/setup_windows.go
index 8fdca21d57..ef7efab71f 100644
--- a/cmd/agent/container/setup_windows.go
+++ b/cmd/agent/container/setup_windows.go
@@ -3,6 +3,8 @@
package container
import (
+ "fmt"
+
"github.com/skevetter/devpod/cmd/flags"
"github.com/spf13/cobra"
)
@@ -13,7 +15,7 @@ func NewSetupContainerCmd(flags *flags.GlobalFlags) *cobra.Command {
Short: "Sets up a container",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
- panic("Windows Containers are not supported")
+ return fmt.Errorf("Windows Containers are not supported")
},
}
}
diff --git a/cmd/agent/container/ssh_server.go b/cmd/agent/container/ssh_server.go
index 6d1c9b1eb2..4b5e6826be 100644
--- a/cmd/agent/container/ssh_server.go
+++ b/cmd/agent/container/ssh_server.go
@@ -7,15 +7,17 @@ import (
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/agent"
+ "github.com/skevetter/devpod/pkg/config"
helperssh "github.com/skevetter/devpod/pkg/ssh/server"
"github.com/skevetter/devpod/pkg/ssh/server/port"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-const BaseLogDir = "/var/devpod"
+var BaseLogDir = agent.ContainerDataDir
-// SSHServerCmd holds the ssh server cmd flags
+// SSHServerCmd holds the ssh server cmd flags.
type SSHServerCmd struct {
*flags.GlobalFlags
@@ -24,25 +26,28 @@ type SSHServerCmd struct {
RemoteUser string
}
-// NewSSHServerCmd creates a new ssh command
+// NewSSHServerCmd creates a new ssh command.
func NewSSHServerCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SSHServerCmd{
GlobalFlags: flags,
}
sshCmd := &cobra.Command{
Use: "ssh-server",
- Short: "Starts the container ssh server",
+ Short: "Starts the container SSH server",
Args: cobra.NoArgs,
RunE: cmd.Run,
}
- sshCmd.Flags().StringVar(&cmd.Address, "address", fmt.Sprintf("127.0.0.1:%d", helperssh.DefaultUserPort), "Address to listen to")
- sshCmd.Flags().StringVar(&cmd.RemoteUser, "remote-user", "", "The remote user for this workspace")
- sshCmd.Flags().StringVar(&cmd.Workdir, "workdir", "", "Directory where commands will run on the host")
+ sshCmd.Flags().
+ StringVar(&cmd.Address, "address", fmt.Sprintf("127.0.0.1:%d", helperssh.DefaultUserPort), "Address to listen to")
+ sshCmd.Flags().
+ StringVar(&cmd.RemoteUser, "remote-user", "", "The remote user for this workspace")
+ sshCmd.Flags().
+ StringVar(&cmd.Workdir, "workdir", "", "Directory where commands will run on the host")
return sshCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SSHServerCmd) Run(_ *cobra.Command, _ []string) error {
logger := getFileLogger(cmd.RemoteUser, cmd.Debug)
server, err := helperssh.NewContainerServer(cmd.Address, cmd.Workdir, logger)
@@ -71,7 +76,7 @@ func getFileLogger(remoteUser string, debug bool) log.Logger {
}
fallback := log.NewDiscardLogger(logLevel)
- targetFolder := filepath.Join(os.TempDir(), ".devpod")
+ targetFolder := filepath.Join(os.TempDir(), config.ConfigDirName)
if remoteUser != "" {
targetFolder = filepath.Join(BaseLogDir, remoteUser)
}
diff --git a/cmd/agent/container/vscode_async.go b/cmd/agent/container/vscode_async.go
index 4efdbeeb88..59828ce1ec 100644
--- a/cmd/agent/container/vscode_async.go
+++ b/cmd/agent/container/vscode_async.go
@@ -11,7 +11,7 @@ import (
"github.com/spf13/cobra"
)
-// VSCodeAsyncCmd holds the cmd flags
+// VSCodeAsyncCmd holds the cmd flags.
type VSCodeAsyncCmd struct {
*flags.GlobalFlags
@@ -19,7 +19,7 @@ type VSCodeAsyncCmd struct {
Flavor string
}
-// NewVSCodeAsyncCmd creates a new command
+// NewVSCodeAsyncCmd creates a new command.
func NewVSCodeAsyncCmd() *cobra.Command {
cmd := &VSCodeAsyncCmd{}
vsCodeAsyncCmd := &cobra.Command{
@@ -31,13 +31,13 @@ func NewVSCodeAsyncCmd() *cobra.Command {
vsCodeAsyncCmd.Flags().StringVar(&cmd.SetupInfo, "setup-info", "", "The container setup info")
_ = vsCodeAsyncCmd.MarkFlagRequired("setup-info")
- vsCodeAsyncCmd.Flags().StringVar(&cmd.Flavor, "flavor", string(vscode.FlavorStable), "The flavor of the VSCode distribution")
+ vsCodeAsyncCmd.Flags().
+ StringVar(&cmd.Flavor, "flavor", string(vscode.FlavorStable), "The flavor of the VSCode distribution")
return vsCodeAsyncCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *VSCodeAsyncCmd) Run(_ *cobra.Command, _ []string) error {
- log.Default.Debugf("Start setting up container...")
decompressed, err := compress.Decompress(cmd.SetupInfo)
if err != nil {
return err
@@ -49,7 +49,6 @@ func (cmd *VSCodeAsyncCmd) Run(_ *cobra.Command, _ []string) error {
return err
}
- // install IDE
err = setupVSCodeExtensions(setupInfo, vscode.Flavor(cmd.Flavor), log.Default)
if err != nil {
return err
diff --git a/cmd/agent/container/vscodeweb_async.go b/cmd/agent/container/vscodeweb_async.go
new file mode 100644
index 0000000000..4894563aa4
--- /dev/null
+++ b/cmd/agent/container/vscodeweb_async.go
@@ -0,0 +1,54 @@
+//nolint:dupl // VSCodeWebAsyncCmd is intentionally parallel to CodeServerAsyncCmd but uses a distinct IDE package
+package container
+
+import (
+ "encoding/json"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/compress"
+ "github.com/skevetter/devpod/pkg/devcontainer/config"
+ "github.com/skevetter/devpod/pkg/ide/vscodeweb"
+ "github.com/skevetter/log"
+ "github.com/spf13/cobra"
+)
+
+// VSCodeWebAsyncCmd holds the cmd flags.
+type VSCodeWebAsyncCmd struct {
+ *flags.GlobalFlags
+
+ SetupInfo string
+}
+
+// NewVSCodeWebAsyncCmd creates a new command.
+func NewVSCodeWebAsyncCmd() *cobra.Command {
+ cmd := &VSCodeWebAsyncCmd{}
+ asyncCmd := &cobra.Command{
+ Use: "vscodeweb-async",
+ Short: "Installs vscode-web extensions",
+ Args: cobra.NoArgs,
+ RunE: cmd.Run,
+ }
+ asyncCmd.Flags().StringVar(&cmd.SetupInfo, "setup-info", "", "The container setup info")
+ _ = asyncCmd.MarkFlagRequired("setup-info")
+ return asyncCmd
+}
+
+// Run runs the command logic.
+func (cmd *VSCodeWebAsyncCmd) Run(_ *cobra.Command, _ []string) error {
+ log.Default.Debugf("Start setting up container...")
+ decompressed, err := compress.Decompress(cmd.SetupInfo)
+ if err != nil {
+ return err
+ }
+
+ setupInfo := &config.Result{}
+ err = json.Unmarshal([]byte(decompressed), setupInfo)
+ if err != nil {
+ return err
+ }
+
+ vsCodeConfiguration := config.GetVSCodeConfiguration(setupInfo.MergedConfig)
+ user := config.GetRemoteUser(setupInfo)
+ return vscodeweb.NewVSCodeWebServer(vsCodeConfiguration.Extensions, "", user, "", "", nil, log.Default).
+ InstallExtensions()
+}
diff --git a/cmd/agent/container_tunnel.go b/cmd/agent/container_tunnel.go
index 9ffbe6cd32..60f4aa8576 100644
--- a/cmd/agent/container_tunnel.go
+++ b/cmd/agent/container_tunnel.go
@@ -11,16 +11,16 @@ import (
"github.com/skevetter/devpod/cmd/agent/workspace"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/agent"
+ pkgconfig "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/devcontainer"
"github.com/skevetter/devpod/pkg/devcontainer/config"
- "github.com/skevetter/devpod/pkg/devcontainer/setup"
"github.com/skevetter/devpod/pkg/encoding"
provider2 "github.com/skevetter/devpod/pkg/provider"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-// ContainerTunnelCmd holds the ws-tunnel cmd flags
+// ContainerTunnelCmd holds the ws-tunnel cmd flags.
type ContainerTunnelCmd struct {
*flags.GlobalFlags
@@ -28,7 +28,7 @@ type ContainerTunnelCmd struct {
User string
}
-// NewContainerTunnelCmd creates a new command
+// NewContainerTunnelCmd creates a new command.
func NewContainerTunnelCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ContainerTunnelCmd{
GlobalFlags: flags,
@@ -37,18 +37,20 @@ func NewContainerTunnelCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "container-tunnel",
Short: "Starts a new container ssh tunnel",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.TODO(), log.Default.ErrorStreamOnly())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context(), log.Default.ErrorStreamOnly())
},
}
- containerTunnelCmd.Flags().StringVar(&cmd.User, "user", "", "The user to create the tunnel with")
- containerTunnelCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
+ containerTunnelCmd.Flags().
+ StringVar(&cmd.User, "user", "", "The user to create the tunnel with")
+ containerTunnelCmd.Flags().
+ StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
_ = containerTunnelCmd.MarkFlagRequired("workspace-info")
return containerTunnelCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ContainerTunnelCmd) Run(ctx context.Context, log log.Logger) error {
// write workspace info
shouldExit, workspaceInfo, err := agent.WriteWorkspaceInfo(cmd.WorkspaceInfo, log)
@@ -104,7 +106,12 @@ func (cmd *ContainerTunnelCmd) Run(ctx context.Context, log log.Logger) error {
return nil
}
-func startDevContainer(ctx context.Context, workspaceConfig *provider2.AgentWorkspaceInfo, runner devcontainer.Runner, log log.Logger) error {
+func startDevContainer(
+ ctx context.Context,
+ workspaceConfig *provider2.AgentWorkspaceInfo,
+ runner devcontainer.Runner,
+ log log.Logger,
+) error {
containerDetails, err := runner.Find(ctx)
if err != nil {
return err
@@ -120,7 +127,7 @@ func startDevContainer(ctx context.Context, workspaceConfig *provider2.AgentWork
} else if encoding.IsLegacyUID(workspaceConfig.Workspace.UID) {
// make sure workspace result is in devcontainer
buf := &bytes.Buffer{}
- err = runner.Command(ctx, "root", "cat "+setup.ResultLocation, nil, buf, buf)
+ err = runner.Command(ctx, "root", "cat "+pkgconfig.DevContainerResultPath, nil, buf, buf)
if err != nil {
// start container
_, err = StartContainer(ctx, runner, log, workspaceConfig)
@@ -133,9 +140,18 @@ func startDevContainer(ctx context.Context, workspaceConfig *provider2.AgentWork
return nil
}
-func StartContainer(ctx context.Context, runner devcontainer.Runner, log log.Logger, workspaceConfig *provider2.AgentWorkspaceInfo) (*config.Result, error) {
+func StartContainer(
+ ctx context.Context,
+ runner devcontainer.Runner,
+ log log.Logger,
+ workspaceConfig *provider2.AgentWorkspaceInfo,
+) (*config.Result, error) {
log.Debugf("starting DevPod container")
- result, err := runner.Up(ctx, devcontainer.UpOptions{NoBuild: true}, workspaceConfig.InjectTimeout)
+ result, err := runner.Up(
+ ctx,
+ devcontainer.UpOptions{NoBuild: true},
+ workspaceConfig.InjectTimeout,
+ )
if err != nil {
return result, err
}
diff --git a/cmd/agent/daemon.go b/cmd/agent/daemon.go
index 23a2ac1c12..858ed9b360 100644
--- a/cmd/agent/daemon.go
+++ b/cmd/agent/daemon.go
@@ -18,14 +18,14 @@ import (
"github.com/spf13/cobra"
)
-// DaemonCmd holds the cmd flags
+// DaemonCmd holds the cmd flags.
type DaemonCmd struct {
*flags.GlobalFlags
Interval string
}
-// NewDaemonCmd creates a new command
+// NewDaemonCmd creates a new command.
func NewDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DaemonCmd{
GlobalFlags: flags,
@@ -34,11 +34,12 @@ func NewDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "daemon",
Short: "Watches for activity and stops the server due to inactivity",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- daemonCmd.Flags().StringVar(&cmd.Interval, "interval", "", "The interval how to poll workspaces")
+ daemonCmd.Flags().
+ StringVar(&cmd.Interval, "interval", "", "The interval how to poll workspaces")
return daemonCmd
}
@@ -49,16 +50,15 @@ func (cmd *DaemonCmd) Run(ctx context.Context) error {
}
logger := log.NewFileLogger(filepath.Join(logFolder, "agent-daemon.log"), logrus.InfoLevel)
- logger.Infof("Starting DevPod Daemon patrol at %s...", logFolder)
+ logger.Infof("starting DevPod daemon patrol at %s", logFolder)
// start patrolling
- cmd.patrol(logger)
+ cmd.patrol(ctx, logger)
- // should never reach this
return nil
}
-func (cmd *DaemonCmd) patrol(log log.Logger) {
+func (cmd *DaemonCmd) patrol(ctx context.Context, log log.Logger) {
// make sure we don't immediately resleep on startup
cmd.initialTouch(log)
@@ -73,12 +73,18 @@ func (cmd *DaemonCmd) patrol(log log.Logger) {
// loop over workspace configs and check their last ModTime
for {
- time.Sleep(interval)
- cmd.doOnce(log)
+ timer := time.NewTimer(interval)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return
+ case <-timer.C:
+ cmd.doOnce(ctx, log)
+ }
}
}
-func (cmd *DaemonCmd) doOnce(log log.Logger) {
+func (cmd *DaemonCmd) doOnce(ctx context.Context, log log.Logger) {
var latestActivity *time.Time
var workspace *provider2.AgentWorkspaceInfo
@@ -92,56 +98,66 @@ func (cmd *DaemonCmd) doOnce(log log.Logger) {
pattern := baseFolder + "/contexts/*/workspaces/*/" + provider2.WorkspaceConfigFile
matches, err := filepath.Glob(pattern)
if err != nil {
- log.Errorf("Error globing pattern %s: %v", pattern, err)
+ log.Errorf("error globing pattern %s: %v", pattern, err)
return
}
// check when the last touch was
- for _, match := range matches {
- activity, activityWorkspace, err := getActivity(match, log)
- if err != nil {
- log.Errorf("Error checking for inactivity: %v", err)
- continue
- } else if activity == nil {
- continue
- }
-
- if latestActivity == nil || activity.After(*latestActivity) {
- latestActivity = activity
- workspace = activityWorkspace
- }
- }
+ latestActivity, workspace = findLatestActivity(matches, log)
// should we run shutdown command?
if latestActivity == nil {
if len(matches) == 0 {
- log.Infof("No workspaces found in path '%s'", baseFolder)
+ log.Infof("no workspaces found in path %q", baseFolder)
} else {
- log.Infof("%d workspaces found in path '%s', but none of them had any auto-stop configured or were still running / never completed successfully", len(matches), baseFolder)
+ log.Infof(
+ "%d workspaces found in path %q, but none of them had any auto-stop "+
+ "configured or were still running / never completed",
+ len(matches),
+ baseFolder,
+ )
}
return
}
+ cmd.checkAndShutdown(ctx, latestActivity, workspace, log)
+}
+
+func (cmd *DaemonCmd) checkAndShutdown(
+ ctx context.Context,
+ latestActivity *time.Time,
+ workspace *provider2.AgentWorkspaceInfo,
+ log log.Logger,
+) {
// check timeout
timeout := agent.DefaultInactivityTimeout
if workspace.Agent.Timeout != "" {
var err error
timeout, err = time.ParseDuration(workspace.Agent.Timeout)
if err != nil {
- log.Errorf("Error parsing inactivity timeout: %v", err)
+ log.Errorf("error parsing inactivity timeout: %v", err)
timeout = agent.DefaultInactivityTimeout
}
}
if latestActivity.Add(timeout).After(time.Now()) {
- log.Infof("Workspace '%s' has latest activity at '%s', will auto-stop machine in %s", workspace.Workspace.ID, latestActivity.String(), time.Until(latestActivity.Add(timeout)).String())
+ log.Infof(
+ "Workspace %q has latest activity at %q, will auto-stop machine in %s",
+ workspace.Workspace.ID,
+ latestActivity.String(),
+ time.Until(latestActivity.Add(timeout)).String(),
+ )
return
}
// run shutdown command
- cmd.runShutdownCommand(workspace, log)
+ cmd.runShutdownCommand(ctx, workspace, log)
}
-func (cmd *DaemonCmd) runShutdownCommand(workspace *provider2.AgentWorkspaceInfo, log log.Logger) {
+func (cmd *DaemonCmd) runShutdownCommand(
+ ctx context.Context,
+ workspace *provider2.AgentWorkspaceInfo,
+ log log.Logger,
+) {
// get environ
environ, err := custom.ToEnvironWithBinaries(workspace, log)
if err != nil {
@@ -151,20 +167,29 @@ func (cmd *DaemonCmd) runShutdownCommand(workspace *provider2.AgentWorkspaceInfo
// we run the timeout command now
buf := &bytes.Buffer{}
- log.Infof("Run shutdown command for workspace %s: %s", workspace.Workspace.ID, strings.Join(workspace.Agent.Exec.Shutdown, " "))
+ log.Infof(
+ "run shutdown command for workspace %s: %s",
+ workspace.Workspace.ID,
+ strings.Join(workspace.Agent.Exec.Shutdown, " "),
+ )
err = clientimplementation.RunCommand(clientimplementation.RunCommandOptions{
- Ctx: context.Background(),
+ Ctx: ctx,
Command: workspace.Agent.Exec.Shutdown,
Environ: environ,
Stdout: buf,
Stderr: buf,
})
if err != nil {
- log.Errorf("Error running %s: %s%w", strings.Join(workspace.Agent.Exec.Shutdown, " "), buf.String(), err)
+ log.Errorf(
+ "error running %s %s: %v",
+ strings.Join(workspace.Agent.Exec.Shutdown, " "),
+ buf.String(),
+ err,
+ )
return
}
- log.Infof("Successful ran command: %s", buf.String())
+ log.Infof("ran command: %s", buf.String())
}
func (cmd *DaemonCmd) initialTouch(log log.Logger) {
@@ -178,25 +203,50 @@ func (cmd *DaemonCmd) initialTouch(log log.Logger) {
pattern := baseFolder + "/contexts/*/workspaces/*/" + provider2.WorkspaceConfigFile
matches, err := filepath.Glob(pattern)
if err != nil {
- log.Errorf("Error globing pattern %s: %v", pattern, err)
+ log.Errorf("error globbing pattern %s: %v", pattern, err)
return
}
// check when the last touch was
now := time.Now()
for _, match := range matches {
- err := os.Chtimes(match, now, now)
+ if err := os.Chtimes(match, now, now); err != nil {
+ log.Errorf("error touching workspace config %s: %v", match, err)
+ continue
+ }
+ }
+}
+
+func findLatestActivity(
+ matches []string,
+ log log.Logger,
+) (*time.Time, *provider2.AgentWorkspaceInfo) {
+ var latestActivity *time.Time
+ var workspace *provider2.AgentWorkspaceInfo
+ for _, match := range matches {
+ activity, activityWorkspace, err := getActivity(match, log)
if err != nil {
- log.Errorf("Error touching workspace config %s: %v", pattern, err)
- return
+ log.Errorf("error checking for inactivity: %v", err)
+ continue
+ } else if activity == nil {
+ continue
+ }
+
+ if latestActivity == nil || activity.After(*latestActivity) {
+ latestActivity = activity
+ workspace = activityWorkspace
}
}
+ return latestActivity, workspace
}
-func getActivity(workspaceConfig string, log log.Logger) (*time.Time, *provider2.AgentWorkspaceInfo, error) {
+func getActivity(
+ workspaceConfig string,
+ log log.Logger,
+) (*time.Time, *provider2.AgentWorkspaceInfo, error) {
workspace, err := agent.ParseAgentWorkspaceInfo(workspaceConfig)
if err != nil {
- log.Errorf("Error reading %s: %v", workspaceConfig, err)
+ log.Errorf("error reading %s: %v", workspaceConfig, err)
return nil, nil, nil
}
diff --git a/cmd/agent/docker_credentials.go b/cmd/agent/docker_credentials.go
index 357f0ecd43..a11335f1ce 100644
--- a/cmd/agent/docker_credentials.go
+++ b/cmd/agent/docker_credentials.go
@@ -11,14 +11,14 @@ import (
"github.com/spf13/cobra"
)
-// DockerCredentialsCmd holds the cmd flags
+// DockerCredentialsCmd holds the cmd flags.
type DockerCredentialsCmd struct {
*flags.GlobalFlags
Port int
}
-// NewDockerCredentialsCmd creates a new command
+// NewDockerCredentialsCmd creates a new command.
func NewDockerCredentialsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DockerCredentialsCmd{
GlobalFlags: flags,
@@ -26,11 +26,12 @@ func NewDockerCredentialsCmd(flags *flags.GlobalFlags) *cobra.Command {
dockerCredentialsCmd := &cobra.Command{
Use: "docker-credentials",
Short: "Retrieves docker-credentials from the local machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args, log.Default.ErrorStreamOnly())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args, log.Default.ErrorStreamOnly())
},
}
- dockerCredentialsCmd.Flags().IntVar(&cmd.Port, "port", 0, "If specified, will use the given port")
+ dockerCredentialsCmd.Flags().
+ IntVar(&cmd.Port, "port", 0, "If specified, will use the given port")
_ = dockerCredentialsCmd.MarkFlagRequired("port")
return dockerCredentialsCmd
}
diff --git a/cmd/agent/git_credentials.go b/cmd/agent/git_credentials.go
index a31ecd9243..ab144668fa 100644
--- a/cmd/agent/git_credentials.go
+++ b/cmd/agent/git_credentials.go
@@ -21,14 +21,14 @@ import (
"github.com/spf13/cobra"
)
-// GitCredentialsCmd holds the cmd flags
+// GitCredentialsCmd holds the cmd flags.
type GitCredentialsCmd struct {
*flags.GlobalFlags
Port int
}
-// NewGitCredentialsCmd creates a new command
+// NewGitCredentialsCmd creates a new command.
func NewGitCredentialsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GitCredentialsCmd{
GlobalFlags: flags,
@@ -36,8 +36,8 @@ func NewGitCredentialsCmd(flags *flags.GlobalFlags) *cobra.Command {
gitCredentialsCmd := &cobra.Command{
Use: "git-credentials",
Short: "Retrieves git-credentials from the local machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args, log.Default.ErrorStreamOnly())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args, log.Default.ErrorStreamOnly())
},
}
gitCredentialsCmd.Flags().IntVar(&cmd.Port, "port", 0, "If specified, will use the given port")
@@ -78,7 +78,9 @@ func (cmd *GitCredentialsCmd) Run(ctx context.Context, args []string, log log.Lo
return nil
}
-func getCredentialsFromWorkspaceServer(credentials *gitcredentials.GitCredentials) *gitcredentials.GitCredentials {
+func getCredentialsFromWorkspaceServer(
+ credentials *gitcredentials.GitCredentials,
+) *gitcredentials.GitCredentials {
if _, err := os.Stat(filepath.Join(container.RootDir, ts.RunnerProxySocket)); err != nil {
// workspace server is not running
return nil
@@ -92,10 +94,18 @@ func getCredentialsFromWorkspaceServer(credentials *gitcredentials.GitCredential
},
}
- credentials, credentialsErr := doRequest(httpClient, credentials, "http://runner-proxy/git-credentials")
+ credentials, credentialsErr := doRequest(
+ httpClient,
+ credentials,
+ "http://runner-proxy/git-credentials",
+ )
if credentialsErr != nil {
- // append error to /tmp/git-credentials.log
- file, err := os.OpenFile("/tmp/git-credentials-error.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ // #nosec G302 -- TODO Consider using a more secure permission setting and ownership if needed.
+ file, err := os.OpenFile(
+ "/tmp/git-credentials-error.log",
+ os.O_APPEND|os.O_CREATE|os.O_WRONLY,
+ 0o644,
+ )
if err != nil {
return nil
}
@@ -108,11 +118,22 @@ func getCredentialsFromWorkspaceServer(credentials *gitcredentials.GitCredential
return credentials
}
-func getCredentialsFromLocalMachine(credentials *gitcredentials.GitCredentials, port int) *gitcredentials.GitCredentials {
- credentials, credentialsErr := doRequest(devpodhttp.GetHTTPClient(), credentials, "http://localhost:"+strconv.Itoa(port)+"/git-credentials")
+func getCredentialsFromLocalMachine(
+ credentials *gitcredentials.GitCredentials,
+ port int,
+) *gitcredentials.GitCredentials {
+ credentials, credentialsErr := doRequest(
+ devpodhttp.GetHTTPClient(),
+ credentials,
+ "http://localhost:"+strconv.Itoa(port)+"/git-credentials",
+ )
if credentialsErr != nil {
- // append error to /tmp/git-credentials.log
- file, err := os.OpenFile("/tmp/git-credentials-error.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ // #nosec G302 -- TODO Consider using a more secure permission setting and ownership if needed.
+ file, err := os.OpenFile(
+ "/tmp/git-credentials-error.log",
+ os.O_APPEND|os.O_CREATE|os.O_WRONLY,
+ 0o644,
+ )
if err != nil {
return nil
}
@@ -125,7 +146,11 @@ func getCredentialsFromLocalMachine(credentials *gitcredentials.GitCredentials,
return credentials
}
-func doRequest(httpClient *http.Client, credentials *gitcredentials.GitCredentials, url string) (*gitcredentials.GitCredentials, error) {
+func doRequest(
+ httpClient *http.Client,
+ credentials *gitcredentials.GitCredentials,
+ url string,
+) (*gitcredentials.GitCredentials, error) {
rawJSON, err := json.Marshal(credentials)
if err != nil {
return nil, fmt.Errorf("error marshalling credentials: %w", err)
@@ -144,7 +169,11 @@ func doRequest(httpClient *http.Client, credentials *gitcredentials.GitCredentia
// has the request succeeded?
if response.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("error reading credentials (%d): %s", response.StatusCode, string(raw))
+ return nil, fmt.Errorf(
+ "error reading credentials (%d): %s",
+ response.StatusCode,
+ string(raw),
+ )
}
credentials = &gitcredentials.GitCredentials{}
diff --git a/cmd/agent/git_ssh_signature.go b/cmd/agent/git_ssh_signature.go
index e4cbbe6bcc..48fa82f7d9 100644
--- a/cmd/agent/git_ssh_signature.go
+++ b/cmd/agent/git_ssh_signature.go
@@ -1,7 +1,10 @@
package agent
import (
- "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/gitsshsigning"
@@ -9,15 +12,6 @@ import (
"github.com/spf13/cobra"
)
-type GitSSHSignatureCmd struct {
- *flags.GlobalFlags
-
- CertPath string
- Namespace string
- BufferFile string
- Command string
-}
-
// NewGitSSHSignatureCmd creates new git-ssh-signature command
// This agent command can be used as git ssh program by setting
//
@@ -28,35 +22,119 @@ type GitSSHSignatureCmd struct {
//
// custom-ssh-signature-handler -Y sign -n git -f /Users/johndoe/.ssh/my-key.pub /tmp/.git_signing_buffer_tmp4Euk6d
func NewGitSSHSignatureCmd(flags *flags.GlobalFlags) *cobra.Command {
- cmd := &GitSSHSignatureCmd{
- GlobalFlags: flags,
- }
-
- gitSshSignatureCmd := &cobra.Command{
+ return &cobra.Command{
Use: "git-ssh-signature",
+ // This command implements the ssh-keygen protocol used by git for commit
+ // signing. Disable cobra's flag parsing so we can handle the ssh-keygen
+ // argument format directly, including boolean flags like -U (ssh-agent
+ // mode) that cobra cannot distinguish from flags that take a value.
+ DisableFlagParsing: true,
RunE: func(_ *cobra.Command, args []string) error {
logger := log.GetInstance()
- if len(args) < 1 {
- logger.Fatalf("Buffer file is required")
- }
+ parsed := parseSSHKeygenArgs(args)
- // Check if the required -Y sign flags are present
- if cmd.Command != "sign" {
- return errors.New("must include '-Y sign' arguments")
+ // For non-sign operations (verify, find-principals, check-novalidate),
+ // delegate command to system ssh-keygen since op does not require the tunnel.
+ if parsed.command != "sign" {
+ return delegateToSSHKeygen(args, logger)
}
- // The last argument is the buffer file
- cmd.BufferFile = args[len(args)-1]
+ if parsed.certPath == "" {
+ return fmt.Errorf("key file (-f) is required")
+ }
+ if parsed.namespace == "" {
+ return fmt.Errorf("namespace (-n) is required")
+ }
+ if parsed.bufferFile == "" {
+ return fmt.Errorf("buffer file is required")
+ }
return gitsshsigning.HandleGitSSHProgramCall(
- cmd.CertPath, cmd.Namespace, cmd.BufferFile, logger)
+ parsed.certPath, parsed.namespace, parsed.bufferFile, logger)
},
}
+}
+
+// sshKeygenArgs holds the parsed result of a git ssh-keygen invocation.
+type sshKeygenArgs struct {
+ command string // -Y value (sign, verify, find-principals, etc.)
+ certPath string // -f value (path to public key)
+ namespace string // -n value (always "git" for commit signing)
+ bufferFile string // last non-flag argument
+}
+
+// parseSSHKeygenArgs parses the ssh-keygen argument format used by git:
+//
+// -Y -n -f [flags...]
+//
+// The buffer file is always the last argument and is never a flag.
+// Unknown flags (e.g. -U for ssh-agent mode) are ignored.
+func parseSSHKeygenArgs(args []string) sshKeygenArgs {
+ result := sshKeygenArgs{
+ command: "sign",
+ } // git only ever calls with sign, but default defensively
+ consumed := make(map[int]bool)
+ for i := 0; i < len(args); i++ {
+ if next := consumeFlag(&result, args, i); next > i {
+ consumed[i] = true
+ consumed[next] = true
+ i = next
+ }
+ }
+ // The buffer file is always the last argument and is never a flag.
+ lastIdx := len(args) - 1
+ if lastIdx >= 0 && !consumed[lastIdx] && !strings.HasPrefix(args[lastIdx], "-") {
+ result.bufferFile = args[lastIdx]
+ }
+ return result
+}
+
+// consumeFlag processes a single known flag from args at position i.
+// Returns the index of the consumed value if a known flag-value pair is found,
+// or i if no value was consumed.
+func consumeFlag(result *sshKeygenArgs, args []string, i int) int {
+ if i+1 >= len(args) {
+ return i
+ }
+ next := args[i+1]
+
+ switch args[i] {
+ case "-Y":
+ if strings.HasPrefix(next, "-") {
+ return i
+ }
+ result.command = next
+ return i + 1
+ case "-f":
+ if strings.HasPrefix(next, "-") {
+ return i
+ }
+ result.certPath = next
+ return i + 1
+ case "-n":
+ if strings.HasPrefix(next, "-") {
+ return i
+ }
+ result.namespace = next
+ return i + 1
+ }
+ return i
+}
+
+// delegateToSSHKeygen forwards args to the system ssh-keygen binary.
+func delegateToSSHKeygen(args []string, logger log.Logger) error {
+ sshKeygen, err := exec.LookPath("ssh-keygen")
+ if err != nil {
+ return fmt.Errorf("find ssh-keygen: %w", err)
+ }
+
+ logger.Debugf("delegating to ssh-keygen: %s %v", sshKeygen, args)
- gitSshSignatureCmd.Flags().StringVarP(&cmd.CertPath, "file", "f", "", "Path to the private key")
- gitSshSignatureCmd.Flags().StringVarP(&cmd.Namespace, "namespace", "n", "", "Namespace")
- gitSshSignatureCmd.Flags().StringVarP(&cmd.Command, "command", "Y", "sign", "Command - should be 'sign'")
+ c := exec.Command(sshKeygen, args...) // #nosec G204,G304,G702
+ c.Stdin = os.Stdin
+ c.Stdout = os.Stdout
+ c.Stderr = os.Stderr
- return gitSshSignatureCmd
+ return c.Run()
}
diff --git a/cmd/agent/git_ssh_signature_helper.go b/cmd/agent/git_ssh_signature_helper.go
index 322ac39768..9d8627ea25 100644
--- a/cmd/agent/git_ssh_signature_helper.go
+++ b/cmd/agent/git_ssh_signature_helper.go
@@ -26,9 +26,10 @@ type GitSSHSignatureHelperCmd struct {
//
// git-ssh-signature-helper [signing-key-path]
//
-// The signing key path is a required argument for this command. It should be what equal to what you would have set as user.signingkey git config.
+// The signing key path is a required argument for this command. It should be what equal to what you
+// would have set as user.signingkey git config.
func NewGitSSHSignatureHelperCmd(flags *flags.GlobalFlags) *cobra.Command {
- cmd := &GitSSHSignatureCmd{
+ cmd := &GitSSHSignatureHelperCmd{
GlobalFlags: flags,
}
diff --git a/cmd/agent/git_ssh_signature_test.go b/cmd/agent/git_ssh_signature_test.go
new file mode 100644
index 0000000000..6504c07e6f
--- /dev/null
+++ b/cmd/agent/git_ssh_signature_test.go
@@ -0,0 +1,80 @@
+package agent
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/suite"
+)
+
+type GitSSHSignatureTestSuite struct {
+ suite.Suite
+}
+
+func TestGitSSHSignatureSuite(t *testing.T) {
+ suite.Run(t, new(GitSSHSignatureTestSuite))
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseBasicSignArgs() {
+ args := []string{"-Y", "sign", "-n", "git", "-f", "/path/to/key.pub", "/tmp/buffer"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "sign", result.command)
+ assert.Equal(s.T(), "git", result.namespace)
+ assert.Equal(s.T(), "/path/to/key.pub", result.certPath)
+ assert.Equal(s.T(), "/tmp/buffer", result.bufferFile)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseWithAgentFlag() {
+ // When the signing key is loaded in the ssh-agent, git passes -U (a boolean
+ // "use agent" flag) immediately before the buffer file. The buffer file must
+ // still be recognised as the last non-flag argument.
+ args := []string{"-Y", "sign", "-n", "git", "-f", "/path/to/key.pub", "-U", "/tmp/buffer"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "sign", result.command)
+ assert.Equal(s.T(), "/path/to/key.pub", result.certPath)
+ assert.Equal(s.T(), "/tmp/buffer", result.bufferFile)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseNonSignCommand() {
+ args := []string{"-Y", "verify", "-n", "git", "-f", "/path/to/key.pub", "/tmp/buffer"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "verify", result.command)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseMissingBufferFile() {
+ // All args end in a flag — no buffer file present.
+ args := []string{"-Y", "sign", "-n", "git", "-f", "/path/to/key.pub", "-U"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "", result.bufferFile)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseDefaultsToSign() {
+ // If -Y is absent the command defaults to "sign".
+ args := []string{"-n", "git", "-f", "/path/to/key.pub", "/tmp/buffer"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "sign", result.command)
+ assert.Equal(s.T(), "/tmp/buffer", result.bufferFile)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseEmptyArgs() {
+ result := parseSSHKeygenArgs([]string{})
+ assert.Equal(s.T(), "sign", result.command)
+ assert.Equal(s.T(), "", result.bufferFile)
+ assert.Equal(s.T(), "", result.certPath)
+ assert.Equal(s.T(), "", result.namespace)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseWithUFlag() {
+ // Git passes -U when using a literal SSH key value. The parser must
+ // still identify certPath and bufferFile with -U present.
+ args := []string{"-Y", "sign", "-n", "git", "-f", "/key.pub", "-U", "/tmp/buf"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "/key.pub", result.certPath)
+ assert.Equal(s.T(), "/tmp/buf", result.bufferFile)
+}
+
+func (s *GitSSHSignatureTestSuite) TestParseBufferFileWithSpaces() {
+ args := []string{"-Y", "sign", "-n", "git", "-f", "/key.pub", "/tmp/my buffer file"}
+ result := parseSSHKeygenArgs(args)
+ assert.Equal(s.T(), "/tmp/my buffer file", result.bufferFile)
+}
diff --git a/cmd/agent/workspace/build.go b/cmd/agent/workspace/build.go
index 1f29baf32c..2ff6e6729b 100644
--- a/cmd/agent/workspace/build.go
+++ b/cmd/agent/workspace/build.go
@@ -12,14 +12,14 @@ import (
"github.com/spf13/cobra"
)
-// BuildCmd holds the cmd flags
+// BuildCmd holds the cmd flags.
type BuildCmd struct {
*flags.GlobalFlags
WorkspaceInfo string
}
-// NewBuildCmd creates a new command
+// NewBuildCmd creates a new command.
func NewBuildCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &BuildCmd{
GlobalFlags: flags,
@@ -28,8 +28,8 @@ func NewBuildCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "build",
Short: "Builds a devcontainer",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
buildCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
@@ -37,12 +37,16 @@ func NewBuildCmd(flags *flags.GlobalFlags) *cobra.Command {
return buildCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *BuildCmd) Run(ctx context.Context) error {
// write workspace info
- shouldExit, workspaceInfo, err := agent.WriteWorkspaceInfoAndDeleteOld(cmd.WorkspaceInfo, func(workspaceInfo *provider2.AgentWorkspaceInfo, log log.Logger) error {
- return deleteWorkspace(ctx, workspaceInfo, log)
- }, log.Default.ErrorStreamOnly())
+ shouldExit, workspaceInfo, err := agent.WriteWorkspaceInfoAndDeleteOld(
+ cmd.WorkspaceInfo,
+ func(workspaceInfo *provider2.AgentWorkspaceInfo, log log.Logger) error {
+ return deleteWorkspace(ctx, workspaceInfo, log)
+ },
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return err
} else if shouldExit {
@@ -106,7 +110,11 @@ func (cmd *BuildCmd) Run(ctx context.Context) error {
return nil
}
-func deleteWorkspace(ctx context.Context, workspaceInfo *provider2.AgentWorkspaceInfo, log log.Logger) error {
+func deleteWorkspace(
+ ctx context.Context,
+ workspaceInfo *provider2.AgentWorkspaceInfo,
+ log log.Logger,
+) error {
err := removeContainer(ctx, workspaceInfo, log)
if err != nil {
log.Errorf("Removing container: %v", err)
diff --git a/cmd/agent/workspace/delete.go b/cmd/agent/workspace/delete.go
index fd35345788..6f435e015c 100644
--- a/cmd/agent/workspace/delete.go
+++ b/cmd/agent/workspace/delete.go
@@ -5,7 +5,6 @@ import (
"fmt"
"os"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/agent"
agentdaemon "github.com/skevetter/devpod/pkg/daemon/agent"
@@ -14,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
-// DeleteCmd holds the cmd flags
+// DeleteCmd holds the cmd flags.
type DeleteCmd struct {
*flags.GlobalFlags
@@ -24,7 +23,7 @@ type DeleteCmd struct {
WorkspaceInfo string
}
-// NewDeleteCmd creates a new command
+// NewDeleteCmd creates a new command.
func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: flags,
@@ -33,12 +32,14 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "delete",
Short: "Cleans up a workspace on the remote server",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- deleteCmd.Flags().BoolVar(&cmd.Container, "container", true, "If enabled, cleans up the DevPod container")
- deleteCmd.Flags().BoolVar(&cmd.Daemon, "daemon", false, "If enabled, cleans up the DevPod daemon")
+ deleteCmd.Flags().
+ BoolVar(&cmd.Container, "container", true, "If enabled, cleans up the DevPod container")
+ deleteCmd.Flags().
+ BoolVar(&cmd.Daemon, "daemon", false, "If enabled, cleans up the DevPod daemon")
deleteCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
_ = deleteCmd.MarkFlagRequired("workspace-info")
@@ -47,7 +48,10 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
func (cmd *DeleteCmd) Run(ctx context.Context) error {
// get workspace
- shouldExit, workspaceInfo, err := agent.WorkspaceInfo(cmd.WorkspaceInfo, log.Default.ErrorStreamOnly())
+ shouldExit, workspaceInfo, err := agent.WorkspaceInfo(
+ cmd.WorkspaceInfo,
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return fmt.Errorf("error parsing workspace info: %w", err)
} else if shouldExit {
@@ -75,10 +79,12 @@ func (cmd *DeleteCmd) Run(ctx context.Context) error {
return nil
}
-func removeContainer(ctx context.Context, workspaceInfo *provider2.AgentWorkspaceInfo, log log.Logger) error {
- log.WithFields(logrus.Fields{
- "workspaceId": workspaceInfo.Workspace.ID,
- }).Debug("removing DevPod container from server")
+func removeContainer(
+ ctx context.Context,
+ workspaceInfo *provider2.AgentWorkspaceInfo,
+ log log.Logger,
+) error {
+ log.Debugf("removing DevPod container from server: workspaceId=%s", workspaceInfo.Workspace.ID)
runner, err := CreateRunner(workspaceInfo, log)
if err != nil {
return err
diff --git a/cmd/agent/workspace/install_dotfiles.go b/cmd/agent/workspace/install_dotfiles.go
index f5aa645ff6..8fc87bcc07 100644
--- a/cmd/agent/workspace/install_dotfiles.go
+++ b/cmd/agent/workspace/install_dotfiles.go
@@ -16,7 +16,7 @@ import (
"github.com/spf13/cobra"
)
-// InstallDotfilesCmd holds the installDotfiles cmd flags
+// InstallDotfilesCmd holds the installDotfiles cmd flags.
type InstallDotfilesCmd struct {
*flags.GlobalFlags
@@ -25,7 +25,7 @@ type InstallDotfilesCmd struct {
StrictHostKeyChecking bool
}
-// NewInstallDotfilesCmd creates a new command
+// NewInstallDotfilesCmd creates a new command.
func NewInstallDotfilesCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &InstallDotfilesCmd{
GlobalFlags: flags,
@@ -34,17 +34,21 @@ func NewInstallDotfilesCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "install-dotfiles",
Short: "installs input dotfiles in the container",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- installDotfilesCmd.Flags().StringVar(&cmd.Repository, "repository", "", "The dotfiles repository")
- installDotfilesCmd.Flags().StringVar(&cmd.InstallScript, "install-script", "", "The dotfiles install command to execute")
- installDotfilesCmd.Flags().BoolVar(&cmd.StrictHostKeyChecking, "strict-host-key-checking", false, "Set to enable strict host key checking for git cloning via SSH")
+ installDotfilesCmd.Flags().
+ StringVar(&cmd.Repository, "repository", "", "The dotfiles repository")
+ installDotfilesCmd.Flags().
+ StringVar(&cmd.InstallScript, "install-script", "", "The dotfiles install command to execute")
+ installDotfilesCmd.Flags().
+ BoolVar(&cmd.StrictHostKeyChecking, "strict-host-key-checking", false,
+ "Set to enable strict host key checking for git cloning via SSH")
return installDotfilesCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *InstallDotfilesCmd) Run(ctx context.Context) error {
logger := log.Default.ErrorStreamOnly()
targetDir := filepath.Join(os.Getenv("HOME"), "dotfiles")
@@ -54,7 +58,14 @@ func (cmd *InstallDotfilesCmd) Run(ctx context.Context) error {
logger.Infof("Cloning dotfiles %s", cmd.Repository)
gitInfo := git.NormalizeRepositoryGitInfo(cmd.Repository)
- if err := git.CloneRepository(ctx, gitInfo, targetDir, "", cmd.StrictHostKeyChecking, logger); err != nil {
+ if err := git.CloneRepository(
+ ctx,
+ gitInfo,
+ targetDir,
+ "",
+ cmd.StrictHostKeyChecking,
+ logger,
+ ); err != nil {
return err
}
} else {
@@ -72,12 +83,15 @@ func (cmd *InstallDotfilesCmd) Run(ctx context.Context) error {
logger.Infof("Executing install script %s", cmd.InstallScript)
command := "./" + strings.TrimPrefix(cmd.InstallScript, "./")
- err := ensureExecutable(command)
+ err := ensureExecutable(ctx, command)
if err != nil {
return fmt.Errorf("failed to make install script %s executable: %w", command, err)
}
- scriptCmd := exec.Command(command)
+ scriptCmd := exec.CommandContext(
+ ctx,
+ command,
+ ) // #nosec G204 -- user-provided dotfile install script
writer := logger.Writer(logrus.InfoLevel, false)
scriptCmd.Stdout = writer
scriptCmd.Stderr = writer
@@ -87,7 +101,7 @@ func (cmd *InstallDotfilesCmd) Run(ctx context.Context) error {
logger.Debugf("Install script not specified, trying known locations")
- return setupDotfiles(logger)
+ return setupDotfiles(ctx, logger)
}
var installScriptPaths = []string{
@@ -101,8 +115,9 @@ var installScriptPaths = []string{
"./setup/setup",
}
-func setupDotfiles(logger log.Logger) error {
- installScriptPaths = slices.DeleteFunc(installScriptPaths, func(path string) bool {
+func setupDotfiles(ctx context.Context, logger log.Logger) error {
+ scripts := slices.Clone(installScriptPaths)
+ scripts = slices.DeleteFunc(scripts, func(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return true
}
@@ -110,27 +125,33 @@ func setupDotfiles(logger log.Logger) error {
return false
})
- for _, installScriptPath := range installScriptPaths {
+ for _, installScriptPath := range scripts {
writer := logger.Writer(logrus.InfoLevel, false)
- err := ensureExecutable(installScriptPath)
+ err := ensureExecutable(ctx, installScriptPath)
if err != nil {
- logger.WithFields(logrus.Fields{
- "scriptPath": installScriptPath,
- "error": err,
- }).Debug("install script not found")
+ logger.Debugf(
+ "install script not found: scriptPath=%s, error=%v",
+ installScriptPath,
+ err,
+ )
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
continue
}
- logger.WithFields(logrus.Fields{
- "scriptPath": installScriptPath,
- }).Debug("executing dotfile install script")
- scriptCmd := exec.Command(installScriptPath)
+ logger.Debugf("executing dotfile install script: scriptPath=%s", installScriptPath)
+ scriptCmd := exec.CommandContext(
+ ctx,
+ installScriptPath,
+ ) // #nosec G204 -- user-provided dotfile install script
scriptCmd.Stdout = writer
scriptCmd.Stderr = writer
if err := scriptCmd.Run(); err != nil {
- logger.WithFields(logrus.Fields{
- "error": err,
- }).Debug("script execution failed")
+ logger.Debugf("script execution failed: error=%v", err)
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
continue
}
@@ -141,6 +162,10 @@ func setupDotfiles(logger log.Logger) error {
logger.Info("Finished script locations, trying to link the files")
+ return linkDotfiles(ctx, logger)
+}
+
+func linkDotfiles(ctx context.Context, logger log.Logger) error {
files, err := os.ReadDir(".")
if err != nil {
return err
@@ -151,33 +176,54 @@ func setupDotfiles(logger log.Logger) error {
return err
}
- // link dotfiles in directory to home
+ home := os.Getenv("HOME")
for _, file := range files {
- if strings.HasPrefix(file.Name(), ".") && !file.IsDir() {
- logger.Debugf("linking %s in home", file.Name())
-
- // remove existing symlink and relink
- if _, err := os.Lstat(filepath.Join(os.Getenv("HOME"), file.Name())); err == nil {
- _ = os.Remove(filepath.Join(os.Getenv("HOME"), file.Name()))
- }
- err = os.Symlink(filepath.Join(pwd, file.Name()), filepath.Join(os.Getenv("HOME"), file.Name()))
- if err != nil {
- return err
- }
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if !strings.HasPrefix(file.Name(), ".") || file.IsDir() {
+ continue
+ }
+ if err := linkDotfile(
+ logger,
+ filepath.Join(pwd, file.Name()),
+ filepath.Join(home, file.Name()),
+ ); err != nil {
+ return err
}
}
return nil
}
-func ensureExecutable(path string) error {
- checkCmd := exec.Command("test", "-f", path)
+func linkDotfile(logger log.Logger, src, dest string) error {
+ logger.Debugf("linking %s in home", filepath.Base(dest))
+ if _, err := os.Lstat(dest); err == nil { // #nosec G703
+ if removeErr := os.Remove(dest); removeErr != nil { // #nosec G703
+ logger.Debugf("failed to remove %s: %v", dest, removeErr)
+ }
+ }
+ return os.Symlink(src, dest)
+}
+
+func ensureExecutable(ctx context.Context, path string) error {
+ checkCmd := exec.CommandContext(
+ ctx,
+ "test",
+ "-f",
+ path,
+ ) // #nosec G204 -- user-provided dotfile path
err := checkCmd.Run()
if err != nil {
return fmt.Errorf("install script %s not found: %w", path, err)
}
- chmodCmd := exec.Command("chmod", "+x", path)
+ chmodCmd := exec.CommandContext(
+ ctx,
+ "chmod",
+ "+x",
+ path,
+ ) // #nosec G204 -- user-provided dotfile path
err = chmodCmd.Run()
if err != nil {
return fmt.Errorf("failed to make install script %s executable: %w", path, err)
diff --git a/cmd/agent/workspace/logs.go b/cmd/agent/workspace/logs.go
index 1cfa5eb188..737b504db2 100644
--- a/cmd/agent/workspace/logs.go
+++ b/cmd/agent/workspace/logs.go
@@ -12,14 +12,14 @@ import (
"github.com/spf13/cobra"
)
-// LogsCmd holds the cmd flags
+// LogsCmd holds the cmd flags.
type LogsCmd struct {
*flags.GlobalFlags
ID string
}
-// NewLogsCmd creates a new command
+// NewLogsCmd creates a new command.
func NewLogsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &LogsCmd{
GlobalFlags: flags,
@@ -28,8 +28,8 @@ func NewLogsCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "logs",
Short: "Returns the workspace container logs",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
c.Flags().StringVar(&cmd.ID, "id", "", "The workspace id")
@@ -40,7 +40,12 @@ func NewLogsCmd(flags *flags.GlobalFlags) *cobra.Command {
func (cmd *LogsCmd) Run(ctx context.Context) error {
// get workspace info
- shouldExit, workspaceInfo, err := agent.ReadAgentWorkspaceInfo(cmd.AgentDir, cmd.Context, cmd.ID, log.Default.ErrorStreamOnly())
+ shouldExit, workspaceInfo, err := agent.ReadAgentWorkspaceInfo(
+ cmd.AgentDir,
+ cmd.Context,
+ cmd.ID,
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return err
} else if shouldExit {
@@ -49,7 +54,12 @@ func (cmd *LogsCmd) Run(ctx context.Context) error {
logger := log.Default.ErrorStreamOnly()
// create new runner
- runner, err := devcontainer.NewRunner(agent.ContainerDevPodHelperLocation, agent.DefaultAgentDownloadURL(), workspaceInfo, logger)
+ runner, err := devcontainer.NewRunner(
+ agent.ContainerDevPodHelperLocation,
+ agent.DefaultAgentDownloadURL(),
+ workspaceInfo,
+ logger,
+ )
if err != nil {
return fmt.Errorf("create runner: %w", err)
}
diff --git a/cmd/agent/workspace/logs_daemon.go b/cmd/agent/workspace/logs_daemon.go
index 1f2c3e2f4b..4b29a7c792 100644
--- a/cmd/agent/workspace/logs_daemon.go
+++ b/cmd/agent/workspace/logs_daemon.go
@@ -13,14 +13,14 @@ import (
"github.com/spf13/cobra"
)
-// LogsDaemonCmd holds the cmd flags
+// LogsDaemonCmd holds the cmd flags.
type LogsDaemonCmd struct {
*flags.GlobalFlags
ID string
}
-// NewLogsDaemonCmd creates a new command
+// NewLogsDaemonCmd creates a new command.
func NewLogsDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &LogsDaemonCmd{
GlobalFlags: flags,
@@ -29,8 +29,8 @@ func NewLogsDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "logs-daemon",
Short: "Returns the daemon logs",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
logsDaemonCmd.Flags().StringVar(&cmd.ID, "id", "", "The workspace id")
@@ -40,7 +40,12 @@ func NewLogsDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
func (cmd *LogsDaemonCmd) Run(ctx context.Context) error {
// get workspace
- shouldExit, _, err := agent.ReadAgentWorkspaceInfo(cmd.AgentDir, cmd.Context, cmd.ID, log.Default.ErrorStreamOnly())
+ shouldExit, _, err := agent.ReadAgentWorkspaceInfo(
+ cmd.AgentDir,
+ cmd.Context,
+ cmd.ID,
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return err
} else if shouldExit {
diff --git a/cmd/agent/workspace/setup_gpg.go b/cmd/agent/workspace/setup_gpg.go
index ed2fa6be41..ecd546f66d 100644
--- a/cmd/agent/workspace/setup_gpg.go
+++ b/cmd/agent/workspace/setup_gpg.go
@@ -13,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
-// SetupGPGCmd holds the setupGPG cmd flags
+// SetupGPGCmd holds the setupGPG cmd flags.
type SetupGPGCmd struct {
*flags.GlobalFlags
@@ -22,7 +22,7 @@ type SetupGPGCmd struct {
GitKey string
}
-// NewSetupGPGCmd creates a new command
+// NewSetupGPGCmd creates a new command.
func NewSetupGPGCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SetupGPGCmd{
GlobalFlags: flags,
@@ -35,9 +35,12 @@ func NewSetupGPGCmd(flags *flags.GlobalFlags) *cobra.Command {
return cmd.Run(cobraCmd.Context(), log.Default.ErrorStreamOnly())
},
}
- setupGPGCmd.Flags().StringVar(&cmd.OwnerTrust, "ownertrust", "", "GPG Owner trust to import in armor form")
- setupGPGCmd.Flags().StringVar(&cmd.SocketPath, "socketpath", "", "path to the gpg socket forwarded")
- setupGPGCmd.Flags().StringVar(&cmd.GitKey, "gitkey", "", "gpg key to use for git commit signing")
+ setupGPGCmd.Flags().
+ StringVar(&cmd.OwnerTrust, "ownertrust", "", "GPG Owner trust to import in armor form")
+ setupGPGCmd.Flags().
+ StringVar(&cmd.SocketPath, "socketpath", "", "path to the gpg socket forwarded")
+ setupGPGCmd.Flags().
+ StringVar(&cmd.GitKey, "gitkey", "", "gpg key to use for git commit signing")
return setupGPGCmd
}
@@ -49,7 +52,7 @@ func NewSetupGPGCmd(flags *flags.GlobalFlags) *cobra.Command {
// - importing those into the container
// - ensuring the gpg-agent is stopped in the container
// - starting a reverse-tunnel of the local unix socket to remote
-// - ensuring paths and permissions are correctly set in the remote
+// - ensuring paths and permissions are correctly set in the remote.
func (cmd *SetupGPGCmd) Run(ctx context.Context, log log.Logger) error {
log.Debugf("Initializing gpg-agent forwarding")
@@ -132,10 +135,8 @@ func (cmd *SetupGPGCmd) Run(ctx context.Context, log log.Logger) error {
if gpgConf.GitKey != "" {
log.Debugf("Setup git signing key")
- err = gitcredentials.SetupGpgGitKey(gpgConf.GitKey)
- if err != nil {
- log.Errorf("Setup git signing key: %v", err)
- return err
+ if err := gitcredentials.SetupGpgGitKey(gpgConf.GitKey); err != nil {
+ log.Warnf("Setup git signing key failed (non-fatal): %v", err)
}
}
diff --git a/cmd/agent/workspace/status.go b/cmd/agent/workspace/status.go
index 08e35d648d..3805b2337f 100644
--- a/cmd/agent/workspace/status.go
+++ b/cmd/agent/workspace/status.go
@@ -12,14 +12,14 @@ import (
"github.com/spf13/cobra"
)
-// StatusCmd holds the cmd flags
+// StatusCmd holds the cmd flags.
type StatusCmd struct {
*flags.GlobalFlags
WorkspaceInfo string
}
-// NewStatusCmd creates a new command
+// NewStatusCmd creates a new command.
func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StatusCmd{
GlobalFlags: flags,
@@ -28,8 +28,8 @@ func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "status",
Short: "Print the status of a remote container",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background(), log.Default.ErrorStreamOnly())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context(), log.Default.ErrorStreamOnly())
},
}
statusCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
diff --git a/cmd/agent/workspace/stop.go b/cmd/agent/workspace/stop.go
index fead021e4c..25e1fe8706 100644
--- a/cmd/agent/workspace/stop.go
+++ b/cmd/agent/workspace/stop.go
@@ -11,14 +11,14 @@ import (
"github.com/spf13/cobra"
)
-// StopCmd holds the cmd flags
+// StopCmd holds the cmd flags.
type StopCmd struct {
*flags.GlobalFlags
WorkspaceInfo string
}
-// NewStopCmd creates a new command
+// NewStopCmd creates a new command.
func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StopCmd{
GlobalFlags: flags,
@@ -27,8 +27,8 @@ func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "stop",
Short: "Stops a workspace on the remote server",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
stopCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
@@ -38,7 +38,10 @@ func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
func (cmd *StopCmd) Run(ctx context.Context) error {
// get workspace
- shouldExit, workspaceInfo, err := agent.WriteWorkspaceInfo(cmd.WorkspaceInfo, log.Default.ErrorStreamOnly())
+ shouldExit, workspaceInfo, err := agent.WriteWorkspaceInfo(
+ cmd.WorkspaceInfo,
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return fmt.Errorf("error parsing workspace info: %w", err)
} else if shouldExit {
@@ -54,7 +57,11 @@ func (cmd *StopCmd) Run(ctx context.Context) error {
return nil
}
-func stopContainer(ctx context.Context, workspaceInfo *provider2.AgentWorkspaceInfo, log log.Logger) error {
+func stopContainer(
+ ctx context.Context,
+ workspaceInfo *provider2.AgentWorkspaceInfo,
+ log log.Logger,
+) error {
log.Debugf("stopping DevPod container")
runner, err := CreateRunner(workspaceInfo, log)
if err != nil {
diff --git a/cmd/agent/workspace/up.go b/cmd/agent/workspace/up.go
index bd46f50caa..6564d8a120 100644
--- a/cmd/agent/workspace/up.go
+++ b/cmd/agent/workspace/up.go
@@ -3,14 +3,13 @@ package workspace
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
- "errors"
-
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/agent"
@@ -18,6 +17,7 @@ import (
"github.com/skevetter/devpod/pkg/agent/tunnelserver"
"github.com/skevetter/devpod/pkg/client/clientimplementation"
"github.com/skevetter/devpod/pkg/command"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/credentials"
agentdaemon "github.com/skevetter/devpod/pkg/daemon/agent"
"github.com/skevetter/devpod/pkg/devcontainer"
@@ -32,14 +32,14 @@ import (
"github.com/spf13/cobra"
)
-// UpCmd holds the up cmd flags
+// UpCmd holds the up cmd flags.
type UpCmd struct {
*flags.GlobalFlags
WorkspaceInfo string
}
-// NewUpCmd creates a new command
+// NewUpCmd creates a new command.
func NewUpCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &UpCmd{
GlobalFlags: flags,
@@ -48,8 +48,8 @@ func NewUpCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "up",
Short: "Starts a new devcontainer",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
upCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
@@ -117,16 +117,23 @@ func (cmd *UpCmd) shouldInstallDaemon(workspaceInfo *provider.AgentWorkspaceInfo
return !workspaceInfo.CLIOptions.Platform.Enabled && !workspaceInfo.CLIOptions.DisableDaemon
}
-func (cmd *UpCmd) handleInitError(err error, workspaceInfo *provider.AgentWorkspaceInfo, logger log.Logger) error {
+func (cmd *UpCmd) handleInitError(
+ err error,
+ workspaceInfo *provider.AgentWorkspaceInfo,
+ logger log.Logger,
+) error {
if logger == nil {
logger = log.Discard
}
- deleteErr := clientimplementation.DeleteWorkspaceFolder(clientimplementation.DeleteWorkspaceFolderParams{
- Context: workspaceInfo.Workspace.Context,
- WorkspaceID: workspaceInfo.Workspace.ID,
- SSHConfigPath: workspaceInfo.Workspace.SSHConfigPath,
- SSHConfigIncludePath: workspaceInfo.Workspace.SSHConfigIncludePath,
- }, logger)
+ deleteErr := clientimplementation.DeleteWorkspaceFolder(
+ clientimplementation.DeleteWorkspaceFolderParams{
+ Context: workspaceInfo.Workspace.Context,
+ WorkspaceID: workspaceInfo.Workspace.ID,
+ SSHConfigPath: workspaceInfo.Workspace.SSHConfigPath,
+ SSHConfigIncludePath: workspaceInfo.Workspace.SSHConfigIncludePath,
+ },
+ logger,
+ )
if deleteErr != nil {
return fmt.Errorf("%s: %w", deleteErr.Error(), err)
}
@@ -153,7 +160,11 @@ func (cmd *UpCmd) up(
return cmd.sendResult(ctx, result, tunnelClient)
}
-func (cmd *UpCmd) sendResult(ctx context.Context, result *config2.Result, tunnelClient tunnel.TunnelClient) error {
+func (cmd *UpCmd) sendResult(
+ ctx context.Context,
+ result *config2.Result,
+ tunnelClient tunnel.TunnelClient,
+) error {
out, err := json.Marshal(result)
if err != nil {
return err
@@ -183,8 +194,16 @@ func (cmd *UpCmd) devPodUp(
}, workspaceInfo.InjectTimeout)
}
-func CreateRunner(workspaceInfo *provider.AgentWorkspaceInfo, log log.Logger) (devcontainer.Runner, error) {
- return devcontainer.NewRunner(agent.ContainerDevPodHelperLocation, agent.DefaultAgentDownloadURL(), workspaceInfo, log)
+func CreateRunner(
+ workspaceInfo *provider.AgentWorkspaceInfo,
+ log log.Logger,
+) (devcontainer.Runner, error) {
+ return devcontainer.NewRunner(
+ agent.ContainerDevPodHelperLocation,
+ agent.DefaultAgentDownloadURL(),
+ workspaceInfo,
+ log,
+ )
}
func InitContentFolder(workspaceInfo *provider.AgentWorkspaceInfo, log log.Logger) (bool, error) {
@@ -218,7 +237,7 @@ func InitContentFolder(workspaceInfo *provider.AgentWorkspaceInfo, log log.Logge
func contentFolderExists(path string, log log.Logger) (bool, error) {
_, err := os.Stat(path)
if err == nil {
- log.WithFields(logrus.Fields{"path": path}).Debug("workspace folder already exists")
+ log.Debugf("workspace folder already exists: path=%s", path)
return true, nil
}
if os.IsNotExist(err) {
@@ -228,7 +247,7 @@ func contentFolderExists(path string, log log.Logger) (bool, error) {
}
func createContentFolder(path string, log log.Logger) error {
- log.WithFields(logrus.Fields{"path": path}).Debug("create content folder")
+ log.Debugf("create content folder: path=%s", path)
if err := os.MkdirAll(path, 0o750); err != nil {
return fmt.Errorf("make workspace folder: %w", err)
}
@@ -242,12 +261,20 @@ func downloadWorkspaceBinaries(workspaceInfo *provider.AgentWorkspaceInfo, log l
workspaceInfo.Workspace.ID,
)
if err != nil {
- return fmt.Errorf("error getting workspace %s binaries dir: %w", workspaceInfo.Workspace.ID, err)
+ return fmt.Errorf(
+ "error getting workspace %s binaries dir: %w",
+ workspaceInfo.Workspace.ID,
+ err,
+ )
}
_, err = provider.DownloadBinaries(workspaceInfo.Agent.Binaries, binariesDir, log)
if err != nil {
- return fmt.Errorf("error downloading workspace %s binaries: %w", workspaceInfo.Workspace.ID, err)
+ return fmt.Errorf(
+ "error downloading workspace %s binaries: %w",
+ workspaceInfo.Workspace.ID,
+ err,
+ )
}
return nil
@@ -400,7 +427,9 @@ func (w *workspaceInitializer) ensureDockerInstalled() (string, error) {
}
if w.isDockerInstallDisabled() {
- w.logger.Debug("docker not found but installation was disabled, installing anyway as it is required")
+ w.logger.Debug(
+ "docker not found but installation was disabled, installing anyway as it is required",
+ )
}
w.logger.Debug("attempting to install docker")
@@ -473,8 +502,11 @@ type prepareWorkspaceParams struct {
// prepareWorkspace initializes the workspace content folder and downloads/prepares the workspace source.
// Note: This function modifies params.workspaceInfo.ContentFolder when platform is enabled with a local folder.
func prepareWorkspace(params prepareWorkspaceParams) error {
- if params.workspaceInfo.CLIOptions.Platform.Enabled && params.workspaceInfo.Workspace.Source.LocalFolder != "" {
- params.workspaceInfo.ContentFolder = agent.GetAgentWorkspaceContentDir(params.workspaceInfo.Origin)
+ if params.workspaceInfo.CLIOptions.Platform.Enabled &&
+ params.workspaceInfo.Workspace.Source.LocalFolder != "" {
+ params.workspaceInfo.ContentFolder = agent.GetAgentWorkspaceContentDir(
+ params.workspaceInfo.Origin,
+ )
}
exists, err := InitContentFolder(params.workspaceInfo, params.log)
@@ -502,7 +534,10 @@ func prepareWorkspace(params prepareWorkspaceParams) error {
if params.workspaceInfo.Workspace.Source.Image != "" {
params.log.Debugf("prepare image")
- return prepareImage(params.workspaceInfo.ContentFolder, params.workspaceInfo.Workspace.Source.Image)
+ return prepareImage(
+ params.workspaceInfo.ContentFolder,
+ params.workspaceInfo.Workspace.Source.Image,
+ )
}
if params.workspaceInfo.Workspace.Source.Container != "" {
@@ -529,13 +564,19 @@ func prepareGitWorkspace(params prepareGitWorkspaceParams) error {
}
}
- if params.workspaceInfo.CLIOptions.Recreate && !params.workspaceInfo.CLIOptions.Reset && params.exists {
- params.log.Info("rebuilding without resetting a git based workspace, keeping old content folder")
+ if params.workspaceInfo.CLIOptions.Recreate && !params.workspaceInfo.CLIOptions.Reset &&
+ params.exists {
+ params.log.Info(
+ "rebuilding without resetting a git based workspace, keeping old content folder",
+ )
return nil
}
if crane.ShouldUse(¶ms.workspaceInfo.CLIOptions) {
- params.log.Infof("pulling devcontainer spec from %v", params.workspaceInfo.CLIOptions.Platform.EnvironmentTemplate)
+ params.log.Infof(
+ "pulling devcontainer spec from %v",
+ params.workspaceInfo.CLIOptions.Platform.EnvironmentTemplate,
+ )
return nil
}
@@ -558,7 +599,10 @@ func prepareLocalWorkspace(
log log.Logger,
) error {
if workspaceInfo.ContentFolder == workspaceInfo.Workspace.Source.LocalFolder {
- log.Debugf("local folder %s with local provider; skip downloading", workspaceInfo.ContentFolder)
+ log.Debugf(
+ "local folder %s with local provider; skip downloading",
+ workspaceInfo.ContentFolder,
+ )
return nil
}
@@ -567,7 +611,10 @@ func prepareLocalWorkspace(
}
func ensureLastDevContainerJson(workspaceInfo *provider.AgentWorkspaceInfo) error {
- filePath := filepath.Join(workspaceInfo.ContentFolder, filepath.FromSlash(workspaceInfo.LastDevContainerConfig.Path))
+ filePath := filepath.Join(
+ workspaceInfo.ContentFolder,
+ filepath.FromSlash(workspaceInfo.LastDevContainerConfig.Path),
+ )
if _, err := os.Stat(filePath); err == nil {
return nil
@@ -599,7 +646,8 @@ type credentialsConfig struct {
}
func configureCredentials(cfg credentialsConfig) (string, string, error) {
- if cfg.workspaceInfo.Agent.InjectDockerCredentials != "true" && cfg.workspaceInfo.Agent.InjectGitCredentials != "true" {
+ if cfg.workspaceInfo.Agent.InjectDockerCredentials != config.BoolTrue &&
+ cfg.workspaceInfo.Agent.InjectGitCredentials != config.BoolTrue {
return "", "", nil
}
@@ -618,17 +666,25 @@ func configureCredentials(cfg credentialsConfig) (string, string, error) {
}
dockerCredentials := ""
- if cfg.workspaceInfo.Agent.InjectDockerCredentials == "true" {
- dockerCredentials, err = dockercredentials.ConfigureCredentialsMachine(cfg.workspaceInfo.Origin, serverPort, cfg.log)
+ if cfg.workspaceInfo.Agent.InjectDockerCredentials == config.BoolTrue {
+ dockerCredentials, err = dockercredentials.ConfigureCredentialsMachine(
+ cfg.workspaceInfo.Origin,
+ serverPort,
+ cfg.log,
+ )
if err != nil {
return "", "", err
}
}
gitCredentials := ""
- if cfg.workspaceInfo.Agent.InjectGitCredentials == "true" {
- gitCredentials = fmt.Sprintf("!'%s' agent git-credentials --port %d", binaryPath, serverPort)
- _ = os.Setenv("DEVPOD_GIT_HELPER_PORT", strconv.Itoa(serverPort))
+ if cfg.workspaceInfo.Agent.InjectGitCredentials == config.BoolTrue {
+ gitCredentials = fmt.Sprintf(
+ "!'%s' agent git-credentials --port %d",
+ binaryPath,
+ serverPort,
+ )
+ _ = os.Setenv(config.EnvGitHelperPort, strconv.Itoa(serverPort))
}
return dockerCredentials, gitCredentials, nil
@@ -640,10 +696,19 @@ func installDaemon(workspaceInfo *provider.AgentWorkspaceInfo, log log.Logger) e
}
log.Debugf("installing DevPod daemon into server")
- return agentdaemon.InstallDaemon(workspaceInfo.Agent.DataPath, workspaceInfo.CLIOptions.DaemonInterval, log)
+ return agentdaemon.InstallDaemon(
+ workspaceInfo.Agent.DataPath,
+ workspaceInfo.CLIOptions.DaemonInterval,
+ log,
+ )
}
-func downloadLocalFolder(ctx context.Context, workspaceDir string, client tunnel.TunnelClient, log log.Logger) error {
+func downloadLocalFolder(
+ ctx context.Context,
+ workspaceDir string,
+ client tunnel.TunnelClient,
+ log log.Logger,
+) error {
log.Infof("Upload folder to server")
stream, err := client.StreamWorkspace(ctx, &tunnel.Empty{})
if err != nil {
@@ -657,7 +722,11 @@ func prepareImage(workspaceDir, image string) error {
devcontainerConfig := []byte(`{
"image": "` + image + `"
}`)
- return os.WriteFile(filepath.Join(workspaceDir, ".devcontainer.json"), devcontainerConfig, 0o600)
+ return os.WriteFile(
+ filepath.Join(workspaceDir, ".devcontainer.json"),
+ devcontainerConfig,
+ 0o600,
+ )
}
// installDocker installs Docker and returns the path to the docker binary.
@@ -690,7 +759,11 @@ func mergeDockerDaemonConfig() error {
return nil
}
- return fmt.Errorf("failed to write docker daemon config (rootless: %v, root: %v)", rootlessErr, rootErr)
+ return fmt.Errorf(
+ "failed to write docker daemon config (rootless: %v, root: %v)",
+ rootlessErr,
+ rootErr,
+ )
}
func tryMergeRootlessDockerConfig() error {
@@ -756,12 +829,12 @@ func writeConfig(configPath string, config map[string]any) error {
}
// #nosec G301 -- directory needs to be accessible by docker daemon
- if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
return fmt.Errorf("create config directory: %w", err)
}
// #nosec G306 -- daemon.json needs to be readable by docker daemon
- if err := os.WriteFile(configPath, mergedData, 0644); err != nil {
+ if err := os.WriteFile(configPath, mergedData, 0o644); err != nil {
return fmt.Errorf("write config: %w", err)
}
diff --git a/cmd/agent/workspace/update_config.go b/cmd/agent/workspace/update_config.go
index 66c6c46e2b..69c6116930 100644
--- a/cmd/agent/workspace/update_config.go
+++ b/cmd/agent/workspace/update_config.go
@@ -9,14 +9,14 @@ import (
"github.com/spf13/cobra"
)
-// UpdateConfigCmd holds the cmd flags
+// UpdateConfigCmd holds the cmd flags.
type UpdateConfigCmd struct {
*flags.GlobalFlags
WorkspaceInfo string
}
-// NewUpdateConfigCmd creates a new command
+// NewUpdateConfigCmd creates a new command.
func NewUpdateConfigCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &UpdateConfigCmd{
GlobalFlags: flags,
@@ -25,11 +25,12 @@ func NewUpdateConfigCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "update-config",
Short: "Updates the workspace config",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, _ []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- updateConfigCmd.Flags().StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
+ updateConfigCmd.Flags().
+ StringVar(&cmd.WorkspaceInfo, "workspace-info", "", "The workspace info")
_ = updateConfigCmd.MarkFlagRequired("workspace-info")
return updateConfigCmd
}
diff --git a/cmd/agent/workspace/workspace.go b/cmd/agent/workspace/workspace.go
index 50c6346217..c983d813e3 100644
--- a/cmd/agent/workspace/workspace.go
+++ b/cmd/agent/workspace/workspace.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewWorkspaceCmd returns a new command
+// NewWorkspaceCmd returns a new command.
func NewWorkspaceCmd(flags *flags.GlobalFlags) *cobra.Command {
workspaceCmd := &cobra.Command{
Use: "workspace",
diff --git a/cmd/build.go b/cmd/build.go
index 89aad2d958..75a557fab8 100644
--- a/cmd/build.go
+++ b/cmd/build.go
@@ -16,7 +16,7 @@ import (
"github.com/spf13/cobra"
)
-// BuildCmd holds the cmd flags
+// BuildCmd holds the cmd flags.
type BuildCmd struct {
*flags.GlobalFlags
provider.CLIOptions
@@ -27,7 +27,7 @@ type BuildCmd struct {
Machine string
}
-// NewBuildCmd creates a new command
+// NewBuildCmd creates a new command.
func NewBuildCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &BuildCmd{
GlobalFlags: flags,
@@ -55,26 +55,31 @@ func NewBuildCmd(flags *flags.GlobalFlags) *cobra.Command {
// check permissions
if !cmd.SkipPush && cmd.Repository != "" {
- err = image.CheckPushPermissions(cmd.Repository)
- if err != nil {
- return fmt.Errorf("cannot push to %s, please make sure you have push permissions to repository %s", cmd.Repository, cmd.Repository)
+ if err := image.CheckPushPermissions(ctx, cmd.Repository); err != nil {
+ return fmt.Errorf(
+ "cannot push to %s, please make sure you have push permissions to repository: %w",
+ cmd.Repository,
+ err,
+ )
}
}
// validate tags
if len(cmd.Tag) > 0 {
if err := image.ValidateTags(cmd.Tag); err != nil {
- return fmt.Errorf("cannot build image,: %w", err)
+ return fmt.Errorf("cannot build image: %w", err)
}
}
- if devPodConfig.ContextOption(config.ContextOptionSSHStrictHostKeyChecking) == "true" {
+ if devPodConfig.ContextOption(
+ config.ContextOptionSSHStrictHostKeyChecking,
+ ) == config.BoolTrue {
cmd.StrictHostKeyChecking = true
}
// create a temporary workspace
exists := workspace2.Exists(ctx, devPodConfig, args, "", cmd.Owner, log.Default)
- sshConfigFile, err := os.CreateTemp("", "devpodssh.config")
+ sshConfigFile, err := os.CreateTemp("", config.BinaryName+"ssh.config")
if err != nil {
return err
}
@@ -128,40 +133,60 @@ func NewBuildCmd(flags *flags.GlobalFlags) *cobra.Command {
},
}
- buildCmd.Flags().StringVar(&cmd.DevContainerImage, "devcontainer-image", "", "The container image to use, this will override the devcontainer.json value in the project")
- buildCmd.Flags().StringVar(&cmd.DevContainerPath, "devcontainer-path", "", "The path to the devcontainer.json relative to the project")
- buildCmd.Flags().StringSliceVar(&cmd.ProviderOptions, "provider-option", []string{}, "Provider option in the form KEY=VALUE")
- buildCmd.Flags().BoolVar(&cmd.SkipDelete, "skip-delete", false, "If true will not delete the workspace after building it")
- buildCmd.Flags().StringVar(&cmd.Machine, "machine", "", "The machine to use for this workspace. The machine needs to exist beforehand or the command will fail. If the workspace already exists, this option has no effect")
+ buildCmd.Flags().
+ StringVar(&cmd.DevContainerImage, "devcontainer-image", "",
+ "The container image to use, this will override the devcontainer.json value in the project")
+ buildCmd.Flags().
+ StringVar(&cmd.DevContainerPath, "devcontainer-path", "", "The path to the devcontainer.json relative to the project")
+ buildCmd.Flags().
+ StringVar(&cmd.AdditionalFeatures, "additional-features", "",
+ `Additional features to apply to the dev container (JSON as per "features" section in devcontainer.json)`)
+ buildCmd.Flags().
+ StringSliceVar(&cmd.ProviderOptions, "provider-option", []string{}, "Provider option in the form KEY=VALUE")
+ buildCmd.Flags().
+ BoolVar(&cmd.SkipDelete, "skip-delete", false, "If true will not delete the workspace after building it")
+ buildCmd.Flags().
+ StringVar(&cmd.Machine, "machine", "",
+ "The machine to use for this workspace. The machine needs to exist beforehand or the "+
+ "command will fail. If the workspace already exists, this option has no effect")
buildCmd.Flags().StringVar(&cmd.Repository, "repository", "", "The repository to push to")
- buildCmd.Flags().StringSliceVar(&cmd.Tag, "tag", []string{}, "Image Tag(s) in the form of a comma separated list --tag latest,arm64 or multiple flags --tag latest --tag arm64")
- buildCmd.Flags().StringSliceVar(&cmd.Platforms, "platform", []string{}, "Set target platform for build")
- buildCmd.Flags().BoolVar(&cmd.SkipPush, "skip-push", false, "If true will not push the image to the repository, useful for testing")
+ buildCmd.Flags().
+ StringSliceVar(&cmd.Tag, "tag", []string{},
+ "Image Tag(s) in the form of a comma separated list --tag latest,arm64 or "+
+ "multiple flags --tag latest --tag arm64")
+ buildCmd.Flags().
+ StringSliceVar(&cmd.Platforms, "platform", []string{}, "Set target platform for build")
+ buildCmd.Flags().
+ BoolVar(&cmd.SkipPush, "skip-push", false, "If true will not push the image to the repository, useful for testing")
buildCmd.Flags().BoolVar(&cmd.PushDuringBuild, "push", false,
"Push image directly to registry during build, skipping load to local daemon.",
)
- buildCmd.Flags().Var(&cmd.GitCloneStrategy, "git-clone-strategy", "The git clone strategy DevPod uses to checkout git based workspaces. Can be full (default), blobless, treeless or shallow")
- buildCmd.Flags().BoolVar(&cmd.GitCloneRecursiveSubmodules, "git-clone-recursive-submodules", false, "If true will clone git submodule repositories recursively")
+ buildCmd.Flags().
+ Var(&cmd.GitCloneStrategy, "git-clone-strategy",
+ "The git clone strategy DevPod uses to checkout git based workspaces. "+
+ "Can be full (default), blobless, treeless or shallow")
+ buildCmd.Flags().
+ BoolVar(&cmd.GitCloneRecursiveSubmodules, "git-clone-recursive-submodules", false,
+ "If true will clone git submodule repositories recursively")
// TESTING
buildCmd.Flags().BoolVar(&cmd.ForceBuild, "force-build", false, "TESTING ONLY")
- buildCmd.Flags().BoolVar(&cmd.ForceInternalBuildKit, "force-internal-buildkit", false, "TESTING ONLY")
+ buildCmd.Flags().
+ BoolVar(&cmd.ForceInternalBuildKit, "force-internal-buildkit", false, "TESTING ONLY")
_ = buildCmd.Flags().MarkHidden("force-build")
_ = buildCmd.Flags().MarkHidden("force-internal-buildkit")
return buildCmd
}
func (cmd *BuildCmd) Run(ctx context.Context, client client.WorkspaceClient) error {
- // build workspace
- err := cmd.build(ctx, client, log.Default)
- if err != nil {
- return err
- }
-
- return nil
+ return cmd.build(ctx, client, log.Default)
}
-func (cmd *BuildCmd) build(ctx context.Context, workspaceClient client.WorkspaceClient, log log.Logger) error {
+func (cmd *BuildCmd) build(
+ ctx context.Context,
+ workspaceClient client.WorkspaceClient,
+ log log.Logger,
+) error {
err := workspaceClient.Lock(ctx)
if err != nil {
return err
@@ -178,11 +203,14 @@ func (cmd *BuildCmd) build(ctx context.Context, workspaceClient client.Workspace
log.Debugf("done building devcontainer")
log.Infof("cleaning up temporary workspace")
}()
- _, err = clientimplementation.BuildAgentClient(ctx, clientimplementation.BuildAgentClientOptions{
- WorkspaceClient: workspaceClient,
- CLIOptions: cmd.CLIOptions,
- AgentCommand: "build",
- Log: log,
- })
+ _, err = clientimplementation.BuildAgentClient(
+ ctx,
+ clientimplementation.BuildAgentClientOptions{
+ WorkspaceClient: workspaceClient,
+ CLIOptions: cmd.CLIOptions,
+ AgentCommand: "build",
+ Log: log,
+ },
+ )
return err
}
diff --git a/cmd/completion/suggestions.go b/cmd/completion/suggestions.go
index f997d9208a..fced020a48 100644
--- a/cmd/completion/suggestions.go
+++ b/cmd/completion/suggestions.go
@@ -3,32 +3,60 @@ package completion
import (
"strings"
- "github.com/spf13/cobra"
-
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
+ "github.com/spf13/cobra"
)
func RegisterFlagCompletionFuns(rootCmd *cobra.Command, globalFlags *flags.GlobalFlags) error {
- if err := rootCmd.RegisterFlagCompletionFunc("provider", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return GetProviderSuggestions(rootCmd, globalFlags.Context, globalFlags.Provider, args, toComplete, globalFlags.Owner, log.Default)
- }); err != nil {
+ if err := rootCmd.RegisterFlagCompletionFunc(
+ "provider",
+ func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+ return GetProviderSuggestions(
+ rootCmd,
+ globalFlags.Context,
+ globalFlags.Provider,
+ args,
+ toComplete,
+ globalFlags.Owner,
+ log.Default,
+ )
+ },
+ ); err != nil {
return err
}
- if err := rootCmd.RegisterFlagCompletionFunc("context", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return GetContextSuggestions(rootCmd, globalFlags.Context, globalFlags.Provider, args, toComplete, globalFlags.Owner, log.Default)
- }); err != nil {
+ if err := rootCmd.RegisterFlagCompletionFunc(
+ "context",
+ func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+ return GetContextSuggestions(
+ rootCmd,
+ globalFlags.Context,
+ globalFlags.Provider,
+ args,
+ toComplete,
+ globalFlags.Owner,
+ log.Default,
+ )
+ },
+ ); err != nil {
return err
}
return nil
}
-func GetWorkspaceSuggestions(rootCmd *cobra.Command, context, provider string, args []string, toComplete string, owner platform.OwnerFilter, logger log.Logger) ([]string, cobra.ShellCompDirective) {
+func GetWorkspaceSuggestions(
+ rootCmd *cobra.Command,
+ context, provider string,
+ args []string,
+ toComplete string,
+ owner platform.OwnerFilter,
+ logger log.Logger,
+) ([]string, cobra.ShellCompDirective) {
devPodConfig, err := config.LoadConfig(context, provider)
if err != nil {
return nil, cobra.ShellCompDirectiveError
@@ -48,7 +76,14 @@ func GetWorkspaceSuggestions(rootCmd *cobra.Command, context, provider string, a
return suggestions, cobra.ShellCompDirectiveNoFileComp
}
-func GetProviderSuggestions(rootCmd *cobra.Command, context, provider string, args []string, toComplete string, owner platform.OwnerFilter, logger log.Logger) ([]string, cobra.ShellCompDirective) {
+func GetProviderSuggestions(
+ rootCmd *cobra.Command,
+ context, provider string,
+ args []string,
+ toComplete string,
+ owner platform.OwnerFilter,
+ logger log.Logger,
+) ([]string, cobra.ShellCompDirective) {
devPodConfig, err := config.LoadConfig(context, provider)
if err != nil {
return nil, cobra.ShellCompDirectiveError
@@ -68,7 +103,14 @@ func GetProviderSuggestions(rootCmd *cobra.Command, context, provider string, ar
return suggestions, cobra.ShellCompDirectiveNoFileComp
}
-func GetContextSuggestions(rootCmd *cobra.Command, context, provider string, args []string, toComplete string, owner platform.OwnerFilter, logger log.Logger) ([]string, cobra.ShellCompDirective) {
+func GetContextSuggestions(
+ rootCmd *cobra.Command,
+ context, provider string,
+ args []string,
+ toComplete string,
+ owner platform.OwnerFilter,
+ logger log.Logger,
+) ([]string, cobra.ShellCompDirective) {
devPodConfig, err := config.LoadConfig(context, provider)
if err != nil {
return nil, cobra.ShellCompDirectiveError
diff --git a/cmd/context/context.go b/cmd/context/context.go
index 7dea7ea010..395422da4a 100644
--- a/cmd/context/context.go
+++ b/cmd/context/context.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewContextCmd returns a new command
+// NewContextCmd returns a new command.
func NewContextCmd(flags *flags.GlobalFlags) *cobra.Command {
contextCmd := &cobra.Command{
Use: "context",
diff --git a/cmd/context/create.go b/cmd/context/create.go
index ef0838fce9..89da25e4e1 100644
--- a/cmd/context/create.go
+++ b/cmd/context/create.go
@@ -13,14 +13,14 @@ import (
"github.com/spf13/cobra"
)
-// CreateCmd holds the create cmd flags
+// CreateCmd holds the create cmd flags.
type CreateCmd struct {
*flags.GlobalFlags
Options []string
}
-// NewCreateCmd creates a new command
+// NewCreateCmd creates a new command.
func NewCreateCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &CreateCmd{
GlobalFlags: flags,
@@ -28,20 +28,21 @@ func NewCreateCmd(flags *flags.GlobalFlags) *cobra.Command {
createCmd := &cobra.Command{
Use: "create",
Short: "Create a new DevPod context",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("please specify the context to create")
}
- return cmd.Run(context.Background(), args[0])
+ return cmd.Run(cobraCmd.Context(), args[0])
},
}
- createCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "context option in the form KEY=VALUE")
+ createCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "context option in the form KEY=VALUE")
return createCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *CreateCmd) Run(ctx context.Context, context string) error {
devPodConfig, err := config.LoadConfig("", cmd.Provider)
if err != nil {
@@ -52,7 +53,7 @@ func (cmd *CreateCmd) Run(ctx context.Context, context string) error {
// verify name
if provider2.ProviderNameRegEx.MatchString(context) {
- return fmt.Errorf("context name can only include smaller case letters, numbers or dashes")
+ return fmt.Errorf("context name can only include lower case letters, numbers or dashes")
} else if len(context) > 48 {
return fmt.Errorf("context name cannot be longer than 48 characters")
}
@@ -112,13 +113,22 @@ func parseOptions(options []string) (map[string]config.OptionValue, error) {
value := strings.Join(splitted[1:], "=")
contextOption, ok := contextOptions[key]
if !ok {
- return nil, fmt.Errorf("invalid option '%s', allowed options are: %v", key, allowedOptions)
+ return nil, fmt.Errorf(
+ "invalid option '%s', allowed options are: %v",
+ key,
+ allowedOptions,
+ )
}
if len(contextOption.Enum) > 0 {
found := slices.Contains(contextOption.Enum, value)
if !found {
- return nil, fmt.Errorf("invalid value '%s' for option '%s', has to match one of the following values: %v", value, key, contextOption.Enum)
+ return nil, fmt.Errorf(
+ "invalid value '%s' for option '%s', has to match one of the following values: %v",
+ value,
+ key,
+ contextOption.Enum,
+ )
}
}
diff --git a/cmd/context/delete.go b/cmd/context/delete.go
index 55fa54ab28..5b0e23e2cf 100644
--- a/cmd/context/delete.go
+++ b/cmd/context/delete.go
@@ -9,12 +9,12 @@ import (
"github.com/spf13/cobra"
)
-// DeleteCmd holds the delete cmd flags
+// DeleteCmd holds the delete cmd flags.
type DeleteCmd struct {
*flags.GlobalFlags
}
-// NewDeleteCmd deletes a new command
+// NewDeleteCmd deletes a new command.
func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: flags,
@@ -22,7 +22,7 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
deleteCmd := &cobra.Command{
Use: "delete",
Short: "Delete a DevPod context",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("please specify the context to delete")
}
@@ -32,14 +32,14 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
devPodContext = args[0]
}
- return cmd.Run(context.Background(), devPodContext)
+ return cmd.Run(cobraCmd.Context(), devPodContext)
},
}
return deleteCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *DeleteCmd) Run(ctx context.Context, context string) error {
devPodConfig, err := config.LoadConfig(context, cmd.Provider)
if err != nil {
diff --git a/cmd/context/list.go b/cmd/context/list.go
index 474106ec68..15f6be314f 100644
--- a/cmd/context/list.go
+++ b/cmd/context/list.go
@@ -9,19 +9,18 @@ import (
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
- "github.com/skevetter/log"
- "github.com/skevetter/log/table"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/spf13/cobra"
)
-// ListCmd holds the list cmd flags
+// ListCmd holds the list cmd flags.
type ListCmd struct {
*flags.GlobalFlags
Output string
}
-// NewListCmd creates a new command
+// NewListCmd creates a new command.
func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ListCmd{
GlobalFlags: flags,
@@ -30,12 +29,13 @@ func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "list",
Aliases: []string{"ls"},
Short: "List DevPod contexts",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- listCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ listCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return listCmd
}
@@ -45,7 +45,7 @@ type ContextWithDefault struct {
Default bool `json:"default,omitempty"`
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ListCmd) Run(ctx context.Context) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -65,7 +65,7 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Default",
}, tableEntries)
@@ -84,7 +84,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/context/options.go b/cmd/context/options.go
index d006b0107f..1b6086e632 100644
--- a/cmd/context/options.go
+++ b/cmd/context/options.go
@@ -8,19 +8,18 @@ import (
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
- "github.com/skevetter/log"
- "github.com/skevetter/log/table"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/spf13/cobra"
)
-// OptionsCmd holds the options cmd flags
+// OptionsCmd holds the options cmd flags.
type OptionsCmd struct {
*flags.GlobalFlags
Output string
}
-// NewOptionsCmd creates a new command
+// NewOptionsCmd creates a new command.
func NewOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &OptionsCmd{
GlobalFlags: flags,
@@ -28,12 +27,13 @@ func NewOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
optionsCmd := &cobra.Command{
Use: "options",
Short: "Show options of a context",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
- optionsCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ optionsCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return optionsCmd
}
@@ -43,7 +43,7 @@ type optionWithValue struct {
Value string `json:"value,omitempty"`
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *OptionsCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, "")
if err != nil {
@@ -72,7 +72,7 @@ func (cmd *OptionsCmd) Run(ctx context.Context, args []string) error {
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Description",
"Default",
@@ -93,7 +93,10 @@ func (cmd *OptionsCmd) Run(ctx context.Context, args []string) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/context/set_options.go b/cmd/context/set_options.go
index d0212c73a9..e16fb24577 100644
--- a/cmd/context/set_options.go
+++ b/cmd/context/set_options.go
@@ -9,14 +9,14 @@ import (
"github.com/spf13/cobra"
)
-// SetOptionsCmd holds the setOptions cmd flags
+// SetOptionsCmd holds the setOptions cmd flags.
type SetOptionsCmd struct {
*flags.GlobalFlags
Options []string
}
-// NewSetOptionsCmd setOptionss a new command
+// NewSetOptionsCmd setOptionss a new command.
func NewSetOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SetOptionsCmd{
GlobalFlags: flags,
@@ -24,7 +24,7 @@ func NewSetOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
setOptionsCmd := &cobra.Command{
Use: "set-options",
Short: "Set options for a DevPod context",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("please specify the context")
}
@@ -34,15 +34,16 @@ func NewSetOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
devPodContext = args[0]
}
- return cmd.Run(context.Background(), devPodContext)
+ return cmd.Run(cobraCmd.Context(), devPodContext)
},
}
- setOptionsCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "context option in the form KEY=VALUE")
+ setOptionsCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "context option in the form KEY=VALUE")
return setOptionsCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SetOptionsCmd) Run(ctx context.Context, context string) error {
devPodConfig, err := config.LoadConfig("", cmd.Provider)
if err != nil {
diff --git a/cmd/context/use.go b/cmd/context/use.go
index 8d51676485..64949f72aa 100644
--- a/cmd/context/use.go
+++ b/cmd/context/use.go
@@ -9,14 +9,14 @@ import (
"github.com/spf13/cobra"
)
-// UseCmd holds the use cmd flags
+// UseCmd holds the use cmd flags.
type UseCmd struct {
*flags.GlobalFlags
Options []string
}
-// NewUseCmd uses a new command
+// NewUseCmd uses a new command.
func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &UseCmd{
GlobalFlags: flags,
@@ -24,20 +24,21 @@ func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
useCmd := &cobra.Command{
Use: "use",
Short: "Set a DevPod context as the default",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("please specify the context to use")
}
- return cmd.Run(context.Background(), args[0])
+ return cmd.Run(cobraCmd.Context(), args[0])
},
}
- useCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "context option in the form KEY=VALUE")
+ useCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "context option in the form KEY=VALUE")
return useCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *UseCmd) Run(ctx context.Context, context string) error {
devPodConfig, err := config.LoadConfig("", cmd.Provider)
if err != nil {
diff --git a/cmd/delete.go b/cmd/delete.go
index 249b17d3aa..fe58f223f0 100644
--- a/cmd/delete.go
+++ b/cmd/delete.go
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
client2 "github.com/skevetter/devpod/pkg/client"
@@ -15,13 +14,13 @@ import (
"github.com/spf13/cobra"
)
-// DeleteCmd holds the delete cmd flags
+// DeleteCmd holds the delete cmd flags.
type DeleteCmd struct {
*flags.GlobalFlags
client2.DeleteOptions
}
-// NewDeleteCmd creates a new command
+// NewDeleteCmd creates a new command.
func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: flags,
@@ -31,63 +30,119 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
Short: "Deletes an existing workspace",
Long: `Deletes an existing workspace. You can specify the workspace by its path or name.
If the workspace is not found, you can use the --ignore-not-found flag to treat it as a successful delete.`,
- RunE: func(_ *cobra.Command, args []string) error {
- _, err := clientimplementation.DecodeOptionsFromEnv(clientimplementation.DevPodFlagsDelete, &cmd.DeleteOptions)
- if err != nil {
- return fmt.Errorf("decode up options: %w", err)
- }
-
- ctx := context.Background()
- devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
- if err != nil {
- return err
- }
-
- err = clientimplementation.DecodePlatformOptionsFromEnv(&cmd.Platform)
- if err != nil {
- return fmt.Errorf("decode platform options: %w", err)
- }
-
- return cmd.Run(ctx, devPodConfig, args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd, args)
},
- ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ ValidArgsFunction: func(
+ rootCmd *cobra.Command, args []string, toComplete string,
+ ) ([]string, cobra.ShellCompDirective) {
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
- deleteCmd.Flags().BoolVar(&cmd.IgnoreNotFound, "ignore-not-found", false, "Treat \"workspace not found\" as a successful delete")
- deleteCmd.Flags().StringVar(&cmd.GracePeriod, "grace-period", "", "The amount of time to give the command to delete the workspace")
- deleteCmd.Flags().BoolVar(&cmd.Force, "force", false, "Delete workspace even if it is not found remotely anymore")
+ deleteCmd.Flags().
+ BoolVar(&cmd.IgnoreNotFound, "ignore-not-found", false, "Treat \"workspace not found\" as a successful delete")
+ deleteCmd.Flags().
+ StringVar(&cmd.GracePeriod, "grace-period", "", "The amount of time to give the command to delete the workspace")
+ deleteCmd.Flags().
+ BoolVar(&cmd.Force, "force", false, "Delete workspace even if it is not found remotely anymore")
return deleteCmd
}
-// Run runs the command logic
-func (cmd *DeleteCmd) Run(ctx context.Context, devPodConfig *config.Config, args []string) error {
- if len(args) == 0 {
- workspaceName, err := workspace.Delete(ctx, devPodConfig, args, cmd.IgnoreNotFound, cmd.Force, cmd.DeleteOptions, cmd.Owner, log.Default)
- if err != nil {
- return err
- }
- log.WithFields(logrus.Fields{
- "workspace": workspaceName,
- })
- log.Default.Donef("deleted workspace")
- return nil
+// Run runs the command logic.
+func (cmd *DeleteCmd) Run(cobraCmd *cobra.Command, args []string) error {
+ devPodConfig, err := cmd.loadConfig()
+ if err != nil {
+ return err
+ }
+
+ ctx := cobraCmd.Context()
+ if len(args) <= 1 {
+ return cmd.deleteSingle(ctx, devPodConfig, args)
}
+ return cmd.deleteMultiple(ctx, devPodConfig, args)
+}
+
+func (cmd *DeleteCmd) loadConfig() (*config.Config, error) {
+ _, err := clientimplementation.DecodeOptionsFromEnv(
+ config.EnvFlagsDelete,
+ &cmd.DeleteOptions,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("decode delete options: %w", err)
+ }
+
+ if err := clientimplementation.DecodePlatformOptionsFromEnv(&cmd.Platform); err != nil {
+ return nil, fmt.Errorf("decode platform options: %w", err)
+ }
+
+ return config.LoadConfig(cmd.Context, cmd.Provider)
+}
+
+func (cmd *DeleteCmd) deleteSingle(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ args []string,
+) error {
+ name, err := cmd.deleteWorkspace(ctx, devPodConfig, args)
+ if err != nil {
+ return err
+ }
+
+ log.Default.Donef("deleted workspace %s", name)
+
+ return nil
+}
+
+func (cmd *DeleteCmd) deleteMultiple(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ args []string,
+) error {
+ var errs []error
for _, arg := range args {
- workspaceName, err := workspace.Delete(ctx, devPodConfig, []string{arg}, cmd.IgnoreNotFound, cmd.Force, cmd.DeleteOptions, cmd.Owner, log.Default)
+ name, err := cmd.deleteWorkspace(ctx, devPodConfig, []string{arg})
if err != nil {
- log.WithFields(logrus.Fields{
- "workspace": arg,
- "err": err,
- }).Error("failed to delete workspace")
+ errs = append(errs, fmt.Errorf("failed to delete workspace %s: %w", arg, err))
+
continue
}
- log.WithFields(logrus.Fields{
- "workspace": workspaceName,
- })
- log.Default.Donef("deleted workspace")
+
+ log.Default.Donef("deleted workspace %s", name)
+ }
+
+ if len(errs) > 0 {
+ return fmt.Errorf(
+ "%d workspace(s) failed to delete: %v",
+ len(errs),
+ errs,
+ )
}
+
return nil
}
+
+func (cmd *DeleteCmd) deleteWorkspace(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ args []string,
+) (string, error) {
+ return workspace.Delete(ctx, workspace.DeleteOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ IgnoreNotFound: cmd.IgnoreNotFound,
+ Force: cmd.Force,
+ ClientDelete: cmd.DeleteOptions,
+ Owner: cmd.Owner,
+ Log: log.Default,
+ })
+}
diff --git a/cmd/export.go b/cmd/export.go
index b9a827d2b4..dd7a924f9f 100644
--- a/cmd/export.go
+++ b/cmd/export.go
@@ -14,12 +14,12 @@ import (
"github.com/spf13/cobra"
)
-// ExportCmd holds the export cmd flags
+// ExportCmd holds the export cmd flags.
type ExportCmd struct {
*flags.GlobalFlags
}
-// NewExportCmd creates a new command
+// NewExportCmd creates a new command.
func NewExportCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ExportCmd{
GlobalFlags: flags,
@@ -28,8 +28,8 @@ func NewExportCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "export [flags] [workspace-path|workspace-name]",
Short: "Exports a workspace configuration",
Hidden: true,
- RunE: func(_ *cobra.Command, args []string) error {
- ctx := context.Background()
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ ctx := cobraCmd.Context()
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
@@ -37,19 +37,34 @@ func NewExportCmd(flags *flags.GlobalFlags) *cobra.Command {
return cmd.Run(ctx, devPodConfig, args)
},
- ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ ValidArgsFunction: func(
+ rootCmd *cobra.Command, args []string, toComplete string,
+ ) ([]string, cobra.ShellCompDirective) {
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
return exportCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ExportCmd) Run(ctx context.Context, devPodConfig *config.Config, args []string) error {
// try to load workspace
logger := log.Default.ErrorStreamOnly()
- client, err := workspace2.Get(ctx, devPodConfig, args, false, cmd.Owner, false, logger)
+ client, err := workspace2.Get(ctx, workspace2.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ Owner: cmd.Owner,
+ Log: logger,
+ })
if err != nil {
return err
}
@@ -70,7 +85,10 @@ func (cmd *ExportCmd) Run(ctx context.Context, devPodConfig *config.Config, args
return nil
}
-func exportWorkspace(devPodConfig *config.Config, workspaceConfig *provider.Workspace) (*provider.ExportConfig, error) {
+func exportWorkspace(
+ devPodConfig *config.Config,
+ workspaceConfig *provider.Workspace,
+) (*provider.ExportConfig, error) {
var err error
// create return config
@@ -84,14 +102,21 @@ func exportWorkspace(devPodConfig *config.Config, workspaceConfig *provider.Work
// has machine?
if workspaceConfig.Machine.ID != "" {
- retConfig.Machine, err = provider.ExportMachine(workspaceConfig.Context, workspaceConfig.Machine.ID)
+ retConfig.Machine, err = provider.ExportMachine(
+ workspaceConfig.Context,
+ workspaceConfig.Machine.ID,
+ )
if err != nil {
return nil, fmt.Errorf("export machine config: %w", err)
}
}
// export provider
- retConfig.Provider, err = provider.ExportProvider(devPodConfig, workspaceConfig.Context, workspaceConfig.Provider.Name)
+ retConfig.Provider, err = provider.ExportProvider(
+ devPodConfig,
+ workspaceConfig.Context,
+ workspaceConfig.Provider.Name,
+ )
if err != nil {
return nil, fmt.Errorf("export provider config: %w", err)
}
diff --git a/cmd/flags/flags.go b/cmd/flags/flags.go
index 5c87052672..b9b2e1832f 100644
--- a/cmd/flags/flags.go
+++ b/cmd/flags/flags.go
@@ -1,6 +1,7 @@
package flags
import (
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
flag "github.com/spf13/pflag"
)
@@ -18,22 +19,47 @@ type GlobalFlags struct {
Silent bool
}
-// SetGlobalFlags applies the global flags
+// SetGlobalFlags applies the global flags.
func SetGlobalFlags(flags *flag.FlagSet) *GlobalFlags {
globalFlags := &GlobalFlags{}
- flags.StringVar(&globalFlags.DevPodHome, "devpod-home", "", "If defined will override the default devpod home")
- flags.StringVar(&globalFlags.LogOutput, "log-output", "plain", "The log format to use. Can be either plain, raw or json")
+ flags.StringVar(
+ &globalFlags.DevPodHome,
+ config.BinaryName+"-home",
+ "",
+ "If defined will override the default devpod home",
+ )
+ flags.StringVar(
+ &globalFlags.LogOutput,
+ "log-output",
+ "plain",
+ "The log format to use. Can be either plain, raw or json",
+ )
flags.StringVar(&globalFlags.Context, "context", "", "The context to use")
- flags.StringVar(&globalFlags.Provider, "provider", "", "The provider to use. Needs to be configured for the selected context")
+ flags.StringVar(
+ &globalFlags.Provider,
+ "provider",
+ "",
+ "The provider to use. Needs to be configured for the selected context",
+ )
flags.BoolVar(&globalFlags.Debug, "debug", false, "Prints the stack trace if an error occurs")
- flags.BoolVar(&globalFlags.Silent, "silent", false, "Run in silent mode and prevents any devpod log output except panics & fatals")
+ flags.BoolVar(
+ &globalFlags.Silent,
+ "silent",
+ false,
+ "Run in silent mode and prevents any devpod log output except panics & fatals",
+ )
flags.Var(&globalFlags.Owner, "owner", "Show pro workspaces for owner")
_ = flags.MarkHidden("owner")
flags.StringVar(&globalFlags.UID, "uid", "", "Set UID for workspace")
_ = flags.MarkHidden("uid")
- flags.StringVar(&globalFlags.AgentDir, "agent-dir", "", "The data folder where agent data is stored.")
+ flags.StringVar(
+ &globalFlags.AgentDir,
+ "agent-dir",
+ "",
+ "The data folder where agent data is stored.",
+ )
_ = flags.MarkHidden("agent-dir")
return globalFlags
}
diff --git a/cmd/helper/check_provider_update.go b/cmd/helper/check_provider_update.go
index bb23f4b804..bc5e9d74c3 100644
--- a/cmd/helper/check_provider_update.go
+++ b/cmd/helper/check_provider_update.go
@@ -17,9 +17,7 @@ import (
"github.com/spf13/cobra"
)
-var (
- errProviderNotFound = errors.New("provider not found")
-)
+var errProviderNotFound = errors.New("provider not found")
type CheckProviderUpdateCmd struct {
*flags.GlobalFlags
@@ -31,7 +29,7 @@ type providerVersionCheck struct {
LatestVersion string `json:"latestVersion,omitempty"`
}
-// NewCheckProviderUpdateCmd creates a new command
+// NewCheckProviderUpdateCmd creates a new command.
func NewCheckProviderUpdateCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &CheckProviderUpdateCmd{
GlobalFlags: flags,
@@ -40,19 +38,23 @@ func NewCheckProviderUpdateCmd(flags *flags.GlobalFlags) *cobra.Command {
shellCmd := &cobra.Command{
Use: "check-provider-update",
Short: "Check if a provider update is available",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
- return cmd.Run(context.Background(), devPodConfig, args)
+ return cmd.Run(cobraCmd.Context(), devPodConfig, args)
},
}
return shellCmd
}
-func (cmd *CheckProviderUpdateCmd) Run(ctx context.Context, devPodConfig *config.Config, args []string) error {
+func (cmd *CheckProviderUpdateCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ args []string,
+) error {
if len(args) != 1 {
return fmt.Errorf("provider is missing")
}
@@ -77,11 +79,15 @@ func (cmd *CheckProviderUpdateCmd) Run(ctx context.Context, devPodConfig *config
if err != nil {
return err
}
- currentProviderVersion, err := semver.Parse(strings.TrimPrefix(currentProvider.Config.Version, "v"))
+ currentProviderVersion, err := semver.Parse(
+ strings.TrimPrefix(currentProvider.Config.Version, "v"),
+ )
if err != nil {
return err
}
- latestProviderVersion, err := semver.Parse(strings.TrimPrefix(latestProviderConfig.Version, "v"))
+ latestProviderVersion, err := semver.Parse(
+ strings.TrimPrefix(latestProviderConfig.Version, "v"),
+ )
if err != nil {
return err
}
@@ -101,7 +107,10 @@ func (cmd *CheckProviderUpdateCmd) Run(ctx context.Context, devPodConfig *config
return nil
}
-func loadLatestProvider(providerSourceRaw string, log log.Logger) (*provider.ProviderConfig, error) {
+func loadLatestProvider(
+ providerSourceRaw string,
+ log log.Logger,
+) (*provider.ProviderConfig, error) {
providerRaw, _, err := workspace.ResolveProvider(providerSourceRaw, log)
if err != nil {
return nil, fmt.Errorf("resolve provider: %w", err)
diff --git a/cmd/helper/fleet_helper.go b/cmd/helper/fleet_helper.go
index 8813750250..ff78fa7201 100644
--- a/cmd/helper/fleet_helper.go
+++ b/cmd/helper/fleet_helper.go
@@ -12,14 +12,14 @@ import (
"github.com/spf13/cobra"
)
-// FleetServerCmd holds the fleet server cmd flags
+// FleetServerCmd holds the fleet server cmd flags.
type FleetServerCmd struct {
*flags.GlobalFlags
WorkspaceID string
}
-// NewFleetServerCmd creates a new fleet command
+// NewFleetServerCmd creates a new fleet command.
func NewFleetServerCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &FleetServerCmd{
GlobalFlags: flags,
@@ -35,7 +35,7 @@ func NewFleetServerCmd(flags *flags.GlobalFlags) *cobra.Command {
return fleetCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (c *FleetServerCmd) Run(cmd *cobra.Command, _ []string) error {
logFile := filepath.Join(os.Getenv("HOME"), ".cache/JetBrains/Fleet/log/fleet.log")
firstConnection := regexp.MustCompile(`.*Received authorization request.*`)
@@ -66,7 +66,7 @@ func (c *FleetServerCmd) Run(cmd *cobra.Command, _ []string) error {
_ = file.Close()
}
case <-cmd.Context().Done():
- //context is done - either canceled or time is up for timeout
+ // context is done - either canceled or time is up for timeout
return nil
}
}
diff --git a/cmd/helper/get_image.go b/cmd/helper/get_image.go
index e27e6f7ea3..a624a0e24d 100644
--- a/cmd/helper/get_image.go
+++ b/cmd/helper/get_image.go
@@ -14,7 +14,7 @@ type GetImageCommand struct {
*flags.GlobalFlags
}
-// NewGetImageCmd creates a new command
+// NewGetImageCmd creates a new command.
func NewGetImageCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GetImageCommand{
GlobalFlags: flags,
diff --git a/cmd/helper/get_provider_name.go b/cmd/helper/get_provider_name.go
index 701e1eb814..d52131aea7 100644
--- a/cmd/helper/get_provider_name.go
+++ b/cmd/helper/get_provider_name.go
@@ -16,7 +16,7 @@ type GetProviderNameCmd struct {
*flags.GlobalFlags
}
-// NewGetProviderNameCmd creates a new command
+// NewGetProviderNameCmd creates a new command.
func NewGetProviderNameCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GetProviderNameCmd{
GlobalFlags: flags,
@@ -24,8 +24,8 @@ func NewGetProviderNameCmd(flags *flags.GlobalFlags) *cobra.Command {
shellCmd := &cobra.Command{
Use: "get-provider-name",
Short: "Retrieves a provider name",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
diff --git a/cmd/helper/get_workspace_config.go b/cmd/helper/get_workspace_config.go
index 0b9bdf6f02..c0d7945eb9 100644
--- a/cmd/helper/get_workspace_config.go
+++ b/cmd/helper/get_workspace_config.go
@@ -28,7 +28,7 @@ type GetWorkspaceConfigCommandResult struct {
ConfigPaths []string `json:"configPaths"`
}
-// NewGetWorkspaceConfigCommand creates a new command
+// NewGetWorkspaceConfigCommand creates a new command.
func NewGetWorkspaceConfigCommand(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GetWorkspaceConfigCommand{
GlobalFlags: flags,
@@ -51,13 +51,19 @@ func NewGetWorkspaceConfigCommand(flags *flags.GlobalFlags) *cobra.Command {
},
}
- shellCmd.Flags().DurationVar(&cmd.timeout, "timeout", 10*time.Second, "Timeout for the command, 10 seconds by default")
- shellCmd.Flags().IntVar(&cmd.maxDepth, "max-depth", 3, "Maximum depth to search for devcontainer files")
+ shellCmd.Flags().
+ DurationVar(&cmd.timeout, "timeout", 10*time.Second, "Timeout for the command, 10 seconds by default")
+ shellCmd.Flags().
+ IntVar(&cmd.maxDepth, "max-depth", 3, "Maximum depth to search for devcontainer files")
return shellCmd
}
-func (cmd *GetWorkspaceConfigCommand) Run(ctx context.Context, devPodConfig *config.Config, args []string) error {
+func (cmd *GetWorkspaceConfigCommand) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ args []string,
+) error {
if len(args) != 1 {
return fmt.Errorf("workspace source is missing")
}
@@ -68,7 +74,7 @@ func (cmd *GetWorkspaceConfigCommand) Run(ctx context.Context, devPodConfig *con
level = logrus.DebugLevel
}
var logger log.Logger = log.NewStdoutLogger(os.Stdin, os.Stdout, os.Stderr, level)
- if os.Getenv("DEVPOD_UI") == "true" {
+ if os.Getenv(config.EnvUI) == config.BoolTrue {
logger = log.Discard
}
logger.Debugf("Resolving devcontainer config for source: %s", rawSource)
@@ -79,7 +85,7 @@ func (cmd *GetWorkspaceConfigCommand) Run(ctx context.Context, devPodConfig *con
done := make(chan *devcontainer.GetWorkspaceConfigResult, 1)
errChan := make(chan error, 1)
- tmpDir, err := os.MkdirTemp("", "devpod")
+ tmpDir, err := os.MkdirTemp("", config.BinaryName)
if err != nil {
return err
}
@@ -87,7 +93,16 @@ func (cmd *GetWorkspaceConfigCommand) Run(ctx context.Context, devPodConfig *con
_ = os.RemoveAll(tmpDir)
}()
go func() {
- result, err := devcontainer.FindDevcontainerFiles(ctx, rawSource, tmpDir, cmd.maxDepth, devPodConfig.ContextOption(config.ContextOptionSSHStrictHostKeyChecking) == "true", logger)
+ result, err := devcontainer.FindDevcontainerFiles(
+ ctx,
+ rawSource,
+ tmpDir,
+ cmd.maxDepth,
+ devPodConfig.ContextOption(
+ config.ContextOptionSSHStrictHostKeyChecking,
+ ) == config.BoolTrue,
+ logger,
+ )
if err != nil {
errChan <- err
return
diff --git a/cmd/helper/get_workspace_name.go b/cmd/helper/get_workspace_name.go
index b281cbd15a..8513d05ba8 100644
--- a/cmd/helper/get_workspace_name.go
+++ b/cmd/helper/get_workspace_name.go
@@ -14,7 +14,7 @@ type GetWorkspaceNameCommand struct {
*flags.GlobalFlags
}
-// NewGetWorkspaceNameCmd creates a new command
+// NewGetWorkspaceNameCmd creates a new command.
func NewGetWorkspaceNameCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GetWorkspaceNameCommand{
GlobalFlags: flags,
@@ -22,8 +22,8 @@ func NewGetWorkspaceNameCmd(flags *flags.GlobalFlags) *cobra.Command {
shellCmd := &cobra.Command{
Use: "get-workspace-name",
Short: "Retrieves a workspace name",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
diff --git a/cmd/helper/get_workspace_uid.go b/cmd/helper/get_workspace_uid.go
index 4fd1416c05..ebc60b3a74 100644
--- a/cmd/helper/get_workspace_uid.go
+++ b/cmd/helper/get_workspace_uid.go
@@ -13,7 +13,7 @@ type GetWorkspaceUIDCommand struct {
*flags.GlobalFlags
}
-// NewGetWorkspaceUIDCmd creates a new command
+// NewGetWorkspaceUIDCmd creates a new command.
func NewGetWorkspaceUIDCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GetWorkspaceUIDCommand{
GlobalFlags: flags,
@@ -21,8 +21,8 @@ func NewGetWorkspaceUIDCmd(flags *flags.GlobalFlags) *cobra.Command {
shellCmd := &cobra.Command{
Use: "get-workspace-uid",
Short: "Retrieves a workspace uid",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
diff --git a/cmd/helper/helper.go b/cmd/helper/helper.go
index 428582281e..496177fbcb 100644
--- a/cmd/helper/helper.go
+++ b/cmd/helper/helper.go
@@ -9,7 +9,7 @@ import (
"github.com/spf13/cobra"
)
-// NewHelperCmd returns a new command
+// NewHelperCmd returns a new command.
func NewHelperCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
helperCmd := &cobra.Command{
Use: "helper",
diff --git a/cmd/helper/http/http.go b/cmd/helper/http/http.go
index 3e7fbe2704..413e3b0077 100644
--- a/cmd/helper/http/http.go
+++ b/cmd/helper/http/http.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewHTTPCmd returns a new command
+// NewHTTPCmd returns a new command.
func NewHTTPCmd(flags *flags.GlobalFlags) *cobra.Command {
httpCmd := &cobra.Command{
Use: "http",
diff --git a/cmd/helper/http/request.go b/cmd/helper/http/request.go
index 635a8198c6..243a3cfc56 100644
--- a/cmd/helper/http/request.go
+++ b/cmd/helper/http/request.go
@@ -20,21 +20,23 @@ type RequestCmd struct {
FailOnErrorCode bool
}
-// NewRequestCmd creates a new ssh command
+// NewRequestCmd creates a new ssh command.
func NewRequestCmd() *cobra.Command {
cmd := &RequestCmd{}
requestCmd := &cobra.Command{
Use: "request",
Short: "Executes a http(s) request",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
requestCmd.Flags().StringVarP(&cmd.Data, "data", "d", "", "Request Data")
requestCmd.Flags().StringVarP(&cmd.Method, "request", "X", "GET", "Request Type")
requestCmd.Flags().StringSliceVarP(&cmd.Headers, "header", "H", []string{}, "Extra Headers")
- requestCmd.Flags().BoolVar(&cmd.FailOnErrorCode, "fail-on-error-code", true, "Let this command fail if the remote is returning an error code")
+ requestCmd.Flags().
+ BoolVar(&cmd.FailOnErrorCode, "fail-on-error-code", true,
+ "Let this command fail if the remote is returning an error code")
return requestCmd
}
@@ -51,10 +53,18 @@ func (cmd *RequestCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("unexpected header '%s', expected form 'HEADER: VALUE'", header)
}
- httpHeader.Add(strings.TrimSpace(splitted[0]), strings.TrimSpace(strings.Join(splitted[1:], ":")))
+ httpHeader.Add(
+ strings.TrimSpace(splitted[0]),
+ strings.TrimSpace(strings.Join(splitted[1:], ":")),
+ )
}
- request, err := http.NewRequest(cmd.Method, args[0], strings.NewReader(cmd.Data))
+ request, err := http.NewRequestWithContext(
+ ctx,
+ cmd.Method,
+ args[0],
+ strings.NewReader(cmd.Data),
+ )
if err != nil {
return err
}
diff --git a/cmd/helper/json/get.go b/cmd/helper/json/get.go
index d3889a8784..f6e500ab9b 100644
--- a/cmd/helper/json/get.go
+++ b/cmd/helper/json/get.go
@@ -2,93 +2,112 @@ package json
import (
"context"
- "encoding/json"
"fmt"
"io"
"os"
+ "regexp"
"strings"
- "github.com/PaesslerAG/jsonpath"
"github.com/spf13/cobra"
+ "github.com/tidwall/gjson"
)
+// GetCmd retrieves a JSON value by path.
type GetCmd struct {
File string
Fail bool
}
-// NewGetCmd creates a new ssh command
+// NewGetCmd creates a new ssh command.
func NewGetCmd() *cobra.Command {
cmd := &GetCmd{}
getCmd := &cobra.Command{
Use: "get",
Short: "Retrieves a JSON value by JSONPath",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
getCmd.Flags().StringVarP(&cmd.File, "file", "f", "", "Parse this json file instead of STDIN")
getCmd.Flags().BoolVar(&cmd.Fail, "fail", false, "Fail if value is not found")
+
return getCmd
}
-func (cmd *GetCmd) Run(ctx context.Context, args []string) error {
- if len(args) == 0 {
- return fmt.Errorf("jsonpath expected")
+// jsonPathToGjson converts a JSONPath expression to a gjson path.
+// It handles expressions like $.foo.bar, $.foo[0].bar, $[0], .foo, [0].foo.
+var bracketIndex = regexp.MustCompile(`\[(\d+)\]`)
+
+func jsonPathToGjson(path string) (string, error) {
+ if path == "" || path == "$" || path == "$." {
+ return "@this", nil
+ }
+ if strings.Contains(path, "..") ||
+ strings.Contains(path, "[?(") ||
+ strings.Contains(path, "*") {
+ return "", fmt.Errorf("unsupported jsonpath expression: %s", path)
}
- if !strings.HasPrefix(args[0], "$") {
- if !strings.HasPrefix(args[0], "[") && !strings.HasPrefix(args[0], ".") {
- args[0] = "." + args[0]
- }
+ path = strings.TrimPrefix(path, "$.")
+ path = strings.TrimPrefix(path, "$")
+ path = strings.TrimPrefix(path, ".")
+ path = bracketIndex.ReplaceAllString(path, ".$1")
+ path = strings.TrimPrefix(path, ".")
+
+ return path, nil
+}
- args[0] = "$" + args[0]
+func writeResult(result gjson.Result) {
+ switch result.Type {
+ case gjson.String:
+ _, _ = os.Stdout.WriteString(result.String())
+ case gjson.True:
+ _, _ = os.Stdout.WriteString("true")
+ case gjson.False:
+ _, _ = os.Stdout.WriteString("false")
+ default:
+ _, _ = os.Stdout.WriteString(result.Raw)
}
+}
- var jsonBytes []byte
- if cmd.File != "" {
- var err error
- jsonBytes, err = os.ReadFile(cmd.File)
- if err != nil {
- return err
- }
- } else {
- var err error
- jsonBytes, err = io.ReadAll(os.Stdin)
- if err != nil {
- return err
- }
+// Run executes the get command.
+func (cmd *GetCmd) Run(ctx context.Context, args []string) error {
+ if len(args) == 0 {
+ return fmt.Errorf("jsonpath expected")
}
- v := any(nil)
- err := json.Unmarshal(jsonBytes, &v)
+ jsonBytes, err := cmd.readInput()
if err != nil {
+ return err
+ }
+
+ if !gjson.ValidBytes(jsonBytes) {
return fmt.Errorf("parse json")
}
- val, err := jsonpath.Get(args[0], v)
+ gjsonPath, err := jsonPathToGjson(args[0])
if err != nil {
+ return err
+ }
+ result := gjson.GetBytes(jsonBytes, gjsonPath)
+
+ if !result.Exists() {
if cmd.Fail {
- return err
+ return fmt.Errorf("unknown key %s", args[0])
}
- return nil
- }
- switch t := val.(type) {
- case string:
- fmt.Print(strings.TrimSpace(t))
- return nil
- case bool, int, int64, rune:
- fmt.Print(t)
return nil
}
- out, err := json.MarshalIndent(val, "", " ")
- if err != nil {
- return err
- }
+ writeResult(result)
- fmt.Print(string(out))
return nil
}
+
+func (cmd *GetCmd) readInput() ([]byte, error) {
+ if cmd.File != "" {
+ return os.ReadFile(cmd.File) //nolint:gosec // file path comes from CLI flag
+ }
+ return io.ReadAll(os.Stdin)
+}
diff --git a/cmd/helper/json/json.go b/cmd/helper/json/json.go
index 4ff3b58277..0adb826749 100644
--- a/cmd/helper/json/json.go
+++ b/cmd/helper/json/json.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewJSONCmd returns a new command
+// NewJSONCmd returns a new command.
func NewJSONCmd(flags *flags.GlobalFlags) *cobra.Command {
jsonCmd := &cobra.Command{
Use: "json",
diff --git a/cmd/helper/sh.go b/cmd/helper/sh.go
index 1bfa56409b..4c36cdf3c4 100644
--- a/cmd/helper/sh.go
+++ b/cmd/helper/sh.go
@@ -14,14 +14,14 @@ type ShellCommand struct {
Login bool
}
-// NewShellCmd creates a new command
+// NewShellCmd creates a new command.
func NewShellCmd() *cobra.Command {
cmd := &ShellCommand{}
shellCmd := &cobra.Command{
Use: "sh",
Short: "Executes a command in a shell",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
diff --git a/cmd/helper/ssh_client.go b/cmd/helper/ssh_client.go
index 065e1233ef..ad88ef96df 100644
--- a/cmd/helper/ssh_client.go
+++ b/cmd/helper/ssh_client.go
@@ -16,14 +16,14 @@ type SSHClient struct {
User string
}
-// NewSSHClientCmd creates a new ssh command
+// NewSSHClientCmd creates a new ssh command.
func NewSSHClientCmd() *cobra.Command {
cmd := &SSHClient{}
sshCmd := &cobra.Command{
Use: "ssh-client",
Short: "Starts a new ssh client session",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
diff --git a/cmd/helper/ssh_git_clone.go b/cmd/helper/ssh_git_clone.go
index dd7e545223..a21102bad0 100644
--- a/cmd/helper/ssh_git_clone.go
+++ b/cmd/helper/ssh_git_clone.go
@@ -22,8 +22,8 @@ func NewSSHGitCloneCmd() *cobra.Command {
sshCmd := &cobra.Command{
Use: "ssh-git-clone",
Short: "Drop-in ssh replacement in GIT_SSH_COMMAND",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
@@ -35,12 +35,19 @@ func NewSSHGitCloneCmd() *cobra.Command {
func (cmd *SSHGitClone) Run(ctx context.Context, args []string) error {
if len(args) < 2 {
- return fmt.Errorf("expected args in format: {user}@{host} {commands...}, received \"%s\"", strings.Join(args, " "))
+ return fmt.Errorf(
+ "expected args in format: {user}@{host} {commands...}, received \"%s\"",
+ strings.Join(args, " "),
+ )
}
host := args[0]
sshCmdArgs := args[1:]
if len(host) == 0 || len(sshCmdArgs) == 0 {
- return fmt.Errorf("unexpected input: host: %s, args: %s", host, strings.Join(sshCmdArgs, " "))
+ return fmt.Errorf(
+ "unexpected input: host: %s, args: %s",
+ host,
+ strings.Join(sshCmdArgs, " "),
+ )
}
user, addr, err := parseSSHHost(host)
diff --git a/cmd/helper/ssh_server.go b/cmd/helper/ssh_server.go
index 656ad78941..36738d072b 100644
--- a/cmd/helper/ssh_server.go
+++ b/cmd/helper/ssh_server.go
@@ -17,7 +17,7 @@ import (
"github.com/spf13/cobra"
)
-// SSHServerCmd holds the ssh server cmd flags
+// SSHServerCmd holds the ssh server cmd flags.
type SSHServerCmd struct {
*flags.GlobalFlags
@@ -29,29 +29,36 @@ type SSHServerCmd struct {
Workdir string
}
-// NewSSHServerCmd creates a new ssh command
+// NewSSHServerCmd creates a new ssh command.
func NewSSHServerCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SSHServerCmd{
GlobalFlags: flags,
}
sshCmd := &cobra.Command{
Use: "ssh-server",
- Short: "Starts a new ssh server",
+ Short: "Starts a new SSH server",
Args: cobra.NoArgs,
RunE: cmd.Run,
}
- sshCmd.Flags().StringVar(&cmd.Address, "address", fmt.Sprintf("0.0.0.0:%d", helperssh.DefaultPort), "Address to listen to")
- sshCmd.Flags().BoolVar(&cmd.Stdio, "stdio", false, "Will listen on stdout and stdin instead of an address")
- sshCmd.Flags().BoolVar(&cmd.TrackActivity, "track-activity", false, "If enabled will write the last activity time to a file")
- sshCmd.Flags().StringVar(&cmd.ReuseSSHAuthSock, "reuse-ssh-auth-sock", "", "If set, the SSH_AUTH_SOCK is expected to already be available in the workspace (under /tmp using the key provided) and the connection reuses this instead of creating a new one")
+ sshCmd.Flags().
+ StringVar(&cmd.Address, "address", fmt.Sprintf("0.0.0.0:%d", helperssh.DefaultPort), "Address to listen to")
+ sshCmd.Flags().
+ BoolVar(&cmd.Stdio, "stdio", false, "Will listen on stdout and stdin instead of an address")
+ sshCmd.Flags().
+ BoolVar(&cmd.TrackActivity, "track-activity", false, "If enabled will write the last activity time to a file")
+ sshCmd.Flags().
+ StringVar(&cmd.ReuseSSHAuthSock, "reuse-ssh-auth-sock", "",
+ "If set, the SSH_AUTH_SOCK is expected to already be available in the workspace "+
+ "(under /tmp using the key provided) and the connection reuses this instead of creating a new one")
_ = sshCmd.Flags().MarkHidden("reuse-ssh-auth-sock")
sshCmd.Flags().StringVar(&cmd.Token, "token", "", "Base64 encoded token to use")
- sshCmd.Flags().StringVar(&cmd.Workdir, "workdir", "", "Directory where commands will run on the host")
+ sshCmd.Flags().
+ StringVar(&cmd.Workdir, "workdir", "", "Directory where commands will run on the host")
return sshCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SSHServerCmd) Run(_ *cobra.Command, _ []string) error {
var (
keys []ssh.PublicKey
@@ -91,7 +98,14 @@ func (cmd *SSHServerCmd) Run(_ *cobra.Command, _ []string) error {
}
// start the server
- server, err := helperssh.NewServer(cmd.Address, hostKey, keys, cmd.Workdir, cmd.ReuseSSHAuthSock, log.Default.ErrorStreamOnly())
+ server, err := helperssh.NewServer(
+ cmd.Address,
+ hostKey,
+ keys,
+ cmd.Workdir,
+ cmd.ReuseSSHAuthSock,
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return err
}
@@ -102,13 +116,21 @@ func (cmd *SSHServerCmd) Run(_ *cobra.Command, _ []string) error {
go func() {
_, err = os.Stat(agent.ContainerActivityFile)
if err != nil {
- err = os.WriteFile(agent.ContainerActivityFile, nil, 0o777)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err)
+ if err := os.WriteFile(
+ agent.ContainerActivityFile,
+ nil,
+ 0o666,
+ ); err != nil { // #nosec G306
+ fmt.Fprintf(os.Stderr, "error writing file: %v\n", err)
+ return
+ }
+ if err := os.Chmod(
+ agent.ContainerActivityFile,
+ 0o666,
+ ); err != nil { // #nosec G302
+ fmt.Fprintf(os.Stderr, "error setting file permissions: %v\n", err)
return
}
-
- _ = os.Chmod(agent.ContainerActivityFile, 0o777)
}
for {
diff --git a/cmd/helper/strings/strings.go b/cmd/helper/strings/strings.go
index 74877894c0..cee3bbf0d8 100644
--- a/cmd/helper/strings/strings.go
+++ b/cmd/helper/strings/strings.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewStringsCmd returns a new command
+// NewStringsCmd returns a new command.
func NewStringsCmd(flags *flags.GlobalFlags) *cobra.Command {
stringsCmd := &cobra.Command{
Use: "strings",
diff --git a/cmd/ide/ide.go b/cmd/ide/ide.go
index 7c31e68fdb..fdc54d275c 100644
--- a/cmd/ide/ide.go
+++ b/cmd/ide/ide.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewIDECmd returns a new command
+// NewIDECmd returns a new command.
func NewIDECmd(flags *flags.GlobalFlags) *cobra.Command {
ideCmd := &cobra.Command{
Use: "ide",
diff --git a/cmd/ide/list.go b/cmd/ide/list.go
index 536e09c188..ba2bc02f56 100644
--- a/cmd/ide/list.go
+++ b/cmd/ide/list.go
@@ -10,19 +10,18 @@ import (
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/ide/ideparse"
- "github.com/skevetter/log"
- "github.com/skevetter/log/table"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/spf13/cobra"
)
-// ListCmd holds the list cmd flags
+// ListCmd holds the list cmd flags.
type ListCmd struct {
*flags.GlobalFlags
Output string
}
-// NewListCmd creates a new command
+// NewListCmd creates a new command.
func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ListCmd{
GlobalFlags: flags,
@@ -31,12 +30,14 @@ func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "list",
Aliases: []string{"ls"},
Short: "List available IDEs",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ Args: cobra.NoArgs,
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- listCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ listCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return listCmd
}
@@ -46,7 +47,7 @@ type IDEWithDefault struct {
Default bool `json:"default,omitempty"`
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ListCmd) Run(ctx context.Context) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -66,7 +67,7 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Default",
}, tableEntries)
@@ -85,7 +86,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/ide/options.go b/cmd/ide/options.go
index 1d19f940a2..9d402daf52 100644
--- a/cmd/ide/options.go
+++ b/cmd/ide/options.go
@@ -10,19 +10,18 @@ import (
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/ide"
"github.com/skevetter/devpod/pkg/ide/ideparse"
- "github.com/skevetter/log"
- "github.com/skevetter/log/table"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/spf13/cobra"
)
-// OptionsCmd holds the options cmd flags
+// OptionsCmd holds the options cmd flags.
type OptionsCmd struct {
*flags.GlobalFlags
Output string
}
-// NewOptionsCmd creates a new command
+// NewOptionsCmd creates a new command.
func NewOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &OptionsCmd{
GlobalFlags: flags,
@@ -30,16 +29,17 @@ func NewOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
optionsCmd := &cobra.Command{
Use: "options",
Short: "List ide options",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("please specify the ide")
}
- return cmd.Run(context.Background(), args[0])
+ return cmd.Run(cobraCmd.Context(), args[0])
},
}
- optionsCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ optionsCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return optionsCmd
}
@@ -49,7 +49,7 @@ type optionWithValue struct {
Value string `json:"value,omitempty"`
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *OptionsCmd) Run(ctx context.Context, ide string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -78,7 +78,7 @@ func (cmd *OptionsCmd) Run(ctx context.Context, ide string) error {
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Description",
"Default",
@@ -99,7 +99,10 @@ func (cmd *OptionsCmd) Run(ctx context.Context, ide string) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/ide/set_options.go b/cmd/ide/set_options.go
index f7ce848541..5644813f2f 100644
--- a/cmd/ide/set_options.go
+++ b/cmd/ide/set_options.go
@@ -11,14 +11,14 @@ import (
"github.com/spf13/cobra"
)
-// SetOptionsCmd holds the setOptions cmd flags
+// SetOptionsCmd holds the setOptions cmd flags.
type SetOptionsCmd struct {
*flags.GlobalFlags
Options []string
}
-// NewSetOptionsCmd creates a new command
+// NewSetOptionsCmd creates a new command.
func NewSetOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SetOptionsCmd{
GlobalFlags: flags,
@@ -26,20 +26,21 @@ func NewSetOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
setOptionsCmd := &cobra.Command{
Use: "set-options",
Short: "Configure ide options",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("please specify the ide")
}
- return cmd.Run(context.Background(), args[0])
+ return cmd.Run(cobraCmd.Context(), args[0])
},
}
- setOptionsCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "IDE option in the form KEY=VALUE")
+ setOptionsCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "IDE option in the form KEY=VALUE")
return setOptionsCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SetOptionsCmd) Run(ctx context.Context, ide string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
diff --git a/cmd/ide/use.go b/cmd/ide/use.go
index 65f0f502dd..0f518450c2 100644
--- a/cmd/ide/use.go
+++ b/cmd/ide/use.go
@@ -14,14 +14,14 @@ import (
"github.com/spf13/cobra"
)
-// UseCmd holds the use cmd flags
+// UseCmd holds the use cmd flags.
type UseCmd struct {
*flags.GlobalFlags
Options []string
}
-// NewUseCmd creates a new command
+// NewUseCmd creates a new command.
func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &UseCmd{
GlobalFlags: flags,
@@ -32,20 +32,23 @@ func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
Long: `Configure the default IDE to use
Available IDEs can be listed with 'devpod ide list'`,
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
- return fmt.Errorf("please specify the ide to use, list available IDEs with 'devpod ide list'")
+ return fmt.Errorf(
+ "please specify the ide to use, list available IDEs with 'devpod ide list'",
+ )
}
- return cmd.Run(context.Background(), args[0])
+ return cmd.Run(cobraCmd.Context(), args[0])
},
}
- useCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "IDE option in the form KEY=VALUE")
+ useCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "IDE option in the form KEY=VALUE")
return useCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *UseCmd) Run(ctx context.Context, ide string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -75,11 +78,16 @@ func (cmd *UseCmd) Run(ctx context.Context, ide string) error {
return nil
}
-func setOptions(devPodConfig *config.Config, ide string, userOptions []string, ideOptions ide.Options) error {
+func setOptions(
+ devPodConfig *config.Config,
+ ide string,
+ userOptions []string,
+ ideOptions ide.Options,
+) error {
userOptions = options2.InheritOptionsFromEnvironment(
userOptions,
ideOptions,
- "DEVPOD_IDE_"+ide+"_",
+ config.EnvIDEPrefix+ide+"_",
)
optionValues, err := ideparse.ParseOptions(userOptions, ideOptions)
diff --git a/cmd/import.go b/cmd/import.go
index 826f9c8420..524d202edc 100644
--- a/cmd/import.go
+++ b/cmd/import.go
@@ -8,7 +8,6 @@ import (
"fmt"
"os"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/extract"
@@ -18,7 +17,7 @@ import (
"github.com/spf13/cobra"
)
-// ImportCmd holds the export cmd flags
+// ImportCmd holds the export cmd flags.
type ImportCmd struct {
*flags.GlobalFlags
@@ -33,7 +32,7 @@ type ImportCmd struct {
Data string
}
-// NewImportCmd creates a new command
+// NewImportCmd creates a new command.
func NewImportCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ImportCmd{
GlobalFlags: flags,
@@ -43,28 +42,29 @@ func NewImportCmd(flags *flags.GlobalFlags) *cobra.Command {
Short: "Imports a workspace configuration",
Args: cobra.NoArgs,
Hidden: true,
- RunE: func(_ *cobra.Command, args []string) error {
- ctx := context.Background()
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
- return cmd.Run(ctx, devPodConfig, log.Default)
+ return cmd.Run(cobraCmd.Context(), devPodConfig, log.Default)
},
}
importCmd.Flags().StringVar(&cmd.WorkspaceID, "workspace-id", "", "To workspace id to use")
importCmd.Flags().StringVar(&cmd.MachineID, "machine-id", "", "The machine id to use")
- importCmd.Flags().BoolVar(&cmd.MachineReuse, "machine-reuse", false, "If machine already exists, reuse existing machine")
+ importCmd.Flags().
+ BoolVar(&cmd.MachineReuse, "machine-reuse", false, "If machine already exists, reuse existing machine")
importCmd.Flags().StringVar(&cmd.ProviderID, "provider-id", "", "The provider id to use")
- importCmd.Flags().BoolVar(&cmd.ProviderReuse, "provider-reuse", false, "If provider already exists, reuse existing provider")
+ importCmd.Flags().
+ BoolVar(&cmd.ProviderReuse, "provider-reuse", false, "If provider already exists, reuse existing provider")
importCmd.Flags().StringVar(&cmd.Data, "data", "", "The data to import as raw json")
_ = importCmd.MarkFlagRequired("data")
return importCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ImportCmd) Run(ctx context.Context, devPodConfig *config.Config, log log.Logger) error {
exportConfig := &provider.ExportConfig{}
err := json.Unmarshal([]byte(cmd.Data), exportConfig)
@@ -114,13 +114,18 @@ func (cmd *ImportCmd) Run(ctx context.Context, devPodConfig *config.Config, log
return nil
}
-func (cmd *ImportCmd) importWorkspace(devPodConfig *config.Config, exportConfig *provider.ExportConfig, log log.Logger) error {
+func (cmd *ImportCmd) importWorkspace(
+ devPodConfig *config.Config,
+ exportConfig *provider.ExportConfig,
+ log log.Logger,
+) error {
workspaceDir, err := provider.GetWorkspaceDir(devPodConfig.DefaultContext, cmd.WorkspaceID)
if err != nil {
return fmt.Errorf("get workspace dir: %w", err)
}
- err = os.MkdirAll(workspaceDir, 0755)
+ // #nosec G301 -- TODO Consider using a more secure permission setting and ownership if needed.
+ err = os.MkdirAll(workspaceDir, 0o755)
if err != nil {
return fmt.Errorf("create workspace dir: %w", err)
}
@@ -136,7 +141,10 @@ func (cmd *ImportCmd) importWorkspace(devPodConfig *config.Config, exportConfig
}
// exchange config
- workspaceConfig, err := provider.LoadWorkspaceConfig(devPodConfig.DefaultContext, cmd.WorkspaceID)
+ workspaceConfig, err := provider.LoadWorkspaceConfig(
+ devPodConfig.DefaultContext,
+ cmd.WorkspaceID,
+ )
if err != nil {
return fmt.Errorf("load machine config: %w", err)
}
@@ -151,13 +159,15 @@ func (cmd *ImportCmd) importWorkspace(devPodConfig *config.Config, exportConfig
return fmt.Errorf("save workspace config: %w", err)
}
- log.WithFields(logrus.Fields{
- "workspaceId": cmd.WorkspaceID,
- }).Done("imported workspace")
+ log.Donef("imported workspace: workspaceId=%s", cmd.WorkspaceID)
return nil
}
-func (cmd *ImportCmd) importMachine(devPodConfig *config.Config, exportConfig *provider.ExportConfig, log log.Logger) error {
+func (cmd *ImportCmd) importMachine(
+ devPodConfig *config.Config,
+ exportConfig *provider.ExportConfig,
+ log log.Logger,
+) error {
if exportConfig.Machine == nil {
return nil
}
@@ -173,7 +183,8 @@ func (cmd *ImportCmd) importMachine(devPodConfig *config.Config, exportConfig *p
return fmt.Errorf("get machine dir: %w", err)
}
- err = os.MkdirAll(machineDir, 0755)
+ // #nosec G301 -- TODO Consider using a more secure permission setting and ownership if needed.
+ err = os.MkdirAll(machineDir, 0o755)
if err != nil {
return fmt.Errorf("create machine dir: %w", err)
}
@@ -203,13 +214,15 @@ func (cmd *ImportCmd) importMachine(devPodConfig *config.Config, exportConfig *p
return fmt.Errorf("save machine config: %w", err)
}
- log.WithFields(logrus.Fields{
- "machineId": cmd.MachineID,
- }).Done("imported machine")
+ log.Donef("imported machine: machineId=%s", cmd.MachineID)
return nil
}
-func (cmd *ImportCmd) importProvider(devPodConfig *config.Config, exportConfig *provider.ExportConfig, log log.Logger) error {
+func (cmd *ImportCmd) importProvider(
+ devPodConfig *config.Config,
+ exportConfig *provider.ExportConfig,
+ log log.Logger,
+) error {
// if provider already exists we skip
if cmd.ProviderReuse && provider.ProviderExists(devPodConfig.DefaultContext, cmd.ProviderID) {
log.Infof("Reusing existing provider %s", cmd.ProviderID)
@@ -221,7 +234,8 @@ func (cmd *ImportCmd) importProvider(devPodConfig *config.Config, exportConfig *
return fmt.Errorf("get provider dir: %w", err)
}
- err = os.MkdirAll(providerDir, 0755)
+ // #nosec G301 -- TODO Consider using a more secure permission setting and ownership if needed.
+ err = os.MkdirAll(providerDir, 0o755)
if err != nil {
return fmt.Errorf("create provider dir: %w", err)
}
@@ -262,13 +276,16 @@ func (cmd *ImportCmd) importProvider(devPodConfig *config.Config, exportConfig *
}
}
- log.WithFields(logrus.Fields{
- "providerId": cmd.ProviderID,
- }).Done("imported provider")
+ log.Donef("imported provider: providerId=%s", cmd.ProviderID)
return nil
}
-func (cmd *ImportCmd) checkForConflictingIDs(ctx context.Context, exportConfig *provider.ExportConfig, devPodConfig *config.Config, log log.Logger) error {
+func (cmd *ImportCmd) checkForConflictingIDs(
+ ctx context.Context,
+ exportConfig *provider.ExportConfig,
+ devPodConfig *config.Config,
+ log log.Logger,
+) error {
workspaces, err := workspace.List(ctx, devPodConfig, false, cmd.Owner, log)
if err != nil {
return fmt.Errorf("error listing workspaces: %w", err)
@@ -278,9 +295,16 @@ func (cmd *ImportCmd) checkForConflictingIDs(ctx context.Context, exportConfig *
if exportConfig.Workspace != nil {
for _, workspace := range workspaces {
if workspace.ID == cmd.WorkspaceID {
- return fmt.Errorf("existing workspace with id %s found, please use --workspace-id to override the workspace id", cmd.WorkspaceID)
+ return fmt.Errorf(
+ "existing workspace with id %s found, please use --workspace-id to override the workspace id",
+ cmd.WorkspaceID,
+ )
} else if workspace.UID == exportConfig.Workspace.UID {
- return fmt.Errorf("existing workspace %s with uid %s found, please use --workspace-id to override the workspace id", workspace.ID, workspace.UID)
+ return fmt.Errorf(
+ "existing workspace %s with uid %s found, please use --workspace-id to override the workspace id",
+ workspace.ID,
+ workspace.UID,
+ )
}
}
}
@@ -288,14 +312,22 @@ func (cmd *ImportCmd) checkForConflictingIDs(ctx context.Context, exportConfig *
// check if machine already exists
if !cmd.MachineReuse && exportConfig.Machine != nil {
if provider.MachineExists(devPodConfig.DefaultContext, cmd.MachineID) {
- return fmt.Errorf("existing machine with id %s found, please use --machine-reuse to skip importing the machine or --machine-id to override the machine id", cmd.MachineID)
+ return fmt.Errorf(
+ "existing machine with id %s found, please use --machine-reuse to skip importing "+
+ "the machine or --machine-id to override the machine id",
+ cmd.MachineID,
+ )
}
}
// check if provider already exists
if !cmd.ProviderReuse && exportConfig.Provider != nil {
if provider.ProviderExists(devPodConfig.DefaultContext, cmd.ProviderID) {
- return fmt.Errorf("existing provider with id %s found, please use --provider-reuse to skip importing the provider or --provider-id to override the provider id", cmd.ProviderID)
+ return fmt.Errorf(
+ "existing provider with id %s found, please use --provider-reuse to skip importing "+
+ "the provider or --provider-id to override the provider id",
+ cmd.ProviderID,
+ )
}
}
diff --git a/cmd/list.go b/cmd/list.go
index 674cd68992..a3b93e6854 100644
--- a/cmd/list.go
+++ b/cmd/list.go
@@ -9,13 +9,13 @@ import (
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
- "github.com/skevetter/log/table"
"github.com/spf13/cobra"
)
-// ListCmd holds the configuration
+// ListCmd holds the configuration.
type ListCmd struct {
*flags.GlobalFlags
@@ -23,7 +23,7 @@ type ListCmd struct {
SkipPro bool
}
-// NewListCmd creates a new destroy command
+// NewListCmd creates a new destroy command.
func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ListCmd{
GlobalFlags: flags,
@@ -33,21 +33,18 @@ func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
Aliases: []string{"ls"},
Short: "Lists existing workspaces",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, args []string) error {
- if len(args) > 0 {
- return fmt.Errorf("no arguments are allowed for this command")
- }
-
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, _ []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- listCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ listCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
listCmd.Flags().BoolVar(&cmd.SkipPro, "skip-pro", false, "Don't list pro workspaces")
return listCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ListCmd) Run(ctx context.Context) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -91,7 +88,7 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
})
}
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Source",
"Machine",
@@ -102,7 +99,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
"Pro",
}, tableEntries)
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/logs.go b/cmd/logs.go
index dd3a9fcb59..6bc78ba9c4 100644
--- a/cmd/logs.go
+++ b/cmd/logs.go
@@ -18,12 +18,12 @@ import (
"github.com/spf13/cobra"
)
-// LogsCmd holds the configuration
+// LogsCmd holds the configuration.
type LogsCmd struct {
*flags.GlobalFlags
}
-// NewLogsCmd creates a new destroy command
+// NewLogsCmd creates a new destroy command.
func NewLogsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &LogsCmd{
GlobalFlags: flags,
@@ -34,22 +34,37 @@ func NewLogsCmd(flags *flags.GlobalFlags) *cobra.Command {
RunE: func(cobraCmd *cobra.Command, args []string) error {
return cmd.Run(cobraCmd.Context(), args)
},
- ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ ValidArgsFunction: func(
+ rootCmd *cobra.Command, args []string, toComplete string,
+ ) ([]string, cobra.ShellCompDirective) {
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
return startCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *LogsCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
- baseClient, err := workspace.Get(ctx, devPodConfig, args, false, cmd.Owner, false, log.Default)
+ baseClient, err := workspace.Get(ctx, workspace.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ Owner: cmd.Owner,
+ Log: log.Default,
+ })
if err != nil {
return err
}
@@ -109,7 +124,12 @@ func (cmd *LogsCmd) Run(ctx context.Context, args []string) error {
}()
// create agent command
- agentCommand := fmt.Sprintf("'%s' agent workspace logs --context '%s' --id '%s'", client.AgentPath(), client.Context(), client.Workspace())
+ agentCommand := fmt.Sprintf(
+ "'%s' agent workspace logs --context '%s' --id '%s'",
+ client.AgentPath(),
+ client.Context(),
+ client.Workspace(),
+ )
if log.GetLevel() == logrus.DebugLevel {
agentCommand += " --debug"
}
diff --git a/cmd/logs_daemon.go b/cmd/logs_daemon.go
index 929df43d7e..b2267ab923 100644
--- a/cmd/logs_daemon.go
+++ b/cmd/logs_daemon.go
@@ -14,12 +14,12 @@ import (
"github.com/spf13/cobra"
)
-// LogsDaemonCmd holds the configuration
+// LogsDaemonCmd holds the configuration.
type LogsDaemonCmd struct {
*flags.GlobalFlags
}
-// NewLogsDaemonCmd creates a new destroy command
+// NewLogsDaemonCmd creates a new destroy command.
func NewLogsDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &LogsDaemonCmd{
GlobalFlags: flags,
@@ -27,26 +27,33 @@ func NewLogsDaemonCmd(flags *flags.GlobalFlags) *cobra.Command {
startCmd := &cobra.Command{
Use: "logs-daemon",
Short: "Prints the daemon logs on the machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
return startCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *LogsDaemonCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
- baseClient, err := workspace.Get(ctx, devPodConfig, args, false, cmd.Owner, false, log.Default)
+ baseClient, err := workspace.Get(ctx, workspace.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ Owner: cmd.Owner,
+ Log: log.Default,
+ })
if err != nil {
return err
} else if baseClient.WorkspaceConfig().Machine.ID == "" {
- return fmt.Errorf("selected workspace is not a machine provider, there is not daemon running")
+ return fmt.Errorf(
+ "selected workspace is not a machine provider, there is not daemon running",
+ )
}
workspaceClient, ok := baseClient.(client.WorkspaceClient)
@@ -59,7 +66,12 @@ func (cmd *LogsDaemonCmd) Run(ctx context.Context, args []string) error {
return err
}
- command := fmt.Sprintf("'%s' agent workspace logs-daemon --context '%s' --id '%s'", workspaceClient.AgentPath(), workspaceClient.Context(), workspaceClient.Workspace())
+ command := fmt.Sprintf(
+ "'%s' agent workspace logs-daemon --context '%s' --id '%s'",
+ workspaceClient.AgentPath(),
+ workspaceClient.Context(),
+ workspaceClient.Workspace(),
+ )
if agentInfo.Agent.DataPath != "" {
command += fmt.Sprintf(" --agent-dir '%s'", agentInfo.Agent.DataPath)
}
diff --git a/cmd/machine/create.go b/cmd/machine/create.go
index 103b2ea065..6f4028ce46 100644
--- a/cmd/machine/create.go
+++ b/cmd/machine/create.go
@@ -4,21 +4,20 @@ import (
"context"
"github.com/skevetter/devpod/cmd/flags"
- "github.com/skevetter/devpod/pkg/client"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-// CreateCmd holds the configuration
+// CreateCmd holds the configuration.
type CreateCmd struct {
*flags.GlobalFlags
ProviderOptions []string
}
-// NewCreateCmd creates a new create command
+// NewCreateCmd creates a new create command.
func NewCreateCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &CreateCmd{
GlobalFlags: flags,
@@ -26,27 +25,33 @@ func NewCreateCmd(flags *flags.GlobalFlags) *cobra.Command {
createCmd := &cobra.Command{
Use: "create [name]",
Short: "Creates a new machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
- createCmd.Flags().StringSliceVar(&cmd.ProviderOptions, "provider-option", []string{}, "Provider option in the form KEY=VALUE")
+ createCmd.Flags().
+ StringSliceVar(&cmd.ProviderOptions, "provider-option", []string{}, "Provider option in the form KEY=VALUE")
return createCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *CreateCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
- machineClient, err := workspace.ResolveMachine(devPodConfig, args, cmd.ProviderOptions, log.Default)
+ machineClient, err := workspace.ResolveMachine(
+ devPodConfig,
+ args,
+ cmd.ProviderOptions,
+ log.Default,
+ )
if err != nil {
return err
}
- err = machineClient.Create(ctx, client.CreateOptions{})
+ err = machineClient.Create(ctx)
if err != nil {
return err
}
diff --git a/cmd/machine/delete.go b/cmd/machine/delete.go
index 9256031e27..d5668c09e1 100644
--- a/cmd/machine/delete.go
+++ b/cmd/machine/delete.go
@@ -13,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
-// DeleteCmd holds the configuration
+// DeleteCmd holds the configuration.
type DeleteCmd struct {
*flags.GlobalFlags
@@ -21,7 +21,7 @@ type DeleteCmd struct {
Force bool
}
-// NewDeleteCmd creates a new destroy command
+// NewDeleteCmd creates a new delete command.
func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: flags,
@@ -29,17 +29,19 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
deleteCmd := &cobra.Command{
Use: "delete [name]",
Short: "Deletes an existing machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
- deleteCmd.Flags().StringVar(&cmd.GracePeriod, "grace-period", "", "The amount of time to give the command to delete the workspace")
- deleteCmd.Flags().BoolVar(&cmd.Force, "force", false, "Delete workspace even if it is not found remotely anymore")
+ deleteCmd.Flags().
+ StringVar(&cmd.GracePeriod, "grace-period", "", "The amount of time to give the command to delete the workspace")
+ deleteCmd.Flags().
+ BoolVar(&cmd.Force, "force", false, "Delete workspace even if it is not found remotely anymore")
return deleteCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -52,7 +54,13 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
}
// check if there are workspaces that still use this machine
- workspaces, err := workspace.List(ctx, devPodConfig, false, platform.SelfOwnerFilter, log.Default)
+ workspaces, err := workspace.List(
+ ctx,
+ devPodConfig,
+ false,
+ platform.SelfOwnerFilter,
+ log.Default,
+ )
if err != nil {
return err
}
@@ -60,7 +68,13 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
// search for workspace that uses this machine
for _, workspace := range workspaces {
if workspace.Machine.ID == machineClient.Machine() {
- return fmt.Errorf("cannot delete machine '%s', because workspace '%s' is still using it. Please delete the workspace '%s' before deleting the machine", workspace.Machine.ID, workspace.ID, workspace.ID)
+ return fmt.Errorf(
+ "cannot delete machine '%s', because workspace '%s' is still using it. "+
+ "Please delete the workspace '%s' before deleting the machine",
+ workspace.Machine.ID,
+ workspace.ID,
+ workspace.ID,
+ )
}
}
diff --git a/cmd/machine/describe.go b/cmd/machine/describe.go
new file mode 100644
index 0000000000..ce9c1a0c2c
--- /dev/null
+++ b/cmd/machine/describe.go
@@ -0,0 +1,57 @@
+package machine
+
+import (
+ "context"
+ "fmt"
+ "os"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/workspace"
+ "github.com/skevetter/log"
+ "github.com/spf13/cobra"
+)
+
+// DescribeCmd holds the configuration.
+type DescribeCmd struct {
+ *flags.GlobalFlags
+}
+
+// NewDescribeCmd creates a new describe command.
+func NewDescribeCmd(flags *flags.GlobalFlags) *cobra.Command {
+ cmd := &DescribeCmd{
+ GlobalFlags: flags,
+ }
+ describeCmd := &cobra.Command{
+ Use: "describe [name]",
+ Short: "Retrieves the description of an existing machine",
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
+ },
+ }
+
+ return describeCmd
+}
+
+// Run runs the command logic.
+func (cmd *DescribeCmd) Run(ctx context.Context, args []string) error {
+ devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
+ if err != nil {
+ return err
+ }
+
+ machineClient, err := workspace.GetMachine(devPodConfig, args, log.Default)
+ if err != nil {
+ return err
+ }
+
+ // get description
+ machineDescription, err := machineClient.Describe(ctx)
+ if err != nil {
+ return err
+ }
+
+ _, _ = fmt.Fprintln(os.Stdout, machineDescription)
+
+ return nil
+}
diff --git a/cmd/machine/inspect.go b/cmd/machine/inspect.go
index b89b75fa57..3f219cbcce 100644
--- a/cmd/machine/inspect.go
+++ b/cmd/machine/inspect.go
@@ -24,8 +24,8 @@ func NewInspectCmd(flags *flags.GlobalFlags) *cobra.Command {
stopCmd := &cobra.Command{
Use: "inspect",
Short: "Inspects an existing machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
diff --git a/cmd/machine/list.go b/cmd/machine/list.go
index fde652b76c..0efcb73545 100644
--- a/cmd/machine/list.go
+++ b/cmd/machine/list.go
@@ -11,19 +11,18 @@ import (
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/provider"
- "github.com/skevetter/log"
- "github.com/skevetter/log/table"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/spf13/cobra"
)
-// ListCmd holds the configuration
+// ListCmd holds the configuration.
type ListCmd struct {
*flags.GlobalFlags
Output string
}
-// NewListCmd creates a new destroy command
+// NewListCmd creates a new list command.
func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ListCmd{
GlobalFlags: flags,
@@ -32,16 +31,17 @@ func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "list",
Aliases: []string{"ls"},
Short: "Lists existing machines",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- listCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ listCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return listCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ListCmd) Run(ctx context.Context) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -62,7 +62,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
case "plain":
tableEntries := [][]string{}
for _, entry := range entries {
- machineConfig, err := provider.LoadMachineConfig(devPodConfig.DefaultContext, entry.Name())
+ machineConfig, err := provider.LoadMachineConfig(
+ devPodConfig.DefaultContext,
+ entry.Name(),
+ )
if err != nil {
return fmt.Errorf("load machine config: %w", err)
}
@@ -77,7 +80,7 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Provider",
"Age",
@@ -85,7 +88,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
case "json":
tableEntries := []*provider.Machine{}
for _, entry := range entries {
- machineConfig, err := provider.LoadMachineConfig(devPodConfig.DefaultContext, entry.Name())
+ machineConfig, err := provider.LoadMachineConfig(
+ devPodConfig.DefaultContext,
+ entry.Name(),
+ )
if err != nil {
return fmt.Errorf("load machine config: %w", err)
}
@@ -101,7 +107,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/machine/machine.go b/cmd/machine/machine.go
index 638a3292e0..4196b3c9fb 100644
--- a/cmd/machine/machine.go
+++ b/cmd/machine/machine.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewMachineCmd returns a new root command
+// NewMachineCmd returns a new root command.
func NewMachineCmd(flags *flags.GlobalFlags) *cobra.Command {
machineCmd := &cobra.Command{
Use: "machine",
@@ -20,5 +20,6 @@ func NewMachineCmd(flags *flags.GlobalFlags) *cobra.Command {
machineCmd.AddCommand(NewDeleteCmd(flags))
machineCmd.AddCommand(NewCreateCmd(flags))
machineCmd.AddCommand(NewInspectCmd(flags))
+ machineCmd.AddCommand(NewDescribeCmd(flags))
return machineCmd
}
diff --git a/cmd/machine/ssh.go b/cmd/machine/ssh.go
index 5140a8bcb6..8ce0e5aa92 100644
--- a/cmd/machine/ssh.go
+++ b/cmd/machine/ssh.go
@@ -10,13 +10,12 @@ import (
"os/exec"
"al.essio.dev/pkg/shellescape"
-
- "github.com/mattn/go-isatty"
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
devagent "github.com/skevetter/devpod/pkg/agent"
"github.com/skevetter/devpod/pkg/client"
"github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/pty"
devssh "github.com/skevetter/devpod/pkg/ssh"
devsshagent "github.com/skevetter/devpod/pkg/ssh/agent"
"github.com/skevetter/devpod/pkg/workspace"
@@ -26,7 +25,7 @@ import (
"golang.org/x/term"
)
-// SSHCmd holds the configuration
+// SSHCmd holds the configuration.
type SSHCmd struct {
*flags.GlobalFlags
@@ -45,6 +44,15 @@ const (
installUsage = "Install local TERM terminfo on remote before PTY"
)
+var (
+ isTerminalFunc = func(fd uintptr) bool {
+ return term.IsTerminal(int(fd)) // #nosec G115 -- fd is always a valid file descriptor
+ }
+ makeInputRawTerm = pty.MakeInputRaw
+ makeOutputRawTerm = pty.MakeOutputRaw
+ restoreTerminalFunc = pty.RestoreTerminal
+)
+
type SSHSessionOptions struct {
TermMode string
InstallTerminfo bool
@@ -66,7 +74,7 @@ type RunSSHSessionOptions struct {
Stderr io.Writer
}
-// NewSSHCmd creates a new destroy command
+// NewSSHCmd creates a new ssh command.
func NewSSHCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SSHCmd{
GlobalFlags: flags,
@@ -74,28 +82,37 @@ func NewSSHCmd(flags *flags.GlobalFlags) *cobra.Command {
sshCmd := &cobra.Command{
Use: "ssh [name]",
Short: "SSH into the machine",
- RunE: func(c *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
- sshCmd.Flags().StringVar(&cmd.Command, "command", "", "The command to execute on the remote machine")
- sshCmd.Flags().BoolVar(&cmd.AgentForwarding, "agent-forwarding", false, "If true, will forward the local ssh keys")
+ sshCmd.Flags().
+ StringVar(&cmd.Command, "command", "", "The command to execute on the remote machine")
+ sshCmd.Flags().
+ BoolVar(&cmd.AgentForwarding, "agent-forwarding", false, "If true, will forward the local ssh keys")
sshCmd.Flags().StringVar(&cmd.TermMode, "term-mode", TermModeAuto, termModeUsage)
sshCmd.Flags().BoolVar(&cmd.InstallTerminfo, "install-terminfo", false, installUsage)
_ = sshCmd.RegisterFlagCompletionFunc(
"term-mode",
func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
- return []string{TermModeAuto, TermModeStrict, TermModeFallback}, cobra.ShellCompDirectiveNoFileComp
+ return []string{
+ TermModeAuto,
+ TermModeStrict,
+ TermModeFallback,
+ }, cobra.ShellCompDirectiveNoFileComp
},
)
return sshCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SSHCmd) Run(ctx context.Context, args []string) error {
if !isValidTermMode(cmd.TermMode) {
- return fmt.Errorf("invalid --term-mode %q: expected one of auto, strict, fallback", cmd.TermMode)
+ return fmt.Errorf(
+ "invalid --term-mode %q: expected one of auto, strict, fallback",
+ cmd.TermMode,
+ )
}
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
@@ -118,7 +135,10 @@ func (cmd *SSHCmd) Run(ctx context.Context, args []string) error {
return StartSSHSession(ctx, StartSSHSessionOptions{
Command: cmd.Command,
AgentForwarding: cmd.AgentForwarding,
- SessionOptions: SSHSessionOptions{TermMode: cmd.TermMode, InstallTerminfo: cmd.InstallTerminfo},
+ SessionOptions: SSHSessionOptions{
+ TermMode: cmd.TermMode,
+ InstallTerminfo: cmd.InstallTerminfo,
+ },
Exec: func(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
command := fmt.Sprintf("'%s' helper ssh-server --stdio", machineClient.AgentPath())
if cmd.Debug {
@@ -235,7 +255,11 @@ func setupPTYIfNeeded(
return setupInteractivePTY(ctx, sshClient, session, options)
}
-func configureAgentForwarding(sshClient *ssh.Client, session *ssh.Session, shouldForward bool) error {
+func configureAgentForwarding(
+ sshClient *ssh.Client,
+ session *ssh.Session,
+ shouldForward bool,
+) error {
authSock := devsshagent.GetSSHAuthSocket()
if !shouldForward || authSock == "" {
return nil
@@ -260,17 +284,18 @@ func setupInteractivePTY(
session *ssh.Session,
options RunSSHSessionOptions,
) (func(), error) {
+ stdin := os.Stdin
stdout := os.Stdout
- if !isatty.IsTerminal(stdout.Fd()) {
+ fd := int(stdout.Fd()) // #nosec G115 -- fd is always a valid file descriptor
+ if !hasInteractiveTerminal(stdin, stdout) {
return noopRestore, nil
}
- restoreTerm, err := makeRawTerm(stdout)
+ restoreTerm, err := makeRawTerm(stdin, stdout)
if err != nil {
return noopRestore, err
}
- fd := int(stdout.Fd()) // #nosec G115 -- fd is always a valid file descriptor
startWindowResizeForwarder(ctx, session, fd)
t := resolvePTYTermWithFallback(ctx, sshClient, options.SessionOptions, options.Stderr)
@@ -283,15 +308,24 @@ func setupInteractivePTY(
return restoreTerm, nil
}
-func makeRawTerm(stdout *os.File) (func(), error) {
- fd := int(stdout.Fd()) // #nosec G115 -- fd is always a valid file descriptor
- state, err := term.MakeRaw(fd)
+func hasInteractiveTerminal(stdin, stdout *os.File) bool {
+ return isTerminalFunc(stdin.Fd()) && isTerminalFunc(stdout.Fd())
+}
+
+func makeRawTerm(stdin, stdout *os.File) (func(), error) {
+ stdinState, err := makeInputRawTerm(stdin.Fd())
+ if err != nil {
+ return noopRestore, err
+ }
+ stdoutState, err := makeOutputRawTerm(stdout.Fd())
if err != nil {
+ _ = restoreTerminalFunc(stdin.Fd(), stdinState)
return noopRestore, err
}
return func() {
- _ = term.Restore(int(stdout.Fd()), state)
+ _ = restoreTerminalFunc(stdout.Fd(), stdoutState)
+ _ = restoreTerminalFunc(stdin.Fd(), stdinState)
}, nil
}
@@ -308,7 +342,12 @@ func resolvePTYTermWithFallback(
return t
}
- _, _ = fmt.Fprintf(stderr, "warning: failed to resolve TERM, falling back to %s: %v\n", defaultTerm, err)
+ _, _ = fmt.Fprintf(
+ stderr,
+ "warning: failed to resolve TERM, falling back to %s: %v\n",
+ defaultTerm,
+ err,
+ )
return defaultTerm
}
@@ -361,7 +400,11 @@ func startSessionCommand(session *ssh.Session, command string) error {
return nil
}
-func resolvePTYTerm(ctx context.Context, sshClient *ssh.Client, sessionOptions SSHSessionOptions) (string, error) {
+func resolvePTYTerm(
+ ctx context.Context,
+ sshClient *ssh.Client,
+ sessionOptions SSHSessionOptions,
+) (string, error) {
localTerm := getLocalTerm()
mode := getTermMode(sessionOptions)
@@ -373,7 +416,10 @@ func resolvePTYTerm(ctx context.Context, sshClient *ssh.Client, sessionOptions S
case TermModeAuto:
return resolveAutoPTYTerm(ctx, sshClient, localTerm, sessionOptions.InstallTerminfo)
default:
- return "", fmt.Errorf("invalid --term-mode %q: expected one of auto, strict, fallback", mode)
+ return "", fmt.Errorf(
+ "invalid --term-mode %q: expected one of auto, strict, fallback",
+ mode,
+ )
}
}
@@ -449,7 +495,11 @@ func remoteTerminfoExists(ctx context.Context, sshClient *ssh.Client, term strin
// It returns (false, nil) when prerequisites are missing or installation exits
// non-zero, because callers should continue with TERM fallback in auto mode.
// It only returns a non-nil error for transport/session failures.
-func installLocalTerminfoOnRemote(ctx context.Context, sshClient *ssh.Client, term string) (bool, error) {
+func installLocalTerminfoOnRemote(
+ ctx context.Context,
+ sshClient *ssh.Client,
+ term string,
+) (bool, error) {
// #nosec G204 -- term is validated by the caller
infocmpCmd := exec.CommandContext(ctx, "infocmp", "-x", term)
output, err := infocmpCmd.Output()
diff --git a/cmd/machine/ssh_test.go b/cmd/machine/ssh_test.go
new file mode 100644
index 0000000000..3c922d1862
--- /dev/null
+++ b/cmd/machine/ssh_test.go
@@ -0,0 +1,261 @@
+package machine
+
+import (
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/skevetter/devpod/pkg/pty"
+)
+
+type filePair struct {
+ reader *os.File
+ writer *os.File
+}
+
+func TestHasInteractiveTerminalRequiresStdinAndStdout(t *testing.T) {
+ stdin := newPipePair(t, "stdin")
+ stdout := newPipePair(t, "stdout")
+ restore := stubIsTerminalFunc(t)
+ defer restore()
+
+ isTerminalFunc = func(fd uintptr) bool {
+ return fd == stdin.reader.Fd()
+ }
+ if hasInteractiveTerminal(stdin.reader, stdout.writer) {
+ t.Fatal("expected missing stdout terminal to disable PTY")
+ }
+
+ isTerminalFunc = func(fd uintptr) bool {
+ return fd == stdout.writer.Fd()
+ }
+ if hasInteractiveTerminal(stdin.reader, stdout.writer) {
+ t.Fatal("expected missing stdin terminal to disable PTY")
+ }
+
+ isTerminalFunc = func(fd uintptr) bool {
+ return fd == stdin.reader.Fd() || fd == stdout.writer.Fd()
+ }
+ if !hasInteractiveTerminal(stdin.reader, stdout.writer) {
+ t.Fatal("expected PTY when both stdin and stdout are terminals")
+ }
+}
+
+func TestMakeRawTermUsesInputAndOutputTerminalState(t *testing.T) {
+ stdin := newPipePair(t, "stdin")
+ stdout := newPipePair(t, "stdout")
+ stdinState := &pty.TerminalState{}
+ stdoutState := &pty.TerminalState{}
+ var calls []string
+ restore := stubTerminalFuncs(t)
+ defer restore()
+
+ makeInputRawTerm = makeRawRecorder(
+ t,
+ rawRecorderOpts{
+ calls: &calls,
+ label: "input",
+ wantFD: stdin.reader.Fd(),
+ state: stdinState,
+ },
+ )
+ makeOutputRawTerm = makeRawRecorder(
+ t,
+ rawRecorderOpts{
+ calls: &calls,
+ label: "output",
+ wantFD: stdout.writer.Fd(),
+ state: stdoutState,
+ },
+ )
+ restoreTerminalFunc = restoreRecorder(t, &calls, map[uintptr]restoreCall{
+ stdout.writer.Fd(): {state: stdoutState, label: "restore-output"},
+ stdin.reader.Fd(): {state: stdinState, label: "restore-input"},
+ })
+
+ restoreTerm, err := makeRawTerm(stdin.reader, stdout.writer)
+ if err != nil {
+ t.Fatalf("make raw term: %v", err)
+ }
+ restoreTerm()
+
+ assertCallsEqual(t, calls, []string{"input", "output", "restore-output", "restore-input"})
+}
+
+func TestMakeRawTermRestoresInputOnOutputFailure(t *testing.T) {
+ stdin := newPipePair(t, "stdin")
+ stdout := newPipePair(t, "stdout")
+ stdinState := &pty.TerminalState{}
+ outputErr := errors.New("output raw failed")
+ var restoreCalled bool
+ restore := stubTerminalFuncs(t)
+ defer restore()
+
+ makeInputRawTerm = makeRawRecorder(
+ t,
+ rawRecorderOpts{wantFD: stdin.reader.Fd(), state: stdinState},
+ )
+ makeOutputRawTerm = makeRawRecorder(
+ t,
+ rawRecorderOpts{wantFD: stdout.writer.Fd(), err: outputErr},
+ )
+ restoreTerminalFunc = func(fd uintptr, state *pty.TerminalState) error {
+ if fd != stdin.reader.Fd() || state != stdinState {
+ t.Fatalf("unexpected restore call: fd=%d state=%p", fd, state)
+ }
+ restoreCalled = true
+ return nil
+ }
+
+ restoreTerm, err := makeRawTerm(stdin.reader, stdout.writer)
+ if !errors.Is(err, outputErr) {
+ t.Fatalf("expected output error, got %v", err)
+ }
+ if restoreTerm == nil {
+ t.Fatal("expected restore function")
+ }
+ if !restoreCalled {
+ t.Fatal("expected stdin terminal state to be restored after output setup failure")
+ }
+}
+
+func TestMakeRawTermStopsWhenInputSetupFails(t *testing.T) {
+ stdin := newPipePair(t, "stdin")
+ stdout := newPipePair(t, "stdout")
+ inputErr := errors.New("input raw failed")
+ var outputCalled bool
+ var restoreCalled bool
+ restore := stubTerminalFuncs(t)
+ defer restore()
+
+ makeInputRawTerm = makeRawRecorder(
+ t,
+ rawRecorderOpts{wantFD: stdin.reader.Fd(), err: inputErr},
+ )
+ makeOutputRawTerm = func(uintptr) (*pty.TerminalState, error) {
+ outputCalled = true
+ return &pty.TerminalState{}, nil
+ }
+ restoreTerminalFunc = func(uintptr, *pty.TerminalState) error {
+ restoreCalled = true
+ return nil
+ }
+
+ restoreTerm, err := makeRawTerm(stdin.reader, stdout.writer)
+ if !errors.Is(err, inputErr) {
+ t.Fatalf("expected input error, got %v", err)
+ }
+ if restoreTerm == nil {
+ t.Fatal("expected restore function")
+ }
+ if outputCalled {
+ t.Fatal("did not expect output raw setup after input failure")
+ }
+ if restoreCalled {
+ t.Fatal("did not expect terminal restore after input failure")
+ }
+}
+
+type restoreCall struct {
+ state *pty.TerminalState
+ label string
+}
+
+func newPipePair(t *testing.T, name string) filePair {
+ t.Helper()
+
+ reader, writer, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("create %s pipe: %v", name, err)
+ }
+ t.Cleanup(func() {
+ _ = reader.Close()
+ _ = writer.Close()
+ })
+
+ return filePair{reader: reader, writer: writer}
+}
+
+func stubIsTerminalFunc(t *testing.T) func() {
+ t.Helper()
+
+ oldIsTerminalFunc := isTerminalFunc
+ t.Cleanup(func() {
+ isTerminalFunc = oldIsTerminalFunc
+ })
+
+ return func() {
+ isTerminalFunc = oldIsTerminalFunc
+ }
+}
+
+func stubTerminalFuncs(t *testing.T) func() {
+ t.Helper()
+
+ oldMakeInputRawTerm := makeInputRawTerm
+ oldMakeOutputRawTerm := makeOutputRawTerm
+ oldRestoreTerminalFunc := restoreTerminalFunc
+ t.Cleanup(func() {
+ makeInputRawTerm = oldMakeInputRawTerm
+ makeOutputRawTerm = oldMakeOutputRawTerm
+ restoreTerminalFunc = oldRestoreTerminalFunc
+ })
+
+ return func() {
+ makeInputRawTerm = oldMakeInputRawTerm
+ makeOutputRawTerm = oldMakeOutputRawTerm
+ restoreTerminalFunc = oldRestoreTerminalFunc
+ }
+}
+
+type rawRecorderOpts struct {
+ calls *[]string
+ label string
+ wantFD uintptr
+ state *pty.TerminalState
+ err error
+}
+
+func makeRawRecorder(t *testing.T, opts rawRecorderOpts) func(uintptr) (*pty.TerminalState, error) {
+ t.Helper()
+
+ return func(fd uintptr) (*pty.TerminalState, error) {
+ if opts.calls != nil && opts.label != "" {
+ *opts.calls = append(*opts.calls, opts.label)
+ }
+ if fd != opts.wantFD {
+ t.Fatalf("expected fd %d, got %d", opts.wantFD, fd)
+ }
+ return opts.state, opts.err
+ }
+}
+
+func restoreRecorder(
+ t *testing.T,
+ calls *[]string,
+ want map[uintptr]restoreCall,
+) func(uintptr, *pty.TerminalState) error {
+ t.Helper()
+
+ return func(fd uintptr, state *pty.TerminalState) error {
+ call, ok := want[fd]
+ if !ok || state != call.state {
+ t.Fatalf("unexpected restore call: fd=%d state=%p", fd, state)
+ }
+ *calls = append(*calls, call.label)
+ return nil
+ }
+}
+
+func assertCallsEqual(t *testing.T, got, want []string) {
+ t.Helper()
+
+ if len(got) != len(want) {
+ t.Fatalf("unexpected calls: got %v want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("unexpected calls: got %v want %v", got, want)
+ }
+ }
+}
diff --git a/cmd/machine/start.go b/cmd/machine/start.go
index 2ce799e379..ec4e0d77c8 100644
--- a/cmd/machine/start.go
+++ b/cmd/machine/start.go
@@ -4,19 +4,18 @@ import (
"context"
"github.com/skevetter/devpod/cmd/flags"
- "github.com/skevetter/devpod/pkg/client"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-// StartCmd holds the configuration
+// StartCmd holds the configuration.
type StartCmd struct {
*flags.GlobalFlags
}
-// NewStartCmd creates a new destroy command
+// NewStartCmd creates a new start command.
func NewStartCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StartCmd{
GlobalFlags: flags,
@@ -24,15 +23,15 @@ func NewStartCmd(flags *flags.GlobalFlags) *cobra.Command {
startCmd := &cobra.Command{
Use: "start [name]",
Short: "Starts an existing machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
return startCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *StartCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -44,7 +43,7 @@ func (cmd *StartCmd) Run(ctx context.Context, args []string) error {
return err
}
- err = machineClient.Start(ctx, client.StartOptions{})
+ err = machineClient.Start(ctx)
if err != nil {
return err
}
diff --git a/cmd/machine/status.go b/cmd/machine/status.go
index eb69013b66..9d02a1e894 100644
--- a/cmd/machine/status.go
+++ b/cmd/machine/status.go
@@ -13,14 +13,14 @@ import (
"github.com/spf13/cobra"
)
-// StatusCmd holds the configuration
+// StatusCmd holds the configuration.
type StatusCmd struct {
*flags.GlobalFlags
Output string
}
-// NewStatusCmd creates a new destroy command
+// NewStatusCmd creates a new status command.
func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StatusCmd{
GlobalFlags: flags,
@@ -28,16 +28,16 @@ func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
statusCmd := &cobra.Command{
Use: "status [name]",
Short: "Retrieves the status of an existing machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
- statusCmd.Flags().StringVar(&cmd.Output, "output", "plain", "Status shows the machine status")
+ statusCmd.Flags().StringVar(&cmd.Output, "output", "plain", "Output format: plain or json")
return statusCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *StatusCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -59,9 +59,19 @@ func (cmd *StatusCmd) Run(ctx context.Context, args []string) error {
case "plain":
switch machineStatus {
case client.StatusStopped:
- log.Default.Infof("Machine '%s' is '%s', you can start it via 'devpod machine start %s'", machineClient.Machine(), machineStatus, machineClient.Machine())
+ log.Default.Infof(
+ "Machine '%s' is '%s', you can start it via 'devpod machine start %s'",
+ machineClient.Machine(),
+ machineStatus,
+ machineClient.Machine(),
+ )
case client.StatusBusy:
- log.Default.Infof("Machine '%s' is '%s', which means its currently unaccessible. This is usually resolved by waiting a couple of minutes", machineClient.Machine(), machineStatus)
+ log.Default.Infof(
+ "Machine '%s' is '%s', which means its currently unaccessible. "+
+ "This is usually resolved by waiting a couple of minutes",
+ machineClient.Machine(),
+ machineStatus,
+ )
case client.StatusNotFound:
log.Default.Infof("Machine '%s' is '%s'", machineClient.Machine(), machineStatus)
default:
@@ -85,7 +95,10 @@ func (cmd *StatusCmd) Run(ctx context.Context, args []string) error {
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/machine/stop.go b/cmd/machine/stop.go
index d88a83fda5..c0f8ceed71 100644
--- a/cmd/machine/stop.go
+++ b/cmd/machine/stop.go
@@ -11,12 +11,12 @@ import (
"github.com/spf13/cobra"
)
-// StopCmd holds the configuration
+// StopCmd holds the configuration.
type StopCmd struct {
*flags.GlobalFlags
}
-// NewStopCmd creates a new destroy command
+// NewStopCmd creates a new stop command.
func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StopCmd{
GlobalFlags: flags,
@@ -24,15 +24,15 @@ func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
stopCmd := &cobra.Command{
Use: "stop [name]",
Short: "Stops an existing machine",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
return stopCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *StopCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
diff --git a/cmd/ping.go b/cmd/ping.go
index ab81890905..b1fcd0106a 100644
--- a/cmd/ping.go
+++ b/cmd/ping.go
@@ -29,7 +29,15 @@ func NewPingCmd(flags *flags.GlobalFlags) *cobra.Command {
return cmd.Run(cobraCmd.Context(), args)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
Hidden: true,
}
@@ -43,7 +51,13 @@ func (cmd *PingCmd) Run(ctx context.Context, args []string) error {
return err
}
- client, err := workspace2.Get(ctx, devPodConfig, args, true, cmd.Owner, false, log.Default.ErrorStreamOnly())
+ client, err := workspace2.Get(ctx, workspace2.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ ChangeLastUsed: true,
+ Owner: cmd.Owner,
+ Log: log.Default.ErrorStreamOnly(),
+ })
if err != nil {
return err
}
diff --git a/cmd/pro/add/add.go b/cmd/pro/add/add.go
index a3817c8047..bd8eae32f8 100644
--- a/cmd/pro/add/add.go
+++ b/cmd/pro/add/add.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewAddCmd creates a new command
+// NewAddCmd creates a new command.
func NewAddCmd(globalFlags *proflags.GlobalFlags) *cobra.Command {
addCmd := &cobra.Command{
Use: "add",
diff --git a/cmd/pro/add/cluster.go b/cmd/pro/add/cluster.go
index 3732004251..816aacc612 100644
--- a/cmd/pro/add/cluster.go
+++ b/cmd/pro/add/cluster.go
@@ -10,20 +10,19 @@ import (
"time"
"github.com/sirupsen/logrus"
- "github.com/skevetter/log"
- "github.com/skevetter/log/survey"
- kerrors "k8s.io/apimachinery/pkg/api/errors"
- "k8s.io/apimachinery/pkg/util/wait"
-
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/workspace"
+ "github.com/skevetter/log"
+ "github.com/skevetter/log/survey"
"github.com/spf13/cobra"
+ kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
@@ -45,7 +44,7 @@ type ClusterCmd struct {
Host string
}
-// NewClusterCmd creates a new command
+// NewClusterCmd creates a new command.
func NewClusterCmd(globalFlags *proflags.GlobalFlags) *cobra.Command {
cmd := &ClusterCmd{
GlobalFlags: globalFlags,
@@ -61,16 +60,26 @@ func NewClusterCmd(globalFlags *proflags.GlobalFlags) *cobra.Command {
},
}
- c.Flags().StringVar(&cmd.Namespace, "namespace", "loft", "The namespace to generate the service account in. The namespace will be created if it does not exist")
- c.Flags().StringVar(&cmd.ServiceAccount, "service-account", "loft-admin", "The service account name to create")
- c.Flags().StringVar(&cmd.DisplayName, "display-name", "", "The display name to show in the UI for this cluster")
- c.Flags().BoolVar(&cmd.Wait, "wait", false, "If true, will wait until the cluster is initialized")
- c.Flags().BoolVar(&cmd.Insecure, "insecure", false, "If true, deploys the agent in insecure mode")
- c.Flags().StringVar(&cmd.HelmChartVersion, "helm-chart-version", "", "The agent chart version to deploy")
+ c.Flags().
+ StringVar(&cmd.Namespace, "namespace", "loft",
+ "The namespace to generate the service account in. The namespace will be created if it does not exist")
+ c.Flags().
+ StringVar(&cmd.ServiceAccount, "service-account", "loft-admin", "The service account name to create")
+ c.Flags().
+ StringVar(&cmd.DisplayName, "display-name", "", "The display name to show in the UI for this cluster")
+ c.Flags().
+ BoolVar(&cmd.Wait, "wait", false, "If true, will wait until the cluster is initialized")
+ c.Flags().
+ BoolVar(&cmd.Insecure, "insecure", false, "If true, deploys the agent in insecure mode")
+ c.Flags().
+ StringVar(&cmd.HelmChartVersion, "helm-chart-version", "", "The agent chart version to deploy")
c.Flags().StringVar(&cmd.HelmChartPath, "helm-chart-path", "", "The agent chart to deploy")
- c.Flags().StringArrayVar(&cmd.HelmSet, "helm-set", []string{}, "Extra helm values for the agent chart")
- c.Flags().StringArrayVar(&cmd.HelmValues, "helm-values", []string{}, "Extra helm values for the agent chart")
- c.Flags().StringVar(&cmd.KubeContext, "kube-context", "", "The kube context to use for installation")
+ c.Flags().
+ StringArrayVar(&cmd.HelmSet, "helm-set", []string{}, "Extra helm values for the agent chart")
+ c.Flags().
+ StringArrayVar(&cmd.HelmValues, "helm-values", []string{}, "Extra helm values for the agent chart")
+ c.Flags().
+ StringVar(&cmd.KubeContext, "kube-context", "", "The kube context to use for installation")
c.Flags().StringVar(&cmd.Host, "host", "", "The pro instance to use")
return c
@@ -105,7 +114,7 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("get pro version: %w", err)
}
- user, team := getUserOrTeam(ctx, baseClient)
+ user, team := getUserOrTeam(baseClient)
_, err = managementClient.Loft().ManagementV1().Clusters().Create(ctx, &managementv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
@@ -127,7 +136,10 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("create cluster: %w", err)
}
- accessKey, err := managementClient.Loft().ManagementV1().Clusters().GetAccessKey(ctx, clusterName, metav1.GetOptions{})
+ accessKey, err := managementClient.Loft().
+ ManagementV1().
+ Clusters().
+ GetAccessKey(ctx, clusterName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("get cluster access key: %w", err)
}
@@ -140,11 +152,20 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
if os.Getenv("DEVELOPMENT") == "true" {
helmArgs = []string{
- "upgrade", "--install", "loft", cmp.Or(os.Getenv("DEVELOPMENT_CHART_DIR"), "./chart"),
+ "upgrade",
+ "--install",
+ "loft",
+ cmp.Or(os.Getenv("DEVELOPMENT_CHART_DIR"), "./chart"),
"--create-namespace",
- "--namespace", namespace,
- "--set", "agentOnly=true",
- "--set", "image=" + cmp.Or(os.Getenv("DEVELOPMENT_IMAGE"), "ghcr.io/loft-sh/enterprise:release-test"),
+ "--namespace",
+ namespace,
+ "--set",
+ "agentOnly=true",
+ "--set",
+ "image=" + cmp.Or(
+ os.Getenv("DEVELOPMENT_IMAGE"),
+ "ghcr.io/loft-sh/enterprise:release-test",
+ ),
}
} else {
if cmd.HelmChartPath != "" {
@@ -162,7 +183,15 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
}
// general arguments
- helmArgs = append(helmArgs, "--install", "--create-namespace", "--namespace", cmd.Namespace, "--set", "agentOnly=true")
+ helmArgs = append(
+ helmArgs,
+ "--install",
+ "--create-namespace",
+ "--namespace",
+ cmd.Namespace,
+ "--set",
+ "agentOnly=true",
+ )
}
for _, set := range cmd.HelmSet {
@@ -196,20 +225,36 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
helmArgs = append(helmArgs, "--kube-context", cmd.KubeContext)
}
- kubeClientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
+ kubeClientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
+ clientcmd.NewDefaultClientConfigLoadingRules(),
+ &clientcmd.ConfigOverrides{},
+ )
if cmd.KubeContext != "" {
kubeConfig, err := kubeClientConfig.RawConfig()
if err != nil {
- return fmt.Errorf("there is an error loading your current kube config (%w), please make sure you have access to a kubernetes cluster and the command `kubectl get namespaces` is working", err)
+ return fmt.Errorf(
+ "there is an error loading your current kube config (%w), please make sure you have access "+
+ "to a kubernetes cluster and the command `kubectl get namespaces` is working",
+ err,
+ )
}
- kubeClientConfig = clientcmd.NewNonInteractiveClientConfig(kubeConfig, cmd.KubeContext, &clientcmd.ConfigOverrides{}, clientcmd.NewDefaultClientConfigLoadingRules())
+ kubeClientConfig = clientcmd.NewNonInteractiveClientConfig(
+ kubeConfig,
+ cmd.KubeContext,
+ &clientcmd.ConfigOverrides{},
+ clientcmd.NewDefaultClientConfigLoadingRules(),
+ )
}
config, err := kubeClientConfig.ClientConfig()
if err != nil {
- return fmt.Errorf("there is an error loading your current kube config (%w), please make sure you have access to a kubernetes cluster and the command `kubectl get namespaces` is working", err)
+ return fmt.Errorf(
+ "there is an error loading your current kube config (%w), please make sure you have access "+
+ "to a kubernetes cluster and the command `kubectl get namespaces` is working",
+ err,
+ )
}
clientset, err := kubernetes.NewForConfig(config)
@@ -244,22 +289,30 @@ func (cmd *ClusterCmd) Run(ctx context.Context, args []string) error {
if cmd.Wait {
cmd.Log.Info("Waiting for the cluster to be initialized...")
- waitErr := wait.PollUntilContextTimeout(ctx, time.Second, 5*time.Minute, false, func(ctx context.Context) (done bool, err error) {
- clusterInstance, err := managementClient.Loft().ManagementV1().Clusters().Get(ctx, clusterName, metav1.GetOptions{})
- if err != nil && !kerrors.IsNotFound(err) {
- return false, err
- }
-
- return clusterInstance != nil && clusterInstance.Status.Phase == storagev1.ClusterStatusPhaseInitialized, nil
- })
+ waitErr := wait.PollUntilContextTimeout(
+ ctx,
+ time.Second,
+ 5*time.Minute,
+ false,
+ func(ctx context.Context) (done bool, err error) {
+ clusterInstance, err := managementClient.Loft().
+ ManagementV1().
+ Clusters().
+ Get(ctx, clusterName, metav1.GetOptions{})
+ if err != nil && !kerrors.IsNotFound(err) {
+ return false, err
+ }
+
+ return clusterInstance != nil &&
+ clusterInstance.Status.Phase == storagev1.ClusterStatusPhaseInitialized, nil
+ },
+ )
if waitErr != nil {
return fmt.Errorf("get cluster: %w", waitErr)
}
}
- cmd.Log.WithFields(logrus.Fields{
- "cluster": clusterName,
- }).Done("added cluster")
+ cmd.Log.Donef("added cluster: cluster=%s", clusterName)
return nil
}
@@ -289,7 +342,7 @@ func ensureHost(devPodConfig *config.Config, host string, log log.Logger) (strin
return h, nil
}
-func getUserOrTeam(ctx context.Context, baseClient client.Client) (string, string) {
+func getUserOrTeam(baseClient client.Client) (string, string) {
var user, team string
self := baseClient.Self()
diff --git a/cmd/pro/check_health.go b/cmd/pro/check_health.go
index 9a8e4cc332..6e616d8078 100644
--- a/cmd/pro/check_health.go
+++ b/cmd/pro/check_health.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// CheckHealthCmd holds the cmd flags
+// CheckHealthCmd holds the cmd flags.
type CheckHealthCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -23,7 +23,7 @@ type CheckHealthCmd struct {
Host string
}
-// NewCheckHealthCmd creates a new command
+// NewCheckHealthCmd creates a new command.
func NewCheckHealthCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &CheckHealthCmd{
GlobalFlags: globalFlags,
@@ -34,7 +34,13 @@ func NewCheckHealthCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Check platform health",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -60,7 +66,11 @@ func NewCheckHealthCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *CheckHealthCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *CheckHealthCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
var buf bytes.Buffer
// ignore --debug because we tunnel json through stdio
cmd.Log.SetLevel(logrus.InfoLevel)
diff --git a/cmd/pro/check_update.go b/cmd/pro/check_update.go
index 675f204357..133e5e67cc 100644
--- a/cmd/pro/check_update.go
+++ b/cmd/pro/check_update.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// CheckUpdateCmd holds the cmd flags
+// CheckUpdateCmd holds the cmd flags.
type CheckUpdateCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -23,7 +23,7 @@ type CheckUpdateCmd struct {
Host string
}
-// NewCheckUpdateCmd creates a new command
+// NewCheckUpdateCmd creates a new command.
func NewCheckUpdateCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &CheckUpdateCmd{
GlobalFlags: globalFlags,
@@ -34,7 +34,13 @@ func NewCheckUpdateCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Check platform provider update",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -65,7 +71,11 @@ type ProviderUpdateInfo struct {
NewVersion string `json:"newVersion,omitempty"`
}
-func (cmd *CheckUpdateCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *CheckUpdateCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
remoteVersion, err := platform.GetDevPodVersion(fmt.Sprintf("https://%s", cmd.Host))
if err != nil {
return err
diff --git a/cmd/pro/completion/suggestions.go b/cmd/pro/completion/suggestions.go
index 495eec491e..b0c5a1a136 100644
--- a/cmd/pro/completion/suggestions.go
+++ b/cmd/pro/completion/suggestions.go
@@ -10,7 +10,14 @@ import (
"github.com/spf13/cobra"
)
-func GetPlatformHostSuggestions(rootCmd *cobra.Command, context, provider string, args []string, toComplete string, owner platform.OwnerFilter, logger log.Logger) ([]string, cobra.ShellCompDirective) {
+func GetPlatformHostSuggestions(
+ rootCmd *cobra.Command,
+ context, provider string,
+ args []string,
+ toComplete string,
+ owner platform.OwnerFilter,
+ logger log.Logger,
+) ([]string, cobra.ShellCompDirective) {
devPodConfig, err := config.LoadConfig(context, provider)
if err != nil {
return nil, cobra.ShellCompDirectiveError
diff --git a/cmd/pro/create_workspace.go b/cmd/pro/create_workspace.go
index 7e5930d7b2..6b5394277a 100644
--- a/cmd/pro/create_workspace.go
+++ b/cmd/pro/create_workspace.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// CreateWorkspaceCmd holds the cmd flags
+// CreateWorkspaceCmd holds the cmd flags.
type CreateWorkspaceCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -24,7 +24,7 @@ type CreateWorkspaceCmd struct {
Instance string
}
-// NewCreateWorkspaceCmd creates a new command
+// NewCreateWorkspaceCmd creates a new command.
func NewCreateWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &CreateWorkspaceCmd{
GlobalFlags: globalFlags,
@@ -35,7 +35,13 @@ func NewCreateWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Create workspace instance",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -52,7 +58,11 @@ func NewCreateWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *CreateWorkspaceCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *CreateWorkspaceCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
opts := devPodConfig.ProviderOptions(provider.Name)
opts[platform.WorkspaceInstanceEnv] = config.OptionValue{Value: cmd.Instance}
diff --git a/cmd/pro/daemon/daemon.go b/cmd/pro/daemon/daemon.go
index 101d0214c2..1982494da5 100644
--- a/cmd/pro/daemon/daemon.go
+++ b/cmd/pro/daemon/daemon.go
@@ -12,7 +12,7 @@ import (
"github.com/spf13/cobra"
)
-// NewCmd creates a new cobra command
+// NewCmd creates a new cobra command.
func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "daemon",
@@ -28,7 +28,11 @@ func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func findProProvider(ctx context.Context, context, provider, host string, log log.Logger) (*config.Config, *providerpkg.ProviderConfig, error) {
+func findProProvider(
+ ctx context.Context,
+ context, provider, host string,
+ log log.Logger,
+) (*config.Config, *providerpkg.ProviderConfig, error) {
devPodConfig, err := config.LoadConfig(context, provider)
if err != nil {
return nil, nil, err
diff --git a/cmd/pro/daemon/netcheck.go b/cmd/pro/daemon/netcheck.go
index 3952e80c59..5beced6fb6 100644
--- a/cmd/pro/daemon/netcheck.go
+++ b/cmd/pro/daemon/netcheck.go
@@ -16,7 +16,7 @@ import (
"tailscale.com/client/local"
)
-// NetcheckCmd holds the DevPod daemon flags
+// NetcheckCmd holds the DevPod daemon flags.
type NetcheckCmd struct {
*proflags.GlobalFlags
@@ -24,7 +24,7 @@ type NetcheckCmd struct {
Log log.Logger
}
-// NewNetcheckCmd creates a new command
+// NewNetcheckCmd creates a new command.
func NewNetcheckCmd(flags *proflags.GlobalFlags) *cobra.Command {
cmd := &NetcheckCmd{
GlobalFlags: flags,
@@ -34,7 +34,13 @@ func NewNetcheckCmd(flags *proflags.GlobalFlags) *cobra.Command {
Use: "netcheck",
Short: "Get the status of the current network",
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -56,14 +62,29 @@ func NewNetcheckCmd(flags *proflags.GlobalFlags) *cobra.Command {
c.Flags().StringVar(&cmd.Host, "host", "", "The pro instance to use")
_ = c.MarkFlagRequired("host")
- _ = c.RegisterFlagCompletionFunc("host", func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetPlatformHostSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, cmd.Log)
- })
+ _ = c.RegisterFlagCompletionFunc(
+ "host",
+ func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+ return completion.GetPlatformHostSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ cmd.Log,
+ )
+ },
+ )
return c
}
-func (cmd *NetcheckCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *providerpkg.ProviderConfig) error {
+func (cmd *NetcheckCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *providerpkg.ProviderConfig,
+) error {
tsClient := &local.Client{
Socket: daemon.GetSocketAddr(provider.Name),
UseSocketOnly: true,
diff --git a/cmd/pro/daemon/start.go b/cmd/pro/daemon/start.go
index be94fc02e6..621196b67a 100644
--- a/cmd/pro/daemon/start.go
+++ b/cmd/pro/daemon/start.go
@@ -9,19 +9,18 @@ import (
"path/filepath"
"syscall"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
- daemon "github.com/skevetter/devpod/pkg/daemon/platform"
- "github.com/skevetter/devpod/pkg/platform/client"
-
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/pro/completion"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
+ daemon "github.com/skevetter/devpod/pkg/daemon/platform"
+ "github.com/skevetter/devpod/pkg/platform/client"
providerpkg "github.com/skevetter/devpod/pkg/provider"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-// StartCmd holds the devpod daemon flags
+// StartCmd holds the devpod daemon flags.
type StartCmd struct {
*proflags.GlobalFlags
@@ -29,7 +28,7 @@ type StartCmd struct {
Log log.Logger
}
-// NewStartCmd creates a new command
+// NewStartCmd creates a new command.
func NewStartCmd(flags *proflags.GlobalFlags) *cobra.Command {
cmd := &StartCmd{
GlobalFlags: flags,
@@ -39,7 +38,13 @@ func NewStartCmd(flags *proflags.GlobalFlags) *cobra.Command {
Use: "start",
Short: "Start the client daemon",
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -50,15 +55,30 @@ func NewStartCmd(flags *proflags.GlobalFlags) *cobra.Command {
c.Flags().StringVar(&cmd.Host, "host", "", "The pro instance to use")
_ = c.MarkFlagRequired("host")
- _ = c.RegisterFlagCompletionFunc("host", func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetPlatformHostSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, cmd.Log)
- })
+ _ = c.RegisterFlagCompletionFunc(
+ "host",
+ func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+ return completion.GetPlatformHostSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ cmd.Log,
+ )
+ },
+ )
return c
}
-func (cmd *StartCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *providerpkg.ProviderConfig) error {
- isDesktopControlled := os.Getenv("DEVPOD_UI") == "true"
+func (cmd *StartCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *providerpkg.ProviderConfig,
+) error {
+ isDesktopControlled := os.Getenv(config.EnvUI) == config.BoolTrue
dir, err := ensureDaemonDir(devPodConfig.DefaultContext, provider.Name)
if err != nil {
return err
diff --git a/cmd/pro/daemon/status.go b/cmd/pro/daemon/status.go
index 25886071b0..95ce5e2579 100644
--- a/cmd/pro/daemon/status.go
+++ b/cmd/pro/daemon/status.go
@@ -5,18 +5,17 @@ import (
"encoding/json"
"fmt"
- platformdaemon "github.com/skevetter/devpod/pkg/daemon/platform"
-
"github.com/skevetter/devpod/cmd/agent"
"github.com/skevetter/devpod/cmd/pro/completion"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
+ platformdaemon "github.com/skevetter/devpod/pkg/daemon/platform"
providerpkg "github.com/skevetter/devpod/pkg/provider"
"github.com/skevetter/log"
"github.com/spf13/cobra"
)
-// StatusCmd holds the DevPod daemon flags
+// StatusCmd holds the DevPod daemon flags.
type StatusCmd struct {
*proflags.GlobalFlags
@@ -24,7 +23,7 @@ type StatusCmd struct {
Log log.Logger
}
-// NewStatusCmd creates a new command
+// NewStatusCmd creates a new command.
func NewStatusCmd(flags *proflags.GlobalFlags) *cobra.Command {
cmd := &StatusCmd{
GlobalFlags: flags,
@@ -34,7 +33,13 @@ func NewStatusCmd(flags *proflags.GlobalFlags) *cobra.Command {
Use: "status",
Short: "Get the status of the daemon",
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -56,14 +61,29 @@ func NewStatusCmd(flags *proflags.GlobalFlags) *cobra.Command {
c.Flags().StringVar(&cmd.Host, "host", "", "The pro instance to use")
_ = c.MarkFlagRequired("host")
- _ = c.RegisterFlagCompletionFunc("host", func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetPlatformHostSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, cmd.Log)
- })
+ _ = c.RegisterFlagCompletionFunc(
+ "host",
+ func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
+ return completion.GetPlatformHostSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ cmd.Log,
+ )
+ },
+ )
return c
}
-func (cmd *StatusCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *providerpkg.ProviderConfig) error {
+func (cmd *StatusCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *providerpkg.ProviderConfig,
+) error {
status, err := platformdaemon.NewLocalClient(provider.Name).Status(ctx, cmd.Debug)
if err != nil {
return err
diff --git a/cmd/pro/delete.go b/cmd/pro/delete.go
index ae93bc0bf0..9086163db0 100644
--- a/cmd/pro/delete.go
+++ b/cmd/pro/delete.go
@@ -7,7 +7,6 @@ import (
"sync"
"time"
- "github.com/sirupsen/logrus"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
providercmd "github.com/skevetter/devpod/cmd/provider"
"github.com/skevetter/devpod/pkg/client/clientimplementation"
@@ -21,14 +20,14 @@ import (
"k8s.io/apimachinery/pkg/util/wait"
)
-// DeleteCmd holds the delete cmd flags
+// DeleteCmd holds the delete cmd flags.
type DeleteCmd struct {
*proflags.GlobalFlags
IgnoreNotFound bool
}
-// NewDeleteCmd creates a new command
+// NewDeleteCmd creates a new command.
func NewDeleteCmd(flags *proflags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: flags,
@@ -36,12 +35,13 @@ func NewDeleteCmd(flags *proflags.GlobalFlags) *cobra.Command {
deleteCmd := &cobra.Command{
Use: "delete",
Short: "Delete or logout from a DevPod Pro Instance",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
}
- deleteCmd.Flags().BoolVar(&cmd.IgnoreNotFound, "ignore-not-found", false, "Treat \"pro instance not found\" as a successful delete")
+ deleteCmd.Flags().
+ BoolVar(&cmd.IgnoreNotFound, "ignore-not-found", false, "Treat \"pro instance not found\" as a successful delete")
return deleteCmd
}
@@ -57,7 +57,10 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
// load pro instance config
proInstanceName := args[0]
- proInstanceConfig, err := provider.LoadProInstanceConfig(devPodConfig.DefaultContext, proInstanceName)
+ proInstanceConfig, err := provider.LoadProInstanceConfig(
+ devPodConfig.DefaultContext,
+ proInstanceName,
+ )
if err != nil {
if os.IsNotExist(err) && cmd.IgnoreNotFound {
return nil
@@ -66,7 +69,10 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("load pro instance %s: %w", proInstanceName, err)
}
- providerConfig, err := provider.LoadProviderConfig(devPodConfig.DefaultContext, proInstanceConfig.Provider)
+ providerConfig, err := provider.LoadProviderConfig(
+ devPodConfig.DefaultContext,
+ proInstanceConfig.Provider,
+ )
if err != nil {
return fmt.Errorf("load provider: %w", err)
}
@@ -74,11 +80,22 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
// stop daemon and clean up local workspaces
if providerConfig.IsDaemonProvider() {
// clean up local workspaces
- workspaces, err := workspace.ListLocalWorkspaces(devPodConfig.DefaultContext, false, log.Default)
+ workspaces, err := workspace.ListLocalWorkspaces(
+ devPodConfig.DefaultContext,
+ false,
+ log.Default,
+ )
if err != nil {
log.Default.Warnf("Failed to list workspaces: %v", err)
} else {
- cleanupLocalWorkspaces(ctx, devPodConfig, workspaces, providerConfig.Name, cmd.Owner, log.Default)
+ cleanupLocalWorkspaces(
+ ctx,
+ devPodConfig,
+ workspaces,
+ providerConfig.Name,
+ cmd.Owner,
+ log.Default,
+ )
}
daemonClient := daemon.NewLocalClient(proInstanceConfig.Provider)
@@ -100,7 +117,10 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
}
// delete the pro instance dir itself
- proInstanceDir, err := provider.GetProInstanceDir(devPodConfig.DefaultContext, proInstanceConfig.Host)
+ proInstanceDir, err := provider.GetProInstanceDir(
+ devPodConfig.DefaultContext,
+ proInstanceConfig.Host,
+ )
if err != nil {
return err
}
@@ -110,14 +130,18 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("delete pro instance dir: %w", err)
}
- log.WithFields(logrus.Fields{
- "proInstanceName": proInstanceName,
- })
- log.Default.Done("deleted pro instance")
+ log.Default.Donef("deleted pro instance: proInstanceName=%s", proInstanceName)
return nil
}
-func cleanupLocalWorkspaces(ctx context.Context, devPodConfig *config.Config, workspaces []*provider.Workspace, providerName string, owner platform.OwnerFilter, log log.Logger) {
+func cleanupLocalWorkspaces(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ workspaces []*provider.Workspace,
+ providerName string,
+ owner platform.OwnerFilter,
+ log log.Logger,
+) {
usedWorkspaces := []*provider.Workspace{}
for _, workspace := range workspaces {
@@ -133,52 +157,53 @@ func cleanupLocalWorkspaces(ctx context.Context, devPodConfig *config.Config, wo
wg.Add(1)
go func(w provider.Workspace) {
defer wg.Done()
- client, err := workspace.Get(ctx, devPodConfig, []string{w.ID}, true, owner, true, log)
+ client, err := workspace.Get(ctx, workspace.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: []string{w.ID},
+ Owner: owner,
+ LocalOnly: true,
+ Log: log,
+ })
if err != nil {
- log.WithFields(logrus.Fields{
- "workspaceId": w.ID,
- "err": err,
- })
- log.Error("failed to get workspace")
+ log.Errorf("failed to get workspace: workspaceId=%s, err=%v", w.ID, err)
return
}
// delete workspace folder
- err = clientimplementation.DeleteWorkspaceFolder(clientimplementation.DeleteWorkspaceFolderParams{
- Context: devPodConfig.DefaultContext,
- WorkspaceID: client.Workspace(),
- SSHConfigPath: client.WorkspaceConfig().SSHConfigPath,
- SSHConfigIncludePath: client.WorkspaceConfig().SSHConfigIncludePath,
- }, log)
+ err = clientimplementation.DeleteWorkspaceFolder(
+ clientimplementation.DeleteWorkspaceFolderParams{
+ Context: devPodConfig.DefaultContext,
+ WorkspaceID: client.Workspace(),
+ SSHConfigPath: client.WorkspaceConfig().SSHConfigPath,
+ SSHConfigIncludePath: client.WorkspaceConfig().SSHConfigIncludePath,
+ },
+ log,
+ )
if err != nil {
- log.WithFields(logrus.Fields{
- "workspaceId": w.ID,
- "err": err,
- })
- log.Error("failed to remove workspace")
+ log.Errorf("failed to remove workspace: workspaceId=%s, err=%v", w.ID, err)
return
}
- log.WithFields(logrus.Fields{
- "workspaceId": w.ID,
- })
- log.Done("removed workspace")
+ log.Donef("removed workspace: workspaceId=%s", w.ID)
}(*w)
}
- log.WithFields(logrus.Fields{
- "count": len(usedWorkspaces),
- })
- log.Info("cleaning up local workspaces")
+ log.Infof("cleaning up local workspaces: count=%v", len(usedWorkspaces))
wg.Wait()
}
}
func waitDaemonStopped(ctx context.Context, providerName string) error {
- return wait.PollUntilContextTimeout(ctx, 250*time.Millisecond, 5*time.Second, true, func(ctx context.Context) (done bool, err error) {
- _, err = daemon.Dial(daemon.GetSocketAddr(providerName))
- if err != nil {
- return true, nil
- }
-
- return false, nil
- })
+ return wait.PollUntilContextTimeout(
+ ctx,
+ 250*time.Millisecond,
+ 5*time.Second,
+ true,
+ func(ctx context.Context) (done bool, err error) {
+ _, err = daemon.Dial(daemon.GetSocketAddr(providerName))
+ if err != nil {
+ return true, nil
+ }
+
+ return false, nil
+ },
+ )
}
diff --git a/cmd/pro/flags/flags.go b/cmd/pro/flags/flags.go
index c57767a551..cfb0337985 100644
--- a/cmd/pro/flags/flags.go
+++ b/cmd/pro/flags/flags.go
@@ -6,18 +6,23 @@ import (
flag "github.com/spf13/pflag"
)
-// GlobalFlags is the flags that contains the global flags
+// GlobalFlags is the flags that contains the global flags.
type GlobalFlags struct {
*flags.GlobalFlags
Config string
}
-// SetGlobalFlags applies the global flags
+// SetGlobalFlags applies the global flags.
func SetGlobalFlags(flags *flag.FlagSet) *GlobalFlags {
globalFlags := &GlobalFlags{}
- flags.StringVar(&globalFlags.Config, "config", client.DefaultCacheConfig, "The config to use (will be created if it does not exist)")
+ flags.StringVar(
+ &globalFlags.Config,
+ "config",
+ client.DefaultCacheConfig,
+ "The config to use (will be created if it does not exist)",
+ )
return globalFlags
}
diff --git a/cmd/pro/import_workspace.go b/cmd/pro/import_workspace.go
index e9a8c715e9..967f9c122f 100644
--- a/cmd/pro/import_workspace.go
+++ b/cmd/pro/import_workspace.go
@@ -5,7 +5,8 @@ import (
"fmt"
"strconv"
- "github.com/sirupsen/logrus"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/cmd/pro/provider/list"
"github.com/skevetter/devpod/pkg/config"
@@ -20,9 +21,6 @@ import (
"github.com/skevetter/log"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
-
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
)
type ImportCmd struct {
@@ -36,7 +34,7 @@ type ImportCmd struct {
log log.Logger
}
-// NewImportCmd creates a new command
+// NewImportCmd creates a new command.
func NewImportCmd(globalFlags *proflags.GlobalFlags) *cobra.Command {
logger := log.GetInstance()
cmd := &ImportCmd{
@@ -53,9 +51,12 @@ func NewImportCmd(globalFlags *proflags.GlobalFlags) *cobra.Command {
}
importCmd.Flags().StringVar(&cmd.WorkspaceId, "workspace-id", "", "ID of a workspace to import")
- importCmd.Flags().StringVar(&cmd.WorkspaceUid, "workspace-uid", "", "UID of a workspace to import")
- importCmd.Flags().StringVar(&cmd.WorkspaceProject, "workspace-project", "", "Project of the workspace to import")
- importCmd.Flags().BoolVar(&cmd.Own, "own", false, "If true, will behave as if workspace was not imported")
+ importCmd.Flags().
+ StringVar(&cmd.WorkspaceUid, "workspace-uid", "", "UID of a workspace to import")
+ importCmd.Flags().
+ StringVar(&cmd.WorkspaceProject, "workspace-project", "", "Project of the workspace to import")
+ importCmd.Flags().
+ BoolVar(&cmd.Own, "own", false, "If true, will behave as if workspace was not imported")
_ = importCmd.MarkFlagRequired("workspace-uid")
return importCmd
}
@@ -78,7 +79,10 @@ func (cmd *ImportCmd) Run(ctx context.Context, args []string) error {
// check if workspace already exists
if provider2.WorkspaceExists(devPodConfig.DefaultContext, cmd.WorkspaceId) {
- workspaceConfig, err := provider2.LoadWorkspaceConfig(devPodConfig.DefaultContext, cmd.WorkspaceId)
+ workspaceConfig, err := provider2.LoadWorkspaceConfig(
+ devPodConfig.DefaultContext,
+ cmd.WorkspaceId,
+ )
if err != nil {
return fmt.Errorf("load workspace: %w", err)
} else if workspaceConfig.UID == cmd.WorkspaceUid {
@@ -91,12 +95,13 @@ func (cmd *ImportCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("workspace %s already exists", cmd.WorkspaceId)
}
- cmd.log.WithFields(logrus.Fields{
- "existingWorkspaceId": cmd.WorkspaceId,
- "existingWorkspaceUid": workspaceConfig.UID,
- "newWorkspaceId": newWorkspaceId,
- }).
- Infof("workspace ID conflict, will import workspace with new ID")
+ cmd.log.Infof(
+ "workspace ID conflict, will import workspace with new ID: "+
+ "existingWorkspaceId=%s, existingWorkspaceUid=%s, newWorkspaceId=%s",
+ cmd.WorkspaceId,
+ workspaceConfig.UID,
+ newWorkspaceId,
+ )
cmd.WorkspaceId = newWorkspaceId
}
@@ -109,7 +114,8 @@ func (cmd *ImportCmd) Run(ctx context.Context, args []string) error {
if err != nil {
return fmt.Errorf("base client: %w", err)
}
- instance, err := platform.FindInstanceInProject(ctx, baseClient, cmd.WorkspaceUid, cmd.WorkspaceProject)
+ opts := platform.FindInstanceOptions{UID: cmd.WorkspaceUid, ProjectName: cmd.WorkspaceProject}
+ instance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return fmt.Errorf("find workspace instance: %w", err)
}
@@ -128,9 +134,7 @@ func (cmd *ImportCmd) Run(ctx context.Context, args []string) error {
if err != nil {
return fmt.Errorf("prepare workspace to import definition: %w", err)
}
- cmd.log.WithFields(logrus.Fields{
- "workspaceId": cmd.WorkspaceId,
- }).Infof("imported workspace")
+ cmd.log.Infof("imported workspace: workspaceId=%s", cmd.WorkspaceId)
return nil
}
@@ -140,14 +144,16 @@ func (cmd *ImportCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("prepare workspace to import definition: %w", err)
}
- cmd.log.WithFields(logrus.Fields{
- "workspaceId": cmd.WorkspaceId,
- }).Infof("imported workspace")
+ cmd.log.Infof("imported workspace: workspaceId=%s", cmd.WorkspaceId)
return nil
}
-func (cmd *ImportCmd) writeNewWorkspaceDefinition(devPodConfig *config.Config, instance *managementv1.DevPodWorkspaceInstance, providerName string) error {
+func (cmd *ImportCmd) writeNewWorkspaceDefinition(
+ devPodConfig *config.Config,
+ instance *managementv1.DevPodWorkspaceInstance,
+ providerName string,
+) error {
workspaceObj := &provider2.Workspace{
ID: cmd.WorkspaceId,
UID: cmd.WorkspaceUid,
@@ -164,7 +170,12 @@ func (cmd *ImportCmd) writeNewWorkspaceDefinition(devPodConfig *config.Config, i
return provider2.SaveWorkspaceConfig(workspaceObj)
}
-func (cmd *ImportCmd) writeWorkspaceDefinition(devPodConfig *config.Config, provider *provider2.ProviderConfig, instanceOpts map[string]string, instance *managementv1.DevPodWorkspaceInstance) error {
+func (cmd *ImportCmd) writeWorkspaceDefinition(
+ devPodConfig *config.Config,
+ provider *provider2.ProviderConfig,
+ instanceOpts map[string]string,
+ instance *managementv1.DevPodWorkspaceInstance,
+) error {
workspaceObj := &provider2.Workspace{
ID: cmd.WorkspaceId,
UID: cmd.WorkspaceUid,
@@ -181,7 +192,16 @@ func (cmd *ImportCmd) writeWorkspaceDefinition(devPodConfig *config.Config, prov
},
}
- devPodConfig, err := options.ResolveOptions(context.Background(), devPodConfig, provider, instanceOpts, false, false, nil, cmd.log)
+ devPodConfig, err := options.ResolveOptions(
+ context.Background(),
+ devPodConfig,
+ provider,
+ instanceOpts,
+ false,
+ false,
+ nil,
+ cmd.log,
+ )
if err != nil {
return fmt.Errorf("resolve options: %w", err)
}
@@ -198,7 +218,11 @@ func (cmd *ImportCmd) writeWorkspaceDefinition(devPodConfig *config.Config, prov
return nil
}
-func resolveInstanceOptions(ctx context.Context, instance *managementv1.DevPodWorkspaceInstance, baseClient client.Client) (map[string]string, error) {
+func resolveInstanceOptions(
+ ctx context.Context,
+ instance *managementv1.DevPodWorkspaceInstance,
+ baseClient client.Client,
+) (map[string]string, error) {
opts := map[string]string{}
projectName := project.ProjectFromNamespace(instance.Namespace)
@@ -223,13 +247,21 @@ func resolveInstanceOptions(ctx context.Context, instance *managementv1.DevPodWo
if err != nil {
return nil, fmt.Errorf("get management client: %w", err)
}
- template, err := list.FindTemplate(ctx, managementClient, projectName, instance.Spec.TemplateRef.Name)
+ template, err := list.FindTemplate(
+ ctx,
+ managementClient,
+ projectName,
+ instance.Spec.TemplateRef.Name,
+ )
if err != nil {
return nil, fmt.Errorf("find template: %w", err)
}
templateParameters := template.Spec.Parameters
if len(template.Spec.Versions) > 0 {
- templateParameters, err = list.GetTemplateParameters(template, instance.Spec.TemplateRef.Version)
+ templateParameters, err = list.GetTemplateParameters(
+ template,
+ instance.Spec.TemplateRef.Version,
+ )
if err != nil {
return nil, fmt.Errorf("get template parameters: %w", err)
}
@@ -242,7 +274,11 @@ func resolveInstanceOptions(ctx context.Context, instance *managementv1.DevPodWo
return opts, nil
}
-func fillParameterOptions(opts map[string]string, parameterDefinitions []storagev1.AppParameter, instanceParameters string) error {
+func fillParameterOptions(
+ opts map[string]string,
+ parameterDefinitions []storagev1.AppParameter,
+ instanceParameters string,
+) error {
parametersMap := map[string]any{}
err := yaml.Unmarshal([]byte(instanceParameters), ¶metersMap)
if err != nil {
@@ -261,7 +297,12 @@ func fillParameterOptions(opts map[string]string, parameterDefinitions []storage
case bool:
strVal = strconv.FormatBool(t)
default:
- return fmt.Errorf("unrecognized type for parameter %s (%s) in file: %v", parameter.Label, parameter.Variable, t)
+ return fmt.Errorf(
+ "unrecognized type for parameter %s (%s) in file: %v",
+ parameter.Label,
+ parameter.Variable,
+ t,
+ )
}
}
diff --git a/cmd/pro/list.go b/cmd/pro/list.go
index ca7311715c..aef2f18099 100644
--- a/cmd/pro/list.go
+++ b/cmd/pro/list.go
@@ -10,13 +10,13 @@ import (
proflags "github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/provider"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
- "github.com/skevetter/log/table"
"github.com/spf13/cobra"
)
-// ListCmd holds the list cmd flags
+// ListCmd holds the list cmd flags.
type ListCmd struct {
proflags.GlobalFlags
@@ -24,7 +24,7 @@ type ListCmd struct {
Login bool
}
-// NewListCmd creates a new command
+// NewListCmd creates a new command.
func NewListCmd(flags *proflags.GlobalFlags) *cobra.Command {
cmd := &ListCmd{
GlobalFlags: *flags,
@@ -34,17 +34,19 @@ func NewListCmd(flags *proflags.GlobalFlags) *cobra.Command {
Aliases: []string{"ls"},
Short: "List available DevPod Pro instances",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- listCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
- listCmd.Flags().BoolVar(&cmd.Login, "login", false, "Check if the user is logged into the pro instance")
+ listCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ listCmd.Flags().
+ BoolVar(&cmd.Login, "login", false, "Check if the user is logged into the pro instance")
return listCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ListCmd) Run(ctx context.Context) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -85,14 +87,14 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
tableHeaders = append(tableHeaders, "Authenticated")
}
- table.PrintTable(log.Default, tableHeaders, tableEntries)
+ table.Print(tableHeaders, tableEntries)
case "json":
tableEntries := []*proTableEntry{}
for _, proInstance := range proInstances {
entry := &proTableEntry{
ProInstance: proInstance,
Context: devPodConfig.DefaultContext,
- Capabilities: getCapabilities(ctx, devPodConfig, proInstance, log.Discard),
+ Capabilities: getCapabilities(devPodConfig, proInstance, log.Discard),
}
if cmd.Login {
err = checkLogin(ctx, devPodConfig, proInstance)
@@ -112,7 +114,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
@@ -134,16 +139,33 @@ var (
capabilityUpdateProvider Capability = "update-provider"
)
-func checkLogin(ctx context.Context, devPodConfig *config.Config, proInstance *provider.ProInstance) error {
+func checkLogin(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ proInstance *provider.ProInstance,
+) error {
// for every pro instance, check auth status by calling login
- if err := login(ctx, devPodConfig, proInstance.Host, proInstance.Provider, "", true, false, log.Default); err != nil {
+ if err := login(
+ ctx,
+ devPodConfig,
+ proInstance.Host,
+ proInstance.Provider,
+ "",
+ true,
+ false,
+ log.Default,
+ ); err != nil {
return fmt.Errorf("not logged into %s", proInstance.Host)
}
return nil
}
-func getCapabilities(ctx context.Context, devPodConfig *config.Config, proInstance *provider.ProInstance, log log.Logger) []Capability {
+func getCapabilities(
+ devPodConfig *config.Config,
+ proInstance *provider.ProInstance,
+ log log.Logger,
+) []Capability {
capabilities := []Capability{}
provider, err := workspace.FindProvider(devPodConfig, proInstance.Provider, log)
if err != nil {
diff --git a/cmd/pro/list_clusters.go b/cmd/pro/list_clusters.go
index 2221987c69..a8cfdf4d16 100644
--- a/cmd/pro/list_clusters.go
+++ b/cmd/pro/list_clusters.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// ListClustersCmd holds the cmd flags
+// ListClustersCmd holds the cmd flags.
type ListClustersCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -24,7 +24,7 @@ type ListClustersCmd struct {
Project string
}
-// NewListClustersCmd creates a new command
+// NewListClustersCmd creates a new command.
func NewListClustersCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &ListClustersCmd{
GlobalFlags: globalFlags,
@@ -35,7 +35,13 @@ func NewListClustersCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "List clusters",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -52,7 +58,11 @@ func NewListClustersCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *ListClustersCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *ListClustersCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
opts := devPodConfig.ProviderOptions(provider.Name)
opts[platform.ProjectEnv] = config.OptionValue{Value: cmd.Project}
diff --git a/cmd/pro/list_projects.go b/cmd/pro/list_projects.go
index 7d6b736695..107822df4b 100644
--- a/cmd/pro/list_projects.go
+++ b/cmd/pro/list_projects.go
@@ -14,7 +14,7 @@ import (
"github.com/spf13/cobra"
)
-// ListProjectsCmd holds the cmd flags
+// ListProjectsCmd holds the cmd flags.
type ListProjectsCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -22,7 +22,7 @@ type ListProjectsCmd struct {
Host string
}
-// NewListProjectsCmd creates a new command
+// NewListProjectsCmd creates a new command.
func NewListProjectsCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &ListProjectsCmd{
GlobalFlags: globalFlags,
@@ -33,7 +33,13 @@ func NewListProjectsCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "List projects",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -48,7 +54,11 @@ func NewListProjectsCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *ListProjectsCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *ListProjectsCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
var buf bytes.Buffer
// ignore --debug because we tunnel json through stdio
cmd.Log.SetLevel(logrus.InfoLevel)
diff --git a/cmd/pro/list_templates.go b/cmd/pro/list_templates.go
index dd5ac61ebd..ca05736f79 100644
--- a/cmd/pro/list_templates.go
+++ b/cmd/pro/list_templates.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// ListTemplatesCmd holds the cmd flags
+// ListTemplatesCmd holds the cmd flags.
type ListTemplatesCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -24,7 +24,7 @@ type ListTemplatesCmd struct {
Project string
}
-// NewListTemplatesCmd creates a new command
+// NewListTemplatesCmd creates a new command.
func NewListTemplatesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &ListTemplatesCmd{
GlobalFlags: globalFlags,
@@ -35,7 +35,13 @@ func NewListTemplatesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "List templates",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -52,7 +58,11 @@ func NewListTemplatesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *ListTemplatesCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *ListTemplatesCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
opts := devPodConfig.ProviderOptions(provider.Name)
opts[platform.ProjectEnv] = config.OptionValue{Value: cmd.Project}
diff --git a/cmd/pro/list_workspaces.go b/cmd/pro/list_workspaces.go
index 460dd8c2cf..824d7f4800 100644
--- a/cmd/pro/list_workspaces.go
+++ b/cmd/pro/list_workspaces.go
@@ -14,7 +14,7 @@ import (
"github.com/spf13/cobra"
)
-// ListWorkspacesCmd holds the cmd flags
+// ListWorkspacesCmd holds the cmd flags.
type ListWorkspacesCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -22,7 +22,7 @@ type ListWorkspacesCmd struct {
Host string
}
-// NewListWorkspacesCmd creates a new command
+// NewListWorkspacesCmd creates a new command.
func NewListWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &ListWorkspacesCmd{
GlobalFlags: globalFlags,
@@ -33,7 +33,13 @@ func NewListWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "List Workspaces",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -48,7 +54,11 @@ func NewListWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *ListWorkspacesCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *ListWorkspacesCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
var buf bytes.Buffer
// ignore --debug because we tunnel json through stdio
cmd.Log.SetLevel(logrus.InfoLevel)
diff --git a/cmd/pro/login.go b/cmd/pro/login.go
index 2ae28d723d..0691406733 100644
--- a/cmd/pro/login.go
+++ b/cmd/pro/login.go
@@ -7,7 +7,6 @@ import (
"strings"
"github.com/blang/semver/v4"
- "github.com/sirupsen/logrus"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
providercmd "github.com/skevetter/devpod/cmd/provider"
"github.com/skevetter/devpod/pkg/config"
@@ -21,10 +20,11 @@ import (
"github.com/spf13/cobra"
)
-const PROVIDER_BINARY = "PRO_PROVIDER"
-const providerRepo = "skevetter/devpod"
+const (
+ PROVIDER_BINARY = "PRO_PROVIDER"
+)
-// LoginCmd holds the login cmd flags
+// LoginCmd holds the login cmd flags.
type LoginCmd struct {
proflags.GlobalFlags
@@ -40,7 +40,7 @@ type LoginCmd struct {
ForceBrowser bool
}
-// NewLoginCmd creates a new command
+// NewLoginCmd creates a new command.
func NewLoginCmd(flags *proflags.GlobalFlags) *cobra.Command {
cmd := &LoginCmd{
GlobalFlags: *flags,
@@ -48,29 +48,39 @@ func NewLoginCmd(flags *proflags.GlobalFlags) *cobra.Command {
loginCmd := &cobra.Command{
Use: "login",
Short: "Log into a DevPod Pro instance",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
- return fmt.Errorf("please specify the DevPod Pro host, e.g. devpod pro login my-pro.my-domain.com")
+ return fmt.Errorf(
+ "please specify the DevPod Pro host, e.g. devpod pro login my-pro.my-domain.com",
+ )
}
- return cmd.Run(context.Background(), args[0], log.Default)
+ return cmd.Run(cobraCmd.Context(), args[0], log.Default)
},
}
- loginCmd.Flags().StringVar(&cmd.AccessKey, "access-key", "", "If defined will use the given access key to login")
- loginCmd.Flags().BoolVar(&cmd.Login, "login", true, "If enabled will automatically try to log into the Loft DevPod Pro")
- loginCmd.Flags().BoolVar(&cmd.Use, "use", true, "If enabled will automatically activate the provider")
- loginCmd.Flags().StringVar(&cmd.Provider, "provider", "", "Optional name how the DevPod Pro provider will be named")
- loginCmd.Flags().StringVar(&cmd.Version, "version", "", "The version to use for the DevPod provider")
- loginCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
- loginCmd.Flags().BoolVar(&cmd.ForceBrowser, "force-browser", false, "Force login through browser")
-
- loginCmd.Flags().StringVar(&cmd.ProviderSource, "provider-source", "", "The source of the provider")
+ loginCmd.Flags().
+ StringVar(&cmd.AccessKey, "access-key", "", "If defined will use the given access key to login")
+ loginCmd.Flags().
+ BoolVar(&cmd.Login, "login", true, "If enabled will automatically try to log into the Loft DevPod Pro")
+ loginCmd.Flags().
+ BoolVar(&cmd.Use, "use", true, "If enabled will automatically activate the provider")
+ loginCmd.Flags().
+ StringVar(&cmd.Provider, "provider", "", "Optional name how the DevPod Pro provider will be named")
+ loginCmd.Flags().
+ StringVar(&cmd.Version, "version", "", "The version to use for the DevPod provider")
+ loginCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
+ loginCmd.Flags().
+ BoolVar(&cmd.ForceBrowser, "force-browser", false, "Force login through browser")
+
+ loginCmd.Flags().
+ StringVar(&cmd.ProviderSource, "provider-source", "", "The source of the provider")
_ = loginCmd.Flags().MarkHidden("provider-source")
return loginCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *LoginCmd) Run(ctx context.Context, fullURL string, log log.Logger) error {
if strings.HasPrefix(fullURL, "http://") {
return fmt.Errorf("http is not supported for DevPod Pro, please use https:// instead")
@@ -114,7 +124,7 @@ func (cmd *LoginCmd) Run(ctx context.Context, fullURL string, log log.Logger) er
} else {
// find a provider name
if cmd.Provider == "" {
- cmd.Provider = "devpod-pro"
+ cmd.Provider = config.ProReleaseName
}
cmd.Provider = provider.ToProInstanceID(cmd.Provider)
@@ -127,9 +137,12 @@ func (cmd *LoginCmd) Run(ctx context.Context, fullURL string, log log.Logger) er
// provider already exists?
if providers[cmd.Provider] != nil {
// alternative name
- cmd.Provider = provider.ToProInstanceID("devpod-" + host)
+ cmd.Provider = provider.ToProInstanceID(config.BinaryName + "-" + host)
if providers[cmd.Provider] != nil {
- return fmt.Errorf("provider %s already exists, please choose a different name via --provider", cmd.Provider)
+ return fmt.Errorf(
+ "provider %s already exists, please choose a different name via --provider",
+ cmd.Provider,
+ )
}
}
}
@@ -150,7 +163,8 @@ func (cmd *LoginCmd) Run(ctx context.Context, fullURL string, log log.Logger) er
if err != nil {
return fmt.Errorf("invalid version %s: %w", remoteVersion, err)
}
- if rv.LT(semver.Version{Major: 0, Minor: 6, Patch: 999}) && remoteVersion != versionpkg.DevVersion {
+ if rv.LT(semver.Version{Major: 0, Minor: 6, Patch: 999}) &&
+ remoteVersion != versionpkg.DevVersion {
log.Debug("remote version < 0.7.0, installing proxy provider")
// proxy providers are deprecated and shouldn't be used
// unless explicitly the server version is below 0.7.0
@@ -186,18 +200,35 @@ func (cmd *LoginCmd) Run(ctx context.Context, fullURL string, log log.Logger) er
// 2. Login to Loft
if cmd.Login {
- err = login(ctx, devPodConfig, fullURL, cmd.Provider, cmd.AccessKey, false, cmd.ForceBrowser, log)
+ err = login(
+ ctx,
+ devPodConfig,
+ fullURL,
+ cmd.Provider,
+ cmd.AccessKey,
+ false,
+ cmd.ForceBrowser,
+ log,
+ )
if err != nil {
return err
}
- log.WithFields(logrus.Fields{
- "url": fullURL,
- }).Done("logged into DevPod Pro instance")
+ log.Donef("logged into DevPod Pro instance: url=%s", fullURL)
}
// 3. Configure provider
if cmd.Use {
- err := providercmd.ConfigureProvider(ctx, providerConfig, devPodConfig.DefaultContext, cmd.Options, false, false, false, nil, log)
+ err := providercmd.ConfigureProvider(ctx, providercmd.ProviderOptionsConfig{
+ Provider: providerConfig,
+ Context: devPodConfig.DefaultContext,
+ UserOptions: cmd.Options,
+ Reconfigure: false,
+ SkipRequired: false,
+ SkipInit: false,
+ SkipSubOptions: false,
+ SingleMachine: nil,
+ Log: log,
+ })
if err != nil {
return fmt.Errorf("configure provider: %w", err)
}
@@ -207,7 +238,11 @@ func (cmd *LoginCmd) Run(ctx context.Context, fullURL string, log log.Logger) er
return nil
}
-func (cmd *LoginCmd) addLoftProvider(devPodConfig *config.Config, url string, log log.Logger) error {
+func (cmd *LoginCmd) addLoftProvider(
+ devPodConfig *config.Config,
+ url string,
+ log log.Logger,
+) error {
// find out loft version
err := cmd.resolveProviderSource(url)
if err != nil {
@@ -218,7 +253,7 @@ func (cmd *LoginCmd) addLoftProvider(devPodConfig *config.Config, url string, lo
log.Infof("Add DevPod Pro provider...")
// is development?
- if cmd.ProviderSource == providerRepo+"@v0.0.0" {
+ if cmd.ProviderSource == config.RepoSlug+"@v0.0.0" {
log.Debugf("Add development provider")
_, err = workspace.AddProviderRaw(workspace.ProviderParams{
DevPodConfig: devPodConfig,
@@ -245,7 +280,7 @@ func (cmd *LoginCmd) resolveProviderSource(url string) error {
return nil
}
if cmd.Version != "" {
- cmd.ProviderSource = providerRepo + "@" + cmd.Version
+ cmd.ProviderSource = config.RepoSlug + "@" + cmd.Version
return nil
}
@@ -253,12 +288,20 @@ func (cmd *LoginCmd) resolveProviderSource(url string) error {
if err != nil {
return fmt.Errorf("get version: %w", err)
}
- cmd.ProviderSource = providerRepo + "@" + version
+ cmd.ProviderSource = config.RepoSlug + "@" + version
return nil
}
-func login(ctx context.Context, devPodConfig *config.Config, url string, providerName string, accessKey string, skipBrowserLogin, forceBrowser bool, log log.Logger) error {
+func login(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ url string,
+ providerName string,
+ accessKey string,
+ skipBrowserLogin, forceBrowser bool,
+ log log.Logger,
+) error {
configPath, err := platform.LoftConfigPath(devPodConfig.DefaultContext, providerName)
if err != nil {
return err
@@ -278,6 +321,9 @@ func login(ctx context.Context, devPodConfig *config.Config, url string, provide
// log in
url = strings.TrimSuffix(url, "/")
+ if err := ctx.Err(); err != nil {
+ return err
+ }
if accessKey != "" && !forceBrowser {
err = loader.LoginWithAccessKey(url, accessKey, true, true)
} else {
diff --git a/cmd/pro/pro.go b/cmd/pro/pro.go
index 13c1c72c0d..66fcf4f464 100644
--- a/cmd/pro/pro.go
+++ b/cmd/pro/pro.go
@@ -19,7 +19,7 @@ import (
"github.com/spf13/cobra"
)
-// NewProCmd returns a new command
+// NewProCmd returns a new command.
func NewProCmd(flags *flags.GlobalFlags, streamLogger *log.StreamLogger) *cobra.Command {
globalFlags := &proflags.GlobalFlags{GlobalFlags: flags}
proCmd := &cobra.Command{
@@ -37,7 +37,7 @@ func NewProCmd(flags *flags.GlobalFlags, streamLogger *log.StreamLogger) *cobra.
streamLogger.SetLevel(logrus.DebugLevel)
}
- if os.Getenv("DEVPOD_DEBUG") == "true" {
+ if os.Getenv(config.EnvDebug) == config.BoolTrue {
log.Default.SetLevel(logrus.DebugLevel)
}
if flags.LogOutput == "json" {
@@ -75,7 +75,11 @@ func NewProCmd(flags *flags.GlobalFlags, streamLogger *log.StreamLogger) *cobra.
return proCmd
}
-func findProProvider(ctx context.Context, context, provider, host string, log log.Logger) (*config.Config, *providerpkg.ProviderConfig, error) {
+func findProProvider(
+ ctx context.Context,
+ context, provider, host string,
+ log log.Logger,
+) (*config.Config, *providerpkg.ProviderConfig, error) {
devPodConfig, err := config.LoadConfig(context, provider)
if err != nil {
return nil, nil, err
diff --git a/cmd/pro/provider/create/create.go b/cmd/pro/provider/create/create.go
index 300077d057..e3711b35c6 100644
--- a/cmd/pro/provider/create/create.go
+++ b/cmd/pro/provider/create/create.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewCmd creates a new cobra command
+// NewCmd creates a new cobra command.
func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "create",
diff --git a/cmd/pro/provider/create/workspace.go b/cmd/pro/provider/create/workspace.go
index 3da85797a0..4dc12e0447 100644
--- a/cmd/pro/provider/create/workspace.go
+++ b/cmd/pro/provider/create/workspace.go
@@ -7,8 +7,9 @@ import (
"io"
"os"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/platform/form"
@@ -20,14 +21,14 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
-// WorkspaceCmd holds the cmd flags
+// WorkspaceCmd holds the cmd flags.
type WorkspaceCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewWorkspaceCmd creates a new command
+// NewWorkspaceCmd creates a new command.
func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WorkspaceCmd{
GlobalFlags: globalFlags,
@@ -46,7 +47,12 @@ func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *WorkspaceCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
@@ -76,16 +82,25 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wri
}
// Info through env, right now only used by CLI
- workspaceID := os.Getenv(provider.WORKSPACE_ID)
- workspaceUID := os.Getenv(provider.WORKSPACE_UID)
- workspaceFolder := os.Getenv(provider.WORKSPACE_FOLDER)
- workspaceContext := os.Getenv(provider.WORKSPACE_CONTEXT)
+ workspaceID := os.Getenv(config.EnvProviderWorkspaceID)
+ workspaceUID := os.Getenv(config.EnvProviderWorkspaceUID)
+ workspaceFolder := os.Getenv(config.EnvProviderWorkspaceFolder)
+ workspaceContext := os.Getenv(config.EnvProviderWorkspaceContext)
workspacePicture := os.Getenv(platform.WorkspacePictureEnv)
workspaceSource := os.Getenv(platform.WorkspaceSourceEnv)
if workspaceUID == "" || workspaceID == "" || workspaceFolder == "" {
- return fmt.Errorf("workspaceID, workspaceUID or workspace folder not found: %s, %s, %s", workspaceID, workspaceUID, workspaceFolder)
+ return fmt.Errorf(
+ "workspaceID, workspaceUID or workspace folder not found: %s, %s, %s",
+ workspaceID,
+ workspaceUID,
+ workspaceFolder,
+ )
}
- instance, err := platform.FindInstance(ctx, baseClient, workspaceUID)
+ instance, err := platform.FindInstance(
+ ctx,
+ baseClient,
+ platform.FindInstanceOptions{UID: workspaceUID},
+ )
if err != nil {
return err
}
@@ -97,7 +112,15 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wri
return fmt.Errorf("unable to create new instance through CLI if stdin is not a terminal")
}
- instance, err = form.CreateInstance(ctx, baseClient, workspaceID, workspaceUID, workspaceSource, workspacePicture, cmd.Log)
+ instance, err = form.CreateInstance(
+ ctx,
+ baseClient,
+ workspaceID,
+ workspaceUID,
+ workspaceSource,
+ workspacePicture,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -127,7 +150,12 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wri
return nil
}
-func createInstance(ctx context.Context, client client.Client, instance *managementv1.DevPodWorkspaceInstance, log log.Logger) (*managementv1.DevPodWorkspaceInstance, error) {
+func createInstance(
+ ctx context.Context,
+ client client.Client,
+ instance *managementv1.DevPodWorkspaceInstance,
+ log log.Logger,
+) (*managementv1.DevPodWorkspaceInstance, error) {
managementClient, err := client.Management()
if err != nil {
return nil, err
diff --git a/cmd/pro/provider/delete.go b/cmd/pro/provider/delete.go
index d67ee01511..6b5c6889ae 100644
--- a/cmd/pro/provider/delete.go
+++ b/cmd/pro/provider/delete.go
@@ -14,14 +14,14 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
-// DeleteCmd holds the cmd flags
+// DeleteCmd holds the cmd flags.
type DeleteCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewDeleteCmd creates a new command
+// NewDeleteCmd creates a new command.
func NewDeleteCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: globalFlags,
@@ -40,7 +40,12 @@ func NewDeleteCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *DeleteCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *DeleteCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
@@ -50,7 +55,8 @@ func (cmd *DeleteCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer
if err != nil {
return err
}
- workspace, err := platform.FindInstanceInProject(ctx, baseClient, info.UID, info.ProjectName)
+ opts := platform.FindInstanceOptions{UID: info.UID, ProjectName: info.ProjectName}
+ workspace, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
} else if workspace == nil {
@@ -62,7 +68,10 @@ func (cmd *DeleteCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer
return err
}
- err = managementClient.Loft().ManagementV1().DevPodWorkspaceInstances(workspace.Namespace).Delete(ctx, workspace.Name, metav1.DeleteOptions{})
+ err = managementClient.Loft().
+ ManagementV1().
+ DevPodWorkspaceInstances(workspace.Namespace).
+ Delete(ctx, workspace.Name, metav1.DeleteOptions{})
if err != nil {
return fmt.Errorf("delete workspace: %w", err)
}
diff --git a/cmd/pro/provider/get/get.go b/cmd/pro/provider/get/get.go
index d5daa2ad53..1b67a71129 100644
--- a/cmd/pro/provider/get/get.go
+++ b/cmd/pro/provider/get/get.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewCmd creates a new cobra command
+// NewCmd creates a new cobra command.
func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "get",
diff --git a/cmd/pro/provider/get/self.go b/cmd/pro/provider/get/self.go
index f291be6d54..e59d4c696e 100644
--- a/cmd/pro/provider/get/self.go
+++ b/cmd/pro/provider/get/self.go
@@ -13,14 +13,14 @@ import (
"github.com/spf13/cobra"
)
-// SelfCmd holds the cmd flags
+// SelfCmd holds the cmd flags.
type SelfCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewSelfCmd creates a new command
+// NewSelfCmd creates a new command.
func NewSelfCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &SelfCmd{
GlobalFlags: globalFlags,
@@ -38,7 +38,12 @@ func NewSelfCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *SelfCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *SelfCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
diff --git a/cmd/pro/provider/get/version.go b/cmd/pro/provider/get/version.go
index ea34e1380a..d5a6656c37 100644
--- a/cmd/pro/provider/get/version.go
+++ b/cmd/pro/provider/get/version.go
@@ -16,7 +16,7 @@ import (
"github.com/spf13/cobra"
)
-// VersionCmd holds the cmd flags
+// VersionCmd holds the cmd flags.
type VersionCmd struct {
*flags.GlobalFlags
@@ -34,7 +34,7 @@ type VersionInfo struct {
CurrentProviderVersion string `json:"currentProviderVersion,omitempty"`
}
-// NewVersionCmd creates a new command
+// NewVersionCmd creates a new command.
func NewVersionCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &VersionCmd{
GlobalFlags: globalFlags,
@@ -52,19 +52,24 @@ func NewVersionCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *VersionCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *VersionCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
}
- providerContext := os.Getenv(provider.PROVIDER_CONTEXT)
+ providerContext := os.Getenv(config.EnvProviderContext)
if providerContext == "" {
providerContext = config.DefaultContext
}
- providerID := os.Getenv(provider.PROVIDER_ID)
+ providerID := os.Getenv(config.EnvProviderID)
if providerID == "" {
- return fmt.Errorf("provider ID %s not defined", providerID)
+ return fmt.Errorf("provider ID env var %s not defined", config.EnvProviderID)
}
// get our own version
diff --git a/cmd/pro/provider/get/workspace.go b/cmd/pro/provider/get/workspace.go
index 0591b83a56..80a9855527 100644
--- a/cmd/pro/provider/get/workspace.go
+++ b/cmd/pro/provider/get/workspace.go
@@ -12,14 +12,14 @@ import (
"github.com/spf13/cobra"
)
-// WorkspaceCmd holds the cmd flags
+// WorkspaceCmd holds the cmd flags.
type WorkspaceCmd struct {
*flags.GlobalFlags
log log.Logger
}
-// NewWorkspaceCmd creates a new command
+// NewWorkspaceCmd creates a new command.
func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WorkspaceCmd{
GlobalFlags: globalFlags,
@@ -48,7 +48,11 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context) error {
return err
}
- instance, err := platform.FindInstanceInProject(ctx, baseClient, workspaceInfo.UID, workspaceInfo.ProjectName)
+ opts := platform.FindInstanceOptions{
+ UID: workspaceInfo.UID,
+ ProjectName: workspaceInfo.ProjectName,
+ }
+ instance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
}
diff --git a/cmd/pro/provider/health.go b/cmd/pro/provider/health.go
index 095071b305..6674748ba8 100644
--- a/cmd/pro/provider/health.go
+++ b/cmd/pro/provider/health.go
@@ -16,14 +16,14 @@ import (
"github.com/spf13/cobra"
)
-// HealthCmd holds the cmd flags
+// HealthCmd holds the cmd flags.
type HealthCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewHealthCmd creates a new command
+// NewHealthCmd creates a new command.
func NewHealthCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &HealthCmd{
GlobalFlags: globalFlags,
@@ -42,7 +42,12 @@ func NewHealthCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *HealthCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *HealthCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
diff --git a/cmd/pro/provider/list/clusters.go b/cmd/pro/provider/list/clusters.go
index a2f618417e..1aea8a5aed 100644
--- a/cmd/pro/provider/list/clusters.go
+++ b/cmd/pro/provider/list/clusters.go
@@ -6,7 +6,7 @@ import (
"fmt"
"os"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
@@ -15,14 +15,14 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
-// ClustersCmd holds the cmd flags
+// ClustersCmd holds the cmd flags.
type ClustersCmd struct {
*flags.GlobalFlags
log log.Logger
}
-// NewClustersCmd creates a new command
+// NewClustersCmd creates a new command.
func NewClustersCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &ClustersCmd{
GlobalFlags: globalFlags,
@@ -65,13 +65,20 @@ func (cmd *ClustersCmd) Run(ctx context.Context) error {
return nil
}
-func Clusters(ctx context.Context, client client.Client, projectName string) (*managementv1.ProjectClusters, error) {
+func Clusters(
+ ctx context.Context,
+ client client.Client,
+ projectName string,
+) (*managementv1.ProjectClusters, error) {
managementClient, err := client.Management()
if err != nil {
return nil, err
}
- clustersList, err := managementClient.Loft().ManagementV1().Projects().ListClusters(ctx, projectName, metav1.GetOptions{})
+ clustersList, err := managementClient.Loft().
+ ManagementV1().
+ Projects().
+ ListClusters(ctx, projectName, metav1.GetOptions{})
if err != nil {
return clustersList, fmt.Errorf("list clusters: %w", err)
}
diff --git a/cmd/pro/provider/list/list.go b/cmd/pro/provider/list/list.go
index d5512b55dc..058e8d2c13 100644
--- a/cmd/pro/provider/list/list.go
+++ b/cmd/pro/provider/list/list.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewCmd creates a new cobra command
+// NewCmd creates a new cobra command.
func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "list",
diff --git a/cmd/pro/provider/list/projects.go b/cmd/pro/provider/list/projects.go
index a1fdc0f731..c1419bea7d 100644
--- a/cmd/pro/provider/list/projects.go
+++ b/cmd/pro/provider/list/projects.go
@@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/log"
@@ -13,14 +13,14 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
-// ProjectsCmd holds the cmd flags
+// ProjectsCmd holds the cmd flags.
type ProjectsCmd struct {
*flags.GlobalFlags
log log.Logger
}
-// NewProjectsCmd creates a new command
+// NewProjectsCmd creates a new command.
func NewProjectsCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &ProjectsCmd{
GlobalFlags: globalFlags,
@@ -65,11 +65,16 @@ func Projects(ctx context.Context, client client.Client) (*managementv1.ProjectL
return nil, err
}
- projectList, err := managementClient.Loft().ManagementV1().Projects().List(ctx, metav1.ListOptions{})
+ projectList, err := managementClient.Loft().
+ ManagementV1().
+ Projects().
+ List(ctx, metav1.ListOptions{})
if err != nil {
return projectList, fmt.Errorf("list projects: %w", err)
} else if len(projectList.Items) == 0 {
- return projectList, fmt.Errorf("you don't have access to any projects, please make sure you have at least access to 1 project")
+ return projectList, fmt.Errorf(
+ "you don't have access to any projects, please make sure you have at least access to 1 project",
+ )
}
return projectList, nil
diff --git a/cmd/pro/provider/list/templates.go b/cmd/pro/provider/list/templates.go
index 90a339673d..649e0124de 100644
--- a/cmd/pro/provider/list/templates.go
+++ b/cmd/pro/provider/list/templates.go
@@ -10,6 +10,8 @@ import (
"strings"
"github.com/blang/semver/v4"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
@@ -17,19 +19,16 @@ import (
"github.com/skevetter/log"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
)
-// TemplatesCmd holds the cmd flags
+// TemplatesCmd holds the cmd flags.
type TemplatesCmd struct {
*flags.GlobalFlags
log log.Logger
}
-// NewTemplatesCmd creates a new command
+// NewTemplatesCmd creates a new command.
func NewTemplatesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &TemplatesCmd{
GlobalFlags: globalFlags,
@@ -72,28 +71,50 @@ func (cmd *TemplatesCmd) Run(ctx context.Context) error {
return nil
}
-func Templates(ctx context.Context, client client.Client, projectName string) (*managementv1.ProjectTemplates, error) {
+func Templates(
+ ctx context.Context,
+ client client.Client,
+ projectName string,
+) (*managementv1.ProjectTemplates, error) {
managementClient, err := client.Management()
if err != nil {
return nil, err
}
- templateList, err := managementClient.Loft().ManagementV1().Projects().ListTemplates(ctx, projectName, metav1.GetOptions{})
+ templateList, err := managementClient.Loft().
+ ManagementV1().
+ Projects().
+ ListTemplates(ctx, projectName, metav1.GetOptions{})
if err != nil {
return templateList, fmt.Errorf("list templates: %w", err)
} else if len(templateList.DevPodWorkspaceTemplates) == 0 {
- return templateList, fmt.Errorf("seems like there is no template allowed in project %s, please make sure to at least have a single template available", projectName)
+ return templateList, fmt.Errorf(
+ "seems like there is no template allowed in project %s, "+
+ "please make sure to at least have a single template available",
+ projectName,
+ )
}
return templateList, nil
}
-func FindTemplate(ctx context.Context, managementClient kube.Interface, projectName, templateName string) (*managementv1.DevPodWorkspaceTemplate, error) {
- templateList, err := managementClient.Loft().ManagementV1().Projects().ListTemplates(ctx, projectName, metav1.GetOptions{})
+func FindTemplate(
+ ctx context.Context,
+ managementClient kube.Interface,
+ projectName, templateName string,
+) (*managementv1.DevPodWorkspaceTemplate, error) {
+ templateList, err := managementClient.Loft().
+ ManagementV1().
+ Projects().
+ ListTemplates(ctx, projectName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("list templates: %w", err)
} else if len(templateList.DevPodWorkspaceTemplates) == 0 {
- return nil, fmt.Errorf("seems like there is no DevPod template allowed in project %s, please make sure to at least have a single template available", projectName)
+ return nil, fmt.Errorf(
+ "seems like there is no DevPod template allowed in project %s, "+
+ "please make sure to at least have a single template available",
+ projectName,
+ )
}
// find template
@@ -112,7 +133,10 @@ func FindTemplate(ctx context.Context, managementClient kube.Interface, projectN
return template, nil
}
-func GetTemplateParameters(template *managementv1.DevPodWorkspaceTemplate, templateVersion string) ([]storagev1.AppParameter, error) {
+func GetTemplateParameters(
+ template *managementv1.DevPodWorkspaceTemplate,
+ templateVersion string,
+) ([]storagev1.AppParameter, error) {
if templateVersion == "latest" {
templateVersion = ""
}
@@ -165,11 +189,17 @@ func GetLatestVersion(versions storagev1.VersionsAccessor) storagev1.VersionAcce
return latestVersion.Object
}
-func GetLatestMatchedVersion(versions storagev1.VersionsAccessor, versionPattern string) (latestVersion storagev1.VersionAccessor, latestMatchedVersion storagev1.VersionAccessor, err error) {
+func GetLatestMatchedVersion(
+ versions storagev1.VersionsAccessor,
+ versionPattern string,
+) (latestVersion storagev1.VersionAccessor, latestMatchedVersion storagev1.VersionAccessor, err error) {
// parse version
splittedVersion := strings.Split(strings.ToLower(strings.TrimPrefix(versionPattern, "v")), ".")
if len(splittedVersion) != 3 {
- return nil, nil, fmt.Errorf("couldn't parse version %s, expected version in format: 0.0.0", versionPattern)
+ return nil, nil, fmt.Errorf(
+ "couldn't parse version %s, expected version in format: 0.0.0",
+ versionPattern,
+ )
}
// find latest version that matches our defined version
diff --git a/cmd/pro/provider/list/workspaces.go b/cmd/pro/provider/list/workspaces.go
index 2447e6573f..ddf365218e 100644
--- a/cmd/pro/provider/list/workspaces.go
+++ b/cmd/pro/provider/list/workspaces.go
@@ -6,26 +6,26 @@ import (
"fmt"
"os"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/platform/labels"
"github.com/skevetter/devpod/pkg/platform/project"
- "github.com/skevetter/devpod/pkg/provider"
"github.com/skevetter/log"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
-// WorkspacesCmd holds the cmd flags
+// WorkspacesCmd holds the cmd flags.
type WorkspacesCmd struct {
*flags.GlobalFlags
log log.Logger
}
-// NewWorkspacesCmd creates a new command
+// NewWorkspacesCmd creates a new command.
func NewWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WorkspacesCmd{
GlobalFlags: globalFlags,
@@ -54,18 +54,26 @@ func (cmd *WorkspacesCmd) Run(ctx context.Context) error {
return err
}
- projectList, err := managementClient.Loft().ManagementV1().Projects().List(ctx, metav1.ListOptions{})
+ projectList, err := managementClient.Loft().
+ ManagementV1().
+ Projects().
+ List(ctx, metav1.ListOptions{})
if err != nil {
return fmt.Errorf("list projects: %w", err)
} else if len(projectList.Items) == 0 {
- return fmt.Errorf("you don't have access to any projects within DevPod Pro, please make sure you have at least access to 1 project")
+ return fmt.Errorf(
+ "you don't have access to any projects within DevPod Pro, please make sure you have at least access to 1 project",
+ )
}
- filterByOwner := os.Getenv(provider.LOFT_FILTER_BY_OWNER) == "true"
+ filterByOwner := os.Getenv(config.EnvLoftFilterByOwner) == config.BoolTrue
workspaces := []*managementv1.DevPodWorkspaceInstance{}
for _, p := range projectList.Items {
ns := project.ProjectNamespace(p.GetName())
- workspaceList, err := managementClient.Loft().ManagementV1().DevPodWorkspaceInstances(ns).List(ctx, metav1.ListOptions{})
+ workspaceList, err := managementClient.Loft().
+ ManagementV1().
+ DevPodWorkspaceInstances(ns).
+ List(ctx, metav1.ListOptions{})
if err != nil {
cmd.log.Info("list workspaces in project \"%s\": %w", p.GetName(), err)
continue
diff --git a/cmd/pro/provider/provider.go b/cmd/pro/provider/provider.go
index db30029e76..63da6cd788 100644
--- a/cmd/pro/provider/provider.go
+++ b/cmd/pro/provider/provider.go
@@ -10,16 +10,14 @@ import (
"github.com/skevetter/devpod/cmd/pro/provider/list"
"github.com/skevetter/devpod/cmd/pro/provider/update"
"github.com/skevetter/devpod/cmd/pro/provider/watch"
- "github.com/skevetter/devpod/pkg/client/clientimplementation"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
- "github.com/skevetter/devpod/pkg/telemetry"
"github.com/skevetter/log"
-
"github.com/spf13/cobra"
)
-// NewProProviderCmd creates a new cobra command
+// NewProProviderCmd creates a new cobra command.
func NewProProviderCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "provider",
@@ -27,26 +25,27 @@ func NewProProviderCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Args: cobra.NoArgs,
Hidden: true,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
- if (globalFlags.Config == "" || globalFlags.Config == client.DefaultCacheConfig) && os.Getenv("LOFT_CONFIG") != "" {
+ if (globalFlags.Config == "" || globalFlags.Config == client.DefaultCacheConfig) &&
+ os.Getenv("LOFT_CONFIG") != "" {
globalFlags.Config = os.Getenv(platform.ConfigEnv)
}
log.Default.SetFormat(log.JSONFormat)
- if os.Getenv(clientimplementation.DevPodDebug) == "true" {
+ if os.Getenv(config.EnvDebug) == config.BoolTrue {
globalFlags.Debug = true
}
// Disable debug hints if we execute pro commands from DevPod Desktop
// We're reusing the agent.AgentExecutedAnnotation for simplicity, could rename in the future
- if os.Getenv(telemetry.UIEnvVar) == "true" {
+ if os.Getenv(config.EnvUI) == config.BoolTrue {
cmd.VisitParents(func(c *cobra.Command) {
// find the root command
- if c.Name() == "devpod" {
+ if c.Name() == config.BinaryName {
if c.Annotations == nil {
c.Annotations = map[string]string{}
}
- c.Annotations[agent.AgentExecutedAnnotation] = "true"
+ c.Annotations[agent.AgentExecutedAnnotation] = config.BoolTrue
}
})
}
diff --git a/cmd/pro/provider/rebuild.go b/cmd/pro/provider/rebuild.go
index 2c1ab6915e..7ba921c7c0 100644
--- a/cmd/pro/provider/rebuild.go
+++ b/cmd/pro/provider/rebuild.go
@@ -17,7 +17,7 @@ import (
const AllWorkspaces = "all"
-// RebuildCmd holds the cmd flags
+// RebuildCmd holds the cmd flags.
type RebuildCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -25,7 +25,7 @@ type RebuildCmd struct {
Project string
}
-// NewRebuildCmd creates a new command
+// NewRebuildCmd creates a new command.
func NewRebuildCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &RebuildCmd{
GlobalFlags: globalFlags,
@@ -58,7 +58,8 @@ func (cmd *RebuildCmd) Run(ctx context.Context, args []string) error {
return err
}
- workspace, err := platform.FindInstanceByName(ctx, baseClient, targetWorkspace, cmd.Project)
+ instanceOpts := platform.FindInstanceOptions{Name: targetWorkspace, ProjectName: cmd.Project}
+ workspace, err := platform.FindInstance(ctx, baseClient, instanceOpts)
if err != nil {
return err
}
@@ -76,7 +77,14 @@ func (cmd *RebuildCmd) Run(ctx context.Context, args []string) error {
return err
}
- _, err = remotecommand.ExecuteConn(ctx, conn, os.Stdin, os.Stdout, os.Stderr, cmd.Log.ErrorStreamOnly())
+ _, err = remotecommand.ExecuteConn(
+ ctx,
+ conn,
+ os.Stdin,
+ os.Stdout,
+ os.Stderr,
+ cmd.Log.ErrorStreamOnly(),
+ )
if err != nil {
return fmt.Errorf("error executing: %w", err)
}
diff --git a/cmd/pro/provider/ssh.go b/cmd/pro/provider/ssh.go
index 3e776b0abd..f4274e43d2 100644
--- a/cmd/pro/provider/ssh.go
+++ b/cmd/pro/provider/ssh.go
@@ -7,6 +7,7 @@ import (
"os"
"github.com/skevetter/devpod/cmd/pro/flags"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/platform/remotecommand"
@@ -14,14 +15,14 @@ import (
"github.com/spf13/cobra"
)
-// SshCmd holds the cmd flags
+// SshCmd holds the cmd flags.
type SshCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewSshCmd creates a new command
+// NewSshCmd creates a new command.
func NewSshCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &SshCmd{
GlobalFlags: globalFlags,
@@ -40,7 +41,12 @@ func NewSshCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *SshCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *SshCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
@@ -50,14 +56,21 @@ func (cmd *SshCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, s
if err != nil {
return err
}
- workspace, err := platform.FindInstanceInProject(ctx, baseClient, info.UID, info.ProjectName)
+ opts := platform.FindInstanceOptions{UID: info.UID, ProjectName: info.ProjectName}
+ workspace, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
} else if workspace == nil {
return fmt.Errorf("couldn't find workspace")
}
- conn, err := platform.DialInstance(baseClient, workspace, "ssh", platform.OptionsFromEnv("DEVPOD_FLAGS_SSH"), cmd.Log)
+ conn, err := platform.DialInstance(
+ baseClient,
+ workspace,
+ "ssh",
+ platform.OptionsFromEnv(config.EnvFlagsSSH),
+ cmd.Log,
+ )
if err != nil {
return err
}
diff --git a/cmd/pro/provider/status.go b/cmd/pro/provider/status.go
index 504f548920..1b80baff50 100644
--- a/cmd/pro/provider/status.go
+++ b/cmd/pro/provider/status.go
@@ -7,8 +7,9 @@ import (
"io"
"os"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/platform/remotecommand"
@@ -16,14 +17,14 @@ import (
"github.com/spf13/cobra"
)
-// StatusCmd holds the cmd flags
+// StatusCmd holds the cmd flags.
type StatusCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewStatusCmd creates a new command
+// NewStatusCmd creates a new command.
func NewStatusCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &StatusCmd{
GlobalFlags: globalFlags,
@@ -42,7 +43,12 @@ func NewStatusCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *StatusCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *StatusCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
@@ -52,7 +58,8 @@ func (cmd *StatusCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer
if err != nil {
return err
}
- workspace, err := platform.FindInstanceInProject(ctx, baseClient, info.UID, info.ProjectName)
+ opts := platform.FindInstanceOptions{UID: info.UID, ProjectName: info.ProjectName}
+ workspace, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
} else if workspace == nil {
@@ -70,7 +77,13 @@ func (cmd *StatusCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer
return nil
}
- conn, err := platform.DialInstance(baseClient, workspace, "getstatus", platform.OptionsFromEnv("DEVPOD_FLAGS_STATUS"), cmd.Log)
+ conn, err := platform.DialInstance(
+ baseClient,
+ workspace,
+ "getstatus",
+ platform.OptionsFromEnv(config.EnvFlagsStatus),
+ cmd.Log,
+ )
if err != nil {
return err
}
diff --git a/cmd/pro/provider/stop.go b/cmd/pro/provider/stop.go
index 3c013fa910..4c3ea2e515 100644
--- a/cmd/pro/provider/stop.go
+++ b/cmd/pro/provider/stop.go
@@ -6,8 +6,7 @@ import (
"io"
"os"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
-
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
@@ -16,14 +15,14 @@ import (
"github.com/spf13/cobra"
)
-// StopCmd holds the cmd flags
+// StopCmd holds the cmd flags.
type StopCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewStopCmd creates a new command
+// NewStopCmd creates a new command.
func NewStopCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &StopCmd{
GlobalFlags: globalFlags,
@@ -42,7 +41,12 @@ func NewStopCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *StopCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *StopCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
@@ -52,14 +56,21 @@ func (cmd *StopCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer,
if err != nil {
return err
}
- workspace, err := platform.FindInstanceInProject(ctx, baseClient, info.UID, info.ProjectName)
+ opts := platform.FindInstanceOptions{UID: info.UID, ProjectName: info.ProjectName}
+ workspace, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
} else if workspace == nil {
return fmt.Errorf("couldn't find workspace")
}
- conn, err := platform.DialInstance(baseClient, workspace, "stop", platform.OptionsFromEnv(storagev1.DevPodFlagsStop), cmd.Log)
+ conn, err := platform.DialInstance(
+ baseClient,
+ workspace,
+ "stop",
+ platform.OptionsFromEnv(storagev1.DevPodFlagsStop),
+ cmd.Log,
+ )
if err != nil {
return err
}
diff --git a/cmd/pro/provider/up.go b/cmd/pro/provider/up.go
index 2acf857ddd..022f02db3f 100644
--- a/cmd/pro/provider/up.go
+++ b/cmd/pro/provider/up.go
@@ -8,20 +8,19 @@ import (
"os"
"github.com/sirupsen/logrus"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
- "github.com/skevetter/devpod/pkg/client/clientimplementation"
+ "github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/platform/remotecommand"
"github.com/skevetter/log"
"github.com/spf13/cobra"
-
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
corev1 "k8s.io/api/core/v1"
)
-// UpCmd holds the cmd flags:
+// UpCmd holds the cmd flags:.
type UpCmd struct {
*flags.GlobalFlags
@@ -35,10 +34,10 @@ type streams struct {
Stderr io.Writer
}
-// NewUpCmd creates a new command
+// NewUpCmd creates a new command.
func NewUpCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
logLevel := logrus.InfoLevel
- if os.Getenv(clientimplementation.DevPodDebug) == "true" || globalFlags.Debug {
+ if os.Getenv(config.EnvDebug) == config.BoolTrue || globalFlags.Debug {
logLevel = logrus.DebugLevel
}
@@ -76,11 +75,16 @@ func (cmd *UpCmd) Run(ctx context.Context) error {
return err
}
- instance, err := platform.FindInstanceInProject(ctx, baseClient, info.UID, info.ProjectName)
+ opts := platform.FindInstanceOptions{UID: info.UID, ProjectName: info.ProjectName}
+ instance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
} else if instance == nil {
- return fmt.Errorf("workspace %s not found in project %s. Looks like it does not exist anymore and you can delete it", info.ID, info.ProjectName)
+ return fmt.Errorf(
+ "workspace %s not found in project %s. Looks like it does not exist anymore and you can delete it",
+ info.ID,
+ info.ProjectName,
+ )
}
// Log current workspace information. This is both useful to the user to understand the workspace configuration
@@ -102,10 +106,14 @@ func (cmd *UpCmd) Run(ctx context.Context) error {
return cmd.up(ctx, instance, baseClient)
}
-func (cmd *UpCmd) up(ctx context.Context, workspace *managementv1.DevPodWorkspaceInstance, client client.Client) error {
+func (cmd *UpCmd) up(
+ ctx context.Context,
+ workspace *managementv1.DevPodWorkspaceInstance,
+ client client.Client,
+) error {
options := platform.OptionsFromEnv(storagev1.DevPodFlagsUp)
- if options != nil && os.Getenv("DEBUG") == "true" {
- options.Add("debug", "true")
+ if options != nil && os.Getenv(config.EnvDebug) == config.BoolTrue {
+ options.Add("debug", config.BoolTrue)
}
conn, err := platform.DialInstance(client, workspace, "up", options, cmd.Log)
@@ -113,7 +121,14 @@ func (cmd *UpCmd) up(ctx context.Context, workspace *managementv1.DevPodWorkspac
return err
}
- _, err = remotecommand.ExecuteConn(ctx, conn, cmd.streams.Stdin, cmd.streams.Stdout, cmd.streams.Stderr, cmd.Log)
+ _, err = remotecommand.ExecuteConn(
+ ctx,
+ conn,
+ cmd.streams.Stdin,
+ cmd.streams.Stdout,
+ cmd.streams.Stderr,
+ cmd.Log,
+ )
if err != nil {
return fmt.Errorf("error executing: %w", err)
}
diff --git a/cmd/pro/provider/update/update.go b/cmd/pro/provider/update/update.go
index b800e55f4e..ff7f8fc100 100644
--- a/cmd/pro/provider/update/update.go
+++ b/cmd/pro/provider/update/update.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewCmd creates a new cobra command
+// NewCmd creates a new cobra command.
func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "update",
diff --git a/cmd/pro/provider/update/workspace.go b/cmd/pro/provider/update/workspace.go
index 560682da96..5ee642e536 100644
--- a/cmd/pro/provider/update/workspace.go
+++ b/cmd/pro/provider/update/workspace.go
@@ -7,7 +7,7 @@ import (
"io"
"os"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
@@ -19,14 +19,14 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
-// WorkspaceCmd holds the cmd flags
+// WorkspaceCmd holds the cmd flags.
type WorkspaceCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewWorkspaceCmd creates a new command
+// NewWorkspaceCmd creates a new command.
func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WorkspaceCmd{
GlobalFlags: globalFlags,
@@ -45,7 +45,12 @@ func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *WorkspaceCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
baseClient, err := client.InitClientFromPath(ctx, cmd.Config)
if err != nil {
return err
@@ -57,15 +62,23 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wri
newInstance := &managementv1.DevPodWorkspaceInstance{}
err := json.Unmarshal([]byte(instanceEnv), newInstance)
if err != nil {
- return fmt.Errorf("unmarshal workpace instance %s: %w", instanceEnv, err)
+ return fmt.Errorf("unmarshal workspace instance %s: %w", instanceEnv, err)
}
newInstance.TypeMeta = metav1.TypeMeta{} // ignore
projectName := project.ProjectFromNamespace(newInstance.GetNamespace())
- oldInstance, err := platform.FindInstanceByName(ctx, baseClient, newInstance.GetName(), projectName)
+ opts := platform.FindInstanceOptions{Name: newInstance.GetName(), ProjectName: projectName}
+ oldInstance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
}
+ if oldInstance == nil {
+ return fmt.Errorf(
+ "workspace instance %q not found in project %q",
+ newInstance.GetName(),
+ projectName,
+ )
+ }
updatedInstance, err := updateInstance(ctx, baseClient, oldInstance, newInstance, cmd.Log)
if err != nil {
@@ -89,13 +102,26 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wri
workspaceUID := os.Getenv(platform.WorkspaceUIDEnv)
project := os.Getenv(platform.ProjectEnv)
if workspaceUID == "" || workspaceID == "" || project == "" {
- return fmt.Errorf("workspaceID, workspaceUID or project not found: %s, %s, %s", workspaceID, workspaceUID, project)
+ return fmt.Errorf(
+ "workspaceID, workspaceUID or project not found: %s, %s, %s",
+ workspaceID,
+ workspaceUID,
+ project,
+ )
}
- oldInstance, err := platform.FindInstanceInProject(ctx, baseClient, workspaceUID, project)
+ opts := platform.FindInstanceOptions{UID: workspaceUID, ProjectName: project}
+ oldInstance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
}
+ if oldInstance == nil {
+ return fmt.Errorf(
+ "workspace instance with UID %q not found in project %q",
+ workspaceUID,
+ project,
+ )
+ }
newInstance, err := form.UpdateInstance(ctx, baseClient, oldInstance, cmd.Log)
if err != nil {
@@ -110,7 +136,13 @@ func (cmd *WorkspaceCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wri
return nil
}
-func updateInstance(ctx context.Context, client client.Client, oldInstance *managementv1.DevPodWorkspaceInstance, newInstance *managementv1.DevPodWorkspaceInstance, log log.Logger) (*managementv1.DevPodWorkspaceInstance, error) {
+func updateInstance(
+ ctx context.Context,
+ client client.Client,
+ oldInstance *managementv1.DevPodWorkspaceInstance,
+ newInstance *managementv1.DevPodWorkspaceInstance,
+ log log.Logger,
+) (*managementv1.DevPodWorkspaceInstance, error) {
// This ensures the template is kept up to date with configuration changes
if newInstance.Spec.TemplateRef != nil {
newInstance.Spec.TemplateRef.SyncOnce = true
diff --git a/cmd/pro/provider/watch/watch.go b/cmd/pro/provider/watch/watch.go
index 7be021dea9..e7389f7d53 100644
--- a/cmd/pro/provider/watch/watch.go
+++ b/cmd/pro/provider/watch/watch.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewCmd creates a new cobra command
+// NewCmd creates a new cobra command.
func NewCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "watch",
diff --git a/cmd/pro/provider/watch/workspaces.go b/cmd/pro/provider/watch/workspaces.go
index 58433408e0..c37dfb3d82 100644
--- a/cmd/pro/provider/watch/workspaces.go
+++ b/cmd/pro/provider/watch/workspaces.go
@@ -9,11 +9,11 @@ import (
"sync"
"time"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
- loftclient "github.com/loft-sh/api/v4/pkg/clientset/versioned"
- informers "github.com/loft-sh/api/v4/pkg/informers/externalversions"
- informermanagementv1 "github.com/loft-sh/api/v4/pkg/informers/externalversions/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
+ loftclient "github.com/skevetter/api/pkg/clientset/versioned"
+ informers "github.com/skevetter/api/pkg/informers/externalversions"
+ informermanagementv1 "github.com/skevetter/api/pkg/informers/externalversions/management/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
@@ -27,14 +27,14 @@ import (
"k8s.io/client-go/tools/cache"
)
-// WorkspacesCmd holds the cmd flags
+// WorkspacesCmd holds the cmd flags.
type WorkspacesCmd struct {
*flags.GlobalFlags
Log log.Logger
}
-// NewWorkspacesCmd creates a new command
+// NewWorkspacesCmd creates a new command.
func NewWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WorkspacesCmd{
GlobalFlags: globalFlags,
@@ -68,12 +68,17 @@ type ProWorkspaceInstanceStatus struct {
IDE *provider.WorkspaceIDEConfig `json:"ide,omitempty"`
}
-func (cmd *WorkspacesCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
+func (cmd *WorkspacesCmd) Run(
+ ctx context.Context,
+ stdin io.Reader,
+ stdout io.Writer,
+ stderr io.Writer,
+) error {
if cmd.Context == "" {
cmd.Context = config.DefaultContext
}
- projectName := os.Getenv(provider.LOFT_PROJECT)
+ projectName := os.Getenv(config.EnvLoftProject)
if projectName == "" {
return fmt.Errorf("project name not found")
}
@@ -99,7 +104,7 @@ func (cmd *WorkspacesCmd) Run(ctx context.Context, stdin io.Reader, stdout io.Wr
workspaceInformer := factory.Management().V1().DevPodWorkspaceInstances()
self := baseClient.Self()
- filterByOwner := os.Getenv(provider.LOFT_FILTER_BY_OWNER) == "true"
+ filterByOwner := os.Getenv(config.EnvLoftFilterByOwner) == config.BoolTrue
instanceStore := newStore(workspaceInformer, self, cmd.Context, filterByOwner, cmd.Log)
_, err = workspaceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
@@ -171,7 +176,13 @@ type instanceStore struct {
log log.Logger
}
-func newStore(informer informermanagementv1.DevPodWorkspaceInstanceInformer, self *managementv1.Self, context string, filterByOwner bool, log log.Logger) *instanceStore {
+func newStore(
+ informer informermanagementv1.DevPodWorkspaceInstanceInformer,
+ self *managementv1.Self,
+ context string,
+ filterByOwner bool,
+ log log.Logger,
+) *instanceStore {
return &instanceStore{
informer: informer,
self: self,
@@ -191,8 +202,11 @@ func (s *instanceStore) Add(instance *managementv1.DevPodWorkspaceInstance) {
return
}
var source *provider.WorkspaceSource
- if instance.GetAnnotations() != nil && instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation] != "" {
- source = provider.ParseWorkspaceSource(instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation])
+ if instance.GetAnnotations() != nil &&
+ instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation] != "" {
+ source = provider.ParseWorkspaceSource(
+ instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation],
+ )
}
var ideConfig *provider.WorkspaceIDEConfig
@@ -221,7 +235,10 @@ func (s *instanceStore) Add(instance *managementv1.DevPodWorkspaceInstance) {
s.m.Unlock()
}
-func (s *instanceStore) Update(oldInstance *managementv1.DevPodWorkspaceInstance, newInstance *managementv1.DevPodWorkspaceInstance) {
+func (s *instanceStore) Update(
+ oldInstance *managementv1.DevPodWorkspaceInstance,
+ newInstance *managementv1.DevPodWorkspaceInstance,
+) {
s.Add(newInstance)
}
@@ -271,12 +288,16 @@ func (s *instanceStore) List() []*ProWorkspaceInstance {
s.m.Unlock()
var source *provider.WorkspaceSource
- if instance.GetAnnotations() != nil && instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation] != "" {
- source = provider.ParseWorkspaceSource(instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation])
+ if instance.GetAnnotations() != nil &&
+ instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation] != "" {
+ source = provider.ParseWorkspaceSource(
+ instance.GetAnnotations()[storagev1.DevPodWorkspaceSourceAnnotation],
+ )
}
var ideConfig *provider.WorkspaceIDEConfig
- if instance.GetLabels() != nil && instance.GetLabels()[storagev1.DevPodWorkspaceIDLabel] != "" {
+ if instance.GetLabels() != nil &&
+ instance.GetLabels()[storagev1.DevPodWorkspaceIDLabel] != "" {
id := instance.GetLabels()[storagev1.DevPodWorkspaceIDLabel]
workspaceConfig, err := provider.LoadWorkspaceConfig(s.context, id)
if err == nil {
diff --git a/cmd/pro/rebuild.go b/cmd/pro/rebuild.go
index a830013c3c..5c3ecf1d13 100644
--- a/cmd/pro/rebuild.go
+++ b/cmd/pro/rebuild.go
@@ -15,9 +15,7 @@ import (
"github.com/spf13/cobra"
)
-const AllWorkspaces = "all"
-
-// RebuildCmd holds the cmd flags
+// RebuildCmd holds the cmd flags.
type RebuildCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -26,7 +24,7 @@ type RebuildCmd struct {
Host string
}
-// NewRebuildCmd creates a new command
+// NewRebuildCmd creates a new command.
func NewRebuildCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &RebuildCmd{
GlobalFlags: globalFlags,
@@ -66,10 +64,14 @@ func (cmd *RebuildCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("resolve host \"%s\": %w", cmd.Host, err)
}
- workspace, err := platform.FindInstanceByName(ctx, baseClient, targetWorkspace, cmd.Project)
+ instanceOpts := platform.FindInstanceOptions{Name: targetWorkspace, ProjectName: cmd.Project}
+ workspace, err := platform.FindInstance(ctx, baseClient, instanceOpts)
if err != nil {
return err
}
+ if workspace == nil {
+ return fmt.Errorf("workspace %q not found in project %q", targetWorkspace, cmd.Project)
+ }
opts := struct {
Recreate bool `json:"recreate"`
@@ -84,7 +86,14 @@ func (cmd *RebuildCmd) Run(ctx context.Context, args []string) error {
return err
}
- _, err = remotecommand.ExecuteConn(ctx, conn, os.Stdin, os.Stdout, os.Stderr, cmd.Log.ErrorStreamOnly())
+ _, err = remotecommand.ExecuteConn(
+ ctx,
+ conn,
+ os.Stdin,
+ os.Stdout,
+ os.Stderr,
+ cmd.Log.ErrorStreamOnly(),
+ )
if err != nil {
return fmt.Errorf("error executing: %w", err)
}
diff --git a/cmd/pro/reset/password.go b/cmd/pro/reset/password.go
index ba9e39b3ac..9dd774cc5e 100644
--- a/cmd/pro/reset/password.go
+++ b/cmd/pro/reset/password.go
@@ -6,8 +6,7 @@ import (
"fmt"
"strings"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
- "github.com/sirupsen/logrus"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/platform/kube"
"github.com/skevetter/devpod/pkg/random"
@@ -20,7 +19,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
)
-// PasswordCmd holds the lags
+// PasswordCmd holds the flags.
type PasswordCmd struct {
*flags.GlobalFlags
@@ -32,7 +31,7 @@ type PasswordCmd struct {
Log log.Logger
}
-// NewPasswordCmd creates a new command
+// NewPasswordCmd creates a new command.
func NewPasswordCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &PasswordCmd{
GlobalFlags: globalFlags,
@@ -52,7 +51,7 @@ devpod pro reset password --user admin
Long: description,
Args: cobra.NoArgs,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- return cmd.Run()
+ return cmd.Run(cobraCmd.Context())
},
}
@@ -63,8 +62,8 @@ devpod pro reset password --user admin
return c
}
-// Run executes the functionality
-func (cmd *PasswordCmd) Run() error {
+// Run executes the functionality.
+func (cmd *PasswordCmd) Run(ctx context.Context) error {
restConfig, err := ctrl.GetConfig()
if err != nil {
return fmt.Errorf("get kube config: %w", err)
@@ -75,108 +74,216 @@ func (cmd *PasswordCmd) Run() error {
return err
}
- // get user
cmd.Log.Infof("Resetting password of user %s", cmd.User)
- user, err := managementClient.Loft().StorageV1().Users().Get(context.Background(), cmd.User, metav1.GetOptions{})
+ user, err := cmd.resolveUser(ctx, managementClient)
+ if err != nil {
+ return err
+ }
+
+ // Compute desired PasswordRef in-memory (no API call)
+ refChanged, err := cmd.ensurePasswordRef(user)
+ if err != nil {
+ return err
+ }
+
+ password, err := cmd.resolvePassword()
+ if err != nil {
+ return err
+ }
+
+ // Write secret before persisting the user's PasswordRef
+ passwordHash := fmt.Appendf(nil, "%x", sha256.Sum256([]byte(password)))
+ if err := cmd.upsertPasswordSecret(ctx, managementClient, user, passwordHash); err != nil {
+ return err
+ }
+
+ // Now persist the user's PasswordRef if it was changed
+ if err := cmd.persistPasswordRef(ctx, managementClient, user, refChanged); err != nil {
+ return err
+ }
+
+ cmd.Log.Done("reset user password")
+ return nil
+}
+
+func (cmd *PasswordCmd) resolveUser(
+ ctx context.Context,
+ managementClient kube.Interface,
+) (*storagev1.User, error) {
+ user, err := managementClient.Loft().
+ StorageV1().
+ Users().
+ Get(ctx, cmd.User, metav1.GetOptions{})
if err != nil && !kerrors.IsNotFound(err) {
- return fmt.Errorf("get user: %w", err)
+ return nil, fmt.Errorf("get user: %w", err)
} else if kerrors.IsNotFound(err) {
- // create user
if !cmd.Create {
- return fmt.Errorf("user %s was not found, run with '--create' to create this user automatically", cmd.User)
+ return nil, fmt.Errorf(
+ "user %s was not found, run with '--create' to create this user automatically",
+ cmd.User,
+ )
}
- user, err = managementClient.Loft().StorageV1().Users().Create(context.Background(), &storagev1.User{
- ObjectMeta: metav1.ObjectMeta{
- Name: cmd.User,
- },
- Spec: storagev1.UserSpec{
- Username: cmd.User,
- Subject: cmd.User,
- Groups: []string{
- "system:masters",
+ user, err = managementClient.Loft().
+ StorageV1().
+ Users().
+ Create(ctx, &storagev1.User{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: cmd.User,
},
- PasswordRef: &storagev1.SecretRef{
- SecretName: "loft-password-" + random.String(5),
- SecretNamespace: "loft",
- Key: "password",
+ Spec: storagev1.UserSpec{
+ Username: cmd.User,
+ Subject: cmd.User,
+ Groups: []string{
+ "system:masters",
+ },
},
- },
- }, metav1.CreateOptions{})
+ }, metav1.CreateOptions{})
if err != nil {
- return err
+ return nil, err
}
}
- // check if user had a password before
- if user.Spec.PasswordRef == nil || user.Spec.PasswordRef.SecretName == "" || user.Spec.PasswordRef.SecretNamespace == "" || user.Spec.PasswordRef.Key == "" {
- if !cmd.Force {
- return fmt.Errorf("user %s had no password. If you want to force password creation, please run with the '--force' flag", cmd.User)
- }
+ return user, nil
+}
- user.Spec.PasswordRef = &storagev1.SecretRef{
- SecretName: "loft-password-" + random.String(5),
- SecretNamespace: "loft",
- Key: "password",
- }
- user, err = managementClient.Loft().StorageV1().Users().Update(context.Background(), user, metav1.UpdateOptions{})
+// persistPasswordRef updates the user resource if the PasswordRef was changed.
+func (cmd *PasswordCmd) persistPasswordRef(
+ ctx context.Context,
+ managementClient kube.Interface,
+ user *storagev1.User,
+ changed bool,
+) error {
+ if !changed {
+ return nil
+ }
+ _, err := managementClient.Loft().
+ StorageV1().
+ Users().
+ Update(ctx, user, metav1.UpdateOptions{})
+ if err != nil {
+ return fmt.Errorf("update user: %w", err)
+ }
+ return nil
+}
+
+func (cmd *PasswordCmd) ensurePasswordRef(user *storagev1.User) (bool, error) {
+ if hasCompletePasswordRef(user) {
+ return false, nil
+ }
+
+ if err := cmd.fillPasswordRef(user); err != nil {
+ return false, err
+ }
+
+ return true, nil
+}
+
+func hasCompletePasswordRef(user *storagev1.User) bool {
+ ref := user.Spec.PasswordRef
+ return ref != nil && ref.SecretName != "" && ref.SecretNamespace != "" && ref.Key != ""
+}
+
+func (cmd *PasswordCmd) fillPasswordRef(user *storagev1.User) error {
+ ref := user.Spec.PasswordRef
+ // If PasswordRef exists with name and namespace but missing key, just default the key
+ if ref != nil && ref.SecretName != "" && ref.SecretNamespace != "" {
+ ref.Key = "password"
+ return nil
+ }
+
+ if !cmd.Force {
+ return fmt.Errorf(
+ "user %s had no password. If you want to force password creation, please run with the '--force' flag",
+ cmd.User,
+ )
+ }
+
+ user.Spec.PasswordRef = defaultPasswordRef(user.Spec.PasswordRef)
+ return nil
+}
+
+func defaultPasswordRef(ref *storagev1.SecretRef) *storagev1.SecretRef {
+ if ref == nil {
+ ref = &storagev1.SecretRef{}
+ }
+ if ref.SecretName == "" {
+ ref.SecretName = "loft-password-" + random.String(5)
+ }
+ if ref.SecretNamespace == "" {
+ ref.SecretNamespace = "loft"
+ }
+ if ref.Key == "" {
+ ref.Key = "password"
+ }
+ return ref
+}
+
+func (cmd *PasswordCmd) resolvePassword() (string, error) {
+ if cmd.Password != "" {
+ return cmd.Password, nil
+ }
+
+ for {
+ password, err := cmd.Log.Question(&survey.QuestionOptions{
+ Question: "Please enter a new password",
+ IsPassword: true,
+ })
if err != nil {
- return fmt.Errorf("update user: %w", err)
+ return "", err
}
- }
- // now ask user for new password
- password := cmd.Password
- if password == "" {
- for {
- password, err = cmd.Log.Question(&survey.QuestionOptions{
- Question: "Please enter a new password",
- IsPassword: true,
- })
- password = strings.TrimSpace(password)
- if err != nil {
- return err
- } else if password == "" {
- cmd.Log.Error("Please enter a password")
- continue
- }
-
- break
+ password = strings.TrimSpace(password)
+ if password != "" {
+ return password, nil
}
+
+ cmd.Log.Error("Please enter a password")
}
- passwordHash := fmt.Appendf(nil, "%x", sha256.Sum256([]byte(password)))
+}
- // check if secret exists
- passwordSecret, err := managementClient.CoreV1().Secrets(user.Spec.PasswordRef.SecretNamespace).Get(context.Background(), user.Spec.PasswordRef.SecretName, metav1.GetOptions{})
+func (cmd *PasswordCmd) upsertPasswordSecret(
+ ctx context.Context,
+ managementClient kube.Interface,
+ user *storagev1.User,
+ passwordHash []byte,
+) error {
+ ref := user.Spec.PasswordRef
+ passwordSecret, err := managementClient.CoreV1().
+ Secrets(ref.SecretNamespace).
+ Get(ctx, ref.SecretName, metav1.GetOptions{})
if err != nil && !kerrors.IsNotFound(err) {
- return err
- } else if kerrors.IsNotFound(err) {
- _, err = managementClient.CoreV1().Secrets(user.Spec.PasswordRef.SecretNamespace).Create(context.Background(), &corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
- Name: user.Spec.PasswordRef.SecretName,
- Namespace: user.Spec.PasswordRef.SecretNamespace,
- },
- Data: map[string][]byte{
- user.Spec.PasswordRef.Key: passwordHash,
- },
- }, metav1.CreateOptions{})
+ return fmt.Errorf("get password secret: %w", err)
+ }
+
+ if kerrors.IsNotFound(err) {
+ _, err = managementClient.CoreV1().
+ Secrets(ref.SecretNamespace).
+ Create(ctx, &corev1.Secret{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: ref.SecretName,
+ Namespace: ref.SecretNamespace,
+ },
+ Data: map[string][]byte{
+ ref.Key: passwordHash,
+ },
+ }, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("create password secret: %w", err)
}
- } else {
- if passwordSecret.Data == nil {
- passwordSecret.Data = map[string][]byte{}
- }
- passwordSecret.Data[user.Spec.PasswordRef.Key] = passwordHash
- _, err = managementClient.CoreV1().Secrets(user.Spec.PasswordRef.SecretNamespace).Update(context.Background(), passwordSecret, metav1.UpdateOptions{})
- if err != nil {
- return fmt.Errorf("update password secret: %w", err)
- }
+ return nil
+ }
+
+ if passwordSecret.Data == nil {
+ passwordSecret.Data = map[string][]byte{}
+ }
+ passwordSecret.Data[ref.Key] = passwordHash
+ _, err = managementClient.CoreV1().
+ Secrets(ref.SecretNamespace).
+ Update(ctx, passwordSecret, metav1.UpdateOptions{})
+ if err != nil {
+ return fmt.Errorf("update password secret: %w", err)
}
- cmd.Log.WithFields(logrus.Fields{
- "user": cmd.User,
- })
- cmd.Log.Done("reset user password")
return nil
}
diff --git a/cmd/pro/reset/reset.go b/cmd/pro/reset/reset.go
index af70914be4..5a6c3485bb 100644
--- a/cmd/pro/reset/reset.go
+++ b/cmd/pro/reset/reset.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewResetCmd creates a new cobra command
+// NewResetCmd creates a new cobra command.
func NewResetCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
c := &cobra.Command{
Use: "reset",
diff --git a/cmd/pro/self.go b/cmd/pro/self.go
index 29d4e61988..16886eab65 100644
--- a/cmd/pro/self.go
+++ b/cmd/pro/self.go
@@ -14,7 +14,7 @@ import (
"github.com/spf13/cobra"
)
-// SelfCmd holds the cmd flags
+// SelfCmd holds the cmd flags.
type SelfCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -22,7 +22,7 @@ type SelfCmd struct {
Host string
}
-// NewSelfCmd creates a new command
+// NewSelfCmd creates a new command.
func NewSelfCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &SelfCmd{
GlobalFlags: globalFlags,
@@ -33,7 +33,13 @@ func NewSelfCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Get self",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -48,7 +54,11 @@ func NewSelfCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *SelfCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *SelfCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
var buf bytes.Buffer
// ignore --debug because we tunnel json through stdio
cmd.Log.SetLevel(logrus.InfoLevel)
diff --git a/cmd/pro/sleep.go b/cmd/pro/sleep.go
index 17a103e132..7aa0e1c613 100644
--- a/cmd/pro/sleep.go
+++ b/cmd/pro/sleep.go
@@ -6,9 +6,8 @@ import (
"strconv"
"time"
- clusterv1 "github.com/loft-sh/agentapi/v4/pkg/apis/loft/cluster/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
- "github.com/sirupsen/logrus"
+ clusterv1 "github.com/skevetter/agentapi/pkg/apis/devsy/cluster/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
@@ -20,7 +19,7 @@ import (
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
)
-// SleepCmd holds the cmd flags
+// SleepCmd holds the cmd flags.
type SleepCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -30,7 +29,7 @@ type SleepCmd struct {
ForceDuration int64
}
-// NewSleepCmd creates a new command
+// NewSleepCmd creates a new command.
func NewSleepCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &SleepCmd{
GlobalFlags: globalFlags,
@@ -47,7 +46,11 @@ func NewSleepCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
}
c.Flags().StringVar(&cmd.Project, "project", "", "The project to use")
- c.Flags().Int64Var(&cmd.ForceDuration, "prevent-wakeup", -1, "The amount of seconds this workspace should sleep until it can be woken up again (use 0 for infinite sleeping). During this time the space can only be woken up by `devpod pro wakeup`, manually deleting the annotation on the namespace or through the UI")
+ c.Flags().
+ Int64Var(&cmd.ForceDuration, "prevent-wakeup", -1,
+ "The amount of seconds this workspace should sleep until it can be woken up again (use 0 for infinite sleeping). "+
+ "During this time the space can only be woken up by `devpod pro wakeup`, "+
+ "manually deleting the annotation on the namespace or through the UI")
_ = c.MarkFlagRequired("project")
c.Flags().StringVar(&cmd.Host, "host", "", "The pro instance to use")
_ = c.MarkFlagRequired("host")
@@ -71,7 +74,8 @@ func (cmd *SleepCmd) Run(ctx context.Context, args []string) error {
return err
}
- workspaceInstance, err := platform.FindInstanceByName(ctx, baseClient, targetWorkspace, cmd.Project)
+ opts := platform.FindInstanceOptions{Name: targetWorkspace, ProjectName: cmd.Project}
+ workspaceInstance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
}
@@ -94,34 +98,47 @@ func (cmd *SleepCmd) Run(ctx context.Context, args []string) error {
}
workspaceInstance.Annotations[clusterv1.SleepModeForceAnnotation] = "true"
if cmd.ForceDuration >= 0 {
- workspaceInstance.Annotations[clusterv1.SleepModeForceDurationAnnotation] = strconv.FormatInt(cmd.ForceDuration, 10)
+ workspaceInstance.Annotations[clusterv1.SleepModeForceDurationAnnotation] = strconv.FormatInt(
+ cmd.ForceDuration,
+ 10,
+ )
}
patchData, err := patch.Data(workspaceInstance)
if err != nil {
return fmt.Errorf("create patch: %w", err)
}
- _, err = managementClient.Loft().ManagementV1().DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).Patch(ctx, workspaceInstance.Name, patch.Type(), patchData, metav1.PatchOptions{})
+ _, err = managementClient.Loft().
+ ManagementV1().
+ DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).
+ Patch(ctx, workspaceInstance.Name, patch.Type(), patchData, metav1.PatchOptions{})
if err != nil {
return err
}
// wait for sleeping
cmd.Log.Info("Wait until workspace is sleeping...")
- err = wait.PollUntilContextTimeout(ctx, time.Second, platform.Timeout(), false, func(ctx context.Context) (done bool, err error) {
- workspaceInstance, err := managementClient.Loft().ManagementV1().DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).Get(ctx, workspaceInstance.Name, metav1.GetOptions{})
- if err != nil {
- return false, err
- }
-
- return workspaceInstance.Status.Phase == storagev1.InstanceSleeping, nil
- })
+ err = wait.PollUntilContextTimeout(
+ ctx,
+ time.Second,
+ platform.Timeout(),
+ false,
+ func(ctx context.Context) (done bool, err error) {
+ workspaceInstance, err := managementClient.Loft().
+ ManagementV1().
+ DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).
+ Get(ctx, workspaceInstance.Name, metav1.GetOptions{})
+ if err != nil {
+ return false, err
+ }
+
+ return workspaceInstance.Status.Phase == storagev1.InstanceSleeping, nil
+ },
+ )
if err != nil {
return fmt.Errorf("error waiting for workspace to start sleeping: %w", err)
}
- cmd.Log.WithFields(logrus.Fields{
- "workspace": workspaceInstance.Name,
- }).Donef("workspace is now sleeping")
+ cmd.Log.Donef("workspace is now sleeping: workspace=%s", workspaceInstance.Name)
return nil
}
diff --git a/cmd/pro/start.go b/cmd/pro/start.go
index 84705ac92f..83758196ec 100644
--- a/cmd/pro/start.go
+++ b/cmd/pro/start.go
@@ -19,16 +19,15 @@ import (
"strings"
"time"
- "github.com/denisbrodbeck/machineid"
- jsonpatch "github.com/evanphx/json-patch"
- "github.com/mgutz/ansi"
- "github.com/skratchdot/open-golang/open"
-
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
- "github.com/loft-sh/api/v4/pkg/auth"
- loftclientset "github.com/loft-sh/api/v4/pkg/clientset/versioned"
+ jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/sirupsen/logrus"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
+ "github.com/skevetter/api/pkg/auth"
+ loftclientset "github.com/skevetter/api/pkg/clientset/versioned"
proflags "github.com/skevetter/devpod/cmd/pro/flags"
+ "github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/machineid"
+ devpodopen "github.com/skevetter/devpod/pkg/open"
"github.com/skevetter/devpod/pkg/platform"
"github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/util"
@@ -49,15 +48,17 @@ import (
"k8s.io/kubectl/pkg/util/term"
)
-const LoftRouterDomainSecret = "loft-router-domain"
-const passwordChangedHint = "(has been changed)"
-const defaultUser = "admin"
+const (
+ LoftRouterDomainSecret = "loft-router-domain" // #nosec G101
+ passwordChangedHint = "(has been changed)"
+ defaultUser = "admin"
+)
-const defaultReleaseName = "devpod-pro"
+var defaultReleaseName = config.ProReleaseName
var defaultDeploymentName = "loft" // Need to update helm chart if we change this!
-// StartCmd holds the login cmd flags
+// StartCmd holds the login cmd flags.
type StartCmd struct {
proflags.GlobalFlags
@@ -88,44 +89,60 @@ type StartCmd struct {
Docker bool
}
-// NewStartCmd creates a new command
+// NewStartCmd creates a new command.
func NewStartCmd(flags *proflags.GlobalFlags) *cobra.Command {
- cmd := &StartCmd{GlobalFlags: *flags,
- Product: "devpod-pro",
- ChartName: "devpod-pro",
- Log: log.Default,
+ cmd := &StartCmd{
+ GlobalFlags: *flags,
+ Product: config.ProReleaseName,
+ ChartName: config.ProReleaseName,
+ Log: log.Default,
}
startCmd := &cobra.Command{
Use: "start",
Short: "Start a Devpod Pro instance",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- startCmd.Flags().BoolVar(&cmd.Docker, "docker", false, "If enabled will try to deploy DevPod Pro to the local docker installation.")
+ startCmd.Flags().
+ BoolVar(&cmd.Docker, "docker", false, "If enabled will try to deploy DevPod Pro to the local docker installation.")
startCmd.Flags().StringVar(&cmd.DockerImage, "docker-image", "", "The docker image to install.")
startCmd.Flags().StringArrayVar(&cmd.DockerArgs, "docker-arg", []string{}, "Extra docker args")
- startCmd.Flags().StringVar(&cmd.Context, "context", "", "The kube context to use for installation")
- startCmd.Flags().StringVar(&cmd.Namespace, "namespace", "devpod-pro", "The namespace to install into")
- startCmd.Flags().StringVar(&cmd.Host, "host", "", "Provide a hostname to enable ingress and configure its hostname")
- startCmd.Flags().StringVar(&cmd.Password, "password", "", "The password to use for the admin account. (If empty this will be the namespace UID)")
+ startCmd.Flags().
+ StringVar(&cmd.Context, "context", "", "The kube context to use for installation")
+ startCmd.Flags().
+ StringVar(&cmd.Namespace, "namespace", config.ProReleaseName, "The namespace to install into")
+ startCmd.Flags().
+ StringVar(&cmd.Host, "host", "", "Provide a hostname to enable ingress and configure its hostname")
+ startCmd.Flags().
+ StringVar(&cmd.Password, "password", "",
+ "The password to use for the admin account. (If empty this will be the namespace UID)")
startCmd.Flags().StringVar(&cmd.Version, "version", "", "The version to install")
- startCmd.Flags().StringVar(&cmd.Values, "values", "", "Path to a file for extra helm chart values")
- startCmd.Flags().BoolVar(&cmd.ReuseValues, "reuse-values", true, "Reuse previous helm values on upgrade")
- startCmd.Flags().BoolVar(&cmd.Upgrade, "upgrade", false, "If true, will try to upgrade the release")
+ startCmd.Flags().
+ StringVar(&cmd.Values, "values", "", "Path to a file for extra helm chart values")
+ startCmd.Flags().
+ BoolVar(&cmd.ReuseValues, "reuse-values", true, "Reuse previous helm values on upgrade")
+ startCmd.Flags().
+ BoolVar(&cmd.Upgrade, "upgrade", false, "If true, will try to upgrade the release")
startCmd.Flags().StringVar(&cmd.Email, "email", "", "The email to use for the installation")
- startCmd.Flags().BoolVar(&cmd.Reset, "reset", false, "If true, an existing instance will be deleted before installing DevPod Pro")
- startCmd.Flags().BoolVar(&cmd.NoWait, "no-wait", false, "If true, will not wait after installing it")
- startCmd.Flags().BoolVar(&cmd.NoTunnel, "no-tunnel", false, "If true, will not create a loft.host tunnel for this installation")
- startCmd.Flags().BoolVar(&cmd.NoLogin, "no-login", false, "If true, will not login to a DevPod Pro instance on start")
- startCmd.Flags().StringVar(&cmd.ChartPath, "chart-path", "", "The local chart path to deploy DevPod Pro")
- startCmd.Flags().StringVar(&cmd.ChartRepo, "chart-repo", "https://charts.loft.sh/", "The chart repo to deploy DevPod Pro")
+ startCmd.Flags().
+ BoolVar(&cmd.Reset, "reset", false, "If true, an existing instance will be deleted before installing DevPod Pro")
+ startCmd.Flags().
+ BoolVar(&cmd.NoWait, "no-wait", false, "If true, will not wait after installing it")
+ startCmd.Flags().
+ BoolVar(&cmd.NoTunnel, "no-tunnel", false, "If true, will not create a loft.host tunnel for this installation")
+ startCmd.Flags().
+ BoolVar(&cmd.NoLogin, "no-login", false, "If true, will not login to a DevPod Pro instance on start")
+ startCmd.Flags().
+ StringVar(&cmd.ChartPath, "chart-path", "", "The local chart path to deploy DevPod Pro")
+ startCmd.Flags().
+ StringVar(&cmd.ChartRepo, "chart-repo", "https://charts.loft.sh/", "The chart repo to deploy DevPod Pro")
return startCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *StartCmd) Run(ctx context.Context) error {
if cmd.Docker {
return cmd.startDocker(ctx)
@@ -136,7 +153,7 @@ func (cmd *StartCmd) Run(ctx context.Context) error {
cmd.LocalPort = "9898"
}
- err := cmd.prepare()
+ err := cmd.prepare(ctx)
if err != nil {
return err
}
@@ -181,7 +198,7 @@ func (cmd *StartCmd) Run(ctx context.Context) error {
return err
}
- err = cmd.upgrade()
+ err = cmd.upgrade(ctx)
if err != nil {
return err
}
@@ -189,39 +206,140 @@ func (cmd *StartCmd) Run(ctx context.Context) error {
return cmd.success(ctx)
}
-func (cmd *StartCmd) upgrade() error {
- extraArgs := []string{}
+func (cmd *StartCmd) appendHostArgs(extraArgs []string) []string {
if cmd.Host != "" || cmd.NoTunnel {
extraArgs = append(extraArgs, "--set-string", "env.DISABLE_LOFT_ROUTER=true")
}
- if cmd.Password != "" {
- extraArgs = append(extraArgs, "--set", "admin.password="+cmd.Password)
- }
if cmd.Host != "" {
- extraArgs = append(extraArgs, "--set", "ingress.enabled=true", "--set", "ingress.host="+cmd.Host)
+ extraArgs = append(
+ extraArgs,
+ "--set",
+ "ingress.enabled=true",
+ "--set",
+ "ingress.host="+cmd.Host,
+ )
extraArgs = append(extraArgs, "--set", "env.LOFT_HOST="+cmd.Host)
- extraArgs = append(extraArgs, "--set", "devpodIngress.enabled=true", "--set", "devpodIngress.host=*."+cmd.Host)
+ extraArgs = append(
+ extraArgs,
+ "--set",
+ "devpodIngress.enabled=true",
+ "--set",
+ "devpodIngress.host=*."+cmd.Host,
+ )
extraArgs = append(extraArgs, "--set", "env.DEVPOD_SUBDOMAIN=*."+cmd.Host)
}
+
+ return extraArgs
+}
+
+func (cmd *StartCmd) buildUpgradeArgs() (extraArgs []string, cleanup func(), err error) {
+ cleanup = func() {}
+ extraArgs = cmd.appendHostArgs(extraArgs)
+ if cmd.Password != "" {
+ valuesFile, ferr := writePasswordValuesFile(cmd.Password)
+ if ferr != nil {
+ return nil, nil, ferr
+ }
+ cleanup = func() { _ = os.Remove(valuesFile) }
+ extraArgs = append(extraArgs, "--values", valuesFile)
+ }
+ extraArgs = cmd.appendReleaseArgs(extraArgs)
+
+ if cmd.Values != "" {
+ absValuesPath, err := filepath.Abs(cmd.Values)
+ if err != nil {
+ cleanup()
+ return nil, nil, err
+ }
+ extraArgs = append(extraArgs, "--values", absValuesPath)
+ }
+
+ return extraArgs, cleanup, nil
+}
+
+func (cmd *StartCmd) appendReleaseArgs(extraArgs []string) []string {
if cmd.Version != "" {
extraArgs = append(extraArgs, "--version", cmd.Version)
}
if cmd.Product != "" {
extraArgs = append(extraArgs, "--set", "product="+cmd.Product)
}
-
- // Do not use --reuse-values if --reset flag is provided because this should be a new install and it will cause issues with `helm template`
if !cmd.Reset && cmd.ReuseValues {
extraArgs = append(extraArgs, "--reuse-values")
}
+ return extraArgs
+}
- if cmd.Values != "" {
- absValuesPath, err := filepath.Abs(cmd.Values)
- if err != nil {
- return err
- }
- extraArgs = append(extraArgs, "--values", absValuesPath)
+func writePasswordValuesFile(password string) (string, error) {
+ f, err := os.CreateTemp("", config.BinaryName+"-values-*.yaml")
+ if err != nil {
+ return "", fmt.Errorf("create temp values file: %w", err)
+ }
+ name := f.Name()
+ if _, err := fmt.Fprintf(f, "admin:\n password: %q\n", password); err != nil {
+ _ = os.Remove(name)
+ return "", fmt.Errorf("write temp values file: %w", err)
}
+ if err := f.Close(); err != nil {
+ _ = os.Remove(name)
+ return "", fmt.Errorf("close temp values file: %w", err)
+ }
+ return name, nil
+}
+
+func (cmd *StartCmd) retryUpgradeAfterPurge(
+ ctx context.Context,
+ chartName, chartRepo string,
+ extraArgs []string,
+) error {
+ cmd.Log.Info("Trying to delete objects blocking current installation")
+
+ manifests, err := getReleaseManifests(
+ ctx,
+ chartName,
+ chartRepo,
+ cmd.Context,
+ cmd.Namespace,
+ extraArgs,
+ cmd.Log,
+ )
+ if err != nil {
+ return err
+ }
+
+ cmd.purgeManifests(ctx, manifests)
+
+ // Retry Loft installation
+ err = upgradeRelease(
+ ctx,
+ chartName,
+ chartRepo,
+ cmd.Context,
+ cmd.Namespace,
+ extraArgs,
+ cmd.Log,
+ )
+ if err != nil {
+ return errors.New(
+ err.Error() + fmt.Sprintf(
+ "\n\nExisting installation failed. Reach out to get help:\n- via Slack: %s (fastest option)\n"+
+ "- via Online Chat: %s\n- via Email: %s\n",
+ greenBold("https://slack.loft.sh/"),
+ greenBold("https://loft.sh/"),
+ greenBold("support@loft.sh"),
+ ),
+ )
+ }
+
+ return nil
+}
+
+func (cmd *StartCmd) upgrade(ctx context.Context) error {
+ extraArgs, cleanup, err := cmd.buildUpgradeArgs()
+ if err != nil {
+ return err
+ }
+ defer cleanup()
chartName := cmd.ChartPath
chartRepo := ""
@@ -230,42 +348,38 @@ func (cmd *StartCmd) upgrade() error {
chartRepo = cmd.ChartRepo
}
- err := upgradeRelease(chartName, chartRepo, cmd.Context, cmd.Namespace, extraArgs, cmd.Log)
+ err = upgradeRelease(ctx, chartName, chartRepo, cmd.Context, cmd.Namespace, extraArgs, cmd.Log)
if err != nil {
if !cmd.Reset {
- return errors.New(err.Error() + fmt.Sprintf("\n\nIf want to purge and reinstall DevPod Pro, run: %s\n", ansi.Color("devpod pro start --reset", "green+b")))
+ return errors.New(
+ err.Error() + fmt.Sprintf(
+ "\n\nIf want to purge and reinstall DevPod Pro, run: %s\n",
+ greenBold("devpod pro start --reset"),
+ ),
+ )
}
// Try to purge Loft and retry install
- cmd.Log.Info("Trying to delete objects blocking current installation")
-
- manifests, err := getReleaseManifests(chartName, chartRepo, cmd.Context, cmd.Namespace, extraArgs, cmd.Log)
- if err != nil {
- return err
- }
-
- kubectlDelete := exec.Command("kubectl", "delete", "-f", "-", "--ignore-not-found=true", "--grace-period=0", "--force")
-
- buffer := bytes.Buffer{}
- buffer.Write([]byte(manifests))
-
- kubectlDelete.Stdin = &buffer
- kubectlDelete.Stdout = os.Stdout
- kubectlDelete.Stderr = os.Stderr
-
- // Ignoring potential errors here
- _ = kubectlDelete.Run()
-
- // Retry Loft installation
- err = upgradeRelease(chartName, chartRepo, cmd.Context, cmd.Namespace, extraArgs, cmd.Log)
- if err != nil {
- return errors.New(err.Error() + fmt.Sprintf("\n\nExisting installation failed. Reach out to get help:\n- via Slack: %s (fastest option)\n- via Online Chat: %s\n- via Email: %s\n", ansi.Color("https://slack.loft.sh/", "green+b"), ansi.Color("https://loft.sh/", "green+b"), ansi.Color("support@loft.sh", "green+b")))
- }
+ return cmd.retryUpgradeAfterPurge(ctx, chartName, chartRepo, extraArgs)
}
return nil
}
+func (cmd *StartCmd) purgeManifests(ctx context.Context, manifests string) {
+ kubectlDelete := exec.CommandContext(ctx, // #nosec G204 -- args are internally constructed
+ "kubectl", "delete", "-f", "-",
+ "--context", cmd.Context,
+ "--namespace", cmd.Namespace,
+ "--ignore-not-found=true",
+ "--grace-period=0", "--force",
+ )
+ kubectlDelete.Stdin = strings.NewReader(manifests)
+ kubectlDelete.Stdout = os.Stdout
+ kubectlDelete.Stderr = os.Stderr
+ _ = kubectlDelete.Run()
+}
+
func (cmd *StartCmd) success(ctx context.Context) error {
if cmd.NoWait {
return nil
@@ -343,8 +457,8 @@ func (cmd *StartCmd) successRemote(ctx context.Context, host string) error {
########################## LOGIN ############################
-Username: `+ansi.Color("admin", "green+b")+`
-Password: `+ansi.Color(password, "green+b")+` # Change via UI or via: `+ansi.Color("devpod pro reset password", "green+b")+`
+Username: `+greenBold("admin")+`
+Password: `+greenBold(password)+` # Change via UI or via: `+greenBold("devpod pro reset password")+`
Login via UI: %s
Login via CLI: %s
@@ -359,8 +473,8 @@ DevPod Pro was successfully installed and can now be reached at: %s
Thanks for using DevPod Pro!
`,
- ansi.Color(url, "green+b"),
- ansi.Color("devpod pro login "+url, "green+b"),
+ greenBold(url),
+ greenBold("devpod pro login "+url),
"https://loft.sh/docs/administration/ssl",
url))
}
@@ -394,10 +508,18 @@ The command will wait until DevPod Pro is reachable under the host.
`)
- cmd.Log.Info("Waiting for you to configure DNS, so DevPod Pro can be reached on https://" + host)
- err = wait.PollUntilContextTimeout(ctx, 5*time.Second, platform.Timeout(), true, func(ctx context.Context) (done bool, err error) {
- return isHostReachable(ctx, host)
- })
+ cmd.Log.Info(
+ "Waiting for you to configure DNS, so DevPod Pro can be reached on https://" + host,
+ )
+ err = wait.PollUntilContextTimeout(
+ ctx,
+ 5*time.Second,
+ platform.Timeout(),
+ true,
+ func(ctx context.Context) (done bool, err error) {
+ return isHostReachable(ctx, host)
+ },
+ )
if err != nil {
return err
}
@@ -407,6 +529,7 @@ The command will wait until DevPod Pro is reachable under the host.
printSuccess()
return nil
}
+
func (cmd *StartCmd) successLocal() error {
url := "https://localhost:" + cmd.LocalPort
@@ -426,8 +549,8 @@ func (cmd *StartCmd) successLocal() error {
########################## LOGIN ############################
-Username: `+ansi.Color("admin", "green+b")+`
-Password: `+ansi.Color(password, "green+b")+` # Change via UI or via: `+ansi.Color("devpod pro reset password", "green+b")+`
+Username: `+greenBold("admin")+`
+Password: `+greenBold(password)+` # Change via UI or via: `+greenBold("devpod pro reset password")+`
Login via UI: %s
Login via CLI: %s
@@ -439,7 +562,7 @@ Login via CLI: %s
DevPod Pro was successfully installed.
Thanks for using DevPod Pro!
-`, ansi.Color(url, "green+b"), ansi.Color("devpod pro login"+" --insecure "+url, "green+b")))
+`, greenBold(url), greenBold("devpod pro login"+" --insecure "+url)))
blockChan := make(chan bool)
<-blockChan
return nil
@@ -447,7 +570,7 @@ Thanks for using DevPod Pro!
func (cmd *StartCmd) startDocker(ctx context.Context) error {
cmd.Log.Infof("Starting DevPod Pro in Docker...")
- name := "devpod-pro"
+ name := config.ProReleaseName
// prepare installation
err := cmd.prepareDocker()
@@ -492,7 +615,11 @@ func (cmd *StartCmd) startDocker(ctx context.Context) error {
if err != nil {
return err
} else if containerID == "" {
- return fmt.Errorf("%w: %s", ErrMissingContainer, "couldn't find Loft container after starting it")
+ return fmt.Errorf(
+ "%w: %s",
+ ErrMissingContainer,
+ "couldn't find Loft container after starting it",
+ )
}
return cmd.successDocker(ctx, containerID)
@@ -511,17 +638,28 @@ func (cmd *StartCmd) successDocker(ctx context.Context, containerID string) erro
// wait for domain to become reachable
cmd.Log.Infof("Wait for DevPod Pro to become available at %s...", host)
- err = wait.PollUntilContextTimeout(ctx, time.Second, time.Minute*10, true, func(ctx context.Context) (bool, error) {
- containerDetails, err := cmd.inspectContainer(ctx, containerID)
- if err != nil {
- return false, fmt.Errorf("inspect loft container: %w", err)
- } else if strings.ToLower(containerDetails.State.Status) == "exited" || strings.ToLower(containerDetails.State.Status) == "dead" {
- logs, _ := cmd.logsContainer(ctx, containerID)
- return false, fmt.Errorf("container failed (status: %s):\n %s", containerDetails.State.Status, logs)
- }
+ err = wait.PollUntilContextTimeout(
+ ctx,
+ time.Second,
+ time.Minute*10,
+ true,
+ func(ctx context.Context) (bool, error) {
+ containerDetails, err := cmd.inspectContainer(ctx, containerID)
+ if err != nil {
+ return false, fmt.Errorf("inspect loft container: %w", err)
+ } else if strings.ToLower(containerDetails.State.Status) == "exited" ||
+ strings.ToLower(containerDetails.State.Status) == "dead" {
+ logs, _ := cmd.logsContainer(ctx, containerID)
+ return false, fmt.Errorf(
+ "container failed (status: %s):\n %s",
+ containerDetails.State.Status,
+ logs,
+ )
+ }
- return isHostReachable(ctx, host)
- })
+ return isHostReachable(ctx, host)
+ },
+ )
if err != nil {
return fmt.Errorf("error waiting for DevPod Pro: %w", err)
}
@@ -538,8 +676,8 @@ func PrintSuccessMessageDockerInstall(host, password string, log log.Logger) {
########################## LOGIN ############################
-Username: `+ansi.Color("admin", "green+b")+`
-Password: `+ansi.Color(password, "green+b")+`
+Username: `+greenBold("admin")+`
+Password: `+greenBold(password)+`
Login via UI: %s
Login via CLI: %s
@@ -550,8 +688,8 @@ DevPod Pro was successfully installed and can now be reached at: %s
Thanks for using DevPod Pro!
`,
- ansi.Color(url, "green+b"),
- ansi.Color("devpod pro login"+" "+url, "green+b"),
+ greenBold(url),
+ greenBold("devpod pro login"+" "+url),
url,
))
}
@@ -569,19 +707,29 @@ func (cmd *StartCmd) waitForLoftDocker(ctx context.Context, containerID string)
// check if no tunnel
if cmd.NoTunnel {
- return "", fmt.Errorf("%w: %s", ErrLoftNotReachable, "cannot connect to DevPod Pro as it has no exposed port and --no-tunnel is enabled")
+ return "", fmt.Errorf(
+ "%w: %s",
+ ErrLoftNotReachable,
+ "cannot connect to DevPod Pro as it has no exposed port and --no-tunnel is enabled",
+ )
}
// wait for router
url := ""
- waitErr := wait.PollUntilContextTimeout(ctx, time.Second, time.Minute*10, true, func(ctx context.Context) (bool, error) {
- url, err = cmd.findLoftRouter(ctx, containerID)
- if err != nil {
- return false, nil
- }
+ waitErr := wait.PollUntilContextTimeout(
+ ctx,
+ time.Second,
+ time.Minute*10,
+ true,
+ func(ctx context.Context) (bool, error) {
+ url, err = cmd.findLoftRouter(ctx, containerID)
+ if err != nil {
+ return false, nil
+ }
- return true, nil
- })
+ return true, nil
+ },
+ )
if waitErr != nil {
return "", fmt.Errorf("error waiting for loft router domain: %w", err)
}
@@ -602,7 +750,10 @@ func (cmd *StartCmd) prepareDocker() error {
// test for helm and kubectl
_, err := exec.LookPath("docker")
if err != nil {
- return fmt.Errorf("seems like docker is not installed. Docker is required for the installation of loft. Please visit https://docs.docker.com/engine/install/ for install instructions")
+ return fmt.Errorf(
+ "seems like docker is not installed. Docker is required for the installation of loft. " +
+ "Please visit https://docs.docker.com/engine/install/ for install instructions",
+ )
}
output, err := exec.Command("docker", "ps").CombinedOutput()
@@ -713,7 +864,11 @@ func (cmd *StartCmd) removeContainer(ctx context.Context, id string) error {
return nil
}
-func (cmd *StartCmd) findLoftContainer(ctx context.Context, name string, onlyRunning bool) (string, error) {
+func (cmd *StartCmd) findLoftContainer(
+ ctx context.Context,
+ name string,
+ onlyRunning bool,
+) (string, error) {
args := []string{"ps", "-q", "-a", "-f", "name=^" + name + "$"}
out, err := cmd.buildDockerCmd(ctx, args...).Output()
if err != nil {
@@ -758,23 +913,71 @@ func (cmd *StartCmd) prepareInstall(ctx context.Context) error {
return uninstall(ctx, cmd.KubeClient, cmd.RestConfig, cmd.Context, cmd.Namespace, log.Discard)
}
-func (cmd *StartCmd) prepare() error {
+func (cmd *StartCmd) prepare(ctx context.Context) error {
loader, err := client.NewClientFromPath(cmd.Config)
if err != nil {
return err
}
+
+ kubeClientConfig, err := cmd.resolveKubeConfig(loader)
+ if err != nil {
+ return err
+ }
+
+ if err := checkCLITools(ctx, cmd.Context); err != nil {
+ return err
+ }
+
+ cmd.RestConfig, err = kubeClientConfig.ClientConfig()
+ if err != nil {
+ return fmt.Errorf(
+ "there is an error loading your current kube config (%w), please make sure you have access "+
+ "to a kubernetes cluster and the command `kubectl get namespaces` is working",
+ err,
+ )
+ }
+ cmd.KubeClient, err = kubernetes.NewForConfig(cmd.RestConfig)
+ if err != nil {
+ return fmt.Errorf(
+ "there is an error loading your current kube config (%w), please make sure you have access "+
+ "to a kubernetes cluster and the command `kubectl get namespaces` is working",
+ err,
+ )
+ }
+
+ // Check if cluster has RBAC correctly configured
+ _, err = cmd.KubeClient.RbacV1().
+ ClusterRoles().
+ Get(ctx, "cluster-admin", metav1.GetOptions{})
+ if err != nil {
+ return fmt.Errorf(
+ "error retrieving cluster role 'cluster-admin': %w. Please make sure RBAC is correctly configured in your cluster",
+ err,
+ )
+ }
+
+ return nil
+}
+
+func (cmd *StartCmd) resolveKubeConfig(
+ loader client.Client,
+) (clientcmd.ClientConfig, error) {
loftConfig := loader.Config()
- // first load the kube config
- kubeClientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
+ kubeClientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
+ clientcmd.NewDefaultClientConfigLoadingRules(),
+ &clientcmd.ConfigOverrides{},
+ )
- // load the raw config
kubeConfig, err := kubeClientConfig.RawConfig()
if err != nil {
- return fmt.Errorf("there is an error loading your current kube config (%w), please make sure you have access to a kubernetes cluster and the command `kubectl get namespaces` is working", err)
+ return nil, fmt.Errorf(
+ "there is an error loading your current kube config (%w), please make sure you have access "+
+ "to a kubernetes cluster and the command `kubectl get namespaces` is working",
+ err,
+ )
}
- // we switch the context to the install config
contextToLoad := kubeConfig.CurrentContext
if cmd.Context != "" {
contextToLoad = cmd.Context
@@ -785,7 +988,7 @@ func (cmd *StartCmd) prepare() error {
Options: []string{contextToLoad, loftConfig.LastInstallContext},
})
if err != nil {
- return err
+ return nil, err
}
}
cmd.Context = contextToLoad
@@ -793,13 +996,21 @@ func (cmd *StartCmd) prepare() error {
loftConfig.LastInstallContext = contextToLoad
_ = loader.Save()
- // kube client config
- kubeClientConfig = clientcmd.NewNonInteractiveClientConfig(kubeConfig, contextToLoad, &clientcmd.ConfigOverrides{}, clientcmd.NewDefaultClientConfigLoadingRules())
+ return clientcmd.NewNonInteractiveClientConfig(
+ kubeConfig,
+ contextToLoad,
+ &clientcmd.ConfigOverrides{},
+ clientcmd.NewDefaultClientConfigLoadingRules(),
+ ), nil
+}
- // test for helm and kubectl
- _, err = exec.LookPath("helm")
+func checkCLITools(ctx context.Context, kubeContext string) error {
+ _, err := exec.LookPath("helm")
if err != nil {
- return fmt.Errorf("seems like helm is not installed. Helm is required for the installation of loft. Please visit https://helm.sh/docs/intro/install/ for install instructions")
+ return fmt.Errorf(
+ "seems like helm is not installed. Helm is required for the installation of loft. " +
+ "Please visit https://helm.sh/docs/intro/install/ for install instructions",
+ )
}
output, err := exec.Command("helm", "version").CombinedOutput()
@@ -809,27 +1020,25 @@ func (cmd *StartCmd) prepare() error {
_, err = exec.LookPath("kubectl")
if err != nil {
- return fmt.Errorf("seems like kubectl is not installed. Kubectl is required for the installation of loft. Please visit https://kubernetes.io/docs/tasks/tools/install-kubectl/ for install instructions")
- }
-
- output, err = exec.Command("kubectl", "version", "--context", contextToLoad).CombinedOutput()
- if err != nil {
- return fmt.Errorf("seems like kubectl cannot connect to your Kubernetes cluster: \n\n%s", output)
- }
-
- cmd.RestConfig, err = kubeClientConfig.ClientConfig()
- if err != nil {
- return fmt.Errorf("there is an error loading your current kube config (%w), please make sure you have access to a kubernetes cluster and the command `kubectl get namespaces` is working", err)
- }
- cmd.KubeClient, err = kubernetes.NewForConfig(cmd.RestConfig)
- if err != nil {
- return fmt.Errorf("there is an error loading your current kube config (%w), please make sure you have access to a kubernetes cluster and the command `kubectl get namespaces` is working", err)
+ return fmt.Errorf(
+ "seems like kubectl is not installed. Kubectl is required for the installation of loft. " +
+ "Please visit https://kubernetes.io/docs/tasks/tools/install-kubectl/ for install instructions",
+ )
}
- // Check if cluster has RBAC correctly configured
- _, err = cmd.KubeClient.RbacV1().ClusterRoles().Get(context.Background(), "cluster-admin", metav1.GetOptions{})
+ kubectlCmd := exec.CommandContext(
+ ctx,
+ "kubectl",
+ "version",
+ "--context",
+ kubeContext,
+ ) // #nosec G204
+ output, err = kubectlCmd.CombinedOutput()
if err != nil {
- return fmt.Errorf("error retrieving cluster role 'cluster-admin': %w. Please make sure RBAC is correctly configured in your cluster", err)
+ return fmt.Errorf(
+ "seems like kubectl cannot connect to your Kubernetes cluster: \n\n%s",
+ output,
+ )
}
return nil
@@ -921,7 +1130,7 @@ func (cmd *StartCmd) handleAlreadyExistingInstallation(ctx context.Context) erro
// Only upgrade if --upgrade flag is present or user decided to enable ingress
if cmd.Upgrade || enableIngress {
- err := cmd.upgrade()
+ err := cmd.upgrade(ctx)
if err != nil {
return err
}
@@ -940,7 +1149,13 @@ func (cmd *StartCmd) waitForDeployment(ctx context.Context) (*corev1.Pod, error)
}
// ensure user admin secret is there
- isNewPassword, err := ensureAdminPassword(ctx, cmd.KubeClient, cmd.RestConfig, cmd.Password, cmd.Log)
+ isNewPassword, err := ensureAdminPassword(
+ ctx,
+ cmd.KubeClient,
+ cmd.RestConfig,
+ cmd.Password,
+ cmd.Log,
+ )
if err != nil {
return nil, err
}
@@ -954,7 +1169,9 @@ func (cmd *StartCmd) waitForDeployment(ctx context.Context) (*corev1.Pod, error)
}
func (cmd *StartCmd) pingLoftRouter(ctx context.Context, loftPod *corev1.Pod) (string, error) {
- loftRouterSecret, err := cmd.KubeClient.CoreV1().Secrets(loftPod.Namespace).Get(ctx, LoftRouterDomainSecret, metav1.GetOptions{})
+ loftRouterSecret, err := cmd.KubeClient.CoreV1().
+ Secrets(loftPod.Namespace).
+ Get(ctx, LoftRouterDomainSecret, metav1.GetOptions{})
if err != nil {
if kerrors.IsNotFound(err) {
return "", nil
@@ -977,19 +1194,30 @@ func (cmd *StartCmd) pingLoftRouter(ctx context.Context, loftPod *corev1.Pod) (s
},
}
cmd.Log.Infof("Waiting until DevPod Pro is reachable at https://%s", loftRouterDomain)
- err = wait.PollUntilContextTimeout(ctx, time.Second*3, time.Minute*5, true, func(ctx context.Context) (bool, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+loftRouterDomain+"/version", nil)
- if err != nil {
- return false, nil
- }
+ err = wait.PollUntilContextTimeout(
+ ctx,
+ time.Second*3,
+ time.Minute*5,
+ true,
+ func(ctx context.Context) (bool, error) {
+ req, err := http.NewRequestWithContext(
+ ctx,
+ http.MethodGet,
+ "https://"+loftRouterDomain+"/version",
+ nil,
+ )
+ if err != nil {
+ return false, nil
+ }
- resp, err := httpClient.Do(req)
- if err != nil {
- return false, nil
- }
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return false, nil
+ }
- return resp.StatusCode == http.StatusOK, nil
- })
+ return resp.StatusCode == http.StatusOK, nil
+ },
+ )
if err != nil {
return "", err
}
@@ -1017,8 +1245,8 @@ func (cmd *StartCmd) successLoftRouter(url string) error {
########################## LOGIN ############################
-Username: `+ansi.Color("admin", "green+b")+`
-Password: `+ansi.Color(password, "green+b")+` # Change via UI or via: `+ansi.Color("devpod pro reset password", "green+b")+`
+Username: `+greenBold("admin")+`
+Password: `+greenBold(password)+` # Change via UI or via: `+greenBold("devpod pro reset password")+`
Login via UI: %s
Login via CLI: %s
@@ -1029,8 +1257,8 @@ DevPod Pro was successfully installed and can now be reached at: %s
Thanks for using DevPod Pro!
`,
- ansi.Color(url, "green+b"),
- ansi.Color("devpod pro login"+" "+url, "green+b"),
+ greenBold(url),
+ greenBold("devpod pro login"+" "+url),
url,
))
return nil
@@ -1044,7 +1272,7 @@ func (cmd *StartCmd) login(url string) error {
// check if we are already logged in
if cmd.isLoggedIn(url) {
// still open the UI
- err := open.Run(url)
+ err := devpodopen.Run(url)
if err != nil {
return fmt.Errorf("couldn't open the login page in a browser: %w", err)
}
@@ -1114,18 +1342,20 @@ func (cmd *StartCmd) loginViaCLI(url string) error {
}
cmd.Log.WriteString(logrus.InfoLevel, "\n")
- cmd.Log.WithFields(logrus.Fields{
- "url": url,
- }).Donef("logged in via CLI")
+ cmd.Log.Donef("logged in via CLI: url=%s", url)
return nil
}
func (cmd *StartCmd) loginUI(url string) error {
- queryString := fmt.Sprintf("username=%s&password=%s", defaultUser, netUrl.QueryEscape(cmd.Password))
+ queryString := fmt.Sprintf(
+ "username=%s&password=%s",
+ defaultUser,
+ netUrl.QueryEscape(cmd.Password),
+ )
loginURL := fmt.Sprintf("%s/login#%s", url, queryString)
- err := open.Run(loginURL)
+ err := devpodopen.Run(loginURL)
if err != nil {
return fmt.Errorf("couldn't open the login page in a browser: %w", err)
}
@@ -1139,12 +1369,27 @@ func (cmd *StartCmd) isLoggedIn(url string) bool {
url = strings.TrimPrefix(url, "https://")
c, err := client.NewClientFromPath(cmd.Config)
- return err == nil && strings.TrimPrefix(strings.TrimSuffix(c.Config().Host, "/"), "https://") == strings.TrimSuffix(url, "/")
+ return err == nil &&
+ strings.TrimPrefix(
+ strings.TrimSuffix(c.Config().Host, "/"),
+ "https://",
+ ) == strings.TrimSuffix(
+ url,
+ "/",
+ )
}
-func uninstall(ctx context.Context, kubeClient kubernetes.Interface, restConfig *rest.Config, kubeContext, namespace string, log log.Logger) error {
- releaseName := "devpod-pro"
- deploy, err := kubeClient.AppsV1().Deployments(namespace).Get(ctx, defaultDeploymentName, metav1.GetOptions{})
+func uninstall(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ restConfig *rest.Config,
+ kubeContext, namespace string,
+ log log.Logger,
+) error {
+ releaseName := config.ProReleaseName
+ deploy, err := kubeClient.AppsV1().
+ Deployments(namespace).
+ Get(ctx, defaultDeploymentName, metav1.GetOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
} else if deploy != nil && deploy.Labels != nil && deploy.Labels["release"] != "" {
@@ -1160,7 +1405,8 @@ func uninstall(ctx context.Context, kubeClient kubernetes.Interface, restConfig
namespace,
}
log.Infof("Executing command: helm %s", strings.Join(args, " "))
- output, err := exec.Command("helm", args...).CombinedOutput()
+ helmCmd := exec.CommandContext(ctx, "helm", args...) // #nosec G204 -- internally constructed
+ output, err := helmCmd.CombinedOutput()
if err != nil {
log.Errorf("error during helm command: %s (%v)", string(output), err)
}
@@ -1171,7 +1417,9 @@ func uninstall(ctx context.Context, kubeClient kubernetes.Interface, restConfig
return err
}
- err = apiRegistrationClient.ApiregistrationV1().APIServices().Delete(ctx, "v1.management.loft.sh", metav1.DeleteOptions{})
+ err = apiRegistrationClient.ApiregistrationV1().
+ APIServices().
+ Delete(ctx, "v1.management.loft.sh", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
@@ -1181,38 +1429,52 @@ func uninstall(ctx context.Context, kubeClient kubernetes.Interface, restConfig
return err
}
- err = kubeClient.CoreV1().Secrets(namespace).Delete(context.Background(), "loft-user-secret-admin", metav1.DeleteOptions{})
+ err = kubeClient.CoreV1().
+ Secrets(namespace).
+ Delete(ctx, "loft-user-secret-admin", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
- err = kubeClient.CoreV1().Secrets(namespace).Delete(context.Background(), LoftRouterDomainSecret, metav1.DeleteOptions{})
+ err = kubeClient.CoreV1().
+ Secrets(namespace).
+ Delete(ctx, LoftRouterDomainSecret, metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
// we also cleanup the validating webhook configuration and apiservice
- err = kubeClient.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(ctx, "loft-agent", metav1.DeleteOptions{})
+ err = kubeClient.AdmissionregistrationV1().
+ ValidatingWebhookConfigurations().
+ Delete(ctx, "loft-agent", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
- err = apiRegistrationClient.ApiregistrationV1().APIServices().Delete(ctx, "v1alpha1.tenancy.kiosk.sh", metav1.DeleteOptions{})
+ err = apiRegistrationClient.ApiregistrationV1().
+ APIServices().
+ Delete(ctx, "v1alpha1.tenancy.kiosk.sh", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
- err = apiRegistrationClient.ApiregistrationV1().APIServices().Delete(ctx, "v1.cluster.loft.sh", metav1.DeleteOptions{})
+ err = apiRegistrationClient.ApiregistrationV1().
+ APIServices().
+ Delete(ctx, "v1.cluster.loft.sh", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
- err = kubeClient.CoreV1().ConfigMaps(namespace).Delete(ctx, "loft-agent-controller", metav1.DeleteOptions{})
+ err = kubeClient.CoreV1().
+ ConfigMaps(namespace).
+ Delete(ctx, "loft-agent-controller", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
- err = kubeClient.CoreV1().ConfigMaps(namespace).Delete(ctx, "loft-applied-defaults", metav1.DeleteOptions{})
+ err = kubeClient.CoreV1().
+ ConfigMaps(namespace).
+ Delete(ctx, "loft-applied-defaults", metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return err
}
@@ -1224,8 +1486,14 @@ func uninstall(ctx context.Context, kubeClient kubernetes.Interface, restConfig
return nil
}
-func isAlreadyInstalled(ctx context.Context, kubeClient kubernetes.Interface, namespace string) (bool, error) {
- _, err := kubeClient.AppsV1().Deployments(namespace).Get(ctx, defaultDeploymentName, metav1.GetOptions{})
+func isAlreadyInstalled(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ namespace string,
+) (bool, error) {
+ _, err := kubeClient.AppsV1().
+ Deployments(namespace).
+ Get(ctx, defaultDeploymentName, metav1.GetOptions{})
if err != nil {
if kerrors.IsNotFound(err) {
return false, nil
@@ -1237,7 +1505,11 @@ func isAlreadyInstalled(ctx context.Context, kubeClient kubernetes.Interface, na
return true, nil
}
-func getDefaultPassword(ctx context.Context, kubeClient kubernetes.Interface, namespace string) (string, error) {
+func getDefaultPassword(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ namespace string,
+) (string, error) {
loftNamespace, err := kubeClient.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if err != nil {
if kerrors.IsNotFound(err) {
@@ -1259,10 +1531,18 @@ func getDefaultPassword(ctx context.Context, kubeClient kubernetes.Interface, na
return string(loftNamespace.UID), nil
}
-func isInstalledLocally(ctx context.Context, kubeClient kubernetes.Interface, namespace string) bool {
- _, err := kubeClient.NetworkingV1().Ingresses(namespace).Get(ctx, "loft-ingress", metav1.GetOptions{})
+func isInstalledLocally(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ namespace string,
+) bool {
+ _, err := kubeClient.NetworkingV1().
+ Ingresses(namespace).
+ Get(ctx, "loft-ingress", metav1.GetOptions{})
if err != nil && !kerrors.IsNotFound(err) {
- _, err = kubeClient.NetworkingV1beta1().Ingresses(namespace).Get(ctx, "loft-ingress", metav1.GetOptions{})
+ _, err = kubeClient.NetworkingV1beta1().
+ Ingresses(namespace).
+ Get(ctx, "loft-ingress", metav1.GetOptions{})
return kerrors.IsNotFound(err)
}
@@ -1271,18 +1551,29 @@ func isInstalledLocally(ctx context.Context, kubeClient kubernetes.Interface, na
func enterHostNameQuestion(log log.Logger) (string, error) {
return log.Question(&survey.QuestionOptions{
- Question: fmt.Sprintf("Enter a hostname for your %s instance (e.g. loft.my-domain.tld): \n ", "DevPod Pro"),
+ Question: fmt.Sprintf(
+ "Enter a hostname for your %s instance (e.g. loft.my-domain.tld): \n ",
+ config.ProductNamePro,
+ ),
ValidationFunc: func(answer string) error {
u, err := netUrl.Parse("https://" + answer)
if err != nil || u.Path != "" || u.Port() != "" || len(strings.Split(answer, ".")) < 2 {
- return fmt.Errorf("please enter a valid hostname without protocol (https://), without path and without port, e.g. loft.my-domain.tld")
+ return fmt.Errorf(
+ "please enter a valid hostname without protocol (https://), without path and without port, " +
+ "e.g. loft.my-domain.tld",
+ )
}
return nil
},
})
}
-func ensureIngressController(ctx context.Context, kubeClient kubernetes.Interface, kubeContext string, log log.Logger) error {
+func ensureIngressController(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ kubeContext string,
+ log log.Logger,
+) error {
// first create an ingress controller
const (
YesOption = "Yes"
@@ -1321,7 +1612,10 @@ func ensureIngressController(ctx context.Context, kubeClient kubernetes.Interfac
log.WriteString(logrus.InfoLevel, "\n")
log.Infof("Executing command: helm %s\n", strings.Join(args, " "))
log.Info("Waiting for ingress controller deployment, this can take several minutes...")
- helmCmd := exec.Command("helm", args...)
+ helmCmd := exec.CommandContext(
+ ctx,
+ "helm",
+ args...) // #nosec G204 -- helm args are constructed internally
output, err := helmCmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error during helm command: %s (%w)", string(output), err)
@@ -1355,7 +1649,9 @@ func ensureIngressController(ctx context.Context, kubeClient kubernetes.Interfac
if err != nil {
return err
}
- _, err = kubeClient.CoreV1().Secrets(secret.Namespace).Patch(ctx, secret.Name, types.MergePatchType, data, metav1.PatchOptions{})
+ _, err = kubeClient.CoreV1().
+ Secrets(secret.Namespace).
+ Patch(ctx, secret.Name, types.MergePatchType, data, metav1.PatchOptions{})
if err != nil {
return err
}
@@ -1396,7 +1692,13 @@ func deleteUser(ctx context.Context, restConfig *rest.Config, name string) error
return nil
}
-func ensureAdminPassword(ctx context.Context, kubeClient kubernetes.Interface, restConfig *rest.Config, password string, log log.Logger) (bool, error) {
+func ensureAdminPassword(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ restConfig *rest.Config,
+ password string,
+ log log.Logger,
+) (bool, error) {
loftClient, err := loftclientset.NewForConfig(restConfig)
if err != nil {
return false, err
@@ -1436,7 +1738,9 @@ func ensureAdminPassword(ctx context.Context, kubeClient kubernetes.Interface, r
passwordHash := fmt.Sprintf("%x", sha256.Sum256([]byte(password)))
- secret, err := kubeClient.CoreV1().Secrets(admin.Spec.PasswordRef.SecretNamespace).Get(ctx, admin.Spec.PasswordRef.SecretName, metav1.GetOptions{})
+ secret, err := kubeClient.CoreV1().
+ Secrets(admin.Spec.PasswordRef.SecretNamespace).
+ Get(ctx, admin.Spec.PasswordRef.SecretName, metav1.GetOptions{})
if err != nil && !kerrors.IsNotFound(err) {
return false, err
} else if err == nil {
@@ -1446,7 +1750,9 @@ func ensureAdminPassword(ctx context.Context, kubeClient kubernetes.Interface, r
}
secret.Data[key] = []byte(passwordHash)
- _, err = kubeClient.CoreV1().Secrets(secret.Namespace).Update(ctx, secret, metav1.UpdateOptions{})
+ _, err = kubeClient.CoreV1().
+ Secrets(secret.Namespace).
+ Update(ctx, secret, metav1.UpdateOptions{})
if err != nil {
return false, fmt.Errorf("update admin password secret: %w", err)
}
@@ -1463,7 +1769,9 @@ func ensureAdminPassword(ctx context.Context, kubeClient kubernetes.Interface, r
key: []byte(passwordHash),
},
}
- _, err = kubeClient.CoreV1().Secrets(secret.Namespace).Create(ctx, secret, metav1.CreateOptions{})
+ _, err = kubeClient.CoreV1().
+ Secrets(secret.Namespace).
+ Create(ctx, secret, metav1.CreateOptions{})
if err != nil {
return false, fmt.Errorf("create admin password secret: %w", err)
}
@@ -1472,10 +1780,18 @@ func ensureAdminPassword(ctx context.Context, kubeClient kubernetes.Interface, r
return false, nil
}
-func getIngressHost(ctx context.Context, kubeClient kubernetes.Interface, namespace string) (string, error) {
- ingress, err := kubeClient.NetworkingV1().Ingresses(namespace).Get(ctx, "loft-ingress", metav1.GetOptions{})
- if err != nil {
- ingress, err := kubeClient.NetworkingV1beta1().Ingresses(namespace).Get(ctx, "loft-ingress", metav1.GetOptions{})
+func getIngressHost(
+ ctx context.Context,
+ kubeClient kubernetes.Interface,
+ namespace string,
+) (string, error) {
+ ingress, err := kubeClient.NetworkingV1().
+ Ingresses(namespace).
+ Get(ctx, "loft-ingress", metav1.GetOptions{})
+ if err != nil {
+ ingress, err := kubeClient.NetworkingV1beta1().
+ Ingresses(namespace).
+ Get(ctx, "loft-ingress", metav1.GetOptions{})
if err != nil {
return "", err
} else {
@@ -1491,7 +1807,11 @@ func getIngressHost(ctx context.Context, kubeClient kubernetes.Interface, namesp
}
}
- return "", fmt.Errorf("couldn't find any host in loft ingress '%s/loft-ingress', please make sure you have not changed any deployed resources", namespace)
+ return "", fmt.Errorf(
+ "couldn't find any host in loft ingress '%s/loft-ingress', "+
+ "please make sure you have not changed any deployed resources",
+ namespace,
+ )
}
type version struct {
@@ -1520,9 +1840,19 @@ func isHostReachable(ctx context.Context, host string) (bool, error) {
v := &version{}
err = json.Unmarshal(out, v)
if err != nil {
- return false, fmt.Errorf("error decoding response from %s: %w. Try running '%s --reset'", url, err, "devpod pro start")
+ return false, fmt.Errorf(
+ "error decoding response from %s: %w. Try running '%s --reset'",
+ url,
+ err,
+ "devpod pro start",
+ )
} else if v.Version == "" {
- return false, fmt.Errorf("unexpected response from %s: %s. Try running '%s --reset'", url, string(out), "devpod pro start")
+ return false, fmt.Errorf(
+ "unexpected response from %s: %s. Try running '%s --reset'",
+ url,
+ string(out),
+ "devpod pro start",
+ )
}
return true, nil
@@ -1531,7 +1861,12 @@ func isHostReachable(ctx context.Context, host string) (bool, error) {
return false, nil
}
-func upgradeRelease(chartName, chartRepo, kubeContext, namespace string, extraArgs []string, log log.Logger) error {
+func upgradeRelease(
+ ctx context.Context,
+ chartName, chartRepo, kubeContext, namespace string,
+ extraArgs []string,
+ log log.Logger,
+) error {
// now we install loft
args := []string{
"upgrade",
@@ -1553,7 +1888,10 @@ func upgradeRelease(chartName, chartRepo, kubeContext, namespace string, extraAr
log.WriteString(logrus.InfoLevel, "\n")
log.Infof("Executing command: helm %s\n", strings.Join(args, " "))
log.Info("Waiting for helm command, this can take up to several minutes...")
- helmCmd := exec.Command("helm", args...)
+ helmCmd := exec.CommandContext(
+ ctx,
+ "helm",
+ args...) // #nosec G204 -- helm args are constructed internally
if chartRepo != "" {
helmWorkDir, err := getHelmWorkdir(chartName)
if err != nil {
@@ -1571,7 +1909,12 @@ func upgradeRelease(chartName, chartRepo, kubeContext, namespace string, extraAr
return nil
}
-func getReleaseManifests(chartName, chartRepo, kubeContext, namespace string, extraArgs []string, _ log.Logger) (string, error) {
+func getReleaseManifests(
+ ctx context.Context,
+ chartName, chartRepo, kubeContext, namespace string,
+ extraArgs []string,
+ _ log.Logger,
+) (string, error) {
args := []string{
"template",
defaultReleaseName,
@@ -1587,7 +1930,10 @@ func getReleaseManifests(chartName, chartRepo, kubeContext, namespace string, ex
}
args = append(args, extraArgs...)
- helmCmd := exec.Command("helm", args...)
+ helmCmd := exec.CommandContext(
+ ctx,
+ "helm",
+ args...) // #nosec G204 -- helm args are constructed internally
if chartRepo != "" {
helmWorkDir, err := getHelmWorkdir(chartName)
if err != nil {
@@ -1612,7 +1958,9 @@ func getHelmWorkdir(chartName string) (string, error) {
if _, err := os.Stat(path.Join(tempDir, chartName)); err == nil {
tempDir, err = os.MkdirTemp(tempDir, chartName)
if err != nil {
- return "", errors.New("problematic directory `" + chartName + "` found: please execute command in a different folder")
+ return "", errors.New(
+ "problematic directory `" + chartName + "` found: please execute command in a different folder",
+ )
}
}
@@ -1709,3 +2057,8 @@ func getMachineUID(log log.Logger) string {
mac.Write([]byte(home))
return fmt.Sprintf("%x", mac.Sum(nil))
}
+
+// greenBold wraps s in ANSI escape codes for green bold text.
+func greenBold(s string) string {
+ return "\033[32;1m" + s + "\033[0m"
+}
diff --git a/cmd/pro/update_provider.go b/cmd/pro/update_provider.go
index 7bce9b6738..00ef004195 100644
--- a/cmd/pro/update_provider.go
+++ b/cmd/pro/update_provider.go
@@ -13,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
-// UpdateProviderCmd holds the cmd flags
+// UpdateProviderCmd holds the cmd flags.
type UpdateProviderCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -22,7 +22,7 @@ type UpdateProviderCmd struct {
Instance string
}
-// NewUpdateProviderCmd creates a new command
+// NewUpdateProviderCmd creates a new command.
func NewUpdateProviderCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &UpdateProviderCmd{
GlobalFlags: globalFlags,
@@ -76,7 +76,17 @@ func (cmd *UpdateProviderCmd) Run(ctx context.Context, args []string) error {
return fmt.Errorf("update provider %s: %w", provider.Name, err)
}
- err = providercmd.ConfigureProvider(ctx, provider, devPodConfig.DefaultContext, []string{}, true, true, true, nil, log.Discard)
+ err = providercmd.ConfigureProvider(ctx, providercmd.ProviderOptionsConfig{
+ Provider: provider,
+ Context: devPodConfig.DefaultContext,
+ UserOptions: []string{},
+ Reconfigure: true,
+ SkipRequired: true,
+ SkipInit: true,
+ SkipSubOptions: false,
+ SingleMachine: nil,
+ Log: log.Discard,
+ })
if err != nil {
return fmt.Errorf(
"configure provider, please retry with 'devpod provider use %s --reconfigure': %w",
diff --git a/cmd/pro/update_workspace.go b/cmd/pro/update_workspace.go
index 0b67396fee..d6ed2bb49e 100644
--- a/cmd/pro/update_workspace.go
+++ b/cmd/pro/update_workspace.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// UpdateWorkspaceCmd holds the cmd flags
+// UpdateWorkspaceCmd holds the cmd flags.
type UpdateWorkspaceCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -24,7 +24,7 @@ type UpdateWorkspaceCmd struct {
Instance string
}
-// NewUpdateWorkspaceCmd creates a new command
+// NewUpdateWorkspaceCmd creates a new command.
func NewUpdateWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &UpdateWorkspaceCmd{
GlobalFlags: globalFlags,
@@ -35,7 +35,13 @@ func NewUpdateWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Update workspace instance",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -52,7 +58,11 @@ func NewUpdateWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *UpdateWorkspaceCmd) Run(ctx context.Context, devPodConfig *config.Config, provider *provider.ProviderConfig) error {
+func (cmd *UpdateWorkspaceCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider.ProviderConfig,
+) error {
opts := devPodConfig.ProviderOptions(provider.Name)
opts[platform.WorkspaceInstanceEnv] = config.OptionValue{Value: cmd.Instance}
diff --git a/cmd/pro/version.go b/cmd/pro/version.go
index d4287c218b..a030d9835c 100644
--- a/cmd/pro/version.go
+++ b/cmd/pro/version.go
@@ -14,7 +14,7 @@ import (
"github.com/spf13/cobra"
)
-// VersionCmd holds the cmd flags
+// VersionCmd holds the cmd flags.
type VersionCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -22,7 +22,7 @@ type VersionCmd struct {
Host string
}
-// NewVersionCmd creates a new command
+// NewVersionCmd creates a new command.
func NewVersionCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &VersionCmd{
GlobalFlags: globalFlags,
@@ -33,7 +33,13 @@ func NewVersionCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Get version",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -48,10 +54,14 @@ func NewVersionCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
return c
}
-func (cmd *VersionCmd) Run(ctx context.Context, devPodConfig *config.Config, providerConfig *provider.ProviderConfig) error {
+func (cmd *VersionCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ providerConfig *provider.ProviderConfig,
+) error {
opts := devPodConfig.ProviderOptions(providerConfig.Name)
- opts[provider.PROVIDER_ID] = config.OptionValue{Value: providerConfig.Name}
- opts[provider.PROVIDER_CONTEXT] = config.OptionValue{Value: cmd.Context}
+ opts[config.EnvProviderID] = config.OptionValue{Value: providerConfig.Name}
+ opts[config.EnvProviderContext] = config.OptionValue{Value: cmd.Context}
var buf bytes.Buffer
// ignore --debug because we tunnel json through stdio
diff --git a/cmd/pro/wakeup.go b/cmd/pro/wakeup.go
index 4ca1bdbd6b..d42f4190c1 100644
--- a/cmd/pro/wakeup.go
+++ b/cmd/pro/wakeup.go
@@ -6,9 +6,8 @@ import (
"strconv"
"time"
- clusterv1 "github.com/loft-sh/agentapi/v4/pkg/apis/loft/cluster/v1"
- storagev1 "github.com/loft-sh/api/v4/pkg/apis/storage/v1"
- "github.com/sirupsen/logrus"
+ clusterv1 "github.com/skevetter/agentapi/pkg/apis/devsy/cluster/v1"
+ storagev1 "github.com/skevetter/api/pkg/apis/storage/v1"
"github.com/skevetter/devpod/cmd/pro/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/platform"
@@ -20,7 +19,7 @@ import (
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
)
-// WakeupCmd holds the cmd flags
+// WakeupCmd holds the cmd flags.
type WakeupCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -29,7 +28,7 @@ type WakeupCmd struct {
Host string
}
-// NewWakeupCmd creates a new command
+// NewWakeupCmd creates a new command.
func NewWakeupCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WakeupCmd{
GlobalFlags: globalFlags,
@@ -69,13 +68,14 @@ func (cmd *WakeupCmd) Run(ctx context.Context, args []string) error {
return err
}
- workspaceInstance, err := platform.FindInstanceByName(ctx, baseClient, targetWorkspace, cmd.Project)
+ opts := platform.FindInstanceOptions{Name: targetWorkspace, ProjectName: cmd.Project}
+ workspaceInstance, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return err
}
if workspaceInstance.Status.Phase != storagev1.InstanceSleeping {
- cmd.Log.Infof("Workspace %s is not sleeping", targetWorkspace, workspaceInstance.Name)
+ cmd.Log.Infof("Workspace %s is not sleeping", workspaceInstance.Name)
return nil
}
@@ -97,35 +97,47 @@ func (cmd *WakeupCmd) Run(ctx context.Context, args []string) error {
}
delete(workspaceInstance.Annotations, clusterv1.SleepModeForceAnnotation)
delete(workspaceInstance.Annotations, clusterv1.SleepModeForceDurationAnnotation)
- workspaceInstance.Annotations[clusterv1.SleepModeLastActivityAnnotation] = strconv.FormatInt(time.Now().Unix(), 10)
+ workspaceInstance.Annotations[clusterv1.SleepModeLastActivityAnnotation] = strconv.FormatInt(
+ time.Now().Unix(),
+ 10,
+ )
patchData, err := patch.Data(workspaceInstance)
if err != nil {
return err
}
- _, err = managementClient.Loft().ManagementV1().DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).Patch(ctx, workspaceInstance.Name, patch.Type(), patchData, metav1.PatchOptions{})
+ _, err = managementClient.Loft().
+ ManagementV1().
+ DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).
+ Patch(ctx, workspaceInstance.Name, patch.Type(), patchData, metav1.PatchOptions{})
if err != nil {
return err
}
// wait for sleeping
cmd.Log.Info("Wait until workspace wakes up...")
- err = wait.PollUntilContextTimeout(ctx, time.Second, platform.Timeout(), false, func(ctx context.Context) (done bool, err error) {
- workspaceInstance, err := managementClient.Loft().ManagementV1().DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).Get(ctx, workspaceInstance.Name, metav1.GetOptions{})
- if err != nil {
- return false, err
- }
-
- return workspaceInstance.Status.Phase == storagev1.InstanceReady, nil
- })
+ err = wait.PollUntilContextTimeout(
+ ctx,
+ time.Second,
+ platform.Timeout(),
+ false,
+ func(ctx context.Context) (done bool, err error) {
+ workspaceInstance, err := managementClient.Loft().
+ ManagementV1().
+ DevPodWorkspaceInstances(project.ProjectNamespace(cmd.Project)).
+ Get(ctx, workspaceInstance.Name, metav1.GetOptions{})
+ if err != nil {
+ return false, err
+ }
+
+ return workspaceInstance.Status.Phase == storagev1.InstanceReady, nil
+ },
+ )
if err != nil {
return fmt.Errorf("error waiting for workspace to wake up: %w", err)
}
- cmd.Log.WithFields(logrus.Fields{
- "workspaceName": workspaceInstance.Name,
- })
- cmd.Log.Donef("woke up workspace")
+ cmd.Log.Donef("woke up workspace: workspaceName=%s", workspaceInstance.Name)
return nil
}
diff --git a/cmd/pro/watch_workspaces.go b/cmd/pro/watch_workspaces.go
index 275c9761a0..289707c120 100644
--- a/cmd/pro/watch_workspaces.go
+++ b/cmd/pro/watch_workspaces.go
@@ -16,7 +16,7 @@ import (
"github.com/spf13/cobra"
)
-// WatchWorkspacesCmd holds the cmd flags
+// WatchWorkspacesCmd holds the cmd flags.
type WatchWorkspacesCmd struct {
*flags.GlobalFlags
Log log.Logger
@@ -26,7 +26,7 @@ type WatchWorkspacesCmd struct {
FilterByOwner bool
}
-// NewWatchWorkspacesCmd creates a new command
+// NewWatchWorkspacesCmd creates a new command.
func NewWatchWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &WatchWorkspacesCmd{
GlobalFlags: globalFlags,
@@ -37,7 +37,13 @@ func NewWatchWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
Short: "Watch workspaces",
Hidden: true,
RunE: func(cobraCmd *cobra.Command, args []string) error {
- devPodConfig, provider, err := findProProvider(cobraCmd.Context(), cmd.Context, cmd.Provider, cmd.Host, cmd.Log)
+ devPodConfig, provider, err := findProProvider(
+ cobraCmd.Context(),
+ cmd.Context,
+ cmd.Provider,
+ cmd.Host,
+ cmd.Log,
+ )
if err != nil {
return err
}
@@ -50,20 +56,25 @@ func NewWatchWorkspacesCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
_ = c.MarkFlagRequired("host")
c.Flags().StringVar(&cmd.Project, "project", "", "The project to use")
_ = c.MarkFlagRequired("project")
- c.Flags().BoolVar(&cmd.FilterByOwner, "filter-by-owner", true, "If true only shows workspaces of current owner")
+ c.Flags().
+ BoolVar(&cmd.FilterByOwner, "filter-by-owner", true, "If true only shows workspaces of current owner")
return c
}
-func (cmd *WatchWorkspacesCmd) Run(ctx context.Context, devPodConfig *config.Config, providerConfig *provider.ProviderConfig) error {
+func (cmd *WatchWorkspacesCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ providerConfig *provider.ProviderConfig,
+) error {
opts := devPodConfig.ProviderOptions(providerConfig.Name)
cancelCtx, cancel := context.WithCancel(ctx)
defer cancel()
if cmd.FilterByOwner {
- opts[provider.LOFT_FILTER_BY_OWNER] = config.OptionValue{Value: "true"}
+ opts[config.EnvLoftFilterByOwner] = config.OptionValue{Value: "true"}
}
- opts[provider.LOFT_PROJECT] = config.OptionValue{Value: cmd.Project}
+ opts[config.EnvLoftProject] = config.OptionValue{Value: cmd.Project}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)
diff --git a/cmd/profile.go b/cmd/profile.go
index 8a2ccd5e5f..c2e5a8c16d 100644
--- a/cmd/profile.go
+++ b/cmd/profile.go
@@ -23,9 +23,11 @@ func init() {
return
}
- f, err := os.OpenFile("/tmp/pprof_ports", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ f, err := os.OpenFile("/tmp/pprof_ports", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err == nil {
- f.Write([]byte(fmt.Sprintf("%d=%d\n", os.Getpid(), listener.Addr().(*net.TCPAddr).Port)))
+ f.Write(
+ []byte(fmt.Sprintf("%d=%d\n", os.Getpid(), listener.Addr().(*net.TCPAddr).Port)),
+ )
f.Close()
}
diff --git a/cmd/provider/add.go b/cmd/provider/add.go
index 2ea9d2f945..531a8b79bb 100644
--- a/cmd/provider/add.go
+++ b/cmd/provider/add.go
@@ -5,7 +5,6 @@ import (
"fmt"
"strings"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/provider"
@@ -15,7 +14,7 @@ import (
"github.com/spf13/cobra"
)
-// AddCmd holds the cmd flags
+// AddCmd holds the cmd flags.
type AddCmd struct {
*flags.GlobalFlags
@@ -27,14 +26,15 @@ type AddCmd struct {
FromExisting string
}
-// NewAddCmd creates a new command
+// NewAddCmd creates a new command.
func NewAddCmd(f *flags.GlobalFlags) *cobra.Command {
cmd := &AddCmd{
GlobalFlags: f,
}
addCmd := &cobra.Command{
- Use: "add [URL or path]",
+ Use: "add [name, GitHub link, URL or path]",
Short: "Adds a new provider to DevPod",
+ Args: cobra.MaximumNArgs(1),
PreRunE: func(cobraCommand *cobra.Command, args []string) error {
if cmd.FromExisting != "" {
return cobraCommand.MarkFlagRequired("name")
@@ -42,8 +42,8 @@ func NewAddCmd(f *flags.GlobalFlags) *cobra.Command {
return nil
},
- RunE: func(_ *cobra.Command, args []string) error {
- ctx := context.Background()
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ ctx := cobraCmd.Context()
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
@@ -52,39 +52,65 @@ func NewAddCmd(f *flags.GlobalFlags) *cobra.Command {
},
}
- addCmd.Flags().BoolVar(&cmd.SingleMachine, "single-machine", false, "If enabled will use a single machine for all workspaces")
- addCmd.Flags().StringVar(&cmd.Name, "name", "", "The name to use for this provider. If empty will use the name within the loaded config")
- addCmd.Flags().StringVar(&cmd.FromExisting, "from-existing", "", "The name of an existing provider to use as a template. Needs to be used in conjunction with the --name flag")
- addCmd.Flags().BoolVar(&cmd.Use, "use", true, "If enabled will automatically activate the provider")
- addCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
+ addCmd.Flags().
+ BoolVar(&cmd.SingleMachine, "single-machine", false, "If enabled will use a single machine for all workspaces")
+ addCmd.Flags().
+ StringVar(&cmd.Name, "name", "",
+ "The name for the new provider. If not specified, the name from the provider's configuration file will be used")
+ addCmd.Flags().
+ StringVar(&cmd.FromExisting, "from-existing", "",
+ "The name of an existing provider to use as a template. Needs to be used in conjunction with the --name flag")
+ addCmd.Flags().
+ BoolVar(&cmd.Use, "use", true, "If enabled will automatically activate the provider")
+ addCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
return addCmd
}
func (cmd *AddCmd) Run(ctx context.Context, devPodConfig *config.Config, args []string) error {
- if len(args) != 1 && cmd.FromExisting == "" {
- return fmt.Errorf("please specify either a local file, URL or Git repository. " +
- "E.g. devpod provider add https://path/to/my/provider.yaml")
- } else if cmd.Name != "" && provider.ProviderNameRegEx.MatchString(cmd.Name) {
- return fmt.Errorf("provider name can only include smaller case letters, numbers or dashes")
- } else if cmd.Name != "" && len(cmd.Name) > 32 {
- return fmt.Errorf("provider name cannot be longer than 32 characters")
- } else if cmd.FromExisting != "" && devPodConfig.Current() != nil && devPodConfig.Current().Providers[cmd.FromExisting] == nil {
- return fmt.Errorf("provider %s does not exist", cmd.FromExisting)
+ providerName := cmd.Name
+
+ if providerName != "" {
+ if provider.ProviderNameRegEx.MatchString(providerName) {
+ return fmt.Errorf(
+ "provider name can only include lowercase letters, numbers or dashes",
+ )
+ }
+ if len(providerName) > 32 {
+ return fmt.Errorf("provider name cannot be longer than 32 characters")
+ }
}
var providerConfig *provider.ProviderConfig
var options []string
if cmd.FromExisting != "" {
- providerWithOptions, err := workspace.CloneProvider(devPodConfig, cmd.Name, cmd.FromExisting, log.Default)
+ if devPodConfig.Current() == nil ||
+ devPodConfig.Current().Providers[cmd.FromExisting] == nil {
+ return fmt.Errorf("provider %s does not exist", cmd.FromExisting)
+ }
+ providerWithOptions, err := workspace.CloneProvider(
+ devPodConfig,
+ providerName,
+ cmd.FromExisting,
+ log.Default,
+ )
if err != nil {
return err
}
providerConfig = providerWithOptions.Config
- options = mergeOptions(providerWithOptions.Config.Options, providerWithOptions.State.Options, cmd.Options)
+ options = mergeOptions(
+ providerWithOptions.Config.Options,
+ providerWithOptions.State.Options,
+ cmd.Options,
+ )
} else {
- c, err := workspace.AddProvider(devPodConfig, cmd.Name, args[0], log.Default)
+ if len(args) != 1 {
+ return fmt.Errorf("please specify either a URL or path, " +
+ "e.g. devpod provider add https://path/to/my/provider.yaml")
+ }
+ c, err := workspace.AddProvider(devPodConfig, providerName, args[0], log.Default)
if err != nil {
return err
}
@@ -92,11 +118,19 @@ func (cmd *AddCmd) Run(ctx context.Context, devPodConfig *config.Config, args []
options = cmd.Options
}
- log.WithFields(logrus.Fields{
- "providerName": providerConfig.Name,
- }).Done("installed provider")
+ log.Default.Donef("installed provider: providerName=%s", providerConfig.Name)
if cmd.Use {
- configureErr := ConfigureProvider(ctx, providerConfig, devPodConfig.DefaultContext, options, true, false, false, &cmd.SingleMachine, log.Default)
+ configureErr := ConfigureProvider(ctx, ProviderOptionsConfig{
+ Provider: providerConfig,
+ Context: devPodConfig.DefaultContext,
+ UserOptions: options,
+ Reconfigure: true,
+ SkipRequired: false,
+ SkipInit: false,
+ SkipSubOptions: false,
+ SingleMachine: &cmd.SingleMachine,
+ Log: log.Default,
+ })
if configureErr != nil {
devPodConfig, err := config.LoadConfig(cmd.Context, "")
if err != nil {
@@ -119,8 +153,12 @@ func (cmd *AddCmd) Run(ctx context.Context, devPodConfig *config.Config, args []
return nil
}
-// mergeOptions combines user options with existing options, user provided options take precedence
-func mergeOptions(desiredOptions map[string]*types.Option, stateOptions map[string]config.OptionValue, userOptions []string) []string {
+// mergeOptions combines user options with existing options, user provided options take precedence.
+func mergeOptions(
+ desiredOptions map[string]*types.Option,
+ stateOptions map[string]config.OptionValue,
+ userOptions []string,
+) []string {
retOptions := []string{}
for key := range desiredOptions {
userOption, ok := getUserOption(userOptions, key)
diff --git a/cmd/provider/delete.go b/cmd/provider/delete.go
index 2ccc1b8bd3..4809ceae06 100644
--- a/cmd/provider/delete.go
+++ b/cmd/provider/delete.go
@@ -5,7 +5,6 @@ import (
"fmt"
"os"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
@@ -16,7 +15,7 @@ import (
"github.com/spf13/cobra"
)
-// DeleteCmd holds the delete cmd flags
+// DeleteCmd holds the delete cmd flags.
type DeleteCmd struct {
*flags.GlobalFlags
@@ -24,7 +23,7 @@ type DeleteCmd struct {
Force bool
}
-// NewDeleteCmd creates a new command
+// NewDeleteCmd creates a new command.
func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &DeleteCmd{
GlobalFlags: flags,
@@ -32,25 +31,32 @@ func NewDeleteCmd(flags *flags.GlobalFlags) *cobra.Command {
deleteCmd := &cobra.Command{
Use: "delete [name]",
Short: "Delete a provider",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ Args: cobra.MaximumNArgs(1),
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetProviderSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, logpkg.Default)
+ return completion.GetProviderSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ logpkg.Default,
+ )
},
}
- deleteCmd.Flags().BoolVar(&cmd.IgnoreNotFound, "ignore-not-found", false, "Treat \"provider not found\" as a successful delete")
- deleteCmd.Flags().BoolVar(&cmd.Force, "force", false, "Force delete the provider and ignore provider is already used")
+ deleteCmd.Flags().
+ BoolVar(&cmd.IgnoreNotFound, "ignore-not-found", false, "Treat \"provider not found\" as a successful delete")
+ deleteCmd.Flags().
+ BoolVar(&cmd.Force, "force", false, "Force delete the provider and ignore provider is already used")
_ = deleteCmd.Flags().MarkHidden("force")
return deleteCmd
}
func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
- if len(args) > 1 {
- return fmt.Errorf("please specify a provider to delete")
- }
-
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
@@ -69,13 +75,17 @@ func (cmd *DeleteCmd) Run(ctx context.Context, args []string) error {
return err
}
- logpkg.WithFields(logrus.Fields{
- "provider": provider,
- }).Done("deleted provider")
+ logpkg.Default.Donef("deleted provider: provider=%s", provider)
return nil
}
-func DeleteProvider(ctx context.Context, devPodConfig *config.Config, provider string, ignoreNotFound, force bool, log logpkg.Logger) error {
+func DeleteProvider(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider string,
+ ignoreNotFound, force bool,
+ log logpkg.Logger,
+) error {
// if force is not set, check if the provider is associated with a pro instance or workspace
if !force {
// check if this provider is associated with a pro instance
@@ -85,7 +95,12 @@ func DeleteProvider(ctx context.Context, devPodConfig *config.Config, provider s
}
for _, instance := range proInstances {
if instance.Provider == provider {
- return fmt.Errorf("cannot delete provider '%s', because it is connected to Pro instance '%s'. Removing the Pro instance will automatically delete this provider", instance.Provider, instance.Host)
+ return fmt.Errorf(
+ "cannot delete provider '%s', because it is connected to Pro instance '%s'. "+
+ "Removing the Pro instance will automatically delete this provider",
+ instance.Provider,
+ instance.Host,
+ )
}
}
@@ -98,7 +113,13 @@ func DeleteProvider(ctx context.Context, devPodConfig *config.Config, provider s
// search for workspace that uses this machine
for _, workspace := range workspaces {
if workspace.Provider.Name == provider {
- return fmt.Errorf("cannot delete provider '%s', because workspace '%s' is still using it. Please delete the workspace '%s' before deleting the provider", workspace.Provider.Name, workspace.ID, workspace.ID)
+ return fmt.Errorf(
+ "cannot delete provider '%s', because workspace '%s' is still using it. "+
+ "Please delete the workspace '%s' before deleting the provider",
+ workspace.Provider.Name,
+ workspace.ID,
+ workspace.ID,
+ )
}
}
}
diff --git a/cmd/provider/delete_test.go b/cmd/provider/delete_test.go
new file mode 100644
index 0000000000..86d5fa7298
--- /dev/null
+++ b/cmd/provider/delete_test.go
@@ -0,0 +1,16 @@
+package provider
+
+import (
+ "testing"
+
+ "github.com/skevetter/devpod/cmd/flags"
+)
+
+func TestDeleteCmd_RejectsMultipleArgs(t *testing.T) {
+ globalFlags := &flags.GlobalFlags{}
+ cmd := NewDeleteCmd(globalFlags)
+ err := cmd.Args(cmd, []string{"provider1", "provider2"})
+ if err == nil {
+ t.Fatal("expected error when passing multiple arguments to delete, got nil")
+ }
+}
diff --git a/cmd/provider/list-default-providers.go b/cmd/provider/list-default-providers.go
index a9ae29448c..2bb274524a 100644
--- a/cmd/provider/list-default-providers.go
+++ b/cmd/provider/list-default-providers.go
@@ -6,69 +6,86 @@ import (
"fmt"
"io"
"net/http"
+ "os"
"strings"
"github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/config"
devpodhttp "github.com/skevetter/devpod/pkg/http"
"github.com/spf13/cobra"
)
-// ListAvailableCmd holds the list cmd flags
+// ListAvailableCmd holds the list cmd flags.
type ListAvailableCmd struct {
*flags.GlobalFlags
}
-func getDevpodProviderList() error {
- req, err := http.NewRequest("GET", "https://api.github.com/users/loft-sh/repos?per_page=100", nil)
- if err != nil {
- return err
+// NewListAvailableCmd creates a new command.
+func NewListAvailableCmd(flags *flags.GlobalFlags) *cobra.Command {
+ cmd := &ListAvailableCmd{
+ GlobalFlags: flags,
}
- resp, err := devpodhttp.GetHTTPClient().Do(req)
- if err != nil {
- return err
+ listAvailableCmd := &cobra.Command{
+ Use: "list-available",
+ Short: "List providers available for installation",
+ Args: cobra.NoArgs,
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
+ },
}
- defer func() { _ = resp.Body.Close() }()
- result, err := io.ReadAll(resp.Body)
- if err != nil {
- return err
- }
+ return listAvailableCmd
+}
- var jsonResult []map[string]any
- err = json.Unmarshal(result, &jsonResult)
+// Run runs the command logic.
+func (cmd *ListAvailableCmd) Run(ctx context.Context) error {
+ jsonResult, err := fetchProviderRepos(ctx)
if err != nil {
return err
}
- fmt.Println("List of available providers from loft:")
+ _, _ = fmt.Fprintln(os.Stdout, "List of available providers from "+config.RepoOwner+":")
for _, v := range jsonResult {
- if strings.Contains(v["name"].(string), "devpod-provider") {
- name := strings.TrimPrefix(v["name"].(string), "devpod-provider-")
- fmt.Println("\t", name)
+ name, ok := v["name"].(string)
+ if !ok || name == "" {
+ continue
+ }
+ if after, ok0 := strings.CutPrefix(name, config.ProviderPrefix); ok0 {
+ _, _ = fmt.Fprintln(os.Stdout, "\t", after)
}
}
return nil
}
-// NewListAvailableCmd creates a new command
-func NewListAvailableCmd(flags *flags.GlobalFlags) *cobra.Command {
- cmd := &ListAvailableCmd{
- GlobalFlags: flags,
+func fetchProviderRepos(ctx context.Context) ([]map[string]any, error) {
+ req, err := http.NewRequestWithContext(ctx,
+ "GET",
+ config.GitHubAPIUserURL+"/repos?per_page=100",
+ nil,
+ )
+ if err != nil {
+ return nil, err
}
- listAvailableCmd := &cobra.Command{
- Use: "list-available",
- Short: "List providers available for installation",
- Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
- },
+ resp, err := devpodhttp.GetHTTPClient().Do(req)
+ if err != nil {
+ return nil, err
}
+ defer func() { _ = resp.Body.Close() }()
- return listAvailableCmd
-}
+ result, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
-// Run runs the command logic
-func (cmd *ListAvailableCmd) Run(ctx context.Context) error {
- return getDevpodProviderList()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return nil, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(result))
+ }
+
+ var jsonResult []map[string]any
+ if err := json.Unmarshal(result, &jsonResult); err != nil {
+ return nil, err
+ }
+
+ return jsonResult, nil
}
diff --git a/cmd/provider/list.go b/cmd/provider/list.go
index 08c4daeb59..45a4a825d3 100644
--- a/cmd/provider/list.go
+++ b/cmd/provider/list.go
@@ -9,21 +9,21 @@ import (
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/skevetter/devpod/pkg/types"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
- "github.com/skevetter/log/table"
"github.com/spf13/cobra"
)
-// ListCmd holds the list cmd flags
+// ListCmd holds the list cmd flags.
type ListCmd struct {
*flags.GlobalFlags
Output string
}
-// NewListCmd creates a new command
+// NewListCmd creates a new command.
func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &ListCmd{
GlobalFlags: flags,
@@ -33,12 +33,13 @@ func NewListCmd(flags *flags.GlobalFlags) *cobra.Command {
Aliases: []string{"ls"},
Short: "List available providers",
Args: cobra.NoArgs,
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background())
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context())
},
}
- listCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ listCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return listCmd
}
@@ -48,7 +49,7 @@ type ProviderWithDefault struct {
Default bool `json:"default,omitempty"`
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *ListCmd) Run(ctx context.Context) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -81,7 +82,7 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Version",
"Default",
@@ -110,7 +111,10 @@ func (cmd *ListCmd) Run(ctx context.Context) error {
}
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/provider/options.go b/cmd/provider/options.go
index 5795372ef9..d2258e66a5 100644
--- a/cmd/provider/options.go
+++ b/cmd/provider/options.go
@@ -11,14 +11,14 @@ import (
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/table"
"github.com/skevetter/devpod/pkg/types"
"github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
- "github.com/skevetter/log/table"
"github.com/spf13/cobra"
)
-// OptionsCmd holds the options cmd flags
+// OptionsCmd holds the options cmd flags.
type OptionsCmd struct {
*flags.GlobalFlags
@@ -26,7 +26,7 @@ type OptionsCmd struct {
Output string
}
-// NewOptionsCmd creates a new command
+// NewOptionsCmd creates a new command.
func NewOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &OptionsCmd{
GlobalFlags: flags,
@@ -34,16 +34,26 @@ func NewOptionsCmd(flags *flags.GlobalFlags) *cobra.Command {
optionsCmd := &cobra.Command{
Use: "options [provider]",
Short: "Show options of an existing provider",
- RunE: func(_ *cobra.Command, args []string) error {
- return cmd.Run(context.Background(), args)
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetProviderSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetProviderSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
- optionsCmd.Flags().BoolVar(&cmd.Hidden, "hidden", false, "If true, will also show hidden options.")
- optionsCmd.Flags().StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
+ optionsCmd.Flags().
+ BoolVar(&cmd.Hidden, "hidden", false, "If true, will also show hidden options.")
+ optionsCmd.Flags().
+ StringVar(&cmd.Output, "output", "plain", "The output format to use. Can be json or plain")
return optionsCmd
}
@@ -54,7 +64,7 @@ type optionWithValue struct {
Value string `json:"value,omitempty"`
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *OptionsCmd) Run(ctx context.Context, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -76,7 +86,11 @@ func (cmd *OptionsCmd) Run(ctx context.Context, args []string) error {
}
}
- providerWithOptions, err := workspace.FindProvider(devPodConfig, providerName, log.Default.ErrorStreamOnly())
+ providerWithOptions, err := workspace.FindProvider(
+ devPodConfig,
+ providerName,
+ log.Default.ErrorStreamOnly(),
+ )
if err != nil {
return err
}
@@ -84,7 +98,12 @@ func (cmd *OptionsCmd) Run(ctx context.Context, args []string) error {
return printOptions(devPodConfig, providerWithOptions, cmd.Output, cmd.Hidden)
}
-func printOptions(devPodConfig *config.Config, provider *workspace.ProviderWithOptions, format string, showHidden bool) error {
+func printOptions(
+ devPodConfig *config.Config,
+ provider *workspace.ProviderWithOptions,
+ format string,
+ showHidden bool,
+) error {
entryOptions := devPodConfig.ProviderOptions(provider.Config.Name)
dynamicOptions := devPodConfig.DynamicProviderOptionDefinitions(provider.Config.Name)
srcOptions := MergeDynamicOptions(provider.Config.Options, dynamicOptions)
@@ -112,7 +131,7 @@ func printOptions(devPodConfig *config.Config, provider *workspace.ProviderWithO
return tableEntries[i][0] < tableEntries[j][0]
})
- table.PrintTable(log.Default, []string{
+ table.Print([]string{
"Name",
"Required",
"Description",
@@ -145,8 +164,11 @@ func printOptions(devPodConfig *config.Config, provider *workspace.ProviderWithO
return nil
}
-// MergeDynamicOptions merges the static provider options and dynamic options
-func MergeDynamicOptions(options map[string]*types.Option, dynamicOptions config.OptionDefinitions) map[string]*types.Option {
+// MergeDynamicOptions merges the static provider options and dynamic options.
+func MergeDynamicOptions(
+ options map[string]*types.Option,
+ dynamicOptions config.OptionDefinitions,
+) map[string]*types.Option {
retOptions := map[string]*types.Option{}
maps.Copy(retOptions, options)
maps.Copy(retOptions, dynamicOptions)
diff --git a/cmd/provider/provider.go b/cmd/provider/provider.go
index 77c445de9d..839a3a8398 100644
--- a/cmd/provider/provider.go
+++ b/cmd/provider/provider.go
@@ -5,7 +5,7 @@ import (
"github.com/spf13/cobra"
)
-// NewProviderCmd returns a new root command
+// NewProviderCmd returns a new root command.
func NewProviderCmd(flags *flags.GlobalFlags) *cobra.Command {
providerCmd := &cobra.Command{
Use: "provider",
@@ -20,5 +20,6 @@ func NewProviderCmd(flags *flags.GlobalFlags) *cobra.Command {
providerCmd.AddCommand(NewAddCmd(flags))
providerCmd.AddCommand(NewUpdateCmd(flags))
providerCmd.AddCommand(NewSetOptionsCmd(flags))
+ providerCmd.AddCommand(NewRenameCmd(flags))
return providerCmd
}
diff --git a/cmd/provider/rename.go b/cmd/provider/rename.go
new file mode 100644
index 0000000000..1de1676cd0
--- /dev/null
+++ b/cmd/provider/rename.go
@@ -0,0 +1,285 @@
+package provider
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/config"
+ "github.com/skevetter/devpod/pkg/provider"
+ workspace "github.com/skevetter/devpod/pkg/workspace"
+ "github.com/skevetter/log"
+ "github.com/spf13/cobra"
+)
+
+// RenameCmd implements the provider rename command.
+type RenameCmd struct {
+ *flags.GlobalFlags
+}
+
+// NewRenameCmd creates a new command for renaming a provider.
+func NewRenameCmd(globalFlags *flags.GlobalFlags) *cobra.Command {
+ cmd := &RenameCmd{
+ GlobalFlags: globalFlags,
+ }
+
+ return &cobra.Command{
+ Use: "rename ",
+ Short: "Rename a provider",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ return cmd.Run(cobraCmd.Context(), args)
+ },
+ }
+}
+
+// Run validates inputs, loads config, and executes the provider rename.
+func (cmd *RenameCmd) Run(ctx context.Context, args []string) error {
+ oldName, newName := args[0], args[1]
+
+ if oldName == newName {
+ return fmt.Errorf("new name is the same as the current name")
+ }
+
+ if err := validateProviderName(newName); err != nil {
+ return err
+ }
+
+ devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
+ if err != nil {
+ return err
+ }
+
+ if err := validateProviderRename(devPodConfig, oldName); err != nil {
+ return err
+ }
+
+ if devPodConfig.Current().Providers[newName] != nil {
+ return fmt.Errorf("provider %s already exists", newName)
+ }
+
+ return renameProvider(ctx, devPodConfig, oldName, newName)
+}
+
+// validateProviderName checks that the given name is non-empty, matches the
+// allowed character set (lowercase letters, numbers, dashes), and does not
+// exceed the maximum length of 32 characters.
+func validateProviderName(newName string) error {
+ if strings.TrimSpace(newName) == "" {
+ return fmt.Errorf("provider name cannot be empty")
+ }
+ if provider.ProviderNameRegEx.MatchString(newName) {
+ return fmt.Errorf("provider name can only include lowercase letters, numbers or dashes")
+ }
+ if len(newName) > 32 {
+ return fmt.Errorf("provider name cannot be longer than 32 characters")
+ }
+ return nil
+}
+
+// getWorkspacesForProvider returns all local workspaces whose provider matches
+// the given name.
+func getWorkspacesForProvider(
+ devPodConfig *config.Config,
+ providerName string,
+) ([]*provider.Workspace, error) {
+ workspaces, err := workspace.ListLocalWorkspaces(
+ devPodConfig.DefaultContext,
+ false,
+ log.Default,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("listing workspaces: %w", err)
+ }
+ var matched []*provider.Workspace
+ for _, ws := range workspaces {
+ if ws.Provider.Name == providerName {
+ matched = append(matched, ws)
+ }
+ }
+ return matched, nil
+}
+
+// getMachinesForProvider returns all machines whose provider matches the given
+// name.
+func getMachinesForProvider(
+ devPodConfig *config.Config,
+ providerName string,
+) ([]*provider.Machine, error) {
+ machines, err := workspace.ListMachines(devPodConfig, log.Default)
+ if err != nil {
+ return nil, fmt.Errorf("listing machines: %w", err)
+ }
+ var matched []*provider.Machine
+ for _, m := range machines {
+ if m.Provider.Name == providerName {
+ matched = append(matched, m)
+ }
+ }
+ return matched, nil
+}
+
+// switchWorkspaces updates each workspace to reference the new provider name.
+// It stops on the first failure and returns the successfully switched
+// workspaces so the caller can roll them back.
+func switchWorkspaces(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ workspaces []*provider.Workspace,
+ newName string,
+) ([]*provider.Workspace, error) {
+ var switched []*provider.Workspace
+ for _, ws := range workspaces {
+ if err := workspace.SwitchProvider(ctx, devPodConfig, ws, newName); err != nil {
+ return switched, fmt.Errorf("failed to switch workspace %s: %w", ws.ID, err)
+ }
+ switched = append(switched, ws)
+ }
+ return switched, nil
+}
+
+// switchMachines updates each machine to reference the new provider name.
+// It stops on the first failure and returns the successfully switched
+// machines so the caller can roll them back.
+func switchMachines(machines []*provider.Machine, newName string) ([]*provider.Machine, error) {
+ var switched []*provider.Machine
+ for _, m := range machines {
+ oldName := m.Provider.Name
+ m.Provider.Name = newName
+ if err := provider.SaveMachineConfig(m); err != nil {
+ m.Provider.Name = oldName
+ return switched, fmt.Errorf("failed to switch machine %s: %w", m.ID, err)
+ }
+ switched = append(switched, m)
+ }
+ return switched, nil
+}
+
+// setDefaultProvider updates the default provider setting if it currently
+// points to oldName. Returns true if the default was changed.
+func setDefaultProvider(devPodConfig *config.Config, oldName, newName string) (bool, error) {
+ if devPodConfig.Current().DefaultProvider != oldName {
+ return false, nil
+ }
+ devPodConfig.Current().DefaultProvider = newName
+ if err := config.SaveConfig(devPodConfig); err != nil {
+ devPodConfig.Current().DefaultProvider = oldName
+ return false, err
+ }
+ return true, nil
+}
+
+// renameState tracks the mutations performed during a rename so they can be
+// undone if a later step fails.
+type renameState struct {
+ devPodConfig *config.Config
+ switchedWorkspaces []*provider.Workspace
+ switchedMachines []*provider.Machine
+ defaultChanged bool
+ oldName, newName string
+}
+
+// restoreProviderState reverts all recorded mutations in reverse order: default provider,
+// workspaces, machines, and finally the provider directory move.
+func (r *renameState) restoreProviderState(ctx context.Context) error {
+ log.Default.Info("rolling back changes")
+ var errs error
+
+ if r.defaultChanged {
+ r.devPodConfig.Current().DefaultProvider = r.oldName
+ if err := config.SaveConfig(r.devPodConfig); err != nil {
+ errs = errors.Join(errs, fmt.Errorf("rollback default provider: %w", err))
+ }
+ }
+
+ _, err := switchWorkspaces(ctx, r.devPodConfig, r.switchedWorkspaces, r.oldName)
+ errs = errors.Join(errs, err)
+
+ _, err = switchMachines(r.switchedMachines, r.oldName)
+ errs = errors.Join(errs, err)
+
+ if moveErr := workspace.MoveProvider(r.devPodConfig, r.newName, r.oldName); moveErr != nil {
+ errs = errors.Join(errs, fmt.Errorf("rollback move provider: %w", moveErr))
+ }
+
+ return errs
+}
+
+// validateProviderRename verifies that the provider exists, is not a pro
+// provider, is not backing a pro instance, and has configuration state.
+func validateProviderRename(devPodConfig *config.Config, oldName string) error {
+ providerWithOptions, err := workspace.FindProvider(devPodConfig, oldName, log.Default)
+ if err != nil {
+ return fmt.Errorf("provider %s not found", oldName)
+ }
+
+ if providerWithOptions.Config.IsProxyProvider() ||
+ providerWithOptions.Config.IsDaemonProvider() {
+ return fmt.Errorf("cannot rename a pro provider; pro providers are managed by the platform")
+ }
+
+ proInstances, err := workspace.ListProInstances(devPodConfig, log.Default)
+ if err != nil {
+ return fmt.Errorf("listing pro instances: %w", err)
+ }
+ for _, inst := range proInstances {
+ if inst.Provider == oldName {
+ return fmt.Errorf(
+ "cannot rename provider %s: it is used by pro instance %s",
+ oldName,
+ inst.Host,
+ )
+ }
+ }
+
+ if devPodConfig.Current().Providers[oldName] == nil {
+ return fmt.Errorf("provider %s has no configuration state", oldName)
+ }
+
+ return nil
+}
+
+// renameProvider performs the rename: moves the provider directory, switches all
+// associated workspaces and machines, and adjusts the default provider. If any
+// step fails the entire operation is rolled back.
+func renameProvider(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ oldName, newName string,
+) error {
+ workspaces, err := getWorkspacesForProvider(devPodConfig, oldName)
+ if err != nil {
+ return err
+ }
+
+ machines, err := getMachinesForProvider(devPodConfig, oldName)
+ if err != nil {
+ return err
+ }
+
+ if err := workspace.MoveProvider(devPodConfig, oldName, newName); err != nil {
+ return fmt.Errorf("moving provider: %w", err)
+ }
+
+ rb := &renameState{devPodConfig: devPodConfig, oldName: oldName, newName: newName}
+
+ rb.switchedWorkspaces, err = switchWorkspaces(ctx, devPodConfig, workspaces, newName)
+ if err != nil {
+ return errors.Join(err, rb.restoreProviderState(ctx))
+ }
+
+ rb.switchedMachines, err = switchMachines(machines, newName)
+ if err != nil {
+ return errors.Join(err, rb.restoreProviderState(ctx))
+ }
+
+ rb.defaultChanged, err = setDefaultProvider(devPodConfig, oldName, newName)
+ if err != nil {
+ return errors.Join(err, rb.restoreProviderState(ctx))
+ }
+
+ log.Default.Donef("renamed provider %s to %s", oldName, newName)
+ return nil
+}
diff --git a/cmd/provider/set_options.go b/cmd/provider/set_options.go
index 585cd447cd..47b1613c78 100644
--- a/cmd/provider/set_options.go
+++ b/cmd/provider/set_options.go
@@ -5,7 +5,6 @@ import (
"fmt"
"os"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
@@ -14,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
-// SetOptionsCmd holds the use cmd flags
+// SetOptionsCmd holds the use cmd flags.
type SetOptionsCmd struct {
*flags.GlobalFlags
@@ -25,7 +24,7 @@ type SetOptionsCmd struct {
Options []string
}
-// NewSetOptionsCmd creates a new command
+// NewSetOptionsCmd creates a new command.
func NewSetOptionsCmd(f *flags.GlobalFlags) *cobra.Command {
cmd := &SetOptionsCmd{
GlobalFlags: f,
@@ -33,27 +32,39 @@ func NewSetOptionsCmd(f *flags.GlobalFlags) *cobra.Command {
setOptionsCmd := &cobra.Command{
Use: "set-options [provider]",
Short: "Sets options for the given provider. Similar to 'devpod provider use', but does not switch the default provider.",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
logger := log.Logger(log.Default)
if cmd.Dry {
logger = log.Default.ErrorStreamOnly()
}
- return cmd.Run(context.Background(), args, logger)
+ return cmd.Run(cobraCmd.Context(), args, logger)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetProviderSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetProviderSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
- setOptionsCmd.Flags().BoolVar(&cmd.SingleMachine, "single-machine", false, "If enabled will use a single machine for all workspaces")
- setOptionsCmd.Flags().BoolVar(&cmd.Reconfigure, "reconfigure", false, "If enabled will not merge existing provider config")
- setOptionsCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
- setOptionsCmd.Flags().BoolVar(&cmd.Dry, "dry", false, "Dry will not persist the options to file and instead return the new filled options")
+ setOptionsCmd.Flags().
+ BoolVar(&cmd.SingleMachine, "single-machine", false, "If enabled will use a single machine for all workspaces")
+ setOptionsCmd.Flags().
+ BoolVar(&cmd.Reconfigure, "reconfigure", false, "If enabled will not merge existing provider config")
+ setOptionsCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
+ setOptionsCmd.Flags().
+ BoolVar(&cmd.Dry, "dry", false, "Dry will not persist the options to file and instead return the new filled options")
return setOptionsCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SetOptionsCmd) Run(ctx context.Context, args []string, log log.Logger) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -68,7 +79,7 @@ func (cmd *SetOptionsCmd) Run(ctx context.Context, args []string, log log.Logger
}
log.Debugf("providerName=%+v", providerName)
- if os.Getenv("DEVPOD_UI") == "" && len(cmd.Options) == 0 {
+ if os.Getenv(config.EnvUI) == "" && len(cmd.Options) == 0 {
return fmt.Errorf("please specify option")
}
log.Debugf("Options=%+v", cmd.Options)
@@ -78,18 +89,17 @@ func (cmd *SetOptionsCmd) Run(ctx context.Context, args []string, log log.Logger
return err
}
- devPodConfig, err = setOptions(
- ctx,
- providerWithOptions.Config,
- devPodConfig.DefaultContext,
- cmd.Options,
- cmd.Reconfigure,
- cmd.Dry,
- cmd.Dry,
- false,
- &cmd.SingleMachine,
- log,
- )
+ devPodConfig, err = configureProviderOptions(ctx, ProviderOptionsConfig{
+ Provider: providerWithOptions.Config,
+ Context: devPodConfig.DefaultContext,
+ UserOptions: cmd.Options,
+ Reconfigure: cmd.Reconfigure,
+ SkipRequired: cmd.Dry,
+ SkipInit: cmd.Dry,
+ SkipSubOptions: false,
+ SingleMachine: &cmd.SingleMachine,
+ Log: log,
+ })
if err != nil {
return err
}
@@ -109,8 +119,6 @@ func (cmd *SetOptionsCmd) Run(ctx context.Context, args []string, log log.Logger
}
// print success message
- log.WithFields(logrus.Fields{
- "providerName": providerWithOptions.Config.Name,
- }).Done("set options for provider")
+ log.Donef("set options for provider: providerName=%s", providerWithOptions.Config.Name)
return nil
}
diff --git a/cmd/provider/update.go b/cmd/provider/update.go
index 071a005dc3..dfc559fec5 100644
--- a/cmd/provider/update.go
+++ b/cmd/provider/update.go
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/workspace"
@@ -12,7 +11,7 @@ import (
"github.com/spf13/cobra"
)
-// UpdateCmd holds the cmd flags
+// UpdateCmd holds the cmd flags.
type UpdateCmd struct {
*flags.GlobalFlags
@@ -20,16 +19,16 @@ type UpdateCmd struct {
Options []string
}
-// NewUpdateCmd creates a new command
+// NewUpdateCmd creates a new command.
func NewUpdateCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &UpdateCmd{
GlobalFlags: flags,
}
updateCmd := &cobra.Command{
- Use: "update [name] [URL or path]",
+ Use: "update [name] [name, GitHub link, URL or path]",
Short: "Updates a provider in DevPod",
- RunE: func(_ *cobra.Command, args []string) error {
- ctx := context.Background()
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ ctx := cobraCmd.Context()
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
@@ -39,15 +38,17 @@ func NewUpdateCmd(flags *flags.GlobalFlags) *cobra.Command {
},
}
- updateCmd.Flags().BoolVar(&cmd.Use, "use", true, "If enabled will automatically activate the provider")
- updateCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
+ updateCmd.Flags().
+ BoolVar(&cmd.Use, "use", true, "If enabled will automatically activate the provider")
+ updateCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
return updateCmd
}
func (cmd *UpdateCmd) Run(ctx context.Context, devPodConfig *config.Config, args []string) error {
if len(args) != 1 && len(args) != 2 {
return fmt.Errorf("please specify either a local file, URL or Git repository. " +
- "E.g. devpod provider update my-provider skevetter/devpod-provider-gcloud")
+ "E.g. devpod provider update my-provider " + config.ProviderPrefix + "gcloud")
}
providerSource := ""
@@ -55,18 +56,34 @@ func (cmd *UpdateCmd) Run(ctx context.Context, devPodConfig *config.Config, args
providerSource = args[1]
}
- providerConfig, err := workspace.UpdateProvider(devPodConfig, args[0], providerSource, log.Default)
+ providerConfig, err := workspace.UpdateProvider(
+ devPodConfig,
+ args[0],
+ providerSource,
+ log.Default,
+ )
if err != nil {
return err
}
- log.WithFields(logrus.Fields{
- "providerName": providerConfig.Name,
- }).Done("updated provider")
+ log.Default.Donef("updated provider: providerName=%s", providerConfig.Name)
if cmd.Use {
- err = ConfigureProvider(ctx, providerConfig, devPodConfig.DefaultContext, cmd.Options, false, false, false, nil, log.Default)
+ err = ConfigureProvider(ctx, ProviderOptionsConfig{
+ Provider: providerConfig,
+ Context: devPodConfig.DefaultContext,
+ UserOptions: cmd.Options,
+ Reconfigure: false,
+ SkipRequired: false,
+ SkipInit: false,
+ SkipSubOptions: false,
+ SingleMachine: nil,
+ Log: log.Default,
+ })
if err != nil {
- log.Default.Errorf("Error configuring provider, please retry with 'devpod provider use %s --reconfigure'", providerConfig.Name)
+ log.Default.Errorf(
+ "Error configuring provider, please retry with 'devpod provider use %s --reconfigure'",
+ providerConfig.Name,
+ )
return fmt.Errorf("configure provider: %w", err)
}
diff --git a/cmd/provider/use.go b/cmd/provider/use.go
index ad7c2a5af9..8a89997bdb 100644
--- a/cmd/provider/use.go
+++ b/cmd/provider/use.go
@@ -17,7 +17,7 @@ import (
"github.com/spf13/cobra"
)
-// UseCmd holds the use cmd flags
+// UseCmd holds the use cmd flags.
type UseCmd struct {
*flags.GlobalFlags
@@ -29,7 +29,7 @@ type UseCmd struct {
SkipInit bool
}
-// NewUseCmd creates a new command
+// NewUseCmd creates a new command.
func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &UseCmd{
GlobalFlags: flags,
@@ -37,15 +37,23 @@ func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
useCmd := &cobra.Command{
Use: "use [name]",
Short: "Configure an existing provider and set as default",
- RunE: func(_ *cobra.Command, args []string) error {
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("please specify the provider to use")
}
- return cmd.Run(context.Background(), args[0])
+ return cmd.Run(cobraCmd.Context(), args[0])
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetProviderSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetProviderSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
@@ -54,15 +62,19 @@ func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
}
func AddFlags(useCmd *cobra.Command, cmd *UseCmd) {
- useCmd.Flags().BoolVar(&cmd.SingleMachine, "single-machine", false, "If enabled will use a single machine for all workspaces")
- useCmd.Flags().BoolVar(&cmd.Reconfigure, "reconfigure", false, "If enabled will not merge existing provider config")
- useCmd.Flags().StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
-
- useCmd.Flags().BoolVar(&cmd.SkipInit, "skip-init", false, "ONLY FOR TESTING: If true will skip init")
+ useCmd.Flags().
+ BoolVar(&cmd.SingleMachine, "single-machine", false, "If enabled will use a single machine for all workspaces")
+ useCmd.Flags().
+ BoolVar(&cmd.Reconfigure, "reconfigure", false, "If enabled will not merge existing provider config")
+ useCmd.Flags().
+ StringArrayVarP(&cmd.Options, "option", "o", []string{}, "Provider option in the form KEY=VALUE")
+
+ useCmd.Flags().
+ BoolVar(&cmd.SkipInit, "skip-init", false, "ONLY FOR TESTING: If true will skip init")
_ = useCmd.Flags().MarkHidden("skip-init")
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *UseCmd) Run(ctx context.Context, providerName string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
@@ -75,11 +87,26 @@ func (cmd *UseCmd) Run(ctx context.Context, providerName string) error {
}
// should reconfigure?
- shouldReconfigure := cmd.Reconfigure || len(cmd.Options) > 0 || providerWithOptions.State == nil || cmd.SingleMachine
+ shouldReconfigure := cmd.Reconfigure || len(cmd.Options) > 0 ||
+ providerWithOptions.State == nil ||
+ cmd.SingleMachine
if shouldReconfigure {
- return ConfigureProvider(ctx, providerWithOptions.Config, devPodConfig.DefaultContext, cmd.Options, cmd.Reconfigure, cmd.SkipInit, false, &cmd.SingleMachine, log.Default)
+ return ConfigureProvider(ctx, ProviderOptionsConfig{
+ Provider: providerWithOptions.Config,
+ Context: devPodConfig.DefaultContext,
+ UserOptions: cmd.Options,
+ Reconfigure: cmd.Reconfigure,
+ SkipRequired: false,
+ SkipInit: cmd.SkipInit,
+ SkipSubOptions: false,
+ SingleMachine: &cmd.SingleMachine,
+ Log: log.Default,
+ })
} else {
- log.Default.Infof("To reconfigure provider %s, run with '--reconfigure' to reconfigure the provider", providerWithOptions.Config.Name)
+ log.Default.Infof(
+ "To reconfigure provider %s, run with '--reconfigure' to reconfigure the provider",
+ providerWithOptions.Config.Name,
+ )
}
// set options
@@ -93,22 +120,31 @@ func (cmd *UseCmd) Run(ctx context.Context, providerName string) error {
}
// print success message
- log.WithFields(logrus.Fields{
- "providerName": providerWithOptions.Config.Name,
- }).Done("switched default provider")
+ log.Default.Donef("switched default provider: providerName=%s", providerWithOptions.Config.Name)
return nil
}
-func ConfigureProvider(ctx context.Context, provider *provider2.ProviderConfig, context string, userOptions []string, reconfigure, skipInit, skipSubOptions bool, singleMachine *bool, log log.Logger) error {
- // set options
- devPodConfig, err := setOptions(ctx, provider, context, userOptions, reconfigure, false, skipInit, skipSubOptions, singleMachine, log)
+type ProviderOptionsConfig struct {
+ Provider *provider2.ProviderConfig
+ Context string
+ UserOptions []string
+ Reconfigure bool
+ SkipRequired bool
+ SkipInit bool
+ SkipSubOptions bool
+ SingleMachine *bool
+ Log log.Logger
+}
+
+func ConfigureProvider(ctx context.Context, cfg ProviderOptionsConfig) error {
+ devPodConfig, err := configureProviderOptions(ctx, cfg)
if err != nil {
return err
}
// set options
defaultContext := devPodConfig.Current()
- defaultContext.DefaultProvider = provider.Name
+ defaultContext.DefaultProvider = cfg.Provider.Name
// save provider config
err = config.SaveConfig(devPodConfig)
@@ -116,66 +152,65 @@ func ConfigureProvider(ctx context.Context, provider *provider2.ProviderConfig,
return fmt.Errorf("save config: %w", err)
}
- log.WithFields(logrus.Fields{
- "providerName": provider.Name,
- }).Done("configured provider")
+ cfg.Log.Donef("configured provider %s", cfg.Provider.Name)
return nil
}
-func setOptions(
+func mergeExistingOptions(
+ options map[string]string,
+ existingOptions map[string]config.OptionValue,
+) {
+ for k, v := range existingOptions {
+ if _, ok := options[k]; !ok && v.UserProvided {
+ options[k] = v.Value
+ }
+ }
+}
+
+func configureProviderOptions(
ctx context.Context,
- provider *provider2.ProviderConfig,
- context string,
- userOptions []string,
- reconfigure,
- skipRequired,
- skipInit,
- skipSubOptions bool,
- singleMachine *bool,
- log log.Logger,
+ cfg ProviderOptionsConfig,
) (*config.Config, error) {
- devPodConfig, err := config.LoadConfig(context, "")
+ devPodConfig, err := config.LoadConfig(cfg.Context, "")
if err != nil {
return nil, err
}
- userOptions = options2.InheritOptionsFromEnvironment(
- userOptions,
- provider.Options,
- "DEVPOD_PROVIDER_"+provider.Name+"_",
+ cfg.UserOptions = options2.InheritOptionsFromEnvironment(
+ cfg.UserOptions,
+ cfg.Provider.Options,
+ config.EnvProviderPrefix+cfg.Provider.Name+"_",
)
// parse options
- options, err := provider2.ParseOptions(userOptions)
+ options, err := provider2.ParseOptions(cfg.UserOptions)
if err != nil {
return nil, fmt.Errorf("parse options: %w", err)
}
// merge with old values
- if !reconfigure {
- for k, v := range devPodConfig.ProviderOptions(provider.Name) {
- _, ok := options[k]
- if !ok && v.UserProvided {
- options[k] = v.Value
- }
- }
+ if !cfg.Reconfigure {
+ mergeExistingOptions(options, devPodConfig.ProviderOptions(cfg.Provider.Name))
}
// fill defaults
- devPodConfig, err = options2.ResolveOptions(ctx, devPodConfig, provider, options, skipRequired, skipSubOptions, singleMachine, log)
+ devPodConfig, err = options2.ResolveOptions(
+ ctx, devPodConfig, cfg.Provider, options,
+ cfg.SkipRequired, cfg.SkipSubOptions, cfg.SingleMachine, cfg.Log,
+ )
if err != nil {
return nil, fmt.Errorf("resolve options: %w", err)
}
// run init command
- if !skipInit {
- stdout := log.Writer(logrus.InfoLevel, false)
+ if !cfg.SkipInit {
+ stdout := cfg.Log.Writer(logrus.InfoLevel, false)
defer func() { _ = stdout.Close() }()
- stderr := log.Writer(logrus.ErrorLevel, false)
+ stderr := cfg.Log.Writer(logrus.ErrorLevel, false)
defer func() { _ = stderr.Close() }()
- err = initProvider(ctx, devPodConfig, provider, stdout, stderr)
+ err = initProvider(ctx, devPodConfig, cfg.Provider, stdout, stderr)
if err != nil {
return nil, err
}
@@ -184,8 +219,12 @@ func setOptions(
return devPodConfig, nil
}
-func initProvider(ctx context.Context, devPodConfig *config.Config, provider *provider2.ProviderConfig, stdout, stderr io.Writer) error {
- // run init command
+func initProvider(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ provider *provider2.ProviderConfig,
+ stdout, stderr io.Writer,
+) error {
err := clientimplementation.RunCommandWithBinaries(clientimplementation.CommandOptions{
Ctx: ctx,
Name: "init",
diff --git a/cmd/root.go b/cmd/root.go
index 1c8960bae4..55112cd19d 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -17,7 +17,6 @@ import (
"github.com/skevetter/devpod/cmd/pro"
"github.com/skevetter/devpod/cmd/provider"
"github.com/skevetter/devpod/cmd/use"
- "github.com/skevetter/devpod/pkg/client/clientimplementation"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/telemetry"
log2 "github.com/skevetter/log"
@@ -29,10 +28,10 @@ import (
var globalFlags *flags.GlobalFlags
-// NewRootCmd returns a new root command
+// NewRootCmd returns a new root command.
func NewRootCmd() *cobra.Command {
return &cobra.Command{
- Use: "devpod",
+ Use: config.BinaryName,
Short: "DevPod",
SilenceUsage: true,
SilenceErrors: true,
@@ -42,19 +41,22 @@ func NewRootCmd() *cobra.Command {
} else if globalFlags.LogOutput == "raw" {
log2.Default.SetFormat(log2.RawFormat)
} else if globalFlags.LogOutput != "plain" {
- return fmt.Errorf("unrecognized log format %s, needs to be either plain, raw or json", globalFlags.LogOutput)
+ return fmt.Errorf(
+ "unrecognized log format %s, needs to be either plain, raw or json",
+ globalFlags.LogOutput,
+ )
}
if globalFlags.Silent {
log2.Default.SetLevel(logrus.FatalLevel)
} else if globalFlags.Debug {
log2.Default.SetLevel(logrus.DebugLevel)
- } else if os.Getenv(clientimplementation.DevPodDebug) == "true" {
+ } else if os.Getenv(config.EnvDebug) == config.BoolTrue {
log2.Default.SetLevel(logrus.DebugLevel)
}
if globalFlags.DevPodHome != "" {
- _ = os.Setenv(config.DEVPOD_HOME, globalFlags.DevPodHome)
+ _ = os.Setenv(config.EnvHome, globalFlags.DevPodHome)
}
devPodConfig, err := config.LoadConfig(globalFlags.Context, globalFlags.Provider)
@@ -66,7 +68,7 @@ func NewRootCmd() *cobra.Command {
},
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
if globalFlags.DevPodHome != "" {
- _ = os.Unsetenv(config.DEVPOD_HOME)
+ _ = os.Unsetenv(config.EnvHome)
}
return nil
@@ -98,11 +100,14 @@ func Execute() {
if globalFlags.Debug {
log2.Default.Fatalf("%+v", err)
} else {
- if rootCmd.Annotations == nil || rootCmd.Annotations[agent.AgentExecutedAnnotation] != "true" {
+ if rootCmd.Annotations == nil ||
+ rootCmd.Annotations[agent.AgentExecutedAnnotation] != config.BoolTrue {
if terminal.IsTerminalIn {
log2.Default.Error("Try using the --debug flag to see a more verbose output")
- } else if os.Getenv(telemetry.UIEnvVar) == "true" {
- log2.Default.Error("Try enabling Debug mode under Settings to see a more verbose output")
+ } else if os.Getenv(config.EnvUI) == config.BoolTrue {
+ log2.Default.Error(
+ "Try enabling Debug mode under Settings to see a more verbose output",
+ )
}
}
log2.Default.Fatal(err)
@@ -110,7 +115,7 @@ func Execute() {
}
}
-// BuildRoot creates a new root command from the
+// BuildRoot creates a new root command from the.
func BuildRoot() *cobra.Command {
rootCmd := NewRootCmd()
persistentFlags := rootCmd.PersistentFlags()
@@ -161,20 +166,26 @@ func inheritFlagsFromEnvironment(flags *flag.FlagSet) {
// calculate environment variable name from flag name
suffix := strings.ToUpper(strings.ReplaceAll(flag.Name, "-", "_"))
- // do not prepend "DEVPOD_" to the environment variable name if the flag name starts with "devpod"
+ // do not prepend the env prefix if the flag name already starts with it
// (applies to one flag - "devpod-home").
var environmentVariable string
- if strings.HasPrefix(suffix, "DEVPOD_") {
+ if strings.HasPrefix(suffix, config.EnvPrefix) {
environmentVariable = suffix
} else {
- environmentVariable = "DEVPOD_" + suffix
+ environmentVariable = config.EnvPrefix + suffix
}
if value, exists := os.LookupEnv(environmentVariable); exists {
// set the variable holding the flag's value to the default supplied by the environment
err := flag.Value.Set(value)
if err != nil {
- log2.Default.Fatalf("failed to set flag %s from the environment variable %s with value %s: %+v", flag.Name, environmentVariable, value, err)
+ log2.Default.Fatalf(
+ "failed to set flag %s from the environment variable %s with value %s: %+v",
+ flag.Name,
+ environmentVariable,
+ value,
+ err,
+ )
}
// reflect this default in the usage output
flag.DefValue = value
diff --git a/cmd/ssh.go b/cmd/ssh.go
index 4e3669ed1e..01027ab28f 100644
--- a/cmd/ssh.go
+++ b/cmd/ssh.go
@@ -3,16 +3,17 @@ package cmd
import (
"context"
"encoding/base64"
+ "errors"
"fmt"
"io"
"os"
"os/exec"
- "path/filepath"
+ "path"
"strings"
+ "sync"
"time"
- "errors"
-
+ "al.essio.dev/pkg/shellescape"
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
@@ -36,7 +37,7 @@ const (
DisableSSHKeepAlive time.Duration = 0 * time.Second
)
-// SSHCmd holds the ssh cmd flags
+// SSHCmd holds the ssh cmd flags.
type SSHCmd struct {
*flags.GlobalFlags
@@ -52,6 +53,7 @@ type SSHCmd struct {
AgentForwarding bool
GPGAgentForwarding bool
GitSSHSignatureForwarding bool
+ GitSSHSigningKey string
// ssh keepalive options
SSHKeepAliveInterval time.Duration `json:"sshKeepAliveInterval,omitempty"`
@@ -65,7 +67,7 @@ type SSHCmd struct {
WorkDir string
}
-// NewSSHCmd creates a new ssh command
+// NewSSHCmd creates a new ssh command.
func NewSSHCmd(f *flags.GlobalFlags) *cobra.Command {
cmd := &SSHCmd{
GlobalFlags: f,
@@ -82,7 +84,14 @@ func NewSSHCmd(f *flags.GlobalFlags) *cobra.Command {
localOnly := cmd.Stdio
ctx := cobraCmd.Context()
- client, err := workspace2.Get(ctx, devPodConfig, args, true, cmd.Owner, localOnly, log.Default.ErrorStreamOnly())
+ client, err := workspace2.Get(ctx, workspace2.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ ChangeLastUsed: true,
+ Owner: cmd.Owner,
+ LocalOnly: localOnly,
+ Log: log.Default.ErrorStreamOnly(),
+ })
if err != nil {
return err
}
@@ -90,25 +99,59 @@ func NewSSHCmd(f *flags.GlobalFlags) *cobra.Command {
return cmd.Run(ctx, devPodConfig, client, log.Default.ErrorStreamOnly())
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
- sshCmd.Flags().StringArrayVarP(&cmd.ForwardPorts, "forward-ports", "L", []string{}, "Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side.")
- sshCmd.Flags().StringArrayVarP(&cmd.ReverseForwardPorts, "reverse-forward-ports", "R", []string{}, "Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be reverse forwarded to the given host and port, or Unix socket, on the remote side.")
- sshCmd.Flags().StringArrayVarP(&cmd.SendEnvVars, "send-env", "", []string{}, "Specifies which local env variables shall be sent to the container.")
- sshCmd.Flags().StringArrayVarP(&cmd.SetEnvVars, "set-env", "", []string{}, "Specifies env variables to be set in the container.")
- sshCmd.Flags().StringVar(&cmd.ForwardPortsTimeout, "forward-ports-timeout", "", "Specifies the timeout after which the command should terminate when the ports are unused.")
- sshCmd.Flags().StringVar(&cmd.Command, "command", "", "The command to execute within the workspace")
+ sshCmd.Flags().
+ StringArrayVarP(&cmd.ForwardPorts, "forward-ports", "L", []string{},
+ "Specifies that connections to the given TCP port or Unix socket on the local (client) "+
+ "host are to be forwarded to the given host, service name, and port, or Unix socket, on the remote side.")
+ sshCmd.Flags().
+ StringArrayVarP(&cmd.ReverseForwardPorts, "reverse-forward-ports", "R", []string{},
+ "Specifies that connections to the given TCP port or Unix socket on the remote side "+
+ "are to be reverse forwarded to the given local host, service name, and port, or Unix socket.")
+ sshCmd.Flags().
+ StringArrayVarP(&cmd.SendEnvVars, "send-env", "", []string{},
+ "Specifies which local env variables shall be sent to the container.")
+ sshCmd.Flags().
+ StringArrayVarP(&cmd.SetEnvVars, "set-env", "", []string{}, "Specifies env variables to be set in the container.")
+ sshCmd.Flags().
+ StringVar(&cmd.ForwardPortsTimeout, "forward-ports-timeout", "",
+ "Specifies the timeout after which the command should terminate when the ports are unused.")
+ sshCmd.Flags().
+ StringVar(&cmd.Command, "command", "", "The command to execute within the workspace")
sshCmd.Flags().StringVar(&cmd.User, "user", "", "The user of the workspace to use")
sshCmd.Flags().StringVar(&cmd.WorkDir, "workdir", "", "The working directory in the container")
- sshCmd.Flags().BoolVar(&cmd.AgentForwarding, "agent-forwarding", true, "If true forward the local ssh keys to the remote machine")
- sshCmd.Flags().StringVar(&cmd.ReuseSSHAuthSock, "reuse-ssh-auth-sock", "", "If set, the SSH_AUTH_SOCK is expected to already be available in the workspace (under /tmp using the key provided) and the connection reuses this instead of creating a new one")
+ sshCmd.Flags().
+ BoolVar(&cmd.AgentForwarding, "agent-forwarding", true, "If true forward the local ssh keys to the remote machine")
+ sshCmd.Flags().
+ StringVar(&cmd.ReuseSSHAuthSock, "reuse-ssh-auth-sock", "",
+ "If set, the SSH_AUTH_SOCK is expected to already be available in the workspace "+
+ "(under /tmp using the key provided) and the connection reuses this instead of creating a new one")
_ = sshCmd.Flags().MarkHidden("reuse-ssh-auth-sock")
- sshCmd.Flags().BoolVar(&cmd.GPGAgentForwarding, "gpg-agent-forwarding", false, "If true forward the local gpg-agent to the remote machine")
- sshCmd.Flags().BoolVar(&cmd.Stdio, "stdio", false, "If true will tunnel connection through stdout and stdin")
- sshCmd.Flags().BoolVar(&cmd.StartServices, "start-services", true, "If false will not start any port-forwarding or git / docker credentials helper")
- sshCmd.Flags().DurationVar(&cmd.SSHKeepAliveInterval, "ssh-keepalive-interval", 55*time.Second, "How often should keepalive request be made (55s)")
+ sshCmd.Flags().
+ BoolVar(&cmd.GPGAgentForwarding, "gpg-agent-forwarding", false,
+ "If true forward the local gpg-agent to the remote machine")
+ sshCmd.Flags().
+ BoolVar(&cmd.Stdio, "stdio", false, "If true will tunnel connection through stdout and stdin")
+ sshCmd.Flags().
+ BoolVar(&cmd.StartServices, "start-services", true,
+ "If false will not start any port-forwarding or git / docker credentials helper")
+ sshCmd.Flags().
+ DurationVar(&cmd.SSHKeepAliveInterval, "ssh-keepalive-interval", 55*time.Second,
+ "How often should keepalive request be made (55s)")
+ sshCmd.Flags().
+ StringVar(&cmd.GitSSHSigningKey, "git-ssh-signing-key", "",
+ "The SSH signing key to use for git commit signing inside the workspace")
sshCmd.Flags().StringVar(
&cmd.TermMode,
"term-mode",
@@ -125,15 +168,19 @@ func NewSSHCmd(f *flags.GlobalFlags) *cobra.Command {
return sshCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *SSHCmd) Run(
ctx context.Context,
devPodConfig *config.Config,
client client2.BaseWorkspaceClient,
- log log.Logger) error {
+ log log.Logger,
+) error {
// add ssh keys to agent
- if devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == "true" && devPodConfig.ContextOption(config.ContextOptionSSHAddPrivateKeys) == "true" {
- log.Debug("adding ssh keys to agent, disable via 'devpod context set-options -o SSH_ADD_PRIVATE_KEYS=false'")
+ if devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == config.BoolTrue &&
+ devPodConfig.ContextOption(config.ContextOptionSSHAddPrivateKeys) == config.BoolTrue {
+ log.Debug(
+ "adding ssh keys to agent, disable via 'devpod context set-options -o SSH_ADD_PRIVATE_KEYS=false'",
+ )
err := devssh.AddPrivateKeysToAgent(ctx, log)
if err != nil {
log.Debugf("Error adding private keys to ssh-agent: %v", err)
@@ -143,7 +190,11 @@ func (cmd *SSHCmd) Run(
// get user
if cmd.User == "" {
var err error
- cmd.User, err = devssh.GetUser(client.WorkspaceConfig().ID, client.WorkspaceConfig().SSHConfigPath, client.WorkspaceConfig().SSHConfigIncludePath)
+ cmd.User, err = devssh.GetUser(
+ client.WorkspaceConfig().ID,
+ client.WorkspaceConfig().SSHConfigPath,
+ client.WorkspaceConfig().SSHConfigIncludePath,
+ )
if err != nil {
return err
}
@@ -202,15 +253,18 @@ func (cmd *SSHCmd) jumpContainerTailscale(
if cmd.StartServices {
go func() {
- err = clientimplementation.StartServicesDaemon(ctx, clientimplementation.StartServicesDaemonOptions{
- DevPodConfig: devPodConfig,
- Client: client,
- SSHClient: toolSSHClient,
- User: cmd.User,
- Log: log,
- ForwardPorts: false,
- ExtraPorts: nil,
- })
+ err = clientimplementation.StartServicesDaemon(
+ ctx,
+ clientimplementation.StartServicesDaemonOptions{
+ DevPodConfig: devPodConfig,
+ Client: client,
+ SSHClient: toolSSHClient,
+ User: cmd.User,
+ Log: log,
+ ForwardPorts: false,
+ ExtraPorts: nil,
+ },
+ )
if err != nil {
log.Errorf("Error starting services: %v", err)
}
@@ -218,8 +272,9 @@ func (cmd *SSHCmd) jumpContainerTailscale(
}
// Handle GPG agent forwarding
- if cmd.GPGAgentForwarding || devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == "true" {
- if gpg.IsGpgTunnelRunning(cmd.User, ctx, toolSSHClient, log) {
+ if cmd.GPGAgentForwarding ||
+ devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == config.BoolTrue {
+ if gpg.IsGpgTunnelRunning(ctx, cmd.User, toolSSHClient, log) {
log.Debugf("[GPG] exporting already running, skipping")
} else if err := cmd.setupGPGAgent(ctx, toolSSHClient, log); err != nil {
return err
@@ -242,8 +297,11 @@ func (cmd *SSHCmd) jumpContainerTailscale(
machine.RunSSHSessionOptions{
AgentForwarding: cmd.AgentForwarding,
Command: cmd.Command,
- SessionOptions: machine.SSHSessionOptions{TermMode: cmd.TermMode, InstallTerminfo: cmd.InstallTerminfo},
- Stderr: os.Stderr,
+ SessionOptions: machine.SSHSessionOptions{
+ TermMode: cmd.TermMode,
+ InstallTerminfo: cmd.InstallTerminfo,
+ },
+ Stderr: os.Stderr,
},
)
}
@@ -325,16 +383,17 @@ func (cmd *SSHCmd) jumpContainer(
}
func (cmd *SSHCmd) forwardTimeout(log log.Logger) (time.Duration, error) {
- timeout := time.Duration(0)
- if cmd.ForwardPortsTimeout != "" {
- timeout, err := time.ParseDuration(cmd.ForwardPortsTimeout)
- if err != nil {
- return timeout, fmt.Errorf("parse forward ports timeout: %w", err)
- }
+ if cmd.ForwardPortsTimeout == "" {
+ return 0, nil
+ }
- log.Infof("Using port forwarding timeout of %s", cmd.ForwardPortsTimeout)
+ timeout, err := time.ParseDuration(cmd.ForwardPortsTimeout)
+ if err != nil {
+ return 0, fmt.Errorf("parse forward ports timeout: %w", err)
}
+ log.Infof("Using port forwarding timeout of %s", cmd.ForwardPortsTimeout)
+
return timeout, nil
}
@@ -343,73 +402,98 @@ func (cmd *SSHCmd) reverseForwardPorts(
containerClient *ssh.Client,
log log.Logger,
) error {
- timeout, err := cmd.forwardTimeout(log)
- if err != nil {
- return fmt.Errorf("parse forward ports timeout: %w", err)
- }
+ return cmd.runPortForwards(ctx, containerClient, portForwardConfig{
+ mappings: cmd.ReverseForwardPorts,
+ logTemplate: "Reverse forwarding remote %s/%s to local %s/%s",
+ forwardFn: devssh.ReversePortForward,
+ }, log)
+}
+
+func (cmd *SSHCmd) forwardPorts(
+ ctx context.Context,
+ containerClient *ssh.Client,
+ log log.Logger,
+) error {
+ return cmd.runPortForwards(ctx, containerClient, portForwardConfig{
+ mappings: cmd.ForwardPorts,
+ logTemplate: "Forwarding local %s/%s to remote %s/%s",
+ forwardFn: devssh.PortForward,
+ }, log)
+}
- errChan := make(chan error, len(cmd.ReverseForwardPorts))
- for _, portMapping := range cmd.ReverseForwardPorts {
+type portForwardFunc func(
+ context.Context,
+ *ssh.Client,
+ string,
+ string,
+ string,
+ string,
+ time.Duration,
+ log.Logger,
+) error
+
+type portForwardConfig struct {
+ mappings []string
+ logTemplate string
+ forwardFn portForwardFunc
+}
+
+type parsedPortForward struct {
+ spec string
+ mapping port.Mapping
+}
+
+func parsePortForwards(mappings []string) ([]parsedPortForward, error) {
+ parsedMappings := make([]parsedPortForward, 0, len(mappings))
+ for _, portMapping := range mappings {
mapping, err := port.ParsePortSpec(portMapping)
if err != nil {
- return fmt.Errorf("parse port mapping: %w", err)
+ return nil, fmt.Errorf("parse port mapping: %w", err)
}
- // start the forwarding
- log.Infof(
- "Reverse forwarding local %s/%s to remote %s/%s",
- mapping.Host.Protocol,
- mapping.Host.Address,
- mapping.Container.Protocol,
- mapping.Container.Address,
- )
- go func(portMapping string) {
- err := devssh.ReversePortForward(
- ctx,
- containerClient,
- mapping.Host.Protocol,
- mapping.Host.Address,
- mapping.Container.Protocol,
- mapping.Container.Address,
- timeout,
- log,
- )
- if !errors.Is(io.EOF, err) {
- errChan <- fmt.Errorf("error forwarding %s: %w", portMapping, err)
- }
- }(portMapping)
+ parsedMappings = append(parsedMappings, parsedPortForward{
+ spec: portMapping,
+ mapping: mapping,
+ })
}
- return <-errChan
+ return parsedMappings, nil
}
-func (cmd *SSHCmd) forwardPorts(
+func (cmd *SSHCmd) runPortForwards(
ctx context.Context,
containerClient *ssh.Client,
- log log.Logger,
+ config portForwardConfig,
+ logger log.Logger,
) error {
- timeout, err := cmd.forwardTimeout(log)
+ timeout, err := cmd.forwardTimeout(logger)
if err != nil {
return fmt.Errorf("parse forward ports timeout: %w", err)
}
- errChan := make(chan error, len(cmd.ForwardPorts))
- for _, portMapping := range cmd.ForwardPorts {
- mapping, err := port.ParsePortSpec(portMapping)
- if err != nil {
- return fmt.Errorf("parse port mapping: %w", err)
- }
+ parsedMappings, err := parsePortForwards(config.mappings)
+ if err != nil {
+ return err
+ }
+
+ errChan := make(chan error, len(parsedMappings))
+ var waitGroup sync.WaitGroup
+ for _, parsedMapping := range parsedMappings {
+ portMapping, mapping := parsedMapping.spec, parsedMapping.mapping
// start the forwarding
- log.Infof(
- "Forwarding local %s/%s to remote %s/%s",
+ logger.Infof(
+ config.logTemplate,
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
)
- go func(portMapping string) {
- err := devssh.PortForward(
+ waitGroup.Add(1)
+ go func(portMapping string, mapping port.Mapping) {
+ defer waitGroup.Done()
+
+ err := config.forwardFn(
ctx,
containerClient,
mapping.Host.Protocol,
@@ -417,18 +501,35 @@ func (cmd *SSHCmd) forwardPorts(
mapping.Container.Protocol,
mapping.Container.Address,
timeout,
- log,
+ logger,
)
- if !errors.Is(io.EOF, err) {
+ if err != nil && !errors.Is(err, io.EOF) {
errChan <- fmt.Errorf("error forwarding %s: %w", portMapping, err)
}
- }(portMapping)
+ }(portMapping, mapping)
}
- return <-errChan
+ go func() {
+ waitGroup.Wait()
+ close(errChan)
+ }()
+
+ for err := range errChan {
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
}
-func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config, containerClient *ssh.Client, workspaceClient client2.BaseWorkspaceClient, log log.Logger) error {
+func (cmd *SSHCmd) startTunnel(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ containerClient *ssh.Client,
+ workspaceClient client2.BaseWorkspaceClient,
+ log log.Logger,
+) error {
// check if we should forward ports
if len(cmd.ForwardPorts) > 0 {
return cmd.forwardPorts(ctx, containerClient, log)
@@ -440,21 +541,38 @@ func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config,
}
if cmd.StartServices {
- configureDockerCredentials := devPodConfig.ContextOption(config.ContextOptionSSHInjectDockerCredentials) == "true"
- configureGitCredentials := devPodConfig.ContextOption(config.ContextOptionSSHInjectGitCredentials) == "true"
- configureGitSSHSignatureHelper := devPodConfig.ContextOption(config.ContextOptionGitSSHSignatureForwarding) == "true"
-
- go cmd.startServices(ctx, devPodConfig, containerClient, workspaceClient.WorkspaceConfig(), configureDockerCredentials, configureGitCredentials, configureGitSSHSignatureHelper, log)
+ configureDockerCredentials := devPodConfig.ContextOption(
+ config.ContextOptionSSHInjectDockerCredentials,
+ ) == config.BoolTrue
+ configureGitCredentials := devPodConfig.ContextOption(
+ config.ContextOptionSSHInjectGitCredentials,
+ ) == config.BoolTrue
+ configureGitSSHSignatureHelper := devPodConfig.ContextOption(
+ config.ContextOptionGitSSHSignatureForwarding,
+ ) == config.BoolTrue
+
+ go cmd.startServices(
+ ctx,
+ devPodConfig,
+ containerClient,
+ workspaceClient.WorkspaceConfig(),
+ configureDockerCredentials,
+ configureGitCredentials,
+ configureGitSSHSignatureHelper,
+ cmd.GitSSHSigningKey,
+ log,
+ )
}
// start ssh
writer := log.ErrorStreamOnly().Writer(logrus.InfoLevel, false)
defer func() { _ = writer.Close() }()
// check if we should do gpg agent forwarding
- if cmd.GPGAgentForwarding || devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == "true" {
+ if cmd.GPGAgentForwarding ||
+ devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == config.BoolTrue {
// Check if a forwarding is already enabled and running, in that case
// we skip the forwarding and keep using the original one
- if gpg.IsGpgTunnelRunning(cmd.User, ctx, containerClient, log) {
+ if gpg.IsGpgTunnelRunning(ctx, cmd.User, containerClient, log) {
log.Debugf("[GPG] exporting already running, skipping")
} else {
err := cmd.setupGPGAgent(ctx, containerClient, log)
@@ -464,22 +582,28 @@ func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config,
}
}
- workdir := filepath.Join("/workspaces", workspaceClient.Workspace())
- if cmd.WorkDir != "" {
- workdir = cmd.WorkDir
- }
+ workdir := resolveWorkdir(cmd.WorkDir, workspaceClient, log)
log.Debugf("Run outer container tunnel")
- command := fmt.Sprintf("'%s' helper ssh-server --track-activity --stdio --workdir '%s'", agent.ContainerDevPodHelperLocation, workdir)
+ commandArgs := []string{
+ agent.ContainerDevPodHelperLocation,
+ "helper",
+ "ssh-server",
+ "--track-activity",
+ "--stdio",
+ "--workdir",
+ workdir,
+ }
if cmd.ReuseSSHAuthSock != "" {
log.Debug("Reusing SSH_AUTH_SOCK")
- command += fmt.Sprintf(" --reuse-ssh-auth-sock=%s", cmd.ReuseSSHAuthSock)
+ commandArgs = append(commandArgs, "--reuse-ssh-auth-sock", cmd.ReuseSSHAuthSock)
}
if cmd.Debug {
- command += " --debug"
+ commandArgs = append(commandArgs, "--debug")
}
+ command := shellescape.QuoteCommand(commandArgs)
if cmd.User != "" && cmd.User != "root" {
- command = fmt.Sprintf("su -c \"%s\" '%s'", command, cmd.User)
+ command = shellescape.QuoteCommand([]string{"su", "-c", command, cmd.User})
}
envVars, err := cmd.retrieveEnVars()
@@ -489,8 +613,7 @@ func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config,
// Traffic is coming in from the outside, we need to forward it to the container
if cmd.Stdio {
- return devssh.Run(devssh.RunOptions{
- Context: ctx,
+ return devssh.Run(ctx, devssh.RunOptions{
Client: containerClient,
Command: command,
Stdin: os.Stdin,
@@ -501,16 +624,19 @@ func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config,
}
return machine.StartSSHSession(ctx, machine.StartSSHSessionOptions{
- User: cmd.User,
- Command: cmd.Command,
- AgentForwarding: cmd.AgentForwarding && devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == "true",
- SessionOptions: machine.SSHSessionOptions{TermMode: cmd.TermMode, InstallTerminfo: cmd.InstallTerminfo},
+ User: cmd.User,
+ Command: cmd.Command,
+ AgentForwarding: cmd.AgentForwarding &&
+ devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == config.BoolTrue,
+ SessionOptions: machine.SSHSessionOptions{
+ TermMode: cmd.TermMode,
+ InstallTerminfo: cmd.InstallTerminfo,
+ },
Exec: func(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
if cmd.SSHKeepAliveInterval != DisableSSHKeepAlive {
go startSSHKeepAlive(ctx, containerClient, cmd.SSHKeepAliveInterval, log)
}
- return devssh.Run(devssh.RunOptions{
- Context: ctx,
+ return devssh.Run(ctx, devssh.RunOptions{
Client: containerClient,
Command: command,
Stdin: stdin,
@@ -523,12 +649,53 @@ func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config,
})
}
+func resolveWorkdir(
+ workdir string,
+ workspaceClient client2.BaseWorkspaceClient,
+ log log.Logger,
+) string {
+ if workdir != "" {
+ return workdir
+ }
+
+ if workspaceFolder := resolveMergedWorkspaceFolder(
+ workspaceClient,
+ log,
+ ); workspaceFolder != "" {
+ return workspaceFolder
+ }
+
+ return path.Join("/workspaces", workspaceClient.Workspace())
+}
+
+func resolveMergedWorkspaceFolder(
+ workspaceClient client2.BaseWorkspaceClient,
+ log log.Logger,
+) string {
+ workspaceConfig := workspaceClient.WorkspaceConfig()
+ if workspaceConfig == nil || workspaceConfig.Context == "" || workspaceConfig.ID == "" {
+ return ""
+ }
+
+ result, err := provider.LoadWorkspaceResult(workspaceConfig.Context, workspaceConfig.ID)
+ if err != nil {
+ log.Debugf("Error loading workspace result for workdir resolution: %v", err)
+ return ""
+ }
+ if result == nil || result.MergedConfig == nil {
+ return ""
+ }
+
+ return result.MergedConfig.WorkspaceFolder
+}
+
func (cmd *SSHCmd) startServices(
ctx context.Context,
devPodConfig *config.Config,
containerClient *ssh.Client,
workspace *provider.Workspace,
configureDockerCredentials, configureGitCredentials, configureGitSSHSignatureHelper bool,
+ gitSSHSigningKey string,
log log.Logger,
) {
if cmd.User != "" {
@@ -545,6 +712,7 @@ func (cmd *SSHCmd) startServices(
ConfigureDockerCredentials: configureDockerCredentials,
ConfigureGitCredentials: configureGitCredentials,
ConfigureGitSSHSignatureHelper: configureGitSSHSignatureHelper,
+ GitSSHSigningKey: gitSSHSigningKey,
Log: log,
},
)
@@ -555,7 +723,7 @@ func (cmd *SSHCmd) startServices(
}
// setupGPGAgent will forward a local gpg-agent into the remote container
-// this works by using cmd/agent/workspace/setup_gpg
+// this works by using cmd/agent/workspace/setup_gpg.
func (cmd *SSHCmd) setupGPGAgent(
ctx context.Context,
containerClient *ssh.Client,
@@ -580,12 +748,7 @@ func (cmd *SSHCmd) setupGPGAgent(
gpgExtraSocketPath := strings.TrimSpace(string(gpgExtraSocketBytes))
log.Debugf("[GPG] detected gpg-agent socket path %s", gpgExtraSocketPath)
- gitGpgKey, err := exec.Command("git", []string{"config", "user.signingKey"}...).Output()
- if err != nil {
- log.Debugf("[GPG] no git signkey detected, skipping")
- } else {
- log.Debugf("[GPG] detected git sign key %s", gitGpgKey)
- }
+ gitKey := gpgSigningKey(log)
cmd.ReverseForwardPorts = append(cmd.ReverseForwardPorts, gpgExtraSocketPath)
@@ -605,15 +768,14 @@ func (cmd *SSHCmd) setupGPGAgent(
forwardAgent = append(forwardAgent, "--debug")
}
- if len(gitGpgKey) > 0 {
- gitKey := strings.TrimSpace(string(gitGpgKey))
+ if gitKey != "" {
forwardAgent = append(forwardAgent, "--gitkey")
- forwardAgent = append(forwardAgent, fmt.Sprintf("'%s'", gitKey))
+ forwardAgent = append(forwardAgent, gitKey)
}
- command := strings.Join(forwardAgent, " ")
+ command := shellescape.QuoteCommand(forwardAgent)
if cmd.User != "" && cmd.User != "root" {
- command = fmt.Sprintf("su -c \"%s\" '%s'", command, cmd.User)
+ command = shellescape.QuoteCommand([]string{"su", "-c", command, cmd.User})
}
log.Debugf(
@@ -627,8 +789,7 @@ func (cmd *SSHCmd) setupGPGAgent(
writer := log.ErrorStreamOnly().Writer(logrus.InfoLevel, false)
defer func() { _ = writer.Close() }()
- err = devssh.Run(devssh.RunOptions{
- Context: ctx,
+ err = devssh.Run(ctx, devssh.RunOptions{
Client: containerClient,
Command: command,
Stdout: writer,
@@ -641,7 +802,51 @@ func (cmd *SSHCmd) setupGPGAgent(
return nil
}
-func startSSHKeepAlive(ctx context.Context, client *ssh.Client, interval time.Duration, log log.Logger) {
+// gpgSigningKey returns the user's GPG signing key from git config,
+// or empty string if no key is configured or the signing format is SSH
+// (SSH signing keys are handled by the separate SSH signature helper).
+func gpgSigningKey(log log.Logger) string {
+ format, err := exec.Command("git", "config", "--get", "gpg.format").Output()
+ formatStr := ""
+ if err == nil {
+ formatStr = strings.TrimSpace(string(format))
+ }
+ if formatStr == "ssh" {
+ log.Debugf(
+ "[GPG] gpg.format is ssh, skipping GPG signing key (handled by SSH signing helper)",
+ )
+ return ""
+ }
+
+ key, err := exec.Command("git", "config", "--get", "user.signingKey").Output()
+ if err != nil {
+ log.Debugf("[GPG] no git signkey detected, skipping")
+ return ""
+ }
+
+ result := strings.TrimSpace(string(key))
+
+ // GPG key IDs are hex fingerprints, not file paths. If the signing key
+ // looks like a file path and the format isn't x509 (which legitimately
+ // uses certificate file paths via gpgsm), it's an SSH key.
+ if (strings.HasPrefix(result, "/") || strings.HasPrefix(result, "~")) && formatStr != "x509" {
+ log.Debugf(
+ "[GPG] signing key %s looks like a file path, skipping (not a GPG key ID)",
+ result,
+ )
+ return ""
+ }
+
+ log.Debugf("[GPG] detected git sign key %s", result)
+ return result
+}
+
+func startSSHKeepAlive(
+ ctx context.Context,
+ client *ssh.Client,
+ interval time.Duration,
+ log log.Logger,
+) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
diff --git a/cmd/ssh_test.go b/cmd/ssh_test.go
new file mode 100644
index 0000000000..6614709569
--- /dev/null
+++ b/cmd/ssh_test.go
@@ -0,0 +1,247 @@
+package cmd
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/skevetter/log"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/crypto/ssh"
+)
+
+const httpPort = "8080:80"
+
+func writeGitConfig(t *testing.T, content string) {
+ t.Helper()
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_CONFIG_HOME", home)
+ t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(home, ".gitconfig"))
+ err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte(content), 0o600)
+ assert.NoError(t, err)
+}
+
+func TestGpgSigningKey_GPGFormat(t *testing.T) {
+ writeGitConfig(t, "[user]\n\tsigningKey = TESTKEY123\n")
+ result := gpgSigningKey(log.Discard)
+ assert.Equal(t, "TESTKEY123", result)
+}
+
+func TestGpgSigningKey_SSHFormat_Skipped(t *testing.T) {
+ writeGitConfig(
+ t,
+ "[gpg]\n\tformat = ssh\n[user]\n\tsigningKey = /home/user/.ssh/id_ed25519.pub\n",
+ )
+ result := gpgSigningKey(log.Discard)
+ assert.Empty(t, result)
+}
+
+func TestGpgSigningKey_NoKeyConfigured(t *testing.T) {
+ writeGitConfig(t, "[user]\n\tname = Test\n")
+ result := gpgSigningKey(log.Discard)
+ assert.Empty(t, result)
+}
+
+func TestGpgSigningKey_X509Format_Returned(t *testing.T) {
+ writeGitConfig(t, "[gpg]\n\tformat = x509\n[user]\n\tsigningKey = /path/to/cert\n")
+ result := gpgSigningKey(log.Discard)
+ assert.Equal(t, "/path/to/cert", result)
+}
+
+func TestGpgSigningKey_SSHKeyPath_Skipped(t *testing.T) {
+ writeGitConfig(t, "[user]\n\tsigningKey = /home/user/.ssh/id_ed25519.pub\n")
+ result := gpgSigningKey(log.Discard)
+ assert.Empty(t, result)
+}
+
+func TestGpgSigningKey_TildeKeyPath_Skipped(t *testing.T) {
+ writeGitConfig(t, "[user]\n\tsigningKey = ~/.ssh/id_ed25519.pub\n")
+ result := gpgSigningKey(log.Discard)
+ assert.Empty(t, result)
+}
+
+func TestForwardTimeout_UsesParsedDuration(t *testing.T) {
+ cmd := &SSHCmd{ForwardPortsTimeout: "90s"}
+
+ timeout, err := cmd.forwardTimeout(log.Discard)
+ require.NoError(t, err)
+ assert.Equal(t, 90*time.Second, timeout)
+}
+
+func runPortForwardsForTest(
+ t *testing.T,
+ cmd *SSHCmd,
+ mappings []string,
+ forwardFn portForwardFunc,
+) (int32, error) {
+ t.Helper()
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+
+ var calls atomic.Int32
+ err := cmd.runPortForwards(ctx, nil, portForwardConfig{
+ mappings: mappings,
+ logTemplate: "test %s/%s %s/%s",
+ forwardFn: func(
+ ctx context.Context,
+ client *ssh.Client,
+ localNetwork string,
+ localAddr string,
+ remoteNetwork string,
+ remoteAddr string,
+ timeout time.Duration,
+ logger log.Logger,
+ ) error {
+ calls.Add(1)
+ return forwardFn(
+ ctx,
+ client,
+ localNetwork,
+ localAddr,
+ remoteNetwork,
+ remoteAddr,
+ timeout,
+ logger,
+ )
+ },
+ }, log.Discard)
+
+ return calls.Load(), err
+}
+
+func TestRunPortForwards_CleanExit(t *testing.T) {
+ calls, err := runPortForwardsForTest(t, &SSHCmd{}, []string{httpPort}, func(
+ context.Context,
+ *ssh.Client,
+ string,
+ string,
+ string,
+ string,
+ time.Duration,
+ log.Logger,
+ ) error {
+ return nil
+ })
+
+ require.NoError(t, err)
+ assert.Equal(t, int32(1), calls)
+}
+
+func TestRunPortForwards_EOFExit(t *testing.T) {
+ calls, err := runPortForwardsForTest(t, &SSHCmd{}, []string{httpPort}, func(
+ context.Context,
+ *ssh.Client,
+ string,
+ string,
+ string,
+ string,
+ time.Duration,
+ log.Logger,
+ ) error {
+ return io.EOF
+ })
+
+ require.NoError(t, err)
+ assert.Equal(t, int32(1), calls)
+}
+
+func TestRunPortForwards_ForwardError(t *testing.T) {
+ calls, err := runPortForwardsForTest(t, &SSHCmd{}, []string{httpPort}, func(
+ context.Context,
+ *ssh.Client,
+ string,
+ string,
+ string,
+ string,
+ time.Duration,
+ log.Logger,
+ ) error {
+ return errors.New("boom")
+ })
+
+ require.Error(t, err)
+ assert.ErrorContains(t, err, "error forwarding 8080:80: boom")
+ assert.Equal(t, int32(1), calls)
+}
+
+func TestRunPortForwards_UsesConfiguredTimeout(t *testing.T) {
+ cmd := &SSHCmd{ForwardPortsTimeout: "90s"}
+ var gotTimeout time.Duration
+
+ calls, err := runPortForwardsForTest(t, cmd, []string{httpPort}, func(
+ _ context.Context,
+ _ *ssh.Client,
+ _ string,
+ _ string,
+ _ string,
+ _ string,
+ timeout time.Duration,
+ _ log.Logger,
+ ) error {
+ gotTimeout = timeout
+ return nil
+ })
+
+ require.NoError(t, err)
+ assert.Equal(t, int32(1), calls)
+ assert.Equal(t, 90*time.Second, gotTimeout)
+}
+
+func TestRunPortForwards_ParseErrorStopsBeforeLaunch(t *testing.T) {
+ calls, err := runPortForwardsForTest(t, &SSHCmd{}, []string{httpPort, ""}, func(
+ context.Context,
+ *ssh.Client,
+ string,
+ string,
+ string,
+ string,
+ time.Duration,
+ log.Logger,
+ ) error {
+ return nil
+ })
+
+ require.Error(t, err)
+ assert.ErrorContains(t, err, "parse port mapping")
+ assert.Equal(t, int32(0), calls)
+}
+
+func TestRunPortForwards_MultipleMappingsReturnError(t *testing.T) {
+ var started atomic.Int32
+ ready := make(chan struct{})
+
+ calls, err := runPortForwardsForTest(t, &SSHCmd{}, []string{httpPort, "8081:81"}, func(
+ _ context.Context,
+ _ *ssh.Client,
+ _ string,
+ localAddr string,
+ _ string,
+ _ string,
+ _ time.Duration,
+ _ log.Logger,
+ ) error {
+ if started.Add(1) == 2 {
+ close(ready)
+ } else {
+ <-ready
+ }
+
+ if localAddr == "localhost:8081" {
+ return errors.New("boom")
+ }
+
+ return nil
+ })
+
+ require.Error(t, err)
+ assert.ErrorContains(t, err, "error forwarding 8081:81: boom")
+ assert.Equal(t, int32(2), calls)
+}
diff --git a/cmd/status.go b/cmd/status.go
index b346b2ef7b..0dca185b56 100644
--- a/cmd/status.go
+++ b/cmd/status.go
@@ -16,7 +16,7 @@ import (
"github.com/spf13/cobra"
)
-// StatusCmd holds the cmd flags
+// StatusCmd holds the cmd flags.
type StatusCmd struct {
*flags.GlobalFlags
client2.StatusOptions
@@ -25,7 +25,7 @@ type StatusCmd struct {
Timeout string
}
-// NewStatusCmd creates a new command
+// NewStatusCmd creates a new command.
func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StatusCmd{
GlobalFlags: flags,
@@ -34,7 +34,10 @@ func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
Use: "status [flags] [workspace-path|workspace-name]",
Short: "Shows the status of a workspace",
RunE: func(cobraCmd *cobra.Command, args []string) error {
- _, err := clientimplementation.DecodeOptionsFromEnv(clientimplementation.DevPodFlagsStatus, &cmd.StatusOptions)
+ _, err := clientimplementation.DecodeOptionsFromEnv(
+ config.EnvFlagsStatus,
+ &cmd.StatusOptions,
+ )
if err != nil {
return fmt.Errorf("decode status options: %w", err)
}
@@ -46,7 +49,12 @@ func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
}
logger := log.Default.ErrorStreamOnly()
- client, err := workspace2.Get(ctx, devPodConfig, args, false, cmd.Owner, false, logger)
+ client, err := workspace2.Get(ctx, workspace2.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ Owner: cmd.Owner,
+ Log: logger,
+ })
if err != nil {
return err
}
@@ -54,18 +62,32 @@ func NewStatusCmd(flags *flags.GlobalFlags) *cobra.Command {
return cmd.Run(ctx, client, logger)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
- statusCmd.Flags().BoolVar(&cmd.ContainerStatus, "container-status", true, "If enabled shows the workspace container status as well")
+ statusCmd.Flags().
+ BoolVar(&cmd.ContainerStatus, "container-status", true, "If enabled shows the workspace container status as well")
statusCmd.Flags().StringVar(&cmd.Output, "output", "plain", "Status shows the workspace status")
- statusCmd.Flags().StringVar(&cmd.Timeout, "timeout", "30s", "The timeout to wait until the status can be retrieved")
+ statusCmd.Flags().
+ StringVar(&cmd.Timeout, "timeout", "30s", "The timeout to wait until the status can be retrieved")
return statusCmd
}
-// Run runs the command logic
-func (cmd *StatusCmd) Run(ctx context.Context, client client2.BaseWorkspaceClient, log log.Logger) error {
+// Run runs the command logic.
+func (cmd *StatusCmd) Run(
+ ctx context.Context,
+ client client2.BaseWorkspaceClient,
+ log log.Logger,
+) error {
// parse timeout
if cmd.Timeout != "" {
duration, err := time.ParseDuration(cmd.Timeout)
@@ -88,11 +110,26 @@ func (cmd *StatusCmd) Run(ctx context.Context, client client2.BaseWorkspaceClien
case "plain":
switch instanceStatus {
case client2.StatusStopped:
- log.Infof("Workspace '%s' is '%s', you can start it via 'devpod up %s'", client.Workspace(), instanceStatus, client.Workspace())
+ log.Infof(
+ "Workspace '%s' is '%s', you can start it via 'devpod up %s'",
+ client.Workspace(),
+ instanceStatus,
+ client.Workspace(),
+ )
case client2.StatusBusy:
- log.Infof("Workspace '%s' is '%s', which means its currently unaccessible. This is usually resolved by waiting a couple of minutes", client.Workspace(), instanceStatus)
+ log.Infof(
+ "Workspace '%s' is '%s', which means its currently unaccessible. "+
+ "This is usually resolved by waiting a couple of minutes",
+ client.Workspace(),
+ instanceStatus,
+ )
case client2.StatusNotFound:
- log.Infof("Workspace '%s' is '%s', you can create it via 'devpod up %s'", client.Workspace(), instanceStatus, client.Workspace())
+ log.Infof(
+ "Workspace '%s' is '%s', you can create it via 'devpod up %s'",
+ client.Workspace(),
+ instanceStatus,
+ client.Workspace(),
+ )
default:
log.Infof("Workspace '%s' is '%s'", client.Workspace(), instanceStatus)
}
@@ -109,7 +146,10 @@ func (cmd *StatusCmd) Run(ctx context.Context, client client2.BaseWorkspaceClien
fmt.Print(string(out))
default:
- return fmt.Errorf("unexpected output format, choose either json or plain. Got %s", cmd.Output)
+ return fmt.Errorf(
+ "unexpected output format, choose either json or plain. Got %s",
+ cmd.Output,
+ )
}
return nil
diff --git a/cmd/stop.go b/cmd/stop.go
index d5b2dd47bb..c8831617f8 100644
--- a/cmd/stop.go
+++ b/cmd/stop.go
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
- "github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
client2 "github.com/skevetter/devpod/pkg/client"
@@ -15,13 +14,13 @@ import (
"github.com/spf13/cobra"
)
-// StopCmd holds the destroy cmd flags
+// StopCmd holds the destroy cmd flags.
type StopCmd struct {
*flags.GlobalFlags
client2.StopOptions
}
-// NewStopCmd creates a new destroy command
+// NewStopCmd creates a new destroy command.
func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &StopCmd{
GlobalFlags: flags,
@@ -42,7 +41,12 @@ func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
return fmt.Errorf("decode platform options: %w", err)
}
- client, err := workspace2.Get(ctx, devPodConfig, args, false, cmd.Owner, false, log.Default)
+ client, err := workspace2.Get(ctx, workspace2.GetOptions{
+ DevPodConfig: devPodConfig,
+ Args: args,
+ Owner: cmd.Owner,
+ Log: log.Default,
+ })
if err != nil {
return err
}
@@ -50,15 +54,27 @@ func NewStopCmd(flags *flags.GlobalFlags) *cobra.Command {
return cmd.Run(ctx, devPodConfig, client)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
}
return stopCmd
}
-// Run runs the command logic
-func (cmd *StopCmd) Run(ctx context.Context, devPodConfig *config.Config, client client2.BaseWorkspaceClient) error {
+// Run runs the command logic.
+func (cmd *StopCmd) Run(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ client client2.BaseWorkspaceClient,
+) error {
// lock workspace
if !cmd.Platform.Enabled {
err := client.Lock(ctx)
@@ -93,10 +109,15 @@ func (cmd *StopCmd) Run(ctx context.Context, devPodConfig *config.Config, client
return nil
}
-func (cmd *StopCmd) stopSingleMachine(ctx context.Context, client client2.BaseWorkspaceClient, devPodConfig *config.Config) (bool, error) {
+func (cmd *StopCmd) stopSingleMachine(
+ ctx context.Context,
+ client client2.BaseWorkspaceClient,
+ devPodConfig *config.Config,
+) (bool, error) {
// check if single machine
singleMachineName := workspace2.SingleMachineName(devPodConfig, client.Provider(), log.Default)
- if !devPodConfig.Current().IsSingleMachine(client.Provider()) || client.WorkspaceConfig().Machine.ID != singleMachineName {
+ if !devPodConfig.Current().IsSingleMachine(client.Provider()) ||
+ client.WorkspaceConfig().Machine.ID != singleMachineName {
return false, nil
}
@@ -121,7 +142,11 @@ func (cmd *StopCmd) stopSingleMachine(ctx context.Context, client client2.BaseWo
}
// if we haven't found another workspace on this machine, delete the whole machine
- machineClient, err := workspace2.GetMachine(devPodConfig, []string{singleMachineName}, log.Default)
+ machineClient, err := workspace2.GetMachine(
+ devPodConfig,
+ []string{singleMachineName},
+ log.Default,
+ )
if err != nil {
return false, fmt.Errorf("get machine: %w", err)
}
@@ -132,8 +157,6 @@ func (cmd *StopCmd) stopSingleMachine(ctx context.Context, client client2.BaseWo
return false, fmt.Errorf("delete machine: %w", err)
}
- log.Default.WithFields(logrus.Fields{
- "workspace": client.Workspace(),
- }).Done("stopped workspace")
+ log.Default.Donef("stopped workspace: workspace=%s", client.Workspace())
return true, nil
}
diff --git a/cmd/troubleshoot.go b/cmd/troubleshoot.go
index d5427af83a..1a60b6b8da 100644
--- a/cmd/troubleshoot.go
+++ b/cmd/troubleshoot.go
@@ -6,7 +6,7 @@ import (
"errors"
"fmt"
- managementv1 "github.com/loft-sh/api/v4/pkg/apis/management/v1"
+ managementv1 "github.com/skevetter/api/pkg/apis/management/v1"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/cmd/provider"
@@ -37,7 +37,15 @@ func NewTroubleshootCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd.Run(cobraCmd.Context(), args)
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return completion.GetWorkspaceSuggestions(rootCmd, cmd.Context, cmd.Provider, args, toComplete, cmd.Owner, log.Default)
+ return completion.GetWorkspaceSuggestions(
+ rootCmd,
+ cmd.Context,
+ cmd.Provider,
+ args,
+ toComplete,
+ cmd.Owner,
+ log.Default,
+ )
},
Hidden: true,
}
@@ -47,7 +55,7 @@ func NewTroubleshootCmd(flags *flags.GlobalFlags) *cobra.Command {
func (cmd *TroubleshootCmd) Run(ctx context.Context, args []string) {
// (ThomasK33): We're creating an anonymous struct here, so that we group
- // everything and then we can serialize it in one call.
+ // everything so that we can serialize it in one call.
var info struct {
CLIVersion string
Config *config.Config
@@ -96,15 +104,26 @@ func (cmd *TroubleshootCmd) Run(ctx context.Context, args []string) {
info.DevPodProInstances, err = collectPlatformInfo(info.Config, logger)
if err != nil {
- info.Errors = append(info.Errors, PrintableError{fmt.Errorf("collect platform info: %w", err)})
+ info.Errors = append(
+ info.Errors,
+ PrintableError{fmt.Errorf("collect platform info: %w", err)},
+ )
}
- workspaceClient, err := workspace.Get(ctx, info.Config, args, false, cmd.Owner, false, logger)
+ workspaceClient, err := workspace.Get(ctx, workspace.GetOptions{
+ DevPodConfig: info.Config,
+ Args: args,
+ Owner: cmd.Owner,
+ Log: logger,
+ })
if err == nil {
info.Workspace = workspaceClient.WorkspaceConfig()
info.WorkspaceStatus, err = workspaceClient.Status(ctx, client.StatusOptions{})
if err != nil {
- info.Errors = append(info.Errors, PrintableError{fmt.Errorf("workspace status: %w", err)})
+ info.Errors = append(
+ info.Errors,
+ PrintableError{fmt.Errorf("workspace status: %w", err)},
+ )
}
if info.Workspace.Pro != nil {
@@ -129,7 +148,10 @@ func (cmd *TroubleshootCmd) Run(ctx context.Context, args []string) {
info.Workspace.Pro.Project,
)
if err != nil {
- info.Errors = append(info.Errors, PrintableError{fmt.Errorf("collect pro workspace info: %w", err)})
+ info.Errors = append(
+ info.Errors,
+ PrintableError{fmt.Errorf("collect pro workspace info: %w", err)},
+ )
}
}
}
@@ -141,7 +163,10 @@ func (cmd *TroubleshootCmd) Run(ctx context.Context, args []string) {
if ok {
status, err := daemon.NewLocalClient(daemonClient.Provider()).Status(ctx, true)
if err != nil {
- info.Errors = append(info.Errors, PrintableError{fmt.Errorf("get daemon status: %w", err)})
+ info.Errors = append(
+ info.Errors,
+ PrintableError{fmt.Errorf("get daemon status: %w", err)},
+ )
} else {
info.DaemonStatus = &status
}
@@ -164,7 +189,8 @@ func collectProWorkspaceInfo(
return nil, fmt.Errorf("init client from host: %w", err)
}
- workspace, err := platform.FindInstanceInProject(ctx, baseClient, workspaceUID, project)
+ opts := platform.FindInstanceOptions{UID: workspaceUID, ProjectName: project}
+ workspace, err := platform.FindInstance(ctx, baseClient, opts)
if err != nil {
return nil, err
} else if workspace == nil {
@@ -190,7 +216,10 @@ func collectProWorkspaceInfo(
// collectProviders collects and configures providers based on the given devPodConfig.
// It returns a map of providers with their default settings and an error if any occurs.
-func collectProviders(devPodConfig *config.Config, logger log.Logger) (map[string]provider.ProviderWithDefault, error) {
+func collectProviders(
+ devPodConfig *config.Config,
+ logger log.Logger,
+) (map[string]provider.ProviderWithDefault, error) {
providers, err := workspace.LoadAllProviders(devPodConfig, logger)
if err != nil {
return nil, err
@@ -207,7 +236,10 @@ func collectProviders(devPodConfig *config.Config, logger log.Logger) (map[strin
continue
}
- srcOptions := provider.MergeDynamicOptions(entry.Config.Options, configuredProviders[entry.Config.Name].DynamicOptions)
+ srcOptions := provider.MergeDynamicOptions(
+ entry.Config.Options,
+ configuredProviders[entry.Config.Name].DynamicOptions,
+ )
entry.Config.Options = srcOptions
retMap[k] = provider.ProviderWithDefault{
ProviderWithOptions: *entry,
@@ -228,7 +260,10 @@ type DevPodProInstance struct {
// It iterates over the pro instances, retrieves their versions, and appends them to the ProInstance slice.
// Any errors encountered during this process are combined and returned along with the ProInstance slice.
// This means that even when an error value is returned, the pro instance slice will contain valid values.
-func collectPlatformInfo(devPodConfig *config.Config, logger log.Logger) ([]DevPodProInstance, error) {
+func collectPlatformInfo(
+ devPodConfig *config.Config,
+ logger log.Logger,
+) ([]DevPodProInstance, error) {
proInstanceList, err := workspace.ListProInstances(devPodConfig, logger)
if err != nil {
return nil, fmt.Errorf("list pro instances: %w", err)
@@ -238,7 +273,9 @@ func collectPlatformInfo(devPodConfig *config.Config, logger log.Logger) ([]DevP
var combinedErrs error
for _, proInstance := range proInstanceList {
- version, err := platform.GetProInstanceDevPodVersion(&pkgprovider.ProInstance{Host: proInstance.Host})
+ version, err := platform.GetProInstanceDevPodVersion(
+ &pkgprovider.ProInstance{Host: proInstance.Host},
+ )
combinedErrs = errors.Join(combinedErrs, err)
proInstances = append(proInstances, DevPodProInstance{
Host: proInstance.Host,
diff --git a/cmd/up.go b/cmd/up.go
index fec1574d45..ed25b5e3b9 100644
--- a/cmd/up.go
+++ b/cmd/up.go
@@ -1,57 +1,39 @@
package cmd
import (
- "bytes"
"context"
"fmt"
"io"
- "net"
"os"
- "os/exec"
"os/signal"
"path/filepath"
- "slices"
"strconv"
"strings"
"syscall"
- "github.com/blang/semver/v4"
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/pkg/agent"
"github.com/skevetter/devpod/pkg/agent/tunnelserver"
client2 "github.com/skevetter/devpod/pkg/client"
"github.com/skevetter/devpod/pkg/client/clientimplementation"
- "github.com/skevetter/devpod/pkg/command"
"github.com/skevetter/devpod/pkg/config"
config2 "github.com/skevetter/devpod/pkg/devcontainer/config"
"github.com/skevetter/devpod/pkg/devcontainer/sshtunnel"
+ "github.com/skevetter/devpod/pkg/dotfiles"
"github.com/skevetter/devpod/pkg/ide"
- "github.com/skevetter/devpod/pkg/ide/fleet"
- "github.com/skevetter/devpod/pkg/ide/jetbrains"
- "github.com/skevetter/devpod/pkg/ide/jupyter"
- "github.com/skevetter/devpod/pkg/ide/openvscode"
- "github.com/skevetter/devpod/pkg/ide/rstudio"
- "github.com/skevetter/devpod/pkg/ide/vscode"
- "github.com/skevetter/devpod/pkg/ide/zed"
- open2 "github.com/skevetter/devpod/pkg/open"
+ "github.com/skevetter/devpod/pkg/ide/opener"
options2 "github.com/skevetter/devpod/pkg/options"
- "github.com/skevetter/devpod/pkg/platform"
- "github.com/skevetter/devpod/pkg/port"
provider2 "github.com/skevetter/devpod/pkg/provider"
devssh "github.com/skevetter/devpod/pkg/ssh"
"github.com/skevetter/devpod/pkg/telemetry"
- "github.com/skevetter/devpod/pkg/tunnel"
"github.com/skevetter/devpod/pkg/util"
- "github.com/skevetter/devpod/pkg/version"
workspace2 "github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
- "github.com/skratchdot/open-golang/open"
"github.com/spf13/cobra"
- "golang.org/x/crypto/ssh"
)
-// UpCmd holds the up cmd flags
+// UpCmd holds the up cmd flags.
type UpCmd struct {
provider2.CLIOptions
*flags.GlobalFlags
@@ -73,7 +55,7 @@ type UpCmd struct {
DotfilesScriptEnvFile []string // Paths to files containing Key=Value pairs to pass to install script
}
-// NewUpCmd creates a new up command
+// NewUpCmd creates a new up command.
func NewUpCmd(f *flags.GlobalFlags) *cobra.Command {
cmd := &UpCmd{GlobalFlags: f}
upCmd := &cobra.Command{
@@ -93,7 +75,7 @@ func (cmd *UpCmd) execute(cobraCmd *cobra.Command, args []string) error {
if err != nil {
return err
}
- if devPodConfig.ContextOption(config.ContextOptionSSHStrictHostKeyChecking) == "true" {
+ if devPodConfig.ContextOption(config.ContextOptionSSHStrictHostKeyChecking) == config.BoolTrue {
cmd.StrictHostKeyChecking = true
}
@@ -104,8 +86,17 @@ func (cmd *UpCmd) execute(cobraCmd *cobra.Command, args []string) error {
if err != nil {
return fmt.Errorf("prepare workspace client: %w", err)
}
- if cmd.ExtraDevContainerPath != "" && client.Provider() != "docker" {
- return fmt.Errorf("extra devcontainer file is only supported with local provider")
+ if hasLocalExtraFeatures(cmd.ExtraDevContainerConfig) {
+ providerConfig, err := provider2.LoadProviderConfig(
+ devPodConfig.DefaultContext,
+ client.Provider(),
+ )
+ if err != nil {
+ return fmt.Errorf("load provider config for local extra features: %w", err)
+ }
+ if err := validateExtraFeatureProvider(cmd.CLIOptions, providerConfig); err != nil {
+ return err
+ }
}
telemetry.CollectorCLI.SetClient(client)
@@ -138,57 +129,130 @@ func (cmd *UpCmd) registerFlags(upCmd *cobra.Command) {
}
func (cmd *UpCmd) registerSSHFlags(upCmd *cobra.Command) {
- upCmd.Flags().BoolVar(&cmd.ConfigureSSH, "configure-ssh", true, "If true will configure the ssh config to include the DevPod workspace")
- upCmd.Flags().BoolVar(&cmd.GPGAgentForwarding, "gpg-agent-forwarding", false, "If true forward the local gpg-agent to the DevPod workspace")
- upCmd.Flags().StringVar(&cmd.SSHConfigPath, "ssh-config", "", "The path to the ssh config to modify, if empty will use ~/.ssh/config")
+ upCmd.Flags().
+ BoolVar(&cmd.ConfigureSSH, "configure-ssh", true,
+ "If true will configure the ssh config to include the DevPod workspace")
+ upCmd.Flags().
+ BoolVar(&cmd.GPGAgentForwarding, "gpg-agent-forwarding", false,
+ "If true forward the local gpg-agent to the DevPod workspace")
+ upCmd.Flags().
+ StringVar(&cmd.SSHConfigPath, "ssh-config", "",
+ "The path to the ssh config to modify, if empty will use ~/.ssh/config")
}
func (cmd *UpCmd) registerDotfilesFlags(upCmd *cobra.Command) {
- upCmd.Flags().StringVar(&cmd.DotfilesSource, "dotfiles", "", "The path or url to the dotfiles to use in the container")
- upCmd.Flags().StringVar(&cmd.DotfilesScript, "dotfiles-script", "", "The path in dotfiles directory to use to install the dotfiles, if empty will try to guess")
- upCmd.Flags().StringSliceVar(&cmd.DotfilesScriptEnv, "dotfiles-script-env", []string{}, "Extra environment variables to put into the dotfiles install script. E.g. MY_ENV_VAR=MY_VALUE")
- upCmd.Flags().StringSliceVar(&cmd.DotfilesScriptEnvFile, "dotfiles-script-env-file", []string{}, "The path to files containing environment variables to set for the dotfiles install script")
+ upCmd.Flags().
+ StringVar(&cmd.DotfilesSource, "dotfiles", "", "The path or url to the dotfiles to use in the container")
+ upCmd.Flags().
+ StringVar(&cmd.DotfilesScript, "dotfiles-script", "",
+ "The path in dotfiles directory to use to install the dotfiles, if empty will try to guess")
+ upCmd.Flags().
+ StringSliceVar(&cmd.DotfilesScriptEnv, "dotfiles-script-env", []string{},
+ "Extra environment variables to put into the dotfiles install script, e.g. MY_ENV_VAR=MY_VALUE")
+ upCmd.Flags().
+ StringSliceVar(&cmd.DotfilesScriptEnvFile, "dotfiles-script-env-file", []string{},
+ "The path to files containing environment variables to set for the dotfiles install script")
}
func (cmd *UpCmd) registerDevContainerFlags(upCmd *cobra.Command) {
- upCmd.Flags().StringVar(&cmd.DevContainerImage, "devcontainer-image", "", "The container image to use, this will override the devcontainer.json value in the project")
- upCmd.Flags().StringVar(&cmd.DevContainerPath, "devcontainer-path", "", "The path to the devcontainer.json relative to the project")
- upCmd.Flags().StringVar(&cmd.DevContainerID, "devcontainer-id", "", "The ID of the devcontainer to use when multiple exist (e.g., folder name in .devcontainer/FOLDER/devcontainer.json)")
- upCmd.Flags().StringVar(&cmd.ExtraDevContainerPath, "extra-devcontainer-path", "", "The path to an additional devcontainer.json file to override original devcontainer.json")
- upCmd.Flags().StringVar(&cmd.FallbackImage, "fallback-image", "", "The fallback image to use if no devcontainer configuration has been detected")
+ upCmd.Flags().
+ StringVar(&cmd.DevContainerImage, "devcontainer-image", "",
+ "The container image to use, this will override the devcontainer.json value in the project")
+ upCmd.Flags().
+ StringVar(&cmd.DevContainerPath, "devcontainer-path", "", "The path to the devcontainer.json relative to the project")
+ upCmd.Flags().
+ StringVar(&cmd.DevContainerID, "devcontainer-id", "",
+ "The ID of the devcontainer to use when multiple exist "+
+ "(e.g., folder name in .devcontainer/FOLDER/devcontainer.json)")
+ upCmd.Flags().
+ StringVar(&cmd.ExtraDevContainerPath, "extra-devcontainer-path", "",
+ "The local path to an additional devcontainer.json for runtime settings and build features. "+
+ "Feature options override the project's; --additional-features takes precedence. "+
+ "Feature changes require rebuilding an existing container")
+ upCmd.Flags().
+ StringVar(&cmd.FallbackImage, "fallback-image", "",
+ "The fallback image to use if no devcontainer configuration has been detected")
+ upCmd.Flags().
+ StringVar(&cmd.AdditionalFeatures, "additional-features", "",
+ `Additional features to apply to the dev container (JSON as per "features" section in devcontainer.json)`)
+ upCmd.Flags().
+ StringArrayVar(&cmd.Mounts, "mount", []string{},
+ "Additional mount to apply when creating the dev container. "+
+ "Format type=,source=,target=[,external=]")
}
func (cmd *UpCmd) registerIDEFlags(upCmd *cobra.Command) {
- upCmd.Flags().StringVar(&cmd.IDE, "ide", "", "The IDE to open the workspace in. If empty will use vscode locally or in browser")
- upCmd.Flags().StringArrayVar(&cmd.IDEOptions, "ide-option", []string{}, "IDE option in the form KEY=VALUE")
- upCmd.Flags().BoolVar(&cmd.OpenIDE, "open-ide", true, "If this is false and an IDE is configured, DevPod will only install the IDE server backend, but not open it")
+ upCmd.Flags().
+ StringVar(&cmd.IDE, "ide", "", "The IDE to open the workspace in. If empty will use vscode locally or in browser")
+ upCmd.Flags().
+ StringArrayVar(&cmd.IDEOptions, "ide-option", []string{}, "IDE option in the form KEY=VALUE")
+ upCmd.Flags().
+ BoolVar(&cmd.OpenIDE, "open-ide", true,
+ "If this is false and an IDE is configured, DevPod will only install the IDE server backend, but not open it")
}
func (cmd *UpCmd) registerGitFlags(upCmd *cobra.Command) {
- upCmd.Flags().Var(&cmd.GitCloneStrategy, "git-clone-strategy", "The git clone strategy DevPod uses to checkout git based workspaces. Can be full (default), blobless, treeless or shallow")
- upCmd.Flags().BoolVar(&cmd.GitCloneRecursiveSubmodules, "git-clone-recursive-submodules", false, "If true will clone git submodule repositories recursively")
- upCmd.Flags().StringVar(&cmd.GitSSHSigningKey, "git-ssh-signing-key", "", "The ssh key to use when signing git commits. Used to explicitly setup DevPod's ssh signature forwarding with given key. Should be same format as value of `git config user.signingkey`")
+ upCmd.Flags().
+ Var(&cmd.GitCloneStrategy, "git-clone-strategy",
+ "The git clone strategy DevPod uses to checkout git based workspaces. "+
+ "Can be full (default), blobless, treeless or shallow")
+ upCmd.Flags().
+ BoolVar(&cmd.GitCloneRecursiveSubmodules, "git-clone-recursive-submodules", false,
+ "If true will clone git submodule repositories recursively")
+ upCmd.Flags().
+ StringVar(&cmd.GitSSHSigningKey, "git-ssh-signing-key", "",
+ "The ssh key to use when signing git commits. Used to explicitly setup DevPod's ssh signature "+
+ "forwarding with given key. Should be same format as value of `git config user.signingkey`")
}
func (cmd *UpCmd) registerPodmanFlags(upCmd *cobra.Command) {
- upCmd.Flags().StringVar(&cmd.Userns, "userns", "", "User namespace to use for the container (Podman only; e.g. \"keep-id\", \"host\", or \"auto\")")
- upCmd.Flags().StringSliceVar(&cmd.UidMap, "uidmap", []string{}, "UID mapping for Podman user namespace (Podman only; format: container_id:host_id:amount, e.g. \"0:1000:1\")")
- upCmd.Flags().StringSliceVar(&cmd.GidMap, "gidmap", []string{}, "GID mapping for Podman user namespace (Podman only; format: container_id:host_id:amount, e.g. \"0:1000:1\")")
+ upCmd.Flags().
+ StringVar(&cmd.Userns, "userns", "",
+ "User namespace to use for the container (Podman only; e.g. \"keep-id\", \"host\", or \"auto\")")
+ upCmd.Flags().
+ StringSliceVar(&cmd.UidMap, "uidmap", []string{},
+ "UID mapping for Podman user namespace "+
+ "(Podman only; format: container_id:host_id:amount, e.g. \"0:1000:1\")")
+ upCmd.Flags().
+ StringSliceVar(&cmd.GidMap, "gidmap", []string{},
+ "GID mapping for Podman user namespace "+
+ "(Podman only; format: container_id:host_id:amount, e.g. \"0:1000:1\")")
}
func (cmd *UpCmd) registerWorkspaceFlags(upCmd *cobra.Command) {
upCmd.Flags().StringVar(&cmd.ID, "id", "", "The id to use for the workspace")
- upCmd.Flags().StringVar(&cmd.Machine, "machine", "", "The machine to use for this workspace. The machine needs to exist beforehand or the command will fail. If the workspace already exists, this option has no effect")
- upCmd.Flags().StringVar(&cmd.Source, "source", "", "Optional source for the workspace. E.g. git:https://github.com/my-org/my-repo")
- upCmd.Flags().StringArrayVar(&cmd.ProviderOptions, "provider-option", []string{}, "Provider option in the form KEY=VALUE")
- upCmd.Flags().BoolVar(&cmd.Reconfigure, "reconfigure", false, "Reconfigure the options for this workspace. Only supported in DevPod Pro right now.")
- upCmd.Flags().BoolVar(&cmd.Recreate, "recreate", false, "If true will remove any existing containers and recreate them")
- upCmd.Flags().BoolVar(&cmd.Reset, "reset", false, "If true will remove any existing containers including sources, and recreate them")
- upCmd.Flags().StringSliceVar(&cmd.PrebuildRepositories, "prebuild-repository", []string{}, "Docker repository that hosts devpod prebuilds for this workspace")
- upCmd.Flags().StringArrayVar(&cmd.WorkspaceEnv, "workspace-env", []string{}, "Extra env variables to put into the workspace. E.g. MY_ENV_VAR=MY_VALUE")
- upCmd.Flags().StringSliceVar(&cmd.WorkspaceEnvFile, "workspace-env-file", []string{}, "The path to files containing a list of extra env variables to put into the workspace. E.g. MY_ENV_VAR=MY_VALUE")
- upCmd.Flags().StringArrayVar(&cmd.InitEnv, "init-env", []string{}, "Extra env variables to inject during the initialization of the workspace. E.g. MY_ENV_VAR=MY_VALUE")
- upCmd.Flags().BoolVar(&cmd.DisableDaemon, "disable-daemon", false, "If enabled, will not install a daemon into the target machine to track activity")
+ upCmd.Flags().
+ StringVar(&cmd.Machine, "machine", "",
+ "The machine to use for this workspace. The machine needs to exist beforehand or the "+
+ "command will fail. If the workspace already exists, this option has no effect")
+ upCmd.Flags().
+ StringVar(&cmd.Source, "source", "", "Optional source for the workspace, e.g. git:https://github.com/my-org/my-repo")
+ upCmd.Flags().
+ StringArrayVar(&cmd.ProviderOptions, "provider-option", []string{}, "Provider option in the form KEY=VALUE")
+ upCmd.Flags().
+ BoolVar(&cmd.Reconfigure, "reconfigure", false,
+ "Reconfigure the options for this workspace. Only supported in DevPod Pro right now.")
+ upCmd.Flags().
+ BoolVar(&cmd.Recreate, "recreate", false, "If true will remove any existing containers and recreate them")
+ upCmd.Flags().
+ BoolVar(&cmd.Reset, "reset", false,
+ "If true will remove any existing containers including sources, and recreate them")
+ upCmd.Flags().
+ StringSliceVar(&cmd.PrebuildRepositories, "prebuild-repository", []string{},
+ "Docker repository that hosts devpod prebuilds for this workspace")
+ upCmd.Flags().
+ StringArrayVar(&cmd.WorkspaceEnv, "workspace-env", []string{},
+ "Extra env variables to put into the workspace, e.g. MY_ENV_VAR=MY_VALUE")
+ upCmd.Flags().
+ StringSliceVar(&cmd.WorkspaceEnvFile, "workspace-env-file", []string{},
+ "The path to files containing a list of extra env variables to put into the workspace, "+
+ "e.g. MY_ENV_VAR=MY_VALUE")
+ upCmd.Flags().
+ StringArrayVar(&cmd.InitEnv, "init-env", []string{},
+ "Extra env variables to inject during the initialization of the workspace, e.g. MY_ENV_VAR=MY_VALUE")
+ upCmd.Flags().
+ BoolVar(&cmd.DisableDaemon, "disable-daemon", false,
+ "If enabled, will not install a daemon into the target machine to track activity")
}
func (cmd *UpCmd) registerTestingFlags(upCmd *cobra.Command) {
@@ -198,7 +262,7 @@ func (cmd *UpCmd) registerTestingFlags(upCmd *cobra.Command) {
_ = upCmd.Flags().MarkHidden("force-dockerless")
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *UpCmd) Run(
ctx context.Context,
devPodConfig *config.Config,
@@ -223,14 +287,14 @@ func (cmd *UpCmd) Run(
return cmd.openIDE(ctx, devPodConfig, client, wctx, log)
}
-// workspaceContext holds the result of workspace preparation
+// workspaceContext holds the result of workspace preparation.
type workspaceContext struct {
result *config2.Result
user string
workdir string
}
-// prepareWorkspace handles initial setup and validation
+// prepareWorkspace handles initial setup and validation.
func (cmd *UpCmd) prepareWorkspace(client client2.BaseWorkspaceClient, log log.Logger) {
if cmd.Reset {
cmd.Recreate = true
@@ -245,12 +309,19 @@ func (cmd *UpCmd) prepareWorkspace(client client2.BaseWorkspaceClient, log log.L
cmd.SSHAuthSockID = util.RandStringBytes(10)
log.Debug("Reusing SSH_AUTH_SOCK", cmd.SSHAuthSockID)
} else if cmd.Platform.Enabled && ide.ReusesAuthSock(targetIDE) {
- log.Debug("Reusing SSH_AUTH_SOCK is not supported with platform mode, consider launching the IDE from the platform UI")
+ log.Debug(
+ "Reusing SSH_AUTH_SOCK is not supported with platform mode, consider launching the IDE from the platform UI",
+ )
}
}
-// executeDevPodUp runs the agent and returns workspace context
-func (cmd *UpCmd) executeDevPodUp(ctx context.Context, devPodConfig *config.Config, client client2.BaseWorkspaceClient, log log.Logger) (*workspaceContext, error) {
+// executeDevPodUp runs the agent and returns workspace context.
+func (cmd *UpCmd) executeDevPodUp(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ client client2.BaseWorkspaceClient,
+ log log.Logger,
+) (*workspaceContext, error) {
result, err := cmd.devPodUp(ctx, devPodConfig, client, log)
if err != nil {
return nil, err
@@ -268,21 +339,30 @@ func (cmd *UpCmd) executeDevPodUp(ctx context.Context, devPodConfig *config.Conf
workdir = result.MergedConfig.WorkspaceFolder
}
if client.WorkspaceConfig().Source.GitSubPath != "" {
- result.SubstitutionContext.ContainerWorkspaceFolder = filepath.Join(result.SubstitutionContext.ContainerWorkspaceFolder, client.WorkspaceConfig().Source.GitSubPath)
+ result.SubstitutionContext.ContainerWorkspaceFolder = filepath.Join(
+ result.SubstitutionContext.ContainerWorkspaceFolder,
+ client.WorkspaceConfig().Source.GitSubPath,
+ )
workdir = result.SubstitutionContext.ContainerWorkspaceFolder
}
return &workspaceContext{result: result, user: user, workdir: workdir}, nil
}
-// configureWorkspace sets up SSH, Git, and dotfiles
-func (cmd *UpCmd) configureWorkspace(devPodConfig *config.Config, client client2.BaseWorkspaceClient, wctx *workspaceContext, log log.Logger) error {
+// configureWorkspace sets up SSH, Git, and dotfiles.
+func (cmd *UpCmd) configureWorkspace(
+ devPodConfig *config.Config,
+ client client2.BaseWorkspaceClient,
+ wctx *workspaceContext,
+ log log.Logger,
+) error {
if cmd.ConfigureSSH {
devPodHome := ""
- if envDevPodHome, ok := os.LookupEnv("DEVPOD_HOME"); ok {
+ if envDevPodHome, ok := os.LookupEnv(config.EnvHome); ok {
devPodHome = envDevPodHome
}
- setupGPGAgentForwarding := cmd.GPGAgentForwarding || devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == "true"
+ setupGPGAgentForwarding := cmd.GPGAgentForwarding ||
+ devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == config.BoolTrue
sshConfigIncludePath := devPodConfig.ContextOption(config.ContextOptionSSHConfigIncludePath)
if err := configureSSH(client, configureSSHParams{
@@ -299,142 +379,44 @@ func (cmd *UpCmd) configureWorkspace(devPodConfig *config.Config, client client2
log.Info("SSH configuration completed in workspace")
}
- if cmd.GitSSHSigningKey != "" {
- if err := setupGitSSHSignature(cmd.GitSSHSigningKey, client, log); err != nil {
- return err
- }
+ if err := dotfiles.Setup(dotfiles.SetupParams{
+ Source: cmd.DotfilesSource,
+ Script: cmd.DotfilesScript,
+ EnvFiles: cmd.DotfilesScriptEnvFile,
+ EnvKeyValues: cmd.DotfilesScriptEnv,
+ Client: client,
+ DevPodConfig: devPodConfig,
+ Log: log,
+ }); err != nil {
+ return err
}
- return setupDotfiles(cmd.DotfilesSource, cmd.DotfilesScript, cmd.DotfilesScriptEnvFile, cmd.DotfilesScriptEnv, client, devPodConfig, log)
+ return nil
}
-// openIDE opens the configured IDE
-func (cmd *UpCmd) openIDE(ctx context.Context, devPodConfig *config.Config, client client2.BaseWorkspaceClient, wctx *workspaceContext, log log.Logger) error {
+// openIDE opens the configured IDE.
+func (cmd *UpCmd) openIDE(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ client client2.BaseWorkspaceClient,
+ wctx *workspaceContext,
+ log log.Logger,
+) error {
if !cmd.OpenIDE {
return nil
}
ideConfig := client.WorkspaceConfig().IDE
- opener := newIDEOpener(cmd, devPodConfig, client, wctx, log)
- return opener.open(ctx, ideConfig.Name, ideConfig.Options)
-}
-
-// ideOpener handles opening different IDE types
-type ideOpener struct {
- cmd *UpCmd
- devPodConfig *config.Config
- client client2.BaseWorkspaceClient
- wctx *workspaceContext
- log log.Logger
-}
-
-func newIDEOpener(cmd *UpCmd, devPodConfig *config.Config, client client2.BaseWorkspaceClient, wctx *workspaceContext, log log.Logger) *ideOpener {
- return &ideOpener{
- cmd: cmd,
- devPodConfig: devPodConfig,
- client: client,
- wctx: wctx,
- log: log,
- }
-}
-
-func (o *ideOpener) open(ctx context.Context, ideName string, ideOptions map[string]config.OptionValue) error {
- folder := o.wctx.result.SubstitutionContext.ContainerWorkspaceFolder
- workspace := o.client.Workspace()
- user := o.wctx.user
-
- switch ideName {
- case string(config.IDEVSCode), string(config.IDEVSCodeInsiders), string(config.IDECursor),
- string(config.IDECodium), string(config.IDEPositron), string(config.IDEWindsurf), string(config.IDEAntigravity):
- return o.openVSCodeFlavor(ctx, ideName, folder, ideOptions)
-
- case string(config.IDERustRover), string(config.IDEGoland), string(config.IDEPyCharm),
- string(config.IDEPhpStorm), string(config.IDEIntellij), string(config.IDECLion),
- string(config.IDERider), string(config.IDERubyMine), string(config.IDEWebStorm), string(config.IDEDataSpell):
- return o.openJetBrains(ideName, folder, workspace, user, ideOptions)
-
- case string(config.IDEOpenVSCode):
- return startVSCodeInBrowser(o.cmd.GPGAgentForwarding, ctx, o.devPodConfig, o.client, folder, user, ideOptions, o.cmd.SSHAuthSockID, o.log)
-
- case string(config.IDEFleet):
- return startFleet(ctx, o.client, o.log)
-
- case string(config.IDEZed):
- return zed.Open(ctx, ideOptions, user, folder, workspace, o.log)
-
- case string(config.IDEJupyterNotebook):
- return startJupyterNotebookInBrowser(o.cmd.GPGAgentForwarding, ctx, o.devPodConfig, o.client, user, ideOptions, o.cmd.SSHAuthSockID, o.log)
-
- case string(config.IDERStudio):
- return startRStudioInBrowser(o.cmd.GPGAgentForwarding, ctx, o.devPodConfig, o.client, user, ideOptions, o.cmd.SSHAuthSockID, o.log)
-
- default:
- return nil
- }
-}
-
-func (o *ideOpener) openVSCodeFlavor(ctx context.Context, ideName, folder string, ideOptions map[string]config.OptionValue) error {
- flavorMap := map[string]vscode.Flavor{
- string(config.IDEVSCode): vscode.FlavorStable,
- string(config.IDEVSCodeInsiders): vscode.FlavorInsiders,
- string(config.IDECursor): vscode.FlavorCursor,
- string(config.IDECodium): vscode.FlavorCodium,
- string(config.IDEPositron): vscode.FlavorPositron,
- string(config.IDEWindsurf): vscode.FlavorWindsurf,
- string(config.IDEAntigravity): vscode.FlavorAntigravity,
- }
-
- params := vscode.OpenParams{
- Workspace: o.client.Workspace(),
- Folder: folder,
- NewWindow: vscode.Options.GetValue(ideOptions, vscode.OpenNewWindow) == "true",
- Flavor: flavorMap[ideName],
- Log: o.log,
- }
-
- return vscode.Open(ctx, params)
-}
-
-func (o *ideOpener) openJetBrains(ideName, folder, workspace, user string, ideOptions map[string]config.OptionValue) error {
- type jetbrainsFactory func() interface{ OpenGateway(string, string) error }
-
- jetbrainsMap := map[string]jetbrainsFactory{
- string(config.IDERustRover): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewRustRoverServer(user, ideOptions, o.log)
- },
- string(config.IDEGoland): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewGolandServer(user, ideOptions, o.log)
- },
- string(config.IDEPyCharm): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewPyCharmServer(user, ideOptions, o.log)
- },
- string(config.IDEPhpStorm): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewPhpStorm(user, ideOptions, o.log)
- },
- string(config.IDEIntellij): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewIntellij(user, ideOptions, o.log)
- },
- string(config.IDECLion): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewCLionServer(user, ideOptions, o.log)
- },
- string(config.IDERider): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewRiderServer(user, ideOptions, o.log)
- },
- string(config.IDERubyMine): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewRubyMineServer(user, ideOptions, o.log)
- },
- string(config.IDEWebStorm): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewWebStormServer(user, ideOptions, o.log)
- },
- string(config.IDEDataSpell): func() interface{ OpenGateway(string, string) error } {
- return jetbrains.NewDataSpellServer(user, ideOptions, o.log)
- },
- }
-
- if factory, ok := jetbrainsMap[ideName]; ok {
- return factory().OpenGateway(folder, workspace)
- }
- return fmt.Errorf("unknown JetBrains IDE: %s", ideName)
+ return opener.Open(ctx, ideConfig.Name, ideConfig.Options, opener.Params{
+ GPGAgentForwarding: cmd.GPGAgentForwarding,
+ SSHAuthSockID: cmd.SSHAuthSockID,
+ GitSSHSigningKey: cmd.GitSSHSigningKey,
+ DevPodConfig: devPodConfig,
+ Client: client,
+ User: wctx.user,
+ Result: wctx.result,
+ Log: log,
+ })
}
func (cmd *UpCmd) devPodUp(
@@ -612,13 +594,18 @@ func (cmd *UpCmd) devPodUpMachine(
// if we run on a platform, we need to pass the platform options
if cmd.Platform.Enabled {
- return clientimplementation.BuildAgentClient(ctx, clientimplementation.BuildAgentClientOptions{
- WorkspaceClient: client,
- CLIOptions: cmd.CLIOptions,
- AgentCommand: "up",
- Log: log,
- TunnelOptions: []tunnelserver.Option{tunnelserver.WithPlatformOptions(&cmd.Platform)},
- })
+ return clientimplementation.BuildAgentClient(
+ ctx,
+ clientimplementation.BuildAgentClientOptions{
+ WorkspaceClient: client,
+ CLIOptions: cmd.CLIOptions,
+ AgentCommand: "up",
+ Log: log,
+ TunnelOptions: []tunnelserver.Option{
+ tunnelserver.WithPlatformOptions(&cmd.Platform),
+ },
+ },
+ )
}
// ssh tunnel command
@@ -638,7 +625,10 @@ func (cmd *UpCmd) devPodUpMachine(
agentCommand += " --debug"
}
- agentInjectFunc := func(cancelCtx context.Context, sshCmd string, sshTunnelStdinReader, sshTunnelStdoutWriter *os.File, writer io.WriteCloser) error {
+ agentInjectFunc := func(
+ cancelCtx context.Context, sshCmd string, sshTunnelStdinReader, sshTunnelStdoutWriter *os.File,
+ writer io.WriteCloser,
+ ) error {
return agent.InjectAgent(&agent.InjectOptions{
Ctx: cancelCtx,
Exec: func(ctx context.Context, command string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
@@ -661,14 +651,15 @@ func (cmd *UpCmd) devPodUpMachine(
})
}
- return sshtunnel.ExecuteCommand(sshtunnel.ExecuteCommandOptions{
- Ctx: ctx,
- Client: client,
- AddPrivateKeys: devPodConfig.ContextOption(config.ContextOptionSSHAddPrivateKeys) == "true",
- AgentInject: agentInjectFunc,
- SSHCommand: sshTunnelCmd,
- Command: agentCommand,
- Log: log,
+ return sshtunnel.ExecuteCommand(ctx, sshtunnel.ExecuteCommandOptions{
+ Client: client,
+ AddPrivateKeys: devPodConfig.ContextOption(
+ config.ContextOptionSSHAddPrivateKeys,
+ ) == config.BoolTrue,
+ AgentInject: agentInjectFunc,
+ SSHCommand: sshTunnelCmd,
+ Command: agentCommand,
+ Log: log,
TunnelServerFunc: func(ctx context.Context, stdin io.WriteCloser, stdout io.Reader) (*config2.Result, error) {
return tunnelserver.RunUpServer(
ctx,
@@ -683,403 +674,6 @@ func (cmd *UpCmd) devPodUpMachine(
})
}
-func startJupyterNotebookInBrowser(
- forwardGpg bool,
- ctx context.Context,
- devPodConfig *config.Config,
- client client2.BaseWorkspaceClient,
- user string,
- ideOptions map[string]config.OptionValue,
- authSockID string,
- logger log.Logger,
-) error {
- if forwardGpg {
- err := performGpgForwarding(client, logger)
- if err != nil {
- return err
- }
- }
-
- // determine port
- jupyterAddress, jupyterPort, err := parseAddressAndPort(
- jupyter.Options.GetValue(ideOptions, jupyter.BindAddressOption),
- jupyter.DefaultServerPort,
- )
- if err != nil {
- return err
- }
-
- // wait until reachable then open browser
- targetURL := fmt.Sprintf("http://localhost:%d/lab", jupyterPort)
- if jupyter.Options.GetValue(ideOptions, jupyter.OpenOption) == "true" {
- go func() {
- err = open2.Open(ctx, targetURL, logger)
- if err != nil {
- logger.WithFields(logrus.Fields{"error": err}).Error("error opening jupyter notebook")
- }
-
- logger.Info("started jupyter notebook in browser mode. Please keep this terminal open as long as you use Jupyter Notebook")
- }()
- }
-
- // start in browser
- logger.Infof("Starting jupyter notebook in browser mode at %s", targetURL)
- extraPorts := []string{fmt.Sprintf("%s:%d", jupyterAddress, jupyter.DefaultServerPort)}
- return startBrowserTunnel(
- ctx,
- devPodConfig,
- client,
- user,
- targetURL,
- false,
- extraPorts,
- authSockID,
- logger,
- )
-}
-
-func startRStudioInBrowser(
- forwardGpg bool,
- ctx context.Context,
- devPodConfig *config.Config,
- client client2.BaseWorkspaceClient,
- user string,
- ideOptions map[string]config.OptionValue,
- authSockID string,
- logger log.Logger,
-) error {
- if forwardGpg {
- err := performGpgForwarding(client, logger)
- if err != nil {
- return err
- }
- }
-
- // determine port
- addr, port, err := parseAddressAndPort(
- rstudio.Options.GetValue(ideOptions, rstudio.BindAddressOption),
- rstudio.DefaultServerPort,
- )
- if err != nil {
- return err
- }
-
- // wait until reachable then open browser
- targetURL := fmt.Sprintf("http://localhost:%d", port)
- if rstudio.Options.GetValue(ideOptions, rstudio.OpenOption) == "true" {
- go func() {
- err = open2.Open(ctx, targetURL, logger)
- if err != nil {
- logger.Errorf("error opening rstudio: %v", err)
- }
-
- logger.Infof(
- "started RStudio Server in browser mode. Please keep this terminal open as long as you use it",
- )
- }()
- }
-
- // start in browser
- logger.Infof("Starting RStudio server in browser mode at %s", targetURL)
- extraPorts := []string{fmt.Sprintf("%s:%d", addr, rstudio.DefaultServerPort)}
- return startBrowserTunnel(
- ctx,
- devPodConfig,
- client,
- user,
- targetURL,
- false,
- extraPorts,
- authSockID,
- logger,
- )
-}
-
-func startFleet(ctx context.Context, client client2.BaseWorkspaceClient, logger log.Logger) error {
- // create ssh command
- stdout := &bytes.Buffer{}
- cmd, err := createSSHCommand(
- ctx,
- client,
- logger,
- []string{"--command", "cat " + fleet.FleetURLFile},
- )
- if err != nil {
- return err
- }
- cmd.Stdout = stdout
- err = cmd.Run()
- if err != nil {
- return command.WrapCommandError(stdout.Bytes(), err)
- }
-
- url := strings.TrimSpace(stdout.String())
- if len(url) == 0 {
- return fmt.Errorf("seems like fleet is not running within the container")
- }
-
- logger.Warnf(
- "Fleet is exposed at a publicly reachable URL, please make sure to not disclose this URL to anyone as they will be able to reach your workspace from that",
- )
- logger.Infof("Starting Fleet at %s ...", url)
- err = open.Run(url)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func startVSCodeInBrowser(
- forwardGpg bool,
- ctx context.Context,
- devPodConfig *config.Config,
- client client2.BaseWorkspaceClient,
- workspaceFolder, user string,
- ideOptions map[string]config.OptionValue,
- authSockID string,
- logger log.Logger,
-) error {
- if forwardGpg {
- err := performGpgForwarding(client, logger)
- if err != nil {
- return err
- }
- }
-
- // determine port
- vscodeAddress, vscodePort, err := parseAddressAndPort(
- openvscode.Options.GetValue(ideOptions, openvscode.BindAddressOption),
- openvscode.DefaultVSCodePort,
- )
- if err != nil {
- return err
- }
-
- // wait until reachable then open browser
- targetURL := fmt.Sprintf("http://localhost:%d/?folder=%s", vscodePort, workspaceFolder)
- if openvscode.Options.GetValue(ideOptions, openvscode.OpenOption) == "true" {
- go func() {
- err = open2.Open(ctx, targetURL, logger)
- if err != nil {
- logger.Errorf("error opening vscode: %v", err)
- }
-
- logger.Infof(
- "started vscode in browser mode. Please keep this terminal open as long as you use VSCode browser version",
- )
- }()
- }
-
- // start in browser
- logger.Infof("Starting vscode in browser mode at %s", targetURL)
- forwardPorts := openvscode.Options.GetValue(ideOptions, openvscode.ForwardPortsOption) == "true"
- extraPorts := []string{fmt.Sprintf("%s:%d", vscodeAddress, openvscode.DefaultVSCodePort)}
- return startBrowserTunnel(
- ctx,
- devPodConfig,
- client,
- user,
- targetURL,
- forwardPorts,
- extraPorts,
- authSockID,
- logger,
- )
-}
-
-func parseAddressAndPort(bindAddressOption string, defaultPort int) (string, int, error) {
- var (
- err error
- address string
- portName int
- )
- if bindAddressOption == "" {
- portName, err = port.FindAvailablePort(defaultPort)
- if err != nil {
- return "", 0, err
- }
-
- address = fmt.Sprintf("%d", portName)
- } else {
- address = bindAddressOption
- _, port, err := net.SplitHostPort(address)
- if err != nil {
- return "", 0, fmt.Errorf("parse host:port: %w", err)
- } else if port == "" {
- return "", 0, fmt.Errorf("parse ADDRESS: expected host:port, got %s", address)
- }
-
- portName, err = strconv.Atoi(port)
- if err != nil {
- return "", 0, fmt.Errorf("parse host:port: %w", err)
- }
- }
-
- return address, portName, nil
-}
-
-// setupBackhaul sets up a long running command in the container to ensure an SSH connection is kept alive
-func setupBackhaul(client client2.BaseWorkspaceClient, authSockId string, log log.Logger) error {
- execPath, err := os.Executable()
- if err != nil {
- return err
- }
-
- remoteUser, err := devssh.GetUser(client.WorkspaceConfig().ID, client.WorkspaceConfig().SSHConfigPath, client.WorkspaceConfig().SSHConfigIncludePath)
- if err != nil {
- remoteUser = "root"
- }
-
- dotCmd := exec.Command(
- execPath,
- "ssh",
- "--agent-forwarding=true",
- fmt.Sprintf("--reuse-ssh-auth-sock=%s", authSockId),
- "--start-services=false",
- "--user",
- remoteUser,
- "--context",
- client.Context(),
- client.Workspace(),
- "--log-output=raw",
- "--command",
- "while true; do sleep 6000000; done", // sleep infinity is not available on all systems
- )
-
- if log.GetLevel() == logrus.DebugLevel {
- dotCmd.Args = append(dotCmd.Args, "--debug")
- }
-
- log.Info("Setting up backhaul SSH connection")
-
- writer := log.Writer(logrus.InfoLevel, false)
-
- dotCmd.Stdout = writer
- dotCmd.Stderr = writer
-
- err = dotCmd.Run()
- if err != nil {
- return err
- }
-
- log.Infof("Done setting up backhaul")
-
- return nil
-}
-
-func startBrowserTunnel(
- ctx context.Context,
- devPodConfig *config.Config,
- client client2.BaseWorkspaceClient,
- user, targetURL string,
- forwardPorts bool,
- extraPorts []string,
- authSockID string,
- logger log.Logger,
-) error {
- // Setup a backhaul SSH connection using the remote user so there is an AUTH SOCK to use
- // With normal IDEs this would be the SSH connection made by the IDE
- // authSockID is not set when in proxy mode since we cannot use the proxies ssh-agent
- if authSockID != "" {
- go func() {
- if err := setupBackhaul(client, authSockID, logger); err != nil {
- logger.Error("Failed to setup backhaul SSH connection: ", err)
- }
- }()
- }
-
- // handle this directly with the daemon client
- daemonClient, ok := client.(client2.DaemonClient)
- if ok {
- toolClient, _, err := daemonClient.SSHClients(ctx, user)
- if err != nil {
- return err
- }
- defer func() { _ = toolClient.Close() }()
-
- err = clientimplementation.StartServicesDaemon(ctx, clientimplementation.StartServicesDaemonOptions{
- DevPodConfig: devPodConfig,
- Client: daemonClient,
- SSHClient: toolClient,
- User: user,
- Log: logger,
- ForwardPorts: forwardPorts,
- ExtraPorts: extraPorts,
- })
- if err != nil {
- return err
- }
- <-ctx.Done()
-
- return nil
- }
-
- err := tunnel.NewTunnel(
- ctx,
- func(ctx context.Context, stdin io.Reader, stdout io.Writer) error {
- writer := logger.Writer(logrus.DebugLevel, false)
- defer func() { _ = writer.Close() }()
-
- cmd, err := createSSHCommand(ctx, client, logger, []string{
- "--log-output=raw",
- fmt.Sprintf("--reuse-ssh-auth-sock=%s", authSockID),
- "--stdio",
- })
- if err != nil {
- return err
- }
- cmd.Stdout = stdout
- cmd.Stdin = stdin
- cmd.Stderr = writer
- return cmd.Run()
- },
- func(ctx context.Context, containerClient *ssh.Client) error {
- // print port to console
- streamLogger, ok := logger.(*log.StreamLogger)
- if ok {
- streamLogger.JSON(logrus.InfoLevel, map[string]string{
- "url": targetURL,
- "done": "true",
- })
- }
-
- configureDockerCredentials := devPodConfig.ContextOption(config.ContextOptionSSHInjectDockerCredentials) == "true"
- configureGitCredentials := devPodConfig.ContextOption(config.ContextOptionSSHInjectGitCredentials) == "true"
- configureGitSSHSignatureHelper := devPodConfig.ContextOption(config.ContextOptionGitSSHSignatureForwarding) == "true"
-
- // run in container
- err := tunnel.RunServices(
- ctx,
- tunnel.RunServicesOptions{
- DevPodConfig: devPodConfig,
- ContainerClient: containerClient,
- User: user,
- ForwardPorts: forwardPorts,
- ExtraPorts: extraPorts,
- PlatformOptions: nil,
- Workspace: client.WorkspaceConfig(),
- ConfigureDockerCredentials: configureDockerCredentials,
- ConfigureGitCredentials: configureGitCredentials,
- ConfigureGitSSHSignatureHelper: configureGitSSHSignatureHelper,
- Log: logger,
- },
- )
- if err != nil {
- return fmt.Errorf("run credentials server in browser tunnel: %w", err)
- }
-
- <-ctx.Done()
- return nil
- },
- )
- if err != nil {
- return err
- }
-
- return nil
-}
-
type configureSSHParams struct {
sshConfigPath string
sshConfigIncludePath string
@@ -1127,7 +721,7 @@ func configureSSH(client client2.BaseWorkspaceClient, params configureSSHParams)
func mergeDevPodUpOptions(baseOptions *provider2.CLIOptions) error {
oldOptions := *baseOptions
found, err := clientimplementation.DecodeOptionsFromEnv(
- clientimplementation.DevPodFlagsUp,
+ config.EnvFlagsUp,
baseOptions,
)
if err != nil {
@@ -1135,7 +729,10 @@ func mergeDevPodUpOptions(baseOptions *provider2.CLIOptions) error {
} else if found {
baseOptions.WorkspaceEnv = append(oldOptions.WorkspaceEnv, baseOptions.WorkspaceEnv...)
baseOptions.InitEnv = append(oldOptions.InitEnv, baseOptions.InitEnv...)
- baseOptions.PrebuildRepositories = append(oldOptions.PrebuildRepositories, baseOptions.PrebuildRepositories...)
+ baseOptions.Mounts = append(oldOptions.Mounts, baseOptions.Mounts...)
+ baseOptions.PrebuildRepositories = append(
+ oldOptions.PrebuildRepositories,
+ baseOptions.PrebuildRepositories...)
baseOptions.IDEOptions = append(oldOptions.IDEOptions, baseOptions.IDEOptions...)
}
@@ -1161,348 +758,90 @@ func mergeEnvFromFiles(baseOptions *provider2.CLIOptions) error {
return nil
}
-var inheritedEnvironmentVariables = []string{
- "GIT_AUTHOR_NAME",
- "GIT_AUTHOR_EMAIL",
- "GIT_AUTHOR_DATE",
- "GIT_COMMITTER_NAME",
- "GIT_COMMITTER_EMAIL",
- "GIT_COMMITTER_DATE",
-}
-
-func createSSHCommand(
- ctx context.Context,
- client client2.BaseWorkspaceClient,
- logger log.Logger,
- extraArgs []string,
-) (*exec.Cmd, error) {
- execPath, err := os.Executable()
- if err != nil {
- return nil, err
- }
-
- args := []string{
- "ssh",
- "--user=root",
- "--agent-forwarding=false",
- "--start-services=false",
- "--context",
- client.Context(),
- client.Workspace(),
- }
- if logger.GetLevel() == logrus.DebugLevel {
- args = append(args, "--debug")
- }
- args = append(args, extraArgs...)
-
- return exec.CommandContext(ctx, execPath, args...), nil
-}
-
-func setupDotfiles(
- dotfiles, script string,
- envFiles, envKeyValuePairs []string,
- client client2.BaseWorkspaceClient,
- devPodConfig *config.Config,
- log log.Logger,
-) error {
- dotfilesRepo := devPodConfig.ContextOption(config.ContextOptionDotfilesURL)
- if dotfiles != "" {
- dotfilesRepo = dotfiles
- }
-
- dotfilesScript := devPodConfig.ContextOption(config.ContextOptionDotfilesScript)
- if script != "" {
- dotfilesScript = script
- }
-
- if dotfilesRepo == "" {
- log.Debug("No dotfiles repo specified, skipping")
+// loadExtraDevContainerConfig reads the local file before forwarding options to a provider.
+func loadExtraDevContainerConfig(options *provider2.CLIOptions) error {
+ if options.ExtraDevContainerConfig != nil || options.ExtraDevContainerPath == "" {
return nil
}
-
- log.Infof("Dotfiles Git repository %s specified", dotfilesRepo)
- log.Debug("Cloning dotfiles into the devcontainer...")
-
- dotCmd, err := buildDotCmd(devPodConfig, dotfilesRepo, dotfilesScript, envFiles, envKeyValuePairs, client, log)
+ extraConfig, err := config2.ParseDevContainerJSONFile(options.ExtraDevContainerPath)
if err != nil {
- return err
+ return fmt.Errorf("parse --extra-devcontainer-path: %w", err)
}
- if log.GetLevel() == logrus.DebugLevel {
- dotCmd.Args = append(dotCmd.Args, "--debug")
- }
-
- log.Debugf("Running dotfiles setup command: %v", dotCmd.Args)
-
- writer := log.Writer(logrus.InfoLevel, false)
-
- dotCmd.Stdout = writer
- dotCmd.Stderr = writer
-
- err = dotCmd.Run()
- if err != nil {
- return err
+ features := make(map[string]any, len(extraConfig.Features))
+ for featureID, featureOptions := range extraConfig.Features {
+ if strings.HasPrefix(featureID, "./") || strings.HasPrefix(featureID, "../") {
+ featureID, err = filepath.Abs(
+ filepath.Join(filepath.Dir(extraConfig.Origin), featureID),
+ )
+ if err != nil {
+ return fmt.Errorf("resolve feature from --extra-devcontainer-path: %w", err)
+ }
+ }
+ features[featureID] = featureOptions
}
-
- log.Infof("Done setting up dotfiles into the devcontainer")
-
+ extraConfig.Features = features
+ options.ExtraDevContainerConfig = extraConfig
return nil
}
-func buildDotCmdAgentArguments(devPodConfig *config.Config, dotfilesRepo, dotfilesScript string, log log.Logger) []string {
- agentArguments := []string{
- "agent",
- "workspace",
- "install-dotfiles",
- "--repository",
- dotfilesRepo,
- }
-
- if devPodConfig.ContextOption(config.ContextOptionSSHStrictHostKeyChecking) == "true" {
- agentArguments = append(agentArguments, "--strict-host-key-checking")
- }
-
- if log.GetLevel() == logrus.DebugLevel {
- agentArguments = append(agentArguments, "--debug")
- }
-
- if dotfilesScript != "" {
- log.Infof("Dotfiles script %s specified", dotfilesScript)
- agentArguments = append(agentArguments, "--install-script", dotfilesScript)
- }
-
- return agentArguments
-}
-
-func buildDotCmd(devPodConfig *config.Config, dotfilesRepo, dotfilesScript string, envFiles, envKeyValuePairs []string, client client2.BaseWorkspaceClient, log log.Logger) (*exec.Cmd, error) {
- sshCmd := []string{
- "ssh",
- "--agent-forwarding=true",
- "--start-services=true",
- }
-
- envFilesKeyValuePairs, err := collectDotfilesScriptEnvKeyvaluePairs(envFiles)
- if err != nil {
- return nil, err
- }
-
- // Collect file-based and CLI options env variables names (aka keys) and
- // configure ssh env var passthrough with send-env
- allEnvKeyValuesPairs := slices.Concat(envFilesKeyValuePairs, envKeyValuePairs)
- allEnvKeys := extractKeysFromEnvKeyValuePairs(allEnvKeyValuesPairs)
- for _, envKey := range allEnvKeys {
- sshCmd = append(sshCmd, "--send-env", envKey)
- }
-
- remoteUser, err := devssh.GetUser(client.WorkspaceConfig().ID, client.WorkspaceConfig().SSHConfigPath, client.WorkspaceConfig().SSHConfigIncludePath)
- if err != nil {
- remoteUser = "root"
- }
-
- agentArguments := buildDotCmdAgentArguments(devPodConfig, dotfilesRepo, dotfilesScript, log)
- sshCmd = append(sshCmd,
- "--user",
- remoteUser,
- "--context",
- client.Context(),
- client.Workspace(),
- "--log-output=raw",
- "--command",
- agent.ContainerDevPodHelperLocation+" "+strings.Join(agentArguments, " "),
- )
- execPath, err := os.Executable()
- if err != nil {
- return nil, err
- }
-
- dotCmd := exec.Command(
- execPath,
- sshCmd...,
- )
-
- dotCmd.Env = append(dotCmd.Environ(), allEnvKeyValuesPairs...)
- return dotCmd, nil
-}
-
-func extractKeysFromEnvKeyValuePairs(envKeyValuePairs []string) []string {
- keys := []string{}
- for _, env := range envKeyValuePairs {
- keyValue := strings.SplitN(env, "=", 2)
- if len(keyValue) == 2 {
- keys = append(keys, keyValue[0])
- }
+func hasLocalExtraFeatures(extraConfig *config2.DevContainerConfig) bool {
+ if extraConfig == nil {
+ return false
}
- return keys
-}
-
-func collectDotfilesScriptEnvKeyvaluePairs(envFiles []string) ([]string, error) {
- keyValues := []string{}
- for _, file := range envFiles {
- envFromFile, err := config2.ParseKeyValueFile(file)
- if err != nil {
- return nil, err
+ for featureID := range extraConfig.Features {
+ if isLocalExtraFeature(featureID) {
+ return true
}
- keyValues = append(keyValues, envFromFile...)
}
- return keyValues, nil
+ return false
}
-func setupGitSSHSignature(signingKey string, client client2.BaseWorkspaceClient, log log.Logger) error {
- execPath, err := os.Executable()
- if err != nil {
- return err
- }
-
- remoteUser, err := devssh.GetUser(client.WorkspaceConfig().ID, client.WorkspaceConfig().SSHConfigPath, client.WorkspaceConfig().SSHConfigIncludePath)
- if err != nil {
- remoteUser = "root"
- }
-
- err = exec.Command(
- execPath,
- "ssh",
- "--agent-forwarding=true",
- "--start-services=true",
- "--user",
- remoteUser,
- "--context",
- client.Context(),
- client.Workspace(),
- "--command", fmt.Sprintf("devpod agent git-ssh-signature-helper %s", signingKey),
- ).Run()
- if err != nil {
- log.Error("failure in setting up git ssh signature helper")
- }
- return nil
+func isLocalExtraFeature(featureID string) bool {
+ return strings.HasPrefix(featureID, "./") || strings.HasPrefix(featureID, "../") ||
+ filepath.IsAbs(featureID)
}
-func performGpgForwarding(
- client client2.BaseWorkspaceClient,
- log log.Logger,
+func validateExtraFeatureProvider(
+ options provider2.CLIOptions,
+ providerConfig *provider2.ProviderConfig,
) error {
- log.Debug("gpg forwarding enabled, performing immediately")
-
- execPath, err := os.Executable()
- if err != nil {
- return err
- }
-
- remoteUser, err := devssh.GetUser(client.WorkspaceConfig().ID, client.WorkspaceConfig().SSHConfigPath, client.WorkspaceConfig().SSHConfigIncludePath)
- if err != nil {
- remoteUser = "root"
- }
-
- log.Info("forwarding gpg-agent")
-
- // perform in background an ssh command forwarding the
- // gpg agent, in order to have it immediately take effect
- go func() {
- err = exec.Command(
- execPath,
- "ssh",
- "--gpg-agent-forwarding=true",
- "--agent-forwarding=true",
- "--start-services=true",
- "--user",
- remoteUser,
- "--context",
- client.Context(),
- client.Workspace(),
- "--log-output=raw",
- "--command", "sleep infinity",
- ).Run()
- if err != nil {
- log.Error("failure in forwarding gpg-agent")
- }
- }()
-
- return nil
-}
-
-// checkProviderUpdate currently only ensures the local provider is in sync with the remote for DevPod Pro instances
-// Potentially auto-upgrade other providers in the future.
-func checkProviderUpdate(devPodConfig *config.Config, proInstance *provider2.ProInstance, log log.Logger) error {
- if version.GetVersion() == version.DevVersion {
- log.Debugf("skipping provider upgrade check during development")
- return nil
- }
- if proInstance == nil {
- log.Debug("no pro instance available, skipping provider upgrade check")
+ if options.ExtraDevContainerConfig == nil || providerConfig.Agent.Local == config.BoolTrue {
return nil
}
-
- // compare versions
- newVersion, err := platform.GetProInstanceDevPodVersion(proInstance)
- if err != nil {
- return fmt.Errorf("version for pro instance %s: %w", proInstance.Host, err)
- }
-
- p, err := workspace2.FindProvider(devPodConfig, proInstance.Provider, log)
- if err != nil {
- return fmt.Errorf("get provider config for pro provider %s: %w", proInstance.Provider, err)
- }
- if p.Config.Version == version.DevVersion {
- return nil
- }
- if p.Config.Source.Internal {
- return nil
- }
-
- v1, err := semver.Parse(strings.TrimPrefix(newVersion, "v"))
- if err != nil {
- return fmt.Errorf("parse version %s: %w", newVersion, err)
- }
- v2, err := semver.Parse(strings.TrimPrefix(p.Config.Version, "v"))
- if err != nil {
- return fmt.Errorf("parse version %s: %w", p.Config.Version, err)
- }
- if v1.Compare(v2) == 0 {
- return nil
- }
- log.Infof("New provider version available, attempting to update %s from %s to %s", proInstance.Provider, p.Config.Version, newVersion)
-
- providerSource, err := workspace2.ResolveProviderSource(devPodConfig, proInstance.Provider, log)
- if err != nil {
- return fmt.Errorf("resolve provider source %s: %w", proInstance.Provider, err)
- }
-
- splitted := strings.Split(providerSource, "@")
- if len(splitted) == 0 {
- return fmt.Errorf("no provider source found %s", providerSource)
- }
- providerSource = splitted[0] + "@" + newVersion
-
- _, err = workspace2.UpdateProvider(devPodConfig, proInstance.Provider, providerSource, log)
- if err != nil {
- return fmt.Errorf("update provider %s: %w", proInstance.Provider, err)
+ for featureID := range options.ExtraDevContainerConfig.Features {
+ if isLocalExtraFeature(featureID) {
+ return fmt.Errorf(
+ "local feature %q from --extra-devcontainer-path is unsupported by remote provider %q; "+
+ "use an OCI or HTTP feature reference",
+ featureID,
+ providerConfig.Name,
+ )
+ }
}
-
- log.WithFields(logrus.Fields{
- "provider": proInstance.Provider,
- }).Done("updated provider")
return nil
}
-func getProInstance(devPodConfig *config.Config, providerName string, log log.Logger) *provider2.ProInstance {
- proInstances, err := workspace2.ListProInstances(devPodConfig, log)
- if err != nil {
- return nil
- } else if len(proInstances) == 0 {
- return nil
- }
-
- proInstance, ok := workspace2.FindProviderProInstance(proInstances, providerName)
- if !ok {
- return nil
- }
-
- return proInstance
+var inheritedEnvironmentVariables = []string{
+ "GIT_AUTHOR_NAME",
+ "GIT_AUTHOR_EMAIL",
+ "GIT_AUTHOR_DATE",
+ "GIT_COMMITTER_NAME",
+ "GIT_COMMITTER_EMAIL",
+ "GIT_COMMITTER_DATE",
}
-func (cmd *UpCmd) prepareClient(ctx context.Context, devPodConfig *config.Config, args []string) (client2.BaseWorkspaceClient, log.Logger, error) {
+func (cmd *UpCmd) prepareClient(
+ ctx context.Context,
+ devPodConfig *config.Config,
+ args []string,
+) (client2.BaseWorkspaceClient, log.Logger, error) {
// try to parse flags from env
if err := mergeDevPodUpOptions(&cmd.CLIOptions); err != nil {
return nil, nil, err
}
+ if err := loadExtraDevContainerConfig(&cmd.CLIOptions); err != nil {
+ return nil, nil, err
+ }
var logger log.Logger = log.Default
if cmd.Platform.Enabled {
@@ -1518,7 +857,11 @@ func (cmd *UpCmd) prepareClient(ctx context.Context, devPodConfig *config.Config
return nil, logger, err
}
- cmd.WorkspaceEnv = options2.InheritFromEnvironment(cmd.WorkspaceEnv, inheritedEnvironmentVariables, "")
+ cmd.WorkspaceEnv = options2.InheritFromEnvironment(
+ cmd.WorkspaceEnv,
+ inheritedEnvironmentVariables,
+ "",
+ )
var source *provider2.WorkspaceSource
if cmd.Source != "" {
@@ -1563,8 +906,8 @@ func (cmd *UpCmd) prepareClient(ctx context.Context, devPodConfig *config.Config
}
if !cmd.Platform.Enabled {
- proInstance := getProInstance(devPodConfig, client.Provider(), logger)
- err = checkProviderUpdate(devPodConfig, proInstance, logger)
+ proInstance := workspace2.GetProInstance(devPodConfig, client.Provider(), logger)
+ err = workspace2.CheckProviderUpdate(devPodConfig, proInstance, logger)
if err != nil {
return nil, logger, err
}
@@ -1600,16 +943,24 @@ func WithSignals(ctx context.Context) (context.Context, func()) {
func validatePodmanFlags(cmd *UpCmd) error {
if cmd.Userns != "" && (len(cmd.UidMap) > 0 || len(cmd.GidMap) > 0) {
- return fmt.Errorf("--userns cannot be combined with --uidmap or --gidmap (mutually exclusive)")
+ return fmt.Errorf(
+ "--userns cannot be combined with --uidmap or --gidmap (mutually exclusive)",
+ )
}
for _, m := range cmd.UidMap {
if !isValidMapping(m) {
- return fmt.Errorf("invalid --uidmap format: %s (expected: container_id:host_id:amount)", m)
+ return fmt.Errorf(
+ "invalid --uidmap format: %s (expected: container_id:host_id:amount)",
+ m,
+ )
}
}
for _, m := range cmd.GidMap {
if !isValidMapping(m) {
- return fmt.Errorf("invalid --gidmap format: %s (expected: container_id:host_id:amount)", m)
+ return fmt.Errorf(
+ "invalid --gidmap format: %s (expected: container_id:host_id:amount)",
+ m,
+ )
}
}
return nil
diff --git a/cmd/up_test.go b/cmd/up_test.go
new file mode 100644
index 0000000000..43869cbb41
--- /dev/null
+++ b/cmd/up_test.go
@@ -0,0 +1,155 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/skevetter/devpod/cmd/flags"
+ "github.com/skevetter/devpod/pkg/client/clientimplementation"
+ "github.com/skevetter/devpod/pkg/config"
+ devcontainerconfig "github.com/skevetter/devpod/pkg/devcontainer/config"
+ "github.com/skevetter/devpod/pkg/provider"
+ "github.com/skevetter/devpod/pkg/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestUpMountFlagIsRepeatableAndPreservesValues(t *testing.T) {
+ upCmd := NewUpCmd(&flags.GlobalFlags{})
+ args := []string{
+ "--mount", `{"type":"volume","source":"cache","target":"/cache"}`,
+ "--mount", `type=bind,source=/tmp/data,target=/data,readonly`,
+ }
+
+ require.NoError(t, upCmd.ParseFlags(args))
+
+ mounts, err := upCmd.Flags().GetStringArray("mount")
+ require.NoError(t, err)
+ require.Equal(t, []string{
+ `{"type":"volume","source":"cache","target":"/cache"}`,
+ `type=bind,source=/tmp/data,target=/data,readonly`,
+ }, mounts)
+}
+
+func TestExtraDevContainerConfigSurvivesForwardingWithoutLocalFile(t *testing.T) {
+ extraPath := filepath.Join(t.TempDir(), "extra.json")
+ require.NoError(t, os.WriteFile(extraPath, []byte(`{
+ // Personal config stays on the client.
+ "features": {"ghcr.io/devcontainers/features/git:1": {"version": "latest"}},
+ "forwardPorts": [3774],
+ }`), 0o600))
+ options := provider.CLIOptions{ExtraDevContainerPath: extraPath}
+ require.NoError(t, loadExtraDevContainerConfig(&options))
+ require.NoError(t, os.Remove(extraPath))
+
+ // Machine agents receive JSON; proxy providers forward the same options through the environment.
+ data, err := json.Marshal(options)
+ require.NoError(t, err)
+ var remote provider.CLIOptions
+ require.NoError(t, json.Unmarshal(data, &remote))
+ for name, value := range clientimplementation.EncodeOptions(remote, config.EnvFlagsUp) {
+ t.Setenv(name, value)
+ }
+ remote = provider.CLIOptions{}
+ require.NoError(t, mergeDevPodUpOptions(&remote))
+ require.NoError(t, loadExtraDevContainerConfig(&remote))
+ require.NotNil(t, remote.ExtraDevContainerConfig)
+ require.Equal(
+ t,
+ options.ExtraDevContainerConfig.Features,
+ remote.ExtraDevContainerConfig.Features,
+ )
+ require.Equal(t, types.StrIntArray{"3774"}, remote.ExtraDevContainerConfig.ForwardPorts)
+}
+
+func TestLoadExtraDevContainerConfig(t *testing.T) {
+ options := provider.CLIOptions{}
+ require.NoError(t, loadExtraDevContainerConfig(&options))
+ require.Nil(t, options.ExtraDevContainerConfig)
+
+ extraPath := filepath.Join(t.TempDir(), "extra.json")
+ options.ExtraDevContainerPath = extraPath
+ for _, content := range []string{"", `{invalid`, `{"features": []}`} {
+ if content != "" {
+ require.NoError(t, os.WriteFile(extraPath, []byte(content), 0o600))
+ }
+ err := loadExtraDevContainerConfig(&options)
+ require.ErrorContains(t, err, "--extra-devcontainer-path")
+ }
+}
+
+func TestLoadExtraDevContainerConfigResolvesLocalFeatureBeforeForwarding(t *testing.T) {
+ extraDir := t.TempDir()
+ extraPath := filepath.Join(extraDir, "extra.json")
+ require.NoError(t, os.WriteFile(extraPath, []byte(`{"features":{"../feature":{}}}`), 0o600))
+ options := provider.CLIOptions{ExtraDevContainerPath: extraPath}
+ require.NoError(t, loadExtraDevContainerConfig(&options))
+
+ resolvedFeaturePath, err := filepath.Abs(filepath.Join(extraDir, "../feature"))
+ require.NoError(t, err)
+ _, ok := options.ExtraDevContainerConfig.Features[resolvedFeaturePath]
+ require.True(t, ok)
+
+ data, err := json.Marshal(options)
+ require.NoError(t, err)
+ var forwarded provider.CLIOptions
+ require.NoError(t, json.Unmarshal(data, &forwarded))
+ _, ok = forwarded.ExtraDevContainerConfig.Features[resolvedFeaturePath]
+ require.True(t, ok)
+}
+
+func TestValidateExtraFeatureProvider(t *testing.T) {
+ t.Run("remote provider rejects local feature references", func(t *testing.T) {
+ options := provider.CLIOptions{
+ ExtraDevContainerConfig: &devcontainerconfig.DevContainerConfig{
+ DevContainerConfigBase: devcontainerconfig.DevContainerConfigBase{
+ Features: map[string]any{
+ "../local-feature": map[string]any{},
+ },
+ },
+ },
+ }
+ remoteProvider := &provider.ProviderConfig{Name: "ssh"}
+ require.ErrorContains(
+ t,
+ validateExtraFeatureProvider(options, remoteProvider),
+ "local feature",
+ )
+ require.ErrorContains(
+ t,
+ validateExtraFeatureProvider(options, remoteProvider),
+ "OCI or HTTP",
+ )
+ })
+
+ t.Run("remote provider keeps OCI and HTTP features", func(t *testing.T) {
+ options := provider.CLIOptions{
+ ExtraDevContainerConfig: &devcontainerconfig.DevContainerConfig{
+ DevContainerConfigBase: devcontainerconfig.DevContainerConfigBase{
+ Features: map[string]any{
+ "ghcr.io/devcontainers/features/git:1": map[string]any{},
+ "https://example.com/feature.tgz": map[string]any{},
+ },
+ },
+ },
+ }
+ remoteProvider := &provider.ProviderConfig{Name: "ssh"}
+ require.NoError(t, validateExtraFeatureProvider(options, remoteProvider))
+ })
+
+ t.Run("renamed local provider allows local features", func(t *testing.T) {
+ options := provider.CLIOptions{
+ ExtraDevContainerConfig: &devcontainerconfig.DevContainerConfig{
+ DevContainerConfigBase: devcontainerconfig.DevContainerConfigBase{
+ Features: map[string]any{"./feature": map[string]any{}},
+ },
+ },
+ }
+ localProvider := &provider.ProviderConfig{
+ Name: "personal-tools",
+ Agent: provider.ProviderAgentConfig{Local: types.StrBool(config.BoolTrue)},
+ }
+ require.NoError(t, validateExtraFeatureProvider(options, localProvider))
+ })
+}
diff --git a/cmd/upgrade.go b/cmd/upgrade.go
index b053dee398..0df8815e84 100644
--- a/cmd/upgrade.go
+++ b/cmd/upgrade.go
@@ -8,32 +8,33 @@ import (
"github.com/spf13/cobra"
)
-// UpgradeCmd is a struct that defines a command call for "upgrade"
+// UpgradeCmd is a struct that defines a command call for "upgrade".
type UpgradeCmd struct {
log log.Logger
Version string
+ DryRun bool
}
-// NewUpgradeCmd creates a new upgrade command
+// NewUpgradeCmd creates a new upgrade command.
func NewUpgradeCmd() *cobra.Command {
cmd := &UpgradeCmd{log: log.GetInstance()}
upgradeCmd := &cobra.Command{
Use: "upgrade",
Short: "Upgrade the DevPod CLI to the newest version",
Args: cobra.NoArgs,
- RunE: cmd.Run,
+ RunE: func(cobraCmd *cobra.Command, args []string) error {
+ ctx := cobraCmd.Context()
+ if err := upgrade.Upgrade(ctx, cmd.Version, cmd.DryRun, cmd.log); err != nil {
+ return fmt.Errorf("unable to upgrade: %w", err)
+ }
+ return nil
+ },
}
- upgradeCmd.Flags().StringVar(&cmd.Version, "version", "", "The version to update to. Defaults to the latest stable version available")
+ upgradeCmd.Flags().
+ StringVar(&cmd.Version, "version", "",
+ "The version to update to. Defaults to the latest stable version available")
+ upgradeCmd.Flags().
+ BoolVar(&cmd.DryRun, "dry-run", false, "Show which version would be downloaded without actually upgrading")
return upgradeCmd
}
-
-// Run executes the command logic
-func (cmd *UpgradeCmd) Run(*cobra.Command, []string) error {
- err := upgrade.Upgrade(cmd.Version, cmd.log)
- if err != nil {
- return fmt.Errorf("unable to upgrade: %w", err)
- }
-
- return nil
-}
diff --git a/cmd/use/use.go b/cmd/use/use.go
index 51e6ebc5b8..afbcb373d7 100644
--- a/cmd/use/use.go
+++ b/cmd/use/use.go
@@ -7,7 +7,7 @@ import (
"github.com/spf13/cobra"
)
-// NewUseCmd returns a new root command
+// NewUseCmd returns a new root command.
func NewUseCmd(flags *flags.GlobalFlags) *cobra.Command {
useCmd := &cobra.Command{
Use: "use",
diff --git a/cmd/version.go b/cmd/version.go
index 7225cf125a..dbb3f1bce3 100644
--- a/cmd/version.go
+++ b/cmd/version.go
@@ -8,11 +8,10 @@ import (
"github.com/spf13/cobra"
)
-// VersionCmd holds the ws-tunnel cmd flags
-type VersionCmd struct {
-}
+// VersionCmd holds the ws-tunnel cmd flags.
+type VersionCmd struct{}
-// NewVersionCmd creates a new ws-tunnel command
+// NewVersionCmd creates a new ws-tunnel command.
func NewVersionCmd() *cobra.Command {
cmd := &VersionCmd{}
versionCmd := &cobra.Command{
@@ -25,7 +24,7 @@ func NewVersionCmd() *cobra.Command {
return versionCmd
}
-// Run runs the command logic
+// Run runs the command logic.
func (cmd *VersionCmd) Run(_ *cobra.Command, _ []string) error {
_, _ = fmt.Fprintln(os.Stdout, version.GetVersion())
return nil
diff --git a/desktop/flatpak/devpod-wrapper b/desktop/flatpak/devpod-wrapper
new file mode 100755
index 0000000000..0e5089a7fd
--- /dev/null
+++ b/desktop/flatpak/devpod-wrapper
@@ -0,0 +1,69 @@
+#!/bin/sh
+
+APP_ID="sh.loft.devpod"
+APP_BIN="/app/bin/devpod-bin"
+
+remove_leftover_wrapper() {
+ script_path="$1"
+ case "$script_path" in
+ */*) ;;
+ *) script_path="$(command -v "$script_path" 2>/dev/null || true)" ;;
+ esac
+
+ [ -n "$script_path" ] && rm -i -- "$script_path"
+}
+
+run_from_host() {
+ flatpak run --command=devpod "$APP_ID" "$@"
+ result="$?"
+
+ if [ "$result" -gt 0 ]; then
+ if ! command -v flatpak >/dev/null 2>&1; then
+ echo "flatpak is not available; cannot verify DevPod installation"
+ elif ! flatpak info "$APP_ID" >/dev/null 2>&1; then
+ echo "Devpod flatpak is not installed anymore"
+ remove_leftover_wrapper "$0"
+ fi
+ fi
+
+ exit "$result"
+}
+
+sync_host_binary() {
+ data_home="${XDG_DATA_HOME:-$HOME/.local/share}"
+ target="${data_home}/devpod"
+
+ /usr/bin/mkdir -p "$data_home"
+
+ if [ ! -e "$target" ] || ! /usr/bin/cmp --silent "$APP_BIN" "$target"; then
+ /usr/bin/rm -f "$target"
+ /usr/bin/cp "$APP_BIN" "$target"
+ fi
+}
+
+main() {
+ if [ -z "${FLATPAK_ID}" ]; then
+ run_from_host "$@"
+ fi
+
+ sync_host_binary
+ data_home="${XDG_DATA_HOME:-$HOME/.local/share}"
+
+ # Start with env flags, then --host, binary, then the original CLI args.
+ set -- "--host" "${data_home}/devpod" "$@"
+ value="${DEVPOD_ADDITIONAL_ENV_VARS:-}"
+ if [ -n "$value" ]; then
+ old_ifs="$IFS"
+ IFS=','
+ for entry in $value; do
+ case "$entry" in
+ *=*) set -- "--env=${entry}" "$@" ;;
+ esac
+ done
+ IFS="$old_ifs"
+ fi
+
+ exec /usr/bin/flatpak-spawn "$@"
+}
+
+main "$@"
diff --git a/desktop/flatpak/sh.loft.devpod.yml b/desktop/flatpak/sh.loft.devpod.yml
index 3640c2ee48..5185f34a3f 100644
--- a/desktop/flatpak/sh.loft.devpod.yml
+++ b/desktop/flatpak/sh.loft.devpod.yml
@@ -18,7 +18,6 @@ finish-args:
- --talk-name=org.freedesktop.Notifications
- --talk-name=org.kde.StatusNotifierWatcher
- --filesystem=xdg-run/keyring
- - --filesystem=xdg-run/podman
modules:
- shared-modules/libayatana-appindicator/libayatana-appindicator-gtk3.json
@@ -37,10 +36,14 @@ modules:
- type: file
url: https://github.com/skevetter/devpod/releases/download/${VERSION}/DevPod.metainfo.xml
sha256: ${META_SHA256}
+
+ - type: file
+ path: devpod-wrapper
build-commands:
- ar -x *.deb
- tar -xf data.tar.gz
- - install -Dm755 usr/bin/devpod /app/bin/devpod
+ - install -Dm755 usr/bin/devpod /app/bin/devpod-bin
+ - install -Dm755 devpod-wrapper /app/bin/devpod
- install -Dm755 "usr/bin/DevPod Desktop" /app/bin/sh.loft.devpod
- install -Dm644 DevPod.desktop /app/share/applications/sh.loft.devpod.desktop
- desktop-file-edit --set-key Exec --set-value sh.loft.devpod /app/share/applications/sh.loft.devpod.desktop
diff --git a/desktop/package.json b/desktop/package.json
index f05504978d..91f9c2bba7 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -26,7 +26,7 @@
"@emotion/styled": "11.14.1",
"@headlessui/react": "2.2.9",
"@kubernetes/client-node": "1.4.0",
- "@loft-enterprise/client": "https://github.com/loft-sh/loft-javascript-client#v4.3.0-devpod.alpha.11",
+ "@loft-enterprise/client": "https://github.com/loft-sh/loft-javascript-client#v4.4.1",
"@tanstack/react-query": "4.43.0",
"@tanstack/react-query-devtools": "4.43.0",
"@tanstack/react-table": "8.21.3",
@@ -35,6 +35,7 @@
"@tauri-apps/plugin-dialog": "2.6.0",
"@tauri-apps/plugin-fs": "2.4.5",
"@tauri-apps/plugin-log": "2.8.0",
+ "@tauri-apps/plugin-opener": "2.5.3",
"@tauri-apps/plugin-os": "2.3.2",
"@tauri-apps/plugin-process": "2.3.1",
"@tauri-apps/plugin-shell": "2.3.5",
@@ -53,7 +54,7 @@
"react": "18.3.1",
"react-dom": "18.3.1",
"react-error-boundary": "4.1.2",
- "react-hook-form": "7.71.1",
+ "react-hook-form": "7.71.2",
"react-icons": "4.12.0",
"react-router": "6.30.3",
"react-router-dom": "6.30.3",
@@ -61,24 +62,24 @@
"uuid": "13.0.0"
},
"devDependencies": {
- "@eslint/compat": "2.0.2",
- "@eslint/eslintrc": "3.3.3",
+ "@eslint/compat": "2.0.3",
+ "@eslint/eslintrc": "3.3.5",
"@eslint/js": "10.0.1",
"@tanstack/eslint-plugin-query": "4.43.0",
- "@tauri-apps/cli": "2.10.0",
- "@types/node": "24.10.13",
+ "@tauri-apps/cli": "2.10.1",
+ "@types/node": "24.12.0",
"@types/react": "18.3.28",
"@types/react-dom": "18.3.7",
- "@typescript-eslint/eslint-plugin": "8.56.0",
- "@typescript-eslint/parser": "8.56.0",
+ "@typescript-eslint/eslint-plugin": "8.56.1",
+ "@typescript-eslint/parser": "8.56.1",
"@vitejs/plugin-react": "5.1.4",
- "eslint": "10.0.0",
+ "eslint": "10.0.3",
"eslint-config-prettier": "10.1.8",
"eslint-config-react-app": "7.0.1",
"eslint-plugin-react": "7.37.5",
"eslint-plugin-react-hooks": "5.2.0",
- "eslint-plugin-react-refresh": "0.5.0",
- "globals": "17.3.0",
+ "eslint-plugin-react-refresh": "0.5.2",
+ "globals": "17.4.0",
"prettier": "3.8.1",
"typescript": "5.9.3",
"vite": "7.3.1"
diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock
index 8c1318150c..88a7ef8567 100644
--- a/desktop/src-tauri/Cargo.lock
+++ b/desktop/src-tauri/Cargo.lock
@@ -77,9 +77,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.101"
+version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "arbitrary"
@@ -305,7 +305,7 @@ dependencies = [
"http-body-util",
"hyper",
"hyper-util",
- "itoa 1.0.17",
+ "itoa",
"matchit",
"memchr",
"mime",
@@ -661,9 +661,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chrono"
-version = "0.4.43"
+version = "0.4.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118"
+checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
dependencies = [
"iana-time-zone",
"js-sys",
@@ -731,6 +731,26 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "const-random"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
+dependencies = [
+ "const-random-macro",
+]
+
+[[package]]
+name = "const-random-macro"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
+dependencies = [
+ "getrandom 0.2.17",
+ "once_cell",
+ "tiny-keccak",
+]
+
[[package]]
name = "convert_case"
version = "0.4.0"
@@ -870,23 +890,6 @@ dependencies = [
"typenum",
]
-[[package]]
-name = "cssparser"
-version = "0.27.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "754b69d351cdc2d8ee09ae203db831e005560fc6030da058f86ad60c92a9cb0a"
-dependencies = [
- "cssparser-macros",
- "dtoa-short",
- "itoa 0.4.8",
- "matches",
- "phf 0.8.0",
- "proc-macro2",
- "quote",
- "smallvec",
- "syn 1.0.109",
-]
-
[[package]]
name = "cssparser"
version = "0.29.6"
@@ -895,7 +898,7 @@ checksum = "f93d03419cb5950ccfd3daf3ff1c7a36ace64609a1a8746d493df1ca0afde0fa"
dependencies = [
"cssparser-macros",
"dtoa-short",
- "itoa 1.0.17",
+ "itoa",
"matches",
"phf 0.10.1",
"proc-macro2",
@@ -914,16 +917,6 @@ dependencies = [
"syn 2.0.114",
]
-[[package]]
-name = "ctor"
-version = "0.1.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096"
-dependencies = [
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "ctor"
version = "0.2.9"
@@ -1046,6 +1039,7 @@ dependencies = [
"tauri-plugin-fs",
"tauri-plugin-log",
"tauri-plugin-notification",
+ "tauri-plugin-opener",
"tauri-plugin-os",
"tauri-plugin-process",
"tauri-plugin-shell",
@@ -1166,6 +1160,15 @@ dependencies = [
"syn 2.0.114",
]
+[[package]]
+name = "dlv-list"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
+dependencies = [
+ "const-random",
+]
+
[[package]]
name = "downcast-rs"
version = "1.2.1"
@@ -1941,6 +1944,12 @@ dependencies = [
"ahash",
]
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -1980,20 +1989,6 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
-[[package]]
-name = "html5ever"
-version = "0.25.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5c13fb08e5d4dfc151ee5e88bae63f7773d61852f3bdc73c9f4b9e1bde03148"
-dependencies = [
- "log",
- "mac",
- "markup5ever 0.10.1",
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "html5ever"
version = "0.29.1"
@@ -2002,7 +1997,7 @@ checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c"
dependencies = [
"log",
"mac",
- "markup5ever 0.14.1",
+ "markup5ever",
"match_token",
]
@@ -2013,7 +2008,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
dependencies = [
"bytes",
- "itoa 1.0.17",
+ "itoa",
]
[[package]]
@@ -2066,7 +2061,7 @@ dependencies = [
"http-body",
"httparse",
"httpdate",
- "itoa 1.0.17",
+ "itoa",
"pin-project-lite",
"pin-utils",
"smallvec",
@@ -2128,7 +2123,7 @@ dependencies = [
"tokio",
"tower-service",
"tracing",
- "windows-registry",
+ "windows-registry 0.6.1",
]
[[package]]
@@ -2316,15 +2311,6 @@ dependencies = [
"serde_core",
]
-[[package]]
-name = "infer"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a898e4b7951673fce96614ce5751d13c40fc5674bc2d759288e46c3ab62598b3"
-dependencies = [
- "cfb",
-]
-
[[package]]
name = "infer"
version = "0.19.0"
@@ -2395,12 +2381,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "itoa"
-version = "0.4.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
-
[[package]]
name = "itoa"
version = "1.0.17"
@@ -2462,17 +2442,6 @@ dependencies = [
"wasm-bindgen",
]
-[[package]]
-name = "json-patch"
-version = "1.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec9ad60d674508f3ca8f380a928cfe7b096bc729c4e2dbfe3852bc45da3ab30b"
-dependencies = [
- "serde",
- "serde_json",
- "thiserror 1.0.69",
-]
-
[[package]]
name = "json-patch"
version = "3.0.1"
@@ -2506,28 +2475,16 @@ dependencies = [
"unicode-segmentation",
]
-[[package]]
-name = "kuchiki"
-version = "0.8.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ea8e9c6e031377cff82ee3001dc8026cdf431ed4e2e6b51f98ab8c73484a358"
-dependencies = [
- "cssparser 0.27.2",
- "html5ever 0.25.2",
- "matches",
- "selectors 0.22.0",
-]
-
[[package]]
name = "kuchikiki"
version = "0.8.8-speedreader"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2"
dependencies = [
- "cssparser 0.29.6",
- "html5ever 0.29.1",
+ "cssparser",
+ "html5ever",
"indexmap 2.13.0",
- "selectors 0.24.0",
+ "selectors",
]
[[package]]
@@ -2650,20 +2607,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "markup5ever"
-version = "0.10.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a24f40fb03852d1cdd84330cddcaf98e9ec08a7b7768e952fad3b4cf048ec8fd"
-dependencies = [
- "log",
- "phf 0.8.0",
- "phf_codegen 0.8.0",
- "string_cache",
- "string_cache_codegen",
- "tendril",
-]
-
[[package]]
name = "markup5ever"
version = "0.14.1"
@@ -2946,16 +2889,6 @@ version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
-[[package]]
-name = "objc2"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "559c5a40fdd30eb5e344fbceacf7595a81e242529fb4e21cf5f43fb4f11ff98d"
-dependencies = [
- "objc-sys",
- "objc2-encode 3.0.0",
-]
-
[[package]]
name = "objc2"
version = "0.5.2"
@@ -2963,7 +2896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
dependencies = [
"objc-sys",
- "objc2-encode 4.1.0",
+ "objc2-encode",
]
[[package]]
@@ -2972,7 +2905,7 @@ version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c2599ce0ec54857b29ce62166b0ed9b4f6f1a70ccc9a71165b6154caca8c05"
dependencies = [
- "objc2-encode 4.1.0",
+ "objc2-encode",
"objc2-exception-helper",
]
@@ -3000,17 +2933,10 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.10.0",
"block2 0.6.2",
- "libc",
"objc2 0.6.3",
- "objc2-cloud-kit",
- "objc2-core-data 0.3.2",
"objc2-core-foundation",
"objc2-core-graphics",
- "objc2-core-image 0.3.2",
- "objc2-core-text",
- "objc2-core-video",
"objc2-foundation 0.3.2",
- "objc2-quartz-core 0.3.2",
]
[[package]]
@@ -3042,7 +2968,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
dependencies = [
- "bitflags 2.10.0",
"objc2 0.6.3",
"objc2-foundation 0.3.2",
]
@@ -3115,25 +3040,6 @@ dependencies = [
"objc2-core-graphics",
]
-[[package]]
-name = "objc2-core-video"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
-dependencies = [
- "bitflags 2.10.0",
- "objc2 0.6.3",
- "objc2-core-foundation",
- "objc2-core-graphics",
- "objc2-io-surface",
-]
-
-[[package]]
-name = "objc2-encode"
-version = "3.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d079845b37af429bfe5dfa76e6d087d788031045b25cfc6fd898486fd9847666"
-
[[package]]
name = "objc2-encode"
version = "4.1.0"
@@ -3185,16 +3091,6 @@ dependencies = [
"objc2-core-foundation",
]
-[[package]]
-name = "objc2-javascript-core"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2a1e6550c4caed348956ce3370c9ffeca70bb1dbed4fa96112e7c6170e074586"
-dependencies = [
- "objc2 0.6.3",
- "objc2-core-foundation",
-]
-
[[package]]
name = "objc2-metal"
version = "0.2.2"
@@ -3244,17 +3140,6 @@ dependencies = [
"objc2-foundation 0.3.2",
]
-[[package]]
-name = "objc2-security"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"
-dependencies = [
- "bitflags 2.10.0",
- "objc2 0.6.3",
- "objc2-core-foundation",
-]
-
[[package]]
name = "objc2-ui-kit"
version = "0.3.2"
@@ -3298,8 +3183,6 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
- "objc2-javascript-core",
- "objc2-security",
]
[[package]]
@@ -3376,6 +3259,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "ordered-multimap"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
+dependencies = [
+ "dlv-list",
+ "hashbrown 0.14.5",
+]
+
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -3509,9 +3402,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12"
dependencies = [
- "phf_macros 0.8.0",
"phf_shared 0.8.0",
- "proc-macro-hack",
]
[[package]]
@@ -3585,20 +3476,6 @@ dependencies = [
"rand 0.8.5",
]
-[[package]]
-name = "phf_macros"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f6fde18ff429ffc8fe78e2bf7f8b7a5a5a6e2a8b58bc5a9ac69198bbda9189c"
-dependencies = [
- "phf_generator 0.8.0",
- "phf_shared 0.8.0",
- "proc-macro-hack",
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "phf_macros"
version = "0.10.0"
@@ -3655,9 +3532,9 @@ dependencies = [
[[package]]
name = "pin-project-lite"
-version = "0.2.16"
+version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pin-utils"
@@ -4277,6 +4154,16 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "rust-ini"
+version = "0.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
+dependencies = [
+ "cfg-if",
+ "ordered-multimap",
+]
+
[[package]]
name = "rust_decimal"
version = "1.40.0"
@@ -4517,26 +4404,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "selectors"
-version = "0.22.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df320f1889ac4ba6bc0cdc9c9af7af4bd64bb927bccdf32d81140dc1f9be12fe"
-dependencies = [
- "bitflags 1.3.2",
- "cssparser 0.27.2",
- "derive_more",
- "fxhash",
- "log",
- "matches",
- "phf 0.8.0",
- "phf_codegen 0.8.0",
- "precomputed-hash",
- "servo_arc 0.1.1",
- "smallvec",
- "thin-slice",
-]
-
[[package]]
name = "selectors"
version = "0.24.0"
@@ -4544,14 +4411,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416"
dependencies = [
"bitflags 1.3.2",
- "cssparser 0.29.6",
+ "cssparser",
"derive_more",
"fxhash",
"log",
"phf 0.8.0",
"phf_codegen 0.8.0",
"precomputed-hash",
- "servo_arc 0.2.0",
+ "servo_arc",
"smallvec",
]
@@ -4624,7 +4491,7 @@ version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
- "itoa 1.0.17",
+ "itoa",
"memchr",
"serde",
"serde_core",
@@ -4637,7 +4504,7 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
- "itoa 1.0.17",
+ "itoa",
"serde",
"serde_core",
]
@@ -4689,7 +4556,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
- "itoa 1.0.17",
+ "itoa",
"ryu",
"serde",
]
@@ -4732,7 +4599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [
"indexmap 2.13.0",
- "itoa 1.0.17",
+ "itoa",
"ryu",
"serde",
"unsafe-libyaml",
@@ -4760,16 +4627,6 @@ dependencies = [
"syn 2.0.114",
]
-[[package]]
-name = "servo_arc"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d98238b800e0d1576d8b6e3de32827c2d74bee68bb97748dcf5071fb53965432"
-dependencies = [
- "nodrop",
- "stable_deref_trait",
-]
-
[[package]]
name = "servo_arc"
version = "0.2.0"
@@ -5177,9 +5034,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "tauri"
-version = "2.10.2"
+version = "2.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "463ae8677aa6d0f063a900b9c41ecd4ac2b7ca82f0b058cc4491540e55b20129"
+checksum = "da77cc00fb9028caf5b5d4650f75e31f1ef3693459dfca7f7e506d1ecef0ba2d"
dependencies = [
"anyhow",
"bytes",
@@ -5216,7 +5073,7 @@ dependencies = [
"tauri-macros",
"tauri-runtime",
"tauri-runtime-wry",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"thiserror 2.0.18",
"tokio",
"tray-icon",
@@ -5229,21 +5086,21 @@ dependencies = [
[[package]]
name = "tauri-build"
-version = "2.5.5"
+version = "2.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca7bd893329425df750813e95bd2b643d5369d929438da96d5bbb7cc2c918f74"
+checksum = "4bbc990d1dbf57a8e1c7fa2327f2a614d8b757805603c1b9ba5c81bade09fd4d"
dependencies = [
"anyhow",
"cargo_toml",
"dirs 6.0.0",
"glob",
"heck 0.5.0",
- "json-patch 3.0.1",
+ "json-patch",
"schemars 0.8.22",
"semver",
"serde",
"serde_json",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"tauri-winres",
"toml 0.9.12+spec-1.1.0",
"walkdir",
@@ -5251,14 +5108,14 @@ dependencies = [
[[package]]
name = "tauri-codegen"
-version = "2.5.4"
+version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aac423e5859d9f9ccdd32e3cf6a5866a15bedbf25aa6630bcb2acde9468f6ae3"
+checksum = "d4a24476afd977c5d5d169f72425868613d82747916dd29e0a357c84c4bd6d29"
dependencies = [
"base64 0.22.1",
"brotli",
"ico",
- "json-patch 3.0.1",
+ "json-patch",
"plist",
"png 0.17.16",
"proc-macro2",
@@ -5268,7 +5125,7 @@ dependencies = [
"serde_json",
"sha2",
"syn 2.0.114",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"thiserror 2.0.18",
"time",
"url",
@@ -5278,16 +5135,16 @@ dependencies = [
[[package]]
name = "tauri-macros"
-version = "2.5.4"
+version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b6a1bd2861ff0c8766b1d38b32a6a410f6dc6532d4ef534c47cfb2236092f59"
+checksum = "d39b349a98dadaffebb73f0a40dcd1f23c999211e5a2e744403db384d0c33de7"
dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 2.0.114",
"tauri-codegen",
- "tauri-utils 2.8.2",
+ "tauri-utils",
]
[[package]]
@@ -5302,7 +5159,7 @@ dependencies = [
"schemars 0.8.22",
"serde",
"serde_json",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"toml 0.9.12+spec-1.1.0",
"walkdir",
]
@@ -5324,18 +5181,23 @@ dependencies = [
[[package]]
name = "tauri-plugin-deep-link"
-version = "0.1.2"
+version = "2.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4536f5f6602e8fdfaa7b3b185076c2a0704f8eb7015f4e58461eb483ec3ed1f8"
+checksum = "94deb2e2e4641514ac496db2cddcfc850d6fc9d51ea17b82292a0490bd20ba5b"
dependencies = [
- "dirs 5.0.1",
- "interprocess",
- "log",
- "objc2 0.4.1",
- "once_cell",
- "tauri-utils 1.4.0",
- "windows-sys 0.48.0",
- "winreg 0.50.0",
+ "dunce",
+ "plist",
+ "rust-ini",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-utils",
+ "thiserror 2.0.18",
+ "tracing",
+ "url",
+ "windows-registry 0.5.3",
+ "windows-result 0.3.4",
]
[[package]]
@@ -5372,7 +5234,7 @@ dependencies = [
"serde_repr",
"tauri",
"tauri-plugin",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"thiserror 2.0.18",
"toml 0.9.12+spec-1.1.0",
"url",
@@ -5419,6 +5281,28 @@ dependencies = [
"url",
]
+[[package]]
+name = "tauri-plugin-opener"
+version = "2.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc624469b06f59f5a29f874bbc61a2ed737c0f9c23ef09855a292c389c42e83f"
+dependencies = [
+ "dunce",
+ "glob",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+ "open",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.18",
+ "url",
+ "windows 0.61.3",
+ "zbus",
+]
+
[[package]]
name = "tauri-plugin-os"
version = "2.3.2"
@@ -5510,7 +5394,7 @@ dependencies = [
"flate2",
"futures-util",
"http",
- "infer 0.19.0",
+ "infer",
"log",
"minisign-verify",
"osakit",
@@ -5534,9 +5418,9 @@ dependencies = [
[[package]]
name = "tauri-runtime"
-version = "2.10.0"
+version = "2.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b885ffeac82b00f1f6fd292b6e5aabfa7435d537cef57d11e38a489956535651"
+checksum = "2826d79a3297ed08cd6ea7f412644ef58e32969504bc4fbd8d7dbeabc4445ea2"
dependencies = [
"cookie",
"dpi",
@@ -5549,7 +5433,7 @@ dependencies = [
"raw-window-handle",
"serde",
"serde_json",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"thiserror 2.0.18",
"url",
"webkit2gtk",
@@ -5559,9 +5443,9 @@ dependencies = [
[[package]]
name = "tauri-runtime-wry"
-version = "2.10.0"
+version = "2.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5204682391625e867d16584fedc83fc292fb998814c9f7918605c789cd876314"
+checksum = "e11ea2e6f801d275fdd890d6c9603736012742a1c33b96d0db788c9cdebf7f9e"
dependencies = [
"gtk",
"http",
@@ -5569,14 +5453,13 @@ dependencies = [
"log",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
- "objc2-foundation 0.3.2",
"once_cell",
"percent-encoding",
"raw-window-handle",
"softbuffer",
"tao",
"tauri-runtime",
- "tauri-utils 2.8.2",
+ "tauri-utils",
"url",
"webkit2gtk",
"webview2-com",
@@ -5586,44 +5469,20 @@ dependencies = [
[[package]]
name = "tauri-utils"
-version = "1.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03fc02bb6072bb397e1d473c6f76c953cda48b4a2d0cce605df284aa74a12e84"
-dependencies = [
- "ctor 0.1.26",
- "dunce",
- "heck 0.4.1",
- "html5ever 0.25.2",
- "infer 0.12.0",
- "json-patch 1.4.0",
- "kuchiki",
- "memchr",
- "phf 0.10.1",
- "semver",
- "serde",
- "serde_json",
- "serde_with",
- "thiserror 1.0.69",
- "url",
- "windows 0.39.0",
-]
-
-[[package]]
-name = "tauri-utils"
-version = "2.8.2"
+version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fcd169fccdff05eff2c1033210b9b94acd07a47e6fa9a3431cf09cfd4f01c87e"
+checksum = "219a1f983a2af3653f75b5747f76733b0da7ff03069c7a41901a5eb3ace4557d"
dependencies = [
"anyhow",
"brotli",
"cargo_metadata",
- "ctor 0.2.9",
+ "ctor",
"dunce",
"glob",
- "html5ever 0.29.1",
+ "html5ever",
"http",
- "infer 0.19.0",
- "json-patch 3.0.1",
+ "infer",
+ "json-patch",
"kuchikiki",
"log",
"memchr",
@@ -5702,12 +5561,6 @@ dependencies = [
"winapi-util",
]
-[[package]]
-name = "thin-slice"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8eaa81235c7058867fa8c0e7314f33dcce9c215f535d1913822a2b3f5e289f3c"
-
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -5769,7 +5622,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
dependencies = [
"deranged",
- "itoa 1.0.17",
+ "itoa",
"libc",
"num-conv",
"num_threads",
@@ -5795,6 +5648,15 @@ dependencies = [
"time-core",
]
+[[package]]
+name = "tiny-keccak"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
+dependencies = [
+ "crunchy",
+]
+
[[package]]
name = "tinystr"
version = "0.8.2"
@@ -5828,9 +5690,9 @@ checksum = "c7c4ceeeca15c8384bbc3e011dbd8fccb7f068a440b752b7d9b32ceb0ca0e2e8"
[[package]]
name = "tokio"
-version = "1.49.0"
+version = "1.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
+checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d"
dependencies = [
"bytes",
"libc",
@@ -6687,7 +6549,7 @@ dependencies = [
"webview2-com-sys",
"windows 0.61.3",
"windows-core 0.61.2",
- "windows-implement 0.60.2",
+ "windows-implement",
"windows-interface",
]
@@ -6779,20 +6641,6 @@ dependencies = [
"windows-version",
]
-[[package]]
-name = "windows"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1c4bd0a50ac6020f65184721f758dba47bb9fbc2133df715ec74a237b26794a"
-dependencies = [
- "windows-implement 0.39.0",
- "windows_aarch64_msvc 0.39.0",
- "windows_i686_gnu 0.39.0",
- "windows_i686_msvc 0.39.0",
- "windows_x86_64_gnu 0.39.0",
- "windows_x86_64_msvc 0.39.0",
-]
-
[[package]]
name = "windows"
version = "0.48.0"
@@ -6830,7 +6678,7 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
- "windows-implement 0.60.2",
+ "windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
@@ -6843,7 +6691,7 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
- "windows-implement 0.60.2",
+ "windows-implement",
"windows-interface",
"windows-link 0.2.1",
"windows-result 0.4.1",
@@ -6861,16 +6709,6 @@ dependencies = [
"windows-threading",
]
-[[package]]
-name = "windows-implement"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ba01f98f509cb5dc05f4e5fc95e535f78260f15fea8fe1a8abdd08f774f1cee7"
-dependencies = [
- "syn 1.0.109",
- "windows-tokens",
-]
-
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -6915,6 +6753,17 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "windows-registry"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"
+dependencies = [
+ "windows-link 0.1.3",
+ "windows-result 0.3.4",
+ "windows-strings 0.4.2",
+]
+
[[package]]
name = "windows-registry"
version = "0.6.1"
@@ -7088,12 +6937,6 @@ dependencies = [
"windows-link 0.1.3",
]
-[[package]]
-name = "windows-tokens"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f838de2fe15fe6bac988e74b798f26499a8b21a9d97edec321e79b28d1d7f597"
-
[[package]]
name = "windows-version"
version = "0.1.7"
@@ -7127,12 +6970,6 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec7711666096bd4096ffa835238905bb33fb87267910e154b18b44eaabb340f2"
-
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
@@ -7157,12 +6994,6 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
-[[package]]
-name = "windows_i686_gnu"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "763fc57100a5f7042e3057e7e8d9bdd7860d330070251a73d003563a3bb49e1b"
-
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
@@ -7199,12 +7030,6 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
-[[package]]
-name = "windows_i686_msvc"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7bc7cbfe58828921e10a9f446fcaaf649204dcfe6c1ddd712c5eebae6bda1106"
-
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
@@ -7229,12 +7054,6 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6868c165637d653ae1e8dc4d82c25d4f97dd6605eaa8d784b5c6e0ab2a252b65"
-
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
@@ -7283,12 +7102,6 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.39.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e4d40883ae9cae962787ca76ba76390ffa29214667a111db9e0a1ad8377e809"
-
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
@@ -7478,7 +7291,7 @@ dependencies = [
"dunce",
"gdkx11",
"gtk",
- "html5ever 0.29.1",
+ "html5ever",
"http",
"javascriptcore-rs",
"jni",
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
index 597edae421..722557a850 100644
--- a/desktop/src-tauri/Cargo.toml
+++ b/desktop/src-tauri/Cargo.toml
@@ -8,11 +8,11 @@ repository = ""
edition = "2024"
[build-dependencies]
-tauri-build = { version = "2.5.5", features = [] }
+tauri-build = { version = "2.5.6", features = [] }
[dependencies]
# Tauri
-tauri = { version = "2.10.2", features = [
+tauri = { version = "2.10.3", features = [
"macos-private-api",
"image-ico",
"image-png",
@@ -26,25 +26,26 @@ serde_yaml = "0.9.34"
serde_urlencoded = "0.7.1"
# Tauri plugins
-tauri-plugin-deep-link = { version = "0.1.2" }
-tauri-plugin-store = { version = "2.4.2" }
-tauri-plugin-dialog = "2"
-tauri-plugin-shell = "2"
-tauri-plugin-clipboard-manager = "2"
-tauri-plugin-fs = "2"
-tauri-plugin-os = "2"
-tauri-plugin-process = "2"
-tauri-plugin-updater = "2.10"
-tauri-plugin-notification = "2"
-tauri-plugin-single-instance = "2"
+tauri-plugin-deep-link = "2.4.7"
+tauri-plugin-store = "2.4.2"
+tauri-plugin-dialog = "2.6.0"
+tauri-plugin-shell = "2.3.5"
+tauri-plugin-clipboard-manager = "2.3.2"
+tauri-plugin-fs = "2.4.5"
+tauri-plugin-opener = "2.5.3"
+tauri-plugin-os = "2.3.2"
+tauri-plugin-process = "2.3.1"
+tauri-plugin-updater = "2.10.0"
+tauri-plugin-notification = "2.3.3"
+tauri-plugin-single-instance = { version = "2.4.0", features = ["deep-link"] }
# Logging
log = { version = "0.4" }
-tauri-plugin-log = { version = "2" }
+tauri-plugin-log = "2.8.0"
# Datetime
-chrono = { version = "0.4.43", features = ["serde"] }
+chrono = { version = "0.4.44", features = ["serde"] }
-tokio = { version = "1.49.0", features = [
+tokio = { version = "1.50.0", features = [
"time",
"parking_lot",
"sync",
@@ -54,7 +55,7 @@ thiserror = "1.0.69"
regex = "1.12.3"
lazy_static = "1.5.0"
url = "2.5.8"
-anyhow = "1.0.101"
+anyhow = "1.0.102"
dirs = "5.0.1"
reqwest = { version = "0.12.28", features = ["json"] }
dispatch = "0.2.0"
@@ -67,7 +68,7 @@ http = "1.4.0"
nix = { version = "0.29.0", features = ["signal"] }
interprocess = "1.2.1"
hyper = { version = "1.8.1", features = ["client", "http1"] }
-pin-project-lite = "0.2.16"
+pin-project-lite = "0.2.17"
bytes = "1.11.1"
http-body-util = "0.1.3"
diff --git a/desktop/src-tauri/capabilities/migrated.json b/desktop/src-tauri/capabilities/migrated.json
index 7fb72ca02b..1735f6fe6b 100644
--- a/desktop/src-tauri/capabilities/migrated.json
+++ b/desktop/src-tauri/capabilities/migrated.json
@@ -9,8 +9,20 @@
"core:default",
"process:allow-exit",
"process:allow-restart",
+ "opener:allow-default-urls",
+ {
+ "identifier": "opener:allow-open-path",
+ "allow": [
+ {
+ "path": "$APPDATA"
+ },
+ {
+ "path": "$APPLOG/*"
+ }
+ ]
+ },
+ "opener:allow-open-url",
"os:default",
- "shell:allow-open",
"shell:allow-kill",
"shell:allow-spawn",
{
diff --git a/desktop/src-tauri/src/custom_protocol.rs b/desktop/src-tauri/src/custom_protocol.rs
index 1f4637d940..63778c0e39 100644
--- a/desktop/src-tauri/src/custom_protocol.rs
+++ b/desktop/src-tauri/src/custom_protocol.rs
@@ -5,17 +5,17 @@ use crate::ui_messages::{
#[cfg(target_os = "linux")]
use crate::ui_messages::{ShowToastMsg, ToastStatus};
use crate::AppState;
-use log::{error, info, warn};
+use log::{info, warn};
use serde::{Deserialize, Serialize};
#[cfg(target_os = "linux")]
use std::env;
use tauri::{AppHandle, Manager, State};
+use tauri_plugin_deep_link::DeepLinkExt;
use thiserror::Error;
use url::Url;
// Should match the one from "tauri.config.json" and "Info.plist"
const APP_IDENTIFIER: &str = "sh.loft.devpod";
-const APP_URL_SCHEME: &str = "devpod";
pub struct CustomProtocol;
@@ -155,9 +155,36 @@ impl ProHandler {
}
}
+async fn handle_deep_link_url(app_handle: &AppHandle, url: &url::Url) {
+ info!("App opened with URL: {:?}", url.to_string());
+
+ let request = UrlParser::parse(&url.to_string());
+ let app_state = app_handle.state::();
+ if let Err(err) = request {
+ warn!("Failed to broadcast custom protocol message: {:?}", err);
+ return;
+ }
+ let request = request.unwrap();
+
+ match request.host.as_str() {
+ "open" => {
+ let msg = CustomProtocol::parse(&request);
+ OpenHandler::handle(msg, app_state).await
+ }
+ "import" => {
+ let msg = CustomProtocol::parse(&request);
+ ImportHandler::handle(msg, app_state).await
+ }
+ "pro" => {
+ let msg = CustomProtocol::parse(&request);
+ ProHandler::handle(msg, app_state).await
+ }
+ _ => {}
+ }
+}
+
impl CustomProtocol {
- pub fn init() -> Self {
- tauri_plugin_deep_link::prepare(APP_IDENTIFIER);
+ pub fn new() -> Self {
Self {}
}
@@ -211,38 +238,38 @@ impl CustomProtocol {
}
pub fn setup(&self, app: AppHandle) {
- let app_handle = app.clone();
-
- let result = tauri_plugin_deep_link::register(APP_URL_SCHEME, move |url_scheme| {
- tauri::async_runtime::block_on(async {
- info!("App opened with URL: {:?}", url_scheme.to_string());
-
- let request = UrlParser::parse(&url_scheme.to_string());
- let app_state = app_handle.state::();
- if let Err(err) = request {
- warn!("Failed to broadcast custom protocol message: {:?}", err);
- return;
+ // Handle URLs from cold-start (app launched via deep link)
+ if let Ok(Some(urls)) = app.deep_link().get_current() {
+ let app_handle = app.clone();
+ tauri::async_runtime::spawn(async move {
+ for url in urls {
+ handle_deep_link_url(&app_handle, &url).await;
}
- let request = request.unwrap();
+ });
+ }
- match request.host.as_str() {
- "open" => {
- let msg = CustomProtocol::parse(&request);
- OpenHandler::handle(msg, app_state).await
- }
- "import" => {
- let msg = CustomProtocol::parse(&request);
- ImportHandler::handle(msg, app_state).await
- }
- "pro" => {
- let msg = CustomProtocol::parse(&request);
- ProHandler::handle(msg, app_state).await
- }
- _ => {}
- }
- })
+ // Handle URLs received while the app is running
+ let app_handle = app.clone();
+ app.deep_link().on_open_url(move |event| {
+ for url_scheme in event.urls() {
+ let app_handle = app_handle.clone();
+ tauri::async_runtime::block_on(async {
+ handle_deep_link_url(&app_handle, &url_scheme).await;
+ });
+ }
});
+ // Register all configured URL schemes at runtime (Linux/Windows only; macOS uses Info.plist)
+ #[cfg(any(target_os = "linux", target_os = "windows"))]
+ let result = app.deep_link().register_all();
+
+ #[cfg(target_os = "windows")]
+ {
+ if let Err(error) = result {
+ log::warn!("Custom protocol setup failed on Windows: {}", error);
+ }
+ }
+
#[cfg(target_os = "linux")]
{
match result {
@@ -277,8 +304,6 @@ impl CustomProtocol {
}
};
}
-
- let _ = result;
}
fn parse<'a, Msg>(request: &'a Request) -> Result
diff --git a/desktop/src-tauri/src/install_cli.rs b/desktop/src-tauri/src/install_cli.rs
index 32e8429516..2d17f11591 100644
--- a/desktop/src-tauri/src/install_cli.rs
+++ b/desktop/src-tauri/src/install_cli.rs
@@ -5,7 +5,6 @@ use std::str::Lines;
use std::{env, path::PathBuf};
use thiserror::Error;
use std::fs;
-use log::info;
#[derive(Error, Debug)]
#[allow(dead_code)]
diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs
index 68f3e4c720..14c877841c 100644
--- a/desktop/src-tauri/src/main.rs
+++ b/desktop/src-tauri/src/main.rs
@@ -71,15 +71,22 @@ fn main() -> anyhow::Result<()> {
// this case is handled by macos itself + tauri::RunEvent::Reopen
#[cfg(not(target_os = "macos"))]
{
- app_builder = app_builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
- let app_state = app.state::();
+ // Single-instance plugin with deep-link feature: when a second instance is
+ // launched with a deep link URL, the plugin automatically forwards it to the
+ // deep-link plugin's on_open_url handler via handle_cli_arguments().
+ app_builder = app_builder.plugin(tauri_plugin_single_instance::init(
+ |app, _args, _cwd| {
+ let app_state = app.state::();
- tauri::async_runtime::block_on(async move {
- if let Err(err) = app_state.ui_messages.send(UiMessage::ShowDashboard).await {
- error!("Failed to broadcast show dashboard message: {}", err);
- };
- });
- }));
+ tauri::async_runtime::block_on(async move {
+ if let Err(err) =
+ app_state.ui_messages.send(UiMessage::ShowDashboard).await
+ {
+ error!("Failed to broadcast show dashboard message: {}", err);
+ };
+ });
+ },
+ ));
}
app_builder = app_builder
.manage(AppState {
@@ -97,10 +104,12 @@ fn main() -> anyhow::Result<()> {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_fs::init())
+ .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_notification::init())
+ .plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.setup(move |app| {
info!("Setup application");
@@ -116,7 +125,7 @@ fn main() -> anyhow::Result<()> {
action_logs::setup(&app.handle())?;
- let custom_protocol = CustomProtocol::init();
+ let custom_protocol = CustomProtocol::new();
custom_protocol.setup(app.handle().clone());
let app_handle = app.handle().clone();
@@ -149,8 +158,20 @@ fn main() -> anyhow::Result<()> {
let app_handle = app.handle().clone();
tauri::async_runtime::block_on(async move {
if let Ok(menu) = system_tray.init(&app_handle).await {
+ let tray_temp_dir = app
+ .path()
+ .app_cache_dir()
+ .unwrap_or_else(|err| {
+ error!(
+ "Failed to resolve app cache dir for tray temp path: {}. Falling back to system temp dir.",
+ err
+ );
+ std::env::temp_dir().join("devpod")
+ });
+
let _tray = TrayIconBuilder::with_id("main")
.icon(Image::from_bytes(SYSTEM_TRAY_ICON_BYTES).unwrap(),)
+ .temp_dir_path(tray_temp_dir)
.icon_as_template(true)
.menu(&menu)
.show_menu_on_left_click(true)
diff --git a/desktop/src/App/Changelog.tsx b/desktop/src/App/Changelog.tsx
index 1dd49b22af..53e76a3d6f 100644
--- a/desktop/src/App/Changelog.tsx
+++ b/desktop/src/App/Changelog.tsx
@@ -32,7 +32,7 @@ export function Changelog({ rawMarkdown }: TChangeLogProps) {
props: {
onClick: (e: TLinkClickEvent) => {
e.preventDefault()
- client.open(e.target.href)
+ client.openUrl(e.target.href)
},
},
},
diff --git a/desktop/src/App/useChangelogModal.tsx b/desktop/src/App/useChangelogModal.tsx
index 92cf896eb2..ef695b4bea 100644
--- a/desktop/src/App/useChangelogModal.tsx
+++ b/desktop/src/App/useChangelogModal.tsx
@@ -14,9 +14,10 @@ import { useEffect, useMemo, useState } from "react"
import { Release } from "@/gen"
import { useReleases } from "@/lib"
import { useVersion } from "@/lib/useVersion"
+import { BINARY_NAME } from "@/client/repo"
import { Changelog } from "./Changelog"
-const LAST_INSTALLED_VERSION_KEY = "devpod-last-installed-version"
+const LAST_INSTALLED_VERSION_KEY = `${BINARY_NAME}-last-installed-version`
export function useChangelogModal(isReady: boolean) {
const currentVersion = useVersion()
diff --git a/desktop/src/client/client.ts b/desktop/src/client/client.ts
index d01087d55d..43fc717f37 100644
--- a/desktop/src/client/client.ts
+++ b/desktop/src/client/client.ts
@@ -6,12 +6,13 @@ import * as clipboard from "@tauri-apps/plugin-clipboard-manager"
import * as dialog from "@tauri-apps/plugin-dialog"
import * as fs from "@tauri-apps/plugin-fs"
import * as log from "@tauri-apps/plugin-log"
+import * as opener from "@tauri-apps/plugin-opener"
import * as os from "@tauri-apps/plugin-os"
import * as process from "@tauri-apps/plugin-process"
-import * as shell from "@tauri-apps/plugin-shell"
import { Command } from "@tauri-apps/plugin-shell"
import * as updater from "@tauri-apps/plugin-updater"
import { TSettings } from "@/contexts"
+import { BINARY_NAME } from "./repo"
import { Release } from "@/gen"
import { Result, Return, hasCapability, isError, noop } from "@/lib"
import { TCommunityContributions, TProInstance, TUnsubscribeFn } from "@/types"
@@ -238,7 +239,7 @@ class Client {
p = await path.join(p, "DevPod.log")
}
- shell.open(p)
+ opener.openPath(p)
} catch {
// noop for now
}
@@ -315,13 +316,13 @@ class Client {
const home_dir = await this.getEnv("HOME")
// this will throw if doesn't exist
const exists = await invoke("file_exists", {
- filepath: home_dir + "/.local/bin/devpod",
+ filepath: home_dir + `/.local/bin/${BINARY_NAME}`,
})
return Return.Value(exists)
}
- const result = await Command.create("run-path-devpod", ["version"]).execute()
+ const result = await Command.create(`run-path-${BINARY_NAME}`, ["version"]).execute()
if (result.code !== 0) {
return Return.Value(false)
}
@@ -332,8 +333,8 @@ class Client {
}
}
- public open(link: string): void {
- shell.open(link)
+ public openUrl(link: string): void {
+ opener.openUrl(link)
}
public async quit(): Promise> {
diff --git a/desktop/src/client/command.ts b/desktop/src/client/command.ts
index 8f4f003945..9fcb96e361 100644
--- a/desktop/src/client/command.ts
+++ b/desktop/src/client/command.ts
@@ -11,6 +11,7 @@ import {
DEVPOD_UI_ENV_VAR,
DEVPOD_ADDITIONAL_ENV_VARS,
} from "./constants"
+import { FLATPAK_ID } from "./repo"
import { TStreamEvent } from "./types"
import { TAURI_SERVER_URL } from "./tauriClient"
import { invoke } from "@tauri-apps/api/core"
@@ -91,7 +92,7 @@ export class Command implements TCommand> {
if (this.isFlatpak === undefined) {
this.isFlatpak = await this.getEnv("FLATPAK_ID")
if (this.isFlatpak) {
- this.extraEnvVars["FLATPAK_ID"] = "sh.loft.devpod"
+ this.extraEnvVars["FLATPAK_ID"] = FLATPAK_ID
this.extraEnvVars[DEVPOD_ADDITIONAL_ENV_VARS] = recordToCSV(this.extraEnvVars)
this.sidecarCommand = ShellCommand.sidecar(DEVPOD_BINARY, this.args, {
env: this.extraEnvVars,
diff --git a/desktop/src/client/constants.ts b/desktop/src/client/constants.ts
index adf4ebd64e..7a17256c77 100644
--- a/desktop/src/client/constants.ts
+++ b/desktop/src/client/constants.ts
@@ -1,4 +1,6 @@
-export const DEVPOD_GIT_REPOSITORY = "https://github.com/skevetter/devpod"
+import { BINARY_NAME, GITHUB_REPO_URL } from "./repo"
+
+export const DEVPOD_GIT_REPOSITORY = GITHUB_REPO_URL
export const DEFAULT_STATIC_COMMAND_CONFIG = {
streamResponse: false,
@@ -7,7 +9,7 @@ export const DEFAULT_STATIC_COMMAND_CONFIG = {
/** placeholder for arbitrary additional flags */
export const WORKSPACE_COMMAND_ADDITIONAL_FLAGS_KEY = "additionalFlags"
-export const DEVPOD_BINARY = "bin/devpod"
+export const DEVPOD_BINARY = `bin/${BINARY_NAME}`
export const DEVPOD_COMMAND_LIST = "list"
export const DEVPOD_COMMAND_STATUS = "status"
export const DEVPOD_COMMAND_UP = "up"
@@ -23,6 +25,7 @@ export const DEVPOD_COMMAND_USE = "use"
export const DEVPOD_COMMAND_ADD = "add"
export const DEVPOD_COMMAND_HELPER = "helper"
export const DEVPOD_COMMAND_UPDATE = "update"
+export const DEVPOD_COMMAND_RENAME = "rename"
export const DEVPOD_COMMAND_CONTEXT = "context"
export const DEVPOD_COMMAND_LOGIN = "login"
export const DEVPOD_COMMAND_IMPORT_WORKSPACE = "import-workspace"
diff --git a/desktop/src/client/providers/client.ts b/desktop/src/client/providers/client.ts
index f466af62d7..d647048bea 100644
--- a/desktop/src/client/providers/client.ts
+++ b/desktop/src/client/providers/client.ts
@@ -57,6 +57,10 @@ export class ProvidersClient implements TDebuggable {
return ProviderCommands.RemoveProvider(id)
}
+ public async rename(id: TProviderID, newName: string): Promise {
+ return ProviderCommands.RenameProvider(id, newName)
+ }
+
public async getOptions(id: TProviderID): Promise> {
return ProviderCommands.GetProviderOptions(id)
}
@@ -89,7 +93,9 @@ export class ProvidersClient implements TDebuggable {
}
public setDangling(id: TProviderID): void {
- this.danglingProviderIDs.push(id)
+ if (!this.danglingProviderIDs.includes(id)) {
+ this.danglingProviderIDs.push(id)
+ }
const ids = this.danglingProviderIDs.slice()
this.storeOperationQueue = this.storeOperationQueue.then(() =>
this.store.set("danglingProviders", ids)
diff --git a/desktop/src/client/providers/providerCommands.ts b/desktop/src/client/providers/providerCommands.ts
index d30d6bf6db..da5211150d 100644
--- a/desktop/src/client/providers/providerCommands.ts
+++ b/desktop/src/client/providers/providerCommands.ts
@@ -15,6 +15,7 @@ import {
DEVPOD_COMMAND_LIST,
DEVPOD_COMMAND_OPTIONS,
DEVPOD_COMMAND_PROVIDER,
+ DEVPOD_COMMAND_RENAME,
DEVPOD_COMMAND_SET_OPTIONS,
DEVPOD_COMMAND_UPDATE,
DEVPOD_COMMAND_USE,
@@ -243,4 +244,23 @@ export class ProviderCommands {
return Return.Ok()
}
+
+ static async RenameProvider(oldName: TProviderID, newName: string) {
+ const result = await ProviderCommands.newCommand([
+ DEVPOD_COMMAND_PROVIDER,
+ DEVPOD_COMMAND_RENAME,
+ oldName,
+ newName,
+ DEVPOD_FLAG_JSON_LOG_OUTPUT,
+ ]).run()
+ if (result.err) {
+ return result
+ }
+
+ if (!isOk(result.val)) {
+ return getErrorFromChildProcess(result.val)
+ }
+
+ return Return.Ok()
+ }
}
diff --git a/desktop/src/client/repo.ts b/desktop/src/client/repo.ts
new file mode 100644
index 0000000000..4e14da47e2
--- /dev/null
+++ b/desktop/src/client/repo.ts
@@ -0,0 +1,21 @@
+export const REPO_OWNER = "skevetter"
+export const REPO_NAME = "devpod"
+export const REPO_SLUG = `${REPO_OWNER}/${REPO_NAME}`
+export const BINARY_NAME = REPO_NAME
+export const PRODUCT_NAME = "DevPod"
+export const PRODUCT_NAME_PRO = `${PRODUCT_NAME} Pro`
+export const PRO_RELEASE_NAME = `${REPO_NAME}-pro`
+export const PROVIDER_PREFIX = `${REPO_NAME}-provider-`
+export const SSH_HOST_SUFFIX = `.${BINARY_NAME}`
+
+export const GITHUB_REPO_URL = `https://github.com/${REPO_SLUG}`
+export const GITHUB_RELEASES_URL = `${GITHUB_REPO_URL}/releases`
+export const GITHUB_ISSUES_URL = `${GITHUB_REPO_URL}/issues/new/choose`
+export const WEBSITE_BASE_URL = `https://${REPO_NAME}.sh`
+export const WEBSITE_DOCS_URL = `${WEBSITE_BASE_URL}/docs`
+export const WEBSITE_PRO_URL = `${WEBSITE_BASE_URL}/pro`
+export const WEBSITE_ASSETS_URL = `${WEBSITE_BASE_URL}/assets`
+
+export const FLATPAK_ID = `sh.loft.${REPO_NAME}`
+export const CONTAINER_NAME = BINARY_NAME
+export const SHARED_MACHINE_PREFIX = `${BINARY_NAME}-shared-`
diff --git a/desktop/src/components/IDEIcon/IDEIcon.tsx b/desktop/src/components/IDEIcon/IDEIcon.tsx
index 3e45392819..e34ec58943 100644
--- a/desktop/src/components/IDEIcon/IDEIcon.tsx
+++ b/desktop/src/components/IDEIcon/IDEIcon.tsx
@@ -29,11 +29,15 @@ import {
RubyMineSvg,
RustRoverSvg,
VSCodeBrowser,
+ OpenVSCodeServerImg,
+ CodeServerSvg,
+ CodeServerDarkSvg,
VSCodeInsidersSvg,
VSCodeSvg,
WebstormSvg,
WindsurfSvg,
AntigravitySvg,
+ BobSvg,
ZedDarkSvg,
ZedSvg,
} from "@/images"
@@ -55,7 +59,7 @@ const IDE_ICONS: Record = {
none: NoneSvg,
vscode: VSCodeSvg,
"vscode-insiders": VSCodeInsidersSvg,
- openvscode: VSCodeBrowser,
+ openvscode: OpenVSCodeServerImg,
intellij: IntelliJSvg,
goland: GolandSvg,
rustrover: RustRoverSvg,
@@ -77,6 +81,10 @@ const IDE_ICONS: Record = {
rstudio: RStudioSvg,
windsurf: WindsurfSvg,
antigravity: AntigravitySvg,
+ bob: BobSvg,
+ "vscode-web": VSCodeBrowser,
+ "code-server": CodeServerSvg,
+ "code-server_dark": CodeServerDarkSvg,
}
type TIDEIconProps = Readonly<{ ide: TIDE; size?: "sm" | "md" }> & BoxProps
diff --git a/desktop/src/components/Layout/Notifications.tsx b/desktop/src/components/Layout/Notifications.tsx
index 7c2cdeeed6..ed036316f2 100644
--- a/desktop/src/components/Layout/Notifications.tsx
+++ b/desktop/src/components/Layout/Notifications.tsx
@@ -111,7 +111,9 @@ export function Notifications({
{pendingUpdate.tag_name} is available
See{" "}
- client.open(pendingUpdate.html_url)}>release notes
+ client.openUrl(pendingUpdate.html_url)}>
+ release notes
+