X Tutup
Skip to content

Commit a864985

Browse files
committed
use WaitGroup for a more idiomatic concurrency pattern
1 parent 81b34d2 commit a864985

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

pkg/cmd/codespace/ssh.go

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"os"
1414
"path/filepath"
1515
"strings"
16+
"sync"
1617
"text/template"
1718

1819
"github.com/MakeNowJust/heredoc"
@@ -199,7 +200,7 @@ func (a *App) printOpenSSHConfig(ctx context.Context, opts configOptions, execut
199200
}
200201

201202
sshUsers := make(chan sshResult)
202-
fetches := 0
203+
var wg sync.WaitGroup
203204
var status error
204205
for _, cs := range csList {
205206
if cs.State != "Available" && opts.codespace == "" {
@@ -209,35 +210,34 @@ func (a *App) printOpenSSHConfig(ctx context.Context, opts configOptions, execut
209210
}
210211

211212
cs := cs
212-
fetches += 1
213+
wg.Add(1)
213214
go func() {
214215
result := sshResult{}
215-
defer func() {
216-
select {
217-
case sshUsers <- result:
218-
case <-ctx.Done():
219-
}
220-
}()
216+
defer wg.Done()
221217

222218
session, err := codespaces.ConnectToLiveshare(ctx, a, noopLogger(), a.apiClient, cs)
223219
if err != nil {
224220
result.err = fmt.Errorf("error connecting to codespace: %w", err)
225-
return
226-
}
227-
defer session.Close()
228-
229-
//a.StartProgressIndicatorWithLabel(fmt.Sprintf("Fetching SSH Details for %s", cs.Name))
230-
_, result.user, err = session.StartSSHServer(ctx)
231-
//a.StopProgressIndicator()
232-
if err != nil {
233-
result.err = fmt.Errorf("error getting ssh server details: %w", err)
234-
return
221+
} else {
222+
defer session.Close()
223+
224+
_, result.user, err = session.StartSSHServer(ctx)
225+
if err != nil {
226+
result.err = fmt.Errorf("error getting ssh server details: %w", err)
227+
} else {
228+
result.codespace = cs
229+
}
235230
}
236231

237-
result.codespace = cs
232+
sshUsers <- result
238233
}()
239234
}
240235

236+
go func() {
237+
wg.Wait()
238+
close(sshUsers)
239+
}()
240+
241241
// While the above fetches are running, ensure that the user has keys installed.
242242
// That lets us report a more useful error message if they don't.
243243
if err = checkAuthorizedKeys(ctx, a.apiClient); err != nil {
@@ -258,8 +258,7 @@ func (a *App) printOpenSSHConfig(ctx context.Context, opts configOptions, execut
258258
return fmt.Errorf("error formatting template: %w", err)
259259
}
260260

261-
for i := 0; i < fetches; i++ {
262-
result := <-sshUsers
261+
for result := range sshUsers {
263262
if result.err != nil {
264263
fmt.Fprintf(os.Stderr, "%v\n", result.err)
265264
status = cmdutil.SilentError

0 commit comments

Comments
 (0)
X Tutup