@@ -3,6 +3,7 @@ package cli
3
3
import (
4
4
"context"
5
5
"io"
6
+ "math/rand"
6
7
"net"
7
8
"os"
8
9
"strings"
@@ -23,21 +24,46 @@ import (
23
24
24
25
func ssh () * cobra.Command {
25
26
var (
26
- stdio bool
27
+ stdio bool
28
+ shuffle bool
27
29
)
28
30
cmd := & cobra.Command {
29
31
Use : "ssh <workspace>" ,
30
- Args : cobra .MinimumNArgs ( 1 ) ,
32
+ Args : cobra .ArbitraryArgs ,
31
33
RunE : func (cmd * cobra.Command , args []string ) error {
32
34
client , err := createClient (cmd )
33
35
if err != nil {
34
36
return err
35
37
}
36
38
37
- workspaceParts := strings .Split (args [0 ], "." )
38
- workspace , err := client .WorkspaceByName (cmd .Context (), codersdk .Me , workspaceParts [0 ])
39
- if err != nil {
40
- return err
39
+ var workspace codersdk.Workspace
40
+ var workspaceParts []string
41
+ if shuffle {
42
+ err := cobra .ExactArgs (0 )(cmd , args )
43
+ if err != nil {
44
+ return err
45
+ }
46
+
47
+ workspaces , err := client .WorkspacesByUser (cmd .Context (), codersdk .Me )
48
+ if err != nil {
49
+ return err
50
+ }
51
+ if len (workspaces ) == 0 {
52
+ return xerrors .New ("no workspaces to shuffle" )
53
+ }
54
+
55
+ workspace = workspaces [rand .Intn (len (workspaces ))]
56
+ } else {
57
+ err := cobra .MinimumNArgs (1 )(cmd , args )
58
+ if err != nil {
59
+ return err
60
+ }
61
+
62
+ workspaceParts = strings .Split (args [0 ], "." )
63
+ workspace , err = client .WorkspaceByName (cmd .Context (), codersdk .Me , workspaceParts [0 ])
64
+ if err != nil {
65
+ return err
66
+ }
41
67
}
42
68
43
69
if workspace .LatestBuild .Transition != database .WorkspaceTransitionStart {
@@ -82,9 +108,14 @@ func ssh() *cobra.Command {
82
108
}
83
109
if agent .ID == uuid .Nil {
84
110
if len (agents ) > 1 {
85
- return xerrors .New ("you must specify the name of an agent" )
111
+ if shuffle {
112
+ agent = agents [rand .Intn (len (agents ))]
113
+ } else {
114
+ return xerrors .New ("you must specify the name of an agent" )
115
+ }
116
+ } else {
117
+ agent = agents [0 ]
86
118
}
87
- agent = agents [0 ]
88
119
}
89
120
// OpenSSH passes stderr directly to the calling TTY.
90
121
// This is required in "stdio" mode so a connecting indicator can be displayed.
@@ -159,6 +190,8 @@ func ssh() *cobra.Command {
159
190
},
160
191
}
161
192
cliflag .BoolVarP (cmd .Flags (), & stdio , "stdio" , "" , "CODER_SSH_STDIO" , false , "Specifies whether to emit SSH output over stdin/stdout." )
193
+ cliflag .BoolVarP (cmd .Flags (), & shuffle , "shuffle" , "" , "CODER_SSH_SHUFFLE" , false , "Specifies whether to choose a random workspace" )
194
+ cmd .Flags ().MarkHidden ("shuffle" )
162
195
163
196
return cmd
164
197
}
0 commit comments