pax_global_header00006660000000000000000000000064131344075750014523gustar00rootroot0000000000000052 comment=6240b64c5baac4be7f827b042afaa90e8fcfa439 schema-registry-0.1.0/000077500000000000000000000000001313440757500146275ustar00rootroot00000000000000schema-registry-0.1.0/.gitignore000066400000000000000000000000061313440757500166130ustar00rootroot00000000000000*.swp schema-registry-0.1.0/.travis.yml000066400000000000000000000000341313440757500167350ustar00rootroot00000000000000language: go go: - tip schema-registry-0.1.0/LICENSE000066400000000000000000000261351313440757500156430ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.schema-registry-0.1.0/README.md000066400000000000000000000041671313440757500161160ustar00rootroot00000000000000Confluent Kafka Schema Registry CLI and client ============================================== This repository contains a Command Line Interface (CLI) and a Go client for the REST API of Confluent's Kafka Schema Registry. [![Build Status](https://travis-ci.org/datamountaineer/schema-registry.svg?branch=master)](https://travis-ci.org/datamountaineer/schema-registry) [![GoDoc](https://godoc.org/github.com/datamountaineer/schema-registry?status.svg)](https://godoc.org/github.com/datamountaineer/schema-registry) CLI --- To install the CLI, assuming a properly setup Go installation, do: `go get github.com/datamountaineer/schema-registry/schema-registry-cli` After that, the CLI is found in `$GOPATH/bin/schema-registry-cli`. Running `schema-registry-cli` without arguments gives: ``` A command line interface for the Confluent schema registry Usage: schema-registry-cli [command] Available Commands: add registers the schema provided through stdin exists checks if the schema provided through stdin exists for the subject get retrieves a schema specified by id or subject subjects lists all registered subjects versions lists all available versions Flags: -h, --help help for schema-registry-cli -e, --url string schema registry url, overrides SCHEMA_REGISTRY_URL (default "http://localhost:8081") -v, --verbose be verbose Use "schema-registry-cli [command] --help" for more information about a command. ``` The schema registry url can be configured through the `SCHEMA_REGISTRY_URL` environment variable, and overridden through `--url`. When none is provided, `http://localhost:8081` is used as default. Client ------ The client package provides a client to deal with the registry from code. It is used by the CLI internally. Usage looks like: ```go import "github.com/datamountaineer/schema-registry" client, _ := schemaregistry.NewClient(schemaregistry.DefaultUrl) client.Subjects() ``` The documentation of the package can be found here: [![GoDoc](https://godoc.org/github.com/datamountaineer/schema-registry?status.svg)](https://godoc.org/github.com/datamountaineer/schema-registry) schema-registry-0.1.0/client.go000066400000000000000000000117151313440757500164410ustar00rootroot00000000000000// Package schemaregistry provides a client for Confluent's Kafka Schema Registry REST API. package schemaregistry import ( "encoding/json" "fmt" "io" "net/http" "net/url" "path" ) // DefaultUrl is the address where a local schema registry listens by default. var DefaultUrl = "http://localhost:8081" // These numbers are used by the schema registry to communicate errors. const ( subjectNotFound = 40401 schemaNotFound = 40403 ) // The Schema type is an object produced by the schema registry. type Schema struct { Schema string `json:"schema"` // The actual AVRO schema Subject string `json:"subject"` // Subject where the schema is registered for Version int `json:"version"` // Version within this subject Id int `json:"id"` // Registry's unique id } type simpleSchema struct { Schema string `json:"schema"` } // A ConfluentError is an error as communicated by the schema registry. // Some day this type might be exposed so that callers can do type assertions on it. type confluentError struct { ErrorCode int `json:"error_code"` Message string `json:"message"` } // Error makes confluentError implement the error interface. func (ce confluentError) Error() string { return fmt.Sprintf("%s (%d)", ce.Message, ce.ErrorCode) } type httpDoer interface { Do(req *http.Request) (resp *http.Response, err error) } // A Client is a client for the schema registry. type Client interface { Subjects() (subjects []string, err error) Versions(subject string) (versions []int, err error) RegisterNewSchema(subject, schema string) (int, error) IsRegistered(subject, schema string) (bool, Schema, error) GetSchemaById(id int) (string, error) GetSchemaBySubject(subject string, ver int) (s Schema, err error) GetLatestSchema(subject string) (s Schema, err error) } type client struct { url url.URL client httpDoer } func parseSchemaRegistryError(resp *http.Response) error { var ce confluentError if err := json.NewDecoder(resp.Body).Decode(&ce); err != nil { return err } return ce } // do performs http requests and json (de)serialization. func (c *client) do(method, urlPath string, in interface{}, out interface{}) error { u := c.url u.Path = path.Join(u.Path, urlPath) var rdp io.Reader if in != nil { var wr *io.PipeWriter rdp, wr = io.Pipe() go func() { wr.CloseWithError(json.NewEncoder(wr).Encode(in)) }() } req, err := http.NewRequest(method, u.String(), rdp) req.Header.Add("Accept", "application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json") if err != nil { return err } resp, err := c.client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return parseSchemaRegistryError(resp) } return json.NewDecoder(resp.Body).Decode(out) } // Subjects returns all registered subjects. func (c *client) Subjects() (subjects []string, err error) { err = c.do("GET", "subjects", nil, &subjects) return } // Versions returns all schema version numbers registered for this subject. func (c *client) Versions(subject string) (versions []int, err error) { err = c.do("GET", fmt.Sprintf("subjects/%s/versions", subject), nil, &versions) return } // RegisterNewSchema registers the given schema for this subject. func (c *client) RegisterNewSchema(subject, schema string) (int, error) { var resp struct { Id int `json:"id"` } err := c.do("POST", fmt.Sprintf("/subjects/%s/versions", subject), simpleSchema{schema}, &resp) return resp.Id, err } // IsRegistered tells if the given schema is registred for this subject. func (c *client) IsRegistered(subject, schema string) (bool, Schema, error) { var fs Schema err := c.do("POST", fmt.Sprintf("/subjects/%s", subject), simpleSchema{schema}, &fs) // schema not found? if ce, confluentErr := err.(confluentError); confluentErr && ce.ErrorCode == schemaNotFound { return false, fs, nil } // error? if err != nil { return false, fs, err } // so we have a schema then return true, fs, nil } // GetSchemaById returns the schema for some id. // The schema registry only provides the schema itself, not the id, subject or version. func (c *client) GetSchemaById(id int) (string, error) { var s Schema err := c.do("GET", fmt.Sprintf("/schemas/ids/%d", id), nil, &s) return s.Schema, err } // GetSchemaBySubject returns the schema for a particular subject and version. func (c *client) GetSchemaBySubject(subject string, ver int) (s Schema, err error) { err = c.do("GET", fmt.Sprintf("/subjects/%s/versions/%d", subject, ver), nil, &s) return } // GetLatestSchema returns the latest version of the subject's schema. func (c *client) GetLatestSchema(subject string) (s Schema, err error) { err = c.do("GET", fmt.Sprintf("/subjects/%s/versions/latest", subject), nil, &s) return } // NewClient returns a new Client that connects to baseurl. func NewClient(baseurl string) (Client, error) { u, err := url.Parse(baseurl) if err != nil { return nil, err } return &client{*u, http.DefaultClient}, nil } schema-registry-0.1.0/client_test.go000066400000000000000000000056621313440757500175040ustar00rootroot00000000000000package schemaregistry import ( "bytes" "encoding/json" "io/ioutil" "net/http" "net/url" "reflect" "strings" "testing" ) const testHost = "testhost:1337" const testUrl = "http://" + testHost type D func(req *http.Request) (*http.Response, error) func (d D) Do(req *http.Request) (*http.Response, error) { return d(req) } // verifies the http.Request, creates an http.Response func dummyHttpHandler(t *testing.T, method, path string, status int, reqBody, respBody interface{}) D { d := D(func(req *http.Request) (*http.Response, error) { if method != "" && req.Method != method { t.Errorf("method is wrong, expected `%s`, got `%s`", method, req.Method) } if req.URL.Host != testHost { t.Errorf("expected host `%s`, got `%s`", testHost, req.URL.Host) } if path != "" && req.URL.Path != path { t.Errorf("path is wrong, expected `%s`, got `%s`", path, req.URL.Path) } if reqBody != nil { expbs, err := json.Marshal(reqBody) if err != nil { t.Error(err) } bs, err := ioutil.ReadAll(req.Body) mustEqual(t, strings.Trim(string(bs), "\r\n"), strings.Trim(string(expbs), "\r\n")) } var resp http.Response resp.StatusCode = status if respBody != nil { bs, err := json.Marshal(respBody) if err != nil { t.Error(err) } resp.Body = ioutil.NopCloser(bytes.NewReader(bs)) } return &resp, nil }) return d } func getUrl() url.URL { u, err := url.Parse(testUrl) if err != nil { panic(err) } return *u } func httpSuccess(t *testing.T, method, path string, reqBody, respBody interface{}) Client { return &client{getUrl(), dummyHttpHandler(t, method, path, 200, reqBody, respBody)} } func httpError(t *testing.T, status, errCode int, errMsg string) Client { return &client{getUrl(), dummyHttpHandler(t, "", "", status, nil, confluentError{errCode, errMsg})} } func mustEqual(t *testing.T, actual, expected interface{}) { if !reflect.DeepEqual(actual, expected) { t.Errorf("expected `%#v`, got `%#v`", expected, actual) } } func TestSubjects(t *testing.T) { subsIn := []string{"rollulus", "hello-subject"} c := httpSuccess(t, "GET", "/subjects", nil, subsIn) subs, err := c.Subjects() if err != nil { t.Error() } mustEqual(t, subs, subsIn) } func TestVersions(t *testing.T) { versIn := []int{1, 2, 3} c := httpSuccess(t, "GET", "/subjects/mysubject/versions", nil, versIn) vers, err := c.Versions("mysubject") if err != nil { t.Error() } mustEqual(t, vers, versIn) } func TestIsRegistered_yes(t *testing.T) { s := `{"x":"y"}` ss := simpleSchema{s} sIn := Schema{s, "mysubject", 4, 7} c := httpSuccess(t, "POST", "/subjects/mysubject", ss, sIn) isreg, sOut, err := c.IsRegistered("mysubject", s) if err != nil { t.Error() } if !isreg { t.Error() } mustEqual(t, sOut, sIn) } func TestIsRegistered_not(t *testing.T) { c := httpError(t, 404, schemaNotFound, "too bad") isreg, _, err := c.IsRegistered("mysubject", "{}") if err != nil { t.Error() } if isreg { t.Error() } } schema-registry-0.1.0/mock.go000066400000000000000000000036761313440757500161230ustar00rootroot00000000000000package schemaregistry type MockClient struct { SubjectsFn func() (subjects []string, err error) VersionsFn func(subject string) (versions []int, err error) RegisterNewSchemaFn func(subject, schema string) (int, error) IsRegisteredFn func(subject, schema string) (bool, Schema, error) GetSchemaByIdFn func(id int) (string, error) GetSchemaBySubjectFn func(subject string, ver int) (Schema, error) GetLatestSchemaFn func(subject string) (Schema, error) } func (c *MockClient) Subjects() (subjects []string, err error) { return c.SubjectsFn() } func (c *MockClient) Versions(subject string) (versions []int, err error) { return c.VersionsFn(subject) } func (c *MockClient) RegisterNewSchema(subject, schema string) (int, error) { return c.RegisterNewSchemaFn(subject, schema) } func (c *MockClient) IsRegistered(subject, schema string) (bool, Schema, error) { return c.IsRegisteredFn(subject, schema) } func (c *MockClient) GetSchemaById(id int) (string, error) { return c.GetSchemaByIdFn(id) } func (c *MockClient) GetSchemaBySubject(subject string, ver int) (Schema, error) { return c.GetSchemaBySubjectFn(subject, ver) } func (c *MockClient) GetLatestSchema(subject string) (Schema, error) { return c.GetLatestSchemaFn(subject) } func NewNOOPClient() Client { return &MockClient{ SubjectsFn: func() (subjects []string, err error) { return []string{}, nil }, VersionsFn: func(subject string) (versions []int, err error) { return []int{}, nil }, RegisterNewSchemaFn: func(subject, schema string) (int, error) { return 0, nil }, IsRegisteredFn: func(subject, schema string) (bool, Schema, error) { return false, Schema{}, nil }, GetSchemaByIdFn: func(id int) (string, error) { return "", nil }, GetSchemaBySubjectFn: func(subject string, ver int) (Schema, error) { return Schema{}, nil }, GetLatestSchemaFn: func(subject string) (Schema, error) { return Schema{}, nil }, } } schema-registry-0.1.0/schema-registry-cli/000077500000000000000000000000001313440757500205025ustar00rootroot00000000000000schema-registry-0.1.0/schema-registry-cli/cmd/000077500000000000000000000000001313440757500212455ustar00rootroot00000000000000schema-registry-0.1.0/schema-registry-cli/cmd/add.go000066400000000000000000000011011313440757500223150ustar00rootroot00000000000000package cmd import ( "fmt" "log" "github.com/spf13/cobra" ) var addCmd = &cobra.Command{ Use: "add ", Short: "registers the schema provided through stdin", Long: ``, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf("expected 1 argument") } id, err := assertClient().RegisterNewSchema(args[0], stdinToString()) if err != nil { return err } log.Printf("registered schema with id %d\n", id) return nil }, } func init() { RootCmd.AddCommand(addCmd) } schema-registry-0.1.0/schema-registry-cli/cmd/exists.go000066400000000000000000000012031313440757500231070ustar00rootroot00000000000000package cmd import ( "fmt" "github.com/spf13/cobra" ) var existsCmd = &cobra.Command{ Use: "exists ", Short: "checks if the schema provided through stdin exists for the subject", Long: ``, RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf("expected 1 argument") } isreg, sch, err := assertClient().IsRegistered(args[0], stdinToString()) if err != nil { return err } fmt.Printf("exists: %v\n", isreg) if isreg { fmt.Printf("id: %d\n", sch.Id) fmt.Printf("version: %d\n", sch.Version) } return nil }, } func init() { RootCmd.AddCommand(existsCmd) } schema-registry-0.1.0/schema-registry-cli/cmd/get.go000066400000000000000000000021341313440757500223530ustar00rootroot00000000000000package cmd import ( "fmt" "strconv" "github.com/spf13/cobra" ) // get can handle three argument styles: , or var getCmd = &cobra.Command{ Use: "get | ( [])", Short: "retrieves a schema specified by id or subject", Long: `The schema can be requested by id or subject. When a subject is given, optionally one can provide a specific version. If no version is specified, the latest version is returned. `, RunE: func(cmd *cobra.Command, args []string) error { if len(args) < 1 || len(args) > 2 { return fmt.Errorf("expected 1 to 2 arguments") } id, idParseErr := strconv.Atoi(args[0]) var err error switch { case len(args) == 1 && idParseErr == nil: err = getById(id) case len(args) == 1 && idParseErr != nil: err = getLatestBySubject(args[0]) case len(args) == 2: ver, err := strconv.Atoi(args[1]) if err != nil { return fmt.Errorf("2nd argument must be a version number") } err = getBySubjectVersion(args[0], ver) default: return fmt.Errorf("?") } return err }, } func init() { RootCmd.AddCommand(getCmd) } schema-registry-0.1.0/schema-registry-cli/cmd/helpers.go000066400000000000000000000025031313440757500232360ustar00rootroot00000000000000package cmd import ( "bufio" "bytes" "encoding/json" "fmt" "io/ioutil" "log" "os" "github.com/datamountaineer/schema-registry" "github.com/spf13/viper" ) func stdinToString() string { bs, err := ioutil.ReadAll(bufio.NewReader(os.Stdin)) if err != nil { panic(err) } return string(bs) } func printSchema(sch schemaregistry.Schema) { log.Printf("version: %d\n", sch.Version) log.Printf("id: %d\n", sch.Id) var indented bytes.Buffer if err := json.Indent(&indented, []byte(sch.Schema), "", " "); err != nil { fmt.Println(sch.Schema) //isn't a json object, which is legal return } indented.WriteTo(os.Stdout) os.Stdout.WriteString("\n") } func getById(id int) error { cl := assertClient() sch, err := cl.GetSchemaById(id) if err != nil { return err } fmt.Println(sch) return nil } func getLatestBySubject(subj string) error { cl := assertClient() sch, err := cl.GetLatestSchema(subj) if err != nil { return err } printSchema(sch) return nil } func getBySubjectVersion(subj string, ver int) error { cl := assertClient() sch, err := cl.GetSchemaBySubject(subj, ver) if err != nil { return err } printSchema(sch) return nil } func assertClient() schemaregistry.Client { c, err := schemaregistry.NewClient(viper.GetString("url")) if err != nil { fmt.Println(err) os.Exit(-1) } return c } schema-registry-0.1.0/schema-registry-cli/cmd/root.go000066400000000000000000000024371313440757500225650ustar00rootroot00000000000000package cmd import ( "fmt" "io/ioutil" "log" "os" "github.com/datamountaineer/schema-registry" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string var registryUrl string var verbose bool = false // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ Use: "schema-registry-cli", Short: "A command line interface for the Confluent schema registry", Long: `A command line interface for the Confluent schema registry`, PersistentPreRun: func(cmd *cobra.Command, args []string) { if !verbose { log.SetOutput(ioutil.Discard) } log.Printf("schema registry url: %s\n", viper.Get("url")) }, } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "be verbose") RootCmd.PersistentFlags().StringVarP(®istryUrl, "url", "e", schemaregistry.DefaultUrl, "schema registry url, overrides SCHEMA_REGISTRY_URL") viper.SetEnvPrefix("schema_registry") viper.BindPFlag("url", RootCmd.PersistentFlags().Lookup("url")) viper.BindEnv("url") } schema-registry-0.1.0/schema-registry-cli/cmd/subjects.go000066400000000000000000000007321313440757500234200ustar00rootroot00000000000000package cmd import ( "fmt" "log" "github.com/spf13/cobra" ) var subjectsCmd = &cobra.Command{ Use: "subjects", Short: "lists all registered subjects", Long: ``, RunE: func(cmd *cobra.Command, args []string) error { subs, err := assertClient().Subjects() if err != nil { return err } log.Printf("there are %d subjects\n", len(subs)) for _, s := range subs { fmt.Println(s) } return nil }, } func init() { RootCmd.AddCommand(subjectsCmd) } schema-registry-0.1.0/schema-registry-cli/cmd/versions.go000066400000000000000000000007511313440757500234470ustar00rootroot00000000000000package cmd import ( "fmt" "github.com/spf13/cobra" ) var versionsCmd = &cobra.Command{ Use: "versions", Short: "lists all available versions", Long: ``, RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf("expected 1 argument") } client := assertClient() vers, err := client.Versions(args[0]) if err != nil { return err } fmt.Printf("%v\n", vers) return nil }, } func init() { RootCmd.AddCommand(versionsCmd) } schema-registry-0.1.0/schema-registry-cli/main.go000066400000000000000000000001721313440757500217550ustar00rootroot00000000000000package main import "github.com/datamountaineer/schema-registry/schema-registry-cli/cmd" func main() { cmd.Execute() }