github.com/Jeffail/benthos/v3@v3.65.0/internal/cli/studio/sync_schema.go (about) 1 package studio 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "net/http" 9 "net/url" 10 "os" 11 12 "github.com/Jeffail/benthos/v3/internal/config/schema" 13 "github.com/urfave/cli/v2" 14 ) 15 16 func syncSchemaCommand(version, dateBuilt string) *cli.Command { 17 return &cli.Command{ 18 Name: "sync-schema", 19 Usage: "Synchronizes the schema of this Benthos instance with a studio session", 20 Description: ` 21 This sync allows custom plugins and templates to be configured and linted 22 correctly within Benthos studio. 23 24 In order to synchronize a single use token must be generated from the session 25 page within the studio application.`[1:], 26 Flags: []cli.Flag{ 27 &cli.StringFlag{ 28 Name: "session", 29 Aliases: []string{"s"}, 30 Required: true, 31 Value: "", 32 Usage: "The session ID to synchronize with.", 33 }, 34 &cli.StringFlag{ 35 Name: "token", 36 Aliases: []string{"t"}, 37 Required: true, 38 Value: "", 39 Usage: "The single use token used to authenticate the request.", 40 }, 41 }, 42 Action: func(c *cli.Context) error { 43 endpoint := c.String("endpoint") 44 sessionID := c.String("session") 45 tokenID := c.String("token") 46 47 u, err := url.Parse(endpoint) 48 if err != nil { 49 fmt.Fprintf(os.Stderr, "Failed to parse endpoint: %v\n", err) 50 os.Exit(1) 51 } 52 u.Path = fmt.Sprintf("/api/v1/token/%v/session/%v/schema", tokenID, sessionID) 53 54 schema := schema.New(version, dateBuilt) 55 schema.Scrub() 56 schemaBytes, err := json.Marshal(schema) 57 if err != nil { 58 fmt.Fprintf(os.Stderr, "Failed to encode schema: %v\n", err) 59 os.Exit(1) 60 } 61 62 res, err := http.Post(u.String(), "application/json", bytes.NewReader(schemaBytes)) 63 if err != nil { 64 fmt.Fprintf(os.Stderr, "Sync request failed: %v\n", err) 65 os.Exit(1) 66 } 67 68 if res.StatusCode < 200 || res.StatusCode > 299 { 69 resBytes, _ := io.ReadAll(res.Body) 70 fmt.Fprintf(os.Stderr, "Sync request failed (%v): %v\n", res.StatusCode, string(resBytes)) 71 os.Exit(1) 72 } 73 return nil 74 }, 75 } 76 }