|
| 1 | +// Copyright (c) 2022 Gitpod GmbH. All rights reserved. |
| 2 | +// Licensed under the GNU Affero General Public License (AGPL). |
| 3 | +// See License-AGPL.txt in the project root for license information. |
| 4 | + |
| 5 | +package cmd |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "log" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | + |
| 15 | + gitpod "github.com/gitpod-io/gitpod/gitpod-cli/pkg/gitpod" |
| 16 | + serverapi "github.com/gitpod-io/gitpod/gitpod-protocol" |
| 17 | + "github.com/spf13/cobra" |
| 18 | +) |
| 19 | + |
| 20 | +// portsVisibilityCmd change visibility of port |
| 21 | +var portsVisibilityCmd = &cobra.Command{ |
| 22 | + Use: "visibility <port>[:private][:public]", |
| 23 | + Short: "Make a port public or private", |
| 24 | + Args: cobra.ExactArgs(1), |
| 25 | + Run: func(cmd *cobra.Command, args []string) { |
| 26 | + portVisibility := args[0] |
| 27 | + s := strings.Split(portVisibility, ":") |
| 28 | + if len(s) != 2 { |
| 29 | + log.Fatal("cannot parse args, should be something like `3000:public` or `3000:private`") |
| 30 | + } |
| 31 | + port, err := strconv.Atoi(s[0]) |
| 32 | + if err != nil { |
| 33 | + log.Fatal("port should be integer") |
| 34 | + } |
| 35 | + visibility := s[1] |
| 36 | + if visibility != serverapi.PortVisibilityPublic && visibility != serverapi.PortVisibilityPrivate { |
| 37 | + log.Fatalf("visibility should be `%s` or `%s`", serverapi.PortVisibilityPublic, serverapi.PortVisibilityPrivate) |
| 38 | + } |
| 39 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 40 | + defer cancel() |
| 41 | + |
| 42 | + wsInfo, err := gitpod.GetWSInfo(ctx) |
| 43 | + if err != nil { |
| 44 | + log.Fatalf("cannot get workspace info, %s", err.Error()) |
| 45 | + } |
| 46 | + client, err := gitpod.ConnectToServer(ctx, wsInfo, []string{ |
| 47 | + "function:openPort", |
| 48 | + "resource:workspace::" + wsInfo.WorkspaceId + "::get/update", |
| 49 | + }) |
| 50 | + if err != nil { |
| 51 | + log.Fatalf("cannot connect to server, %s", err.Error()) |
| 52 | + } |
| 53 | + if _, err := client.OpenPort(ctx, wsInfo.WorkspaceId, &serverapi.WorkspaceInstancePort{ |
| 54 | + Port: float64(port), |
| 55 | + Visibility: visibility, |
| 56 | + }); err != nil { |
| 57 | + log.Fatalf("failed to change port visibility: %s", err.Error()) |
| 58 | + } |
| 59 | + fmt.Printf("port %v is now %s\n", port, visibility) |
| 60 | + }, |
| 61 | +} |
| 62 | + |
| 63 | +func init() { |
| 64 | + portsCmd.AddCommand(portsVisibilityCmd) |
| 65 | +} |
0 commit comments