diff --git a/Makefile b/Makefile index 74931727..ba53e3eb 100644 --- a/Makefile +++ b/Makefile @@ -21,18 +21,11 @@ setup: deps devtools ## Set up dev env .PHONY: generate-mocks generate-mocks: ## Generate mock objects @echo "==> Generating mock objects" - go install github.com/vektra/mockery/v2@v2.43.0 + go install github.com/vektra/mockery/v2@v2.53.5 mockery --name TiDBCloudClient --recursive --output=internal/mock --outpkg mock --filename api_client.go mockery --name EventsSender --recursive --output=internal/mock --outpkg mock --filename sender.go mockery --name Uploader --recursive --output=internal/mock --outpkg mock --filename uploader.go -.PHONY: generate-pingchat-client -generate-pingchat-client: ## Generate PingChat client - @echo "==> Generating PingChat client" - rm -rf pkg/tidbcloud/pingchat - cd tools/openapi-generator && npx openapi-generator-cli generate --inline-schema-options RESOLVE_INLINE_ENUMS=true --additional-properties=withGoMod=false,enumClassPrefix=true --global-property=apiTests=false,apiDocs=false,modelDocs=false,modelTests=false -i ../../pkg/tidbcloud/pingchat.swagger.json -g go -o ../../pkg/tidbcloud/pingchat --package-name pingchat -c go/config.yaml - cd pkg && go fmt ./tidbcloud/pingchat/... && goimports -w . - .PHONY: addcopy addcopy: ## Add copyright to all files @scripts/add-copy.sh diff --git a/go.mod b/go.mod index 5dab150e..be5bf827 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,6 @@ module github.com/tidbcloud/tidbcloud-cli -go 1.23.0 - -toolchain go1.23.1 +go 1.24 require ( github.com/AlecAivazis/survey/v2 v2.3.6 @@ -39,7 +37,7 @@ require ( go.einride.tech/aip v0.67.1 go.uber.org/zap v1.27.0 golang.org/x/oauth2 v0.27.0 - golang.org/x/sys v0.31.0 + golang.org/x/sys v0.35.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -111,12 +109,13 @@ require ( github.com/yuin/goldmark v1.6.0 // indirect github.com/yuin/goldmark-emoji v1.0.2 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/crypto v0.36.0 // indirect + golang.org/x/crypto v0.41.0 // indirect golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 // indirect - golang.org/x/net v0.38.0 // indirect - golang.org/x/sync v0.12.0 // indirect - golang.org/x/term v0.30.0 // indirect - golang.org/x/text v0.23.0 // indirect + golang.org/x/net v0.43.0 // indirect + golang.org/x/sync v0.16.0 // indirect + golang.org/x/term v0.34.0 // indirect + golang.org/x/text v0.28.0 // indirect + golang.org/x/tools v0.36.0 // indirect google.golang.org/protobuf v1.34.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect diff --git a/go.sum b/go.sum index 8b9cf962..0ae39582 100644 --- a/go.sum +++ b/go.sum @@ -723,15 +723,15 @@ go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 h1:LoYXNGAShUG3m/ehNk4iFctuhGX/+R1ZpfJ4/ia80JM= golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= -golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= +golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= @@ -740,15 +740,15 @@ golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfS golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= -golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= -golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= +golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= -golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= +golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -763,24 +763,24 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= -golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210503060354-a79de5458b56/go.mod h1:tfny5GFUkzUvx4ps4ajbZsCe5lw1metzhBm9T3x7oIY= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= -golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y= -golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g= +golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4= +golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= -golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= @@ -791,8 +791,8 @@ golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= -golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= +golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg= +golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU= diff --git a/internal/cli/ai/ai.go b/internal/cli/ai/ai.go deleted file mode 100644 index b3ab9301..00000000 --- a/internal/cli/ai/ai.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2025 PingCAP, Inc. -// -// 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. - -package ai - -import ( - "fmt" - "regexp" - - "github.com/tidbcloud/tidbcloud-cli/internal" - "github.com/tidbcloud/tidbcloud-cli/internal/config" - "github.com/tidbcloud/tidbcloud-cli/internal/flag" - "github.com/tidbcloud/tidbcloud-cli/internal/output" - "github.com/tidbcloud/tidbcloud-cli/internal/ui" - "github.com/tidbcloud/tidbcloud-cli/internal/util" - "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/pingchat" - - tea "github.com/charmbracelet/bubbletea" - "github.com/pingcap/errors" - "github.com/spf13/cobra" -) - -const ( - regexPattern = `\[\^(\d+)\]` -) - -var ( - re = regexp.MustCompile(regexPattern) - domain = []pingchat.PingchatChatInfoDomainInner{"tidbcloud"} -) - -type AIOpts struct { - interactive bool -} - -func (o AIOpts) NonInteractiveFlags() []string { - return []string{ - flag.Query, - } -} - -func AICmd(h *internal.Helper) *cobra.Command { - opts := AIOpts{ - interactive: true, - } - - cmd := &cobra.Command{ - Use: "ai", - Short: "Chat with TiDB Bot", - Args: cobra.NoArgs, - Annotations: make(map[string]string), - Example: fmt.Sprintf(` Chat with TiDB Bot in interactive mode: - $ %[1]s ai - - Chat with TiDB Bot in non-interactive mode: - $ %[1]s ai -q "How to create a cluster?"`, - config.CliName), - PreRunE: func(cmd *cobra.Command, args []string) error { - flags := opts.NonInteractiveFlags() - for _, fn := range flags { - f := cmd.Flags().Lookup(fn) - if f != nil && f.Changed { - opts.interactive = false - } - } - - // mark required flags in non-interactive mode - if !opts.interactive { - for _, fn := range flags { - err := cmd.MarkFlagRequired(fn) - if err != nil { - return errors.Trace(err) - } - } - } - - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - client, err := h.Client() - if err != nil { - return err - } - - context := cmd.Context() - if opts.interactive { - task := func(messages []ui.ChatMessage) tea.Msg { - msgs := make([]pingchat.PingchatChatMessage, 0, len(messages)) - for _, message := range messages { - content := message.Content - role, err := convertRole(message.Role) - if err != nil { - return ui.EndSendingMsg{ - Err: err, - } - } - msg := pingchat.PingchatChatMessage{ - Content: content, - Role: role, - } - msgs = append(msgs, msg) - } - chat, err := client.Chat(context, &pingchat.PingchatChatInfo{ - Messages: msgs, - Domain: domain, - }) - - if err != nil { - return ui.EndSendingMsg{ - Err: err, - } - } - - linkContent := "\n\n" - for i, link := range chat.Links { - linkContent = fmt.Sprintf("%s[%d] [%s](%s)\n", linkContent, i+1, *link.Title, *link.Link) - } - - // Replace occurrences of [^\d+] with [\d+] for better user comprehension. - content := re.ReplaceAllString(*chat.Content, "[$1]") - - return ui.EndSendingMsg{ - Msg: ui.ChatMessage{ - Role: ui.RoleBot, - Content: content, - LinkContent: linkContent, - }, - } - } - - model := ui.InitialChatBoxModel(task, "TiDB Bot") - p := tea.NewProgram(model, - tea.WithAltScreen(), // use the full size of the terminal in its "alternate screen buffer" - ) - typeModel, err := p.Run() - if err != nil { - return err - } - if m, _ := typeModel.(ui.ChatBoxModel); m.Interrupted { - return util.InterruptError - } - if m, _ := typeModel.(ui.ChatBoxModel); m.Err != nil { - return m.Err - } - } else { - query, err := cmd.Flags().GetString(flag.Query) - if err != nil { - return errors.Trace(err) - } - - chat, err := client.Chat(context, &pingchat.PingchatChatInfo{ - Messages: []pingchat.PingchatChatMessage{ - { - Content: query, - Role: pingchat.PINGCHATCHATMESSAGEROLE_USER, - }, - }, - Domain: domain, - }) - if err != nil { - return err - } - - err = output.PrintJson(h.IOStreams.Out, chat) - return errors.Trace(err) - } - - return nil - }, - } - - cmd.Flags().StringP(flag.Query, flag.QueryShort, "", "The query to chat with TiDB Bot.") - return cmd -} - -func convertRole(role ui.Role) (pingchat.PingchatChatMessageRole, error) { - switch role { - case ui.RoleUser: - return pingchat.PINGCHATCHATMESSAGEROLE_USER, nil - case ui.RoleBot: - return pingchat.PINGCHATCHATMESSAGEROLE_ASSISTANT, nil - default: - return "", errors.New("unknown chat role") - } -} diff --git a/internal/cli/ai/ai_test.go b/internal/cli/ai/ai_test.go deleted file mode 100644 index 5fb8be93..00000000 --- a/internal/cli/ai/ai_test.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2025 PingCAP, Inc. -// -// 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. - -package ai - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "os" - "testing" - - "github.com/tidbcloud/tidbcloud-cli/internal" - "github.com/tidbcloud/tidbcloud-cli/internal/iostream" - "github.com/tidbcloud/tidbcloud-cli/internal/mock" - "github.com/tidbcloud/tidbcloud-cli/internal/service/cloud" - "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/pingchat" - - mockTool "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" -) - -type AISuite struct { - suite.Suite - h *internal.Helper - mockClient *mock.TiDBCloudClient -} - -func (suite *AISuite) SetupTest() { - if err := os.Setenv("NO_COLOR", "true"); err != nil { - suite.T().Error(err) - } - - suite.mockClient = new(mock.TiDBCloudClient) - suite.h = &internal.Helper{ - Client: func() (cloud.TiDBCloudClient, error) { - return suite.mockClient, nil - }, - IOStreams: iostream.Test(), - } -} - -func (suite *AISuite) TestAIArgs() { - assert := require.New(suite.T()) - - link := "https://tidbcloud.com" - links := []pingchat.PingchatLink{ - { - Link: &link, - }, - } - answer := "hello" - chatResp := &pingchat.PingchatChatResponse{ - Content: &answer, - Links: links, - } - - res, _ := json.MarshalIndent(chatResp, "", " ") - - suite.mockClient.On("Chat", context.Background(), mockTool.Anything).Return(chatResp, nil) - - tests := []struct { - name string - args []string - err error - stdoutString string - stderrString string - }{ - { - name: "chat success", - args: []string{"--query", "hello"}, - stdoutString: string(res) + "\n", - }, - { - name: "chat succes with shorthand flag", - args: []string{"-q", "hello"}, - stdoutString: string(res) + "\n", - }, - { - name: "with unknown flag", - args: []string{"--cluster-name", "test"}, - err: fmt.Errorf("unknown flag: --cluster-name"), - }, - } - - for _, tt := range tests { - suite.T().Run(tt.name, func(t *testing.T) { - cmd := AICmd(suite.h) - suite.h.IOStreams.Out.(*bytes.Buffer).Reset() - suite.h.IOStreams.Err.(*bytes.Buffer).Reset() - cmd.SetArgs(tt.args) - err := cmd.Execute() - assert.Equal(tt.err, err) - - assert.Equal(tt.stdoutString, suite.h.IOStreams.Out.(*bytes.Buffer).String()) - assert.Equal(tt.stderrString, suite.h.IOStreams.Err.(*bytes.Buffer).String()) - if tt.err == nil { - suite.mockClient.AssertExpectations(suite.T()) - } - }) - } -} - -func TestAISuite(t *testing.T) { - suite.Run(t, new(AISuite)) -} diff --git a/internal/cli/config/set.go b/internal/cli/config/set.go index ae8111f1..dcc0d472 100644 --- a/internal/cli/config/set.go +++ b/internal/cli/config/set.go @@ -54,7 +54,7 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) return fmt.Errorf("no profile is configured, please use `config create` to create a profile") } - if propertyName == prop.ApiUrl || propertyName == prop.ServerlessEndpoint { + if propertyName == prop.IAMEndpoint || propertyName == prop.ServerlessEndpoint || propertyName == prop.OAuthEndpoint { _, err := prop.ValidateApiUrl(value) if err != nil { return err diff --git a/internal/cli/config/set_test.go b/internal/cli/config/set_test.go index 4d72eb49..f5dd398e 100644 --- a/internal/cli/config/set_test.go +++ b/internal/cli/config/set_test.go @@ -100,7 +100,7 @@ func (suite *SetConfigSuite) TestSetConfigArgs() { }, { name: "set config with unknown property", - args: []string{"api-url", "baidu.com"}, + args: []string{"serverless-endpoint", "baidu.com"}, err: errors.Annotate(&url.Error{ Op: "parse", URL: "baidu.com", diff --git a/internal/cli/root.go b/internal/cli/root.go index 7be703d8..c5072913 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -22,7 +22,6 @@ import ( "strings" "github.com/tidbcloud/tidbcloud-cli/internal" - "github.com/tidbcloud/tidbcloud-cli/internal/cli/ai" "github.com/tidbcloud/tidbcloud-cli/internal/cli/auth" configCmd "github.com/tidbcloud/tidbcloud-cli/internal/cli/config" "github.com/tidbcloud/tidbcloud-cli/internal/cli/project" @@ -57,11 +56,6 @@ func Execute(ctx context.Context) { h := &internal.Helper{ Client: func() (cloud.TiDBCloudClient, error) { publicKey, privateKey := config.GetPublicKey(), config.GetPrivateKey() - apiUrl := config.GetApiUrl() - // If the user has not set the api url, use the default one. - if apiUrl == "" { - apiUrl = cloud.DefaultApiUrl - } serverlessEndpoint := config.GetServerlessEndpoint() if serverlessEndpoint == "" { serverlessEndpoint = cloud.DefaultServerlessEndpoint @@ -74,7 +68,7 @@ func Execute(ctx context.Context) { var delegate cloud.TiDBCloudClient if publicKey != "" && privateKey != "" { var err error - delegate, err = cloud.NewClientDelegateWithApiKey(publicKey, privateKey, apiUrl, serverlessEndpoint, iamEndpoint) + delegate, err = cloud.NewClientDelegateWithApiKey(publicKey, privateKey, serverlessEndpoint, iamEndpoint) if err != nil { return nil, err } @@ -93,7 +87,7 @@ func Execute(ctx context.Context) { } return nil, err } - delegate, err = cloud.NewClientDelegateWithToken(token, apiUrl, serverlessEndpoint, iamEndpoint) + delegate, err = cloud.NewClientDelegateWithToken(token, serverlessEndpoint, iamEndpoint) if err != nil { return nil, err } @@ -201,7 +195,6 @@ func RootCmd(h *internal.Helper) *cobra.Command { rootCmd.AddCommand(auth.AuthCmd(h)) rootCmd.AddCommand(configCmd.ConfigCmd(h)) rootCmd.AddCommand(serverless.Cmd(h)) - rootCmd.AddCommand(ai.AICmd(h)) rootCmd.AddCommand(project.ProjectCmd(h)) rootCmd.AddCommand(version.VersionCmd(h)) rootCmd.AddCommand(upgrade.Cmd(h)) diff --git a/internal/cli/serverless/export/download_without_prompt.go b/internal/cli/serverless/export/download_without_prompt.go index 832c7006..0f6c0984 100644 --- a/internal/cli/serverless/export/download_without_prompt.go +++ b/internal/cli/serverless/export/download_without_prompt.go @@ -104,7 +104,7 @@ func (d *downloadPool) Start() error { if pathName == "" { pathName = "current folder" } - fmt.Fprintf(d.h.IOStreams.Out, color.GreenString("start to download files to %s:\n", pathName)) + fmt.Fprintf(d.h.IOStreams.Out, "%s\n", color.GreenString("start to download files to "+pathName)) // start produce go d.produce() // start consumers: @@ -131,7 +131,7 @@ func (d *downloadPool) Start() error { } downloadResults = append(downloadResults, result) } - fmt.Fprintf(d.h.IOStreams.Out, GenerateDownloadSummary(succeededCount, skippedCount, failedCount)) + fmt.Fprintf(d.h.IOStreams.Out, "%s\n", GenerateDownloadSummary(succeededCount, skippedCount, failedCount)) index := 0 for _, f := range downloadResults { if f.status != Succeeded { diff --git a/internal/config/profile.go b/internal/config/profile.go index 15ec18a7..126745fd 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -113,12 +113,6 @@ func (p *Profile) GetPrivateKey() (privateKey string) { return } -func GetApiUrl() (apiUrl string) { return activeProfile.GetApiUrl() } -func (p *Profile) GetApiUrl() (apiUrl string) { - apiUrl = viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.ApiUrl)) - return -} - func GetServerlessEndpoint() (apiUrl string) { return activeProfile.GetServerlessEndpoint() } func (p *Profile) GetServerlessEndpoint() (newApiUrl string) { newApiUrl = viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.ServerlessEndpoint)) diff --git a/internal/mock/api_client.go b/internal/mock/api_client.go index a211a921..815a83f9 100644 --- a/internal/mock/api_client.go +++ b/internal/mock/api_client.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.43.0. DO NOT EDIT. +// Code generated by mockery v2.53.5. DO NOT EDIT. package mock @@ -19,8 +19,6 @@ import ( imp "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless/imp" mock "github.com/stretchr/testify/mock" - - pingchat "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/pingchat" ) // TiDBCloudClient is an autogenerated mock type for the TiDBCloudClient type @@ -94,36 +92,6 @@ func (_m *TiDBCloudClient) CancelUpload(ctx context.Context, clusterId string, u return r0 } -// Chat provides a mock function with given fields: ctx, chatInfo -func (_m *TiDBCloudClient) Chat(ctx context.Context, chatInfo *pingchat.PingchatChatInfo) (*pingchat.PingchatChatResponse, error) { - ret := _m.Called(ctx, chatInfo) - - if len(ret) == 0 { - panic("no return value specified for Chat") - } - - var r0 *pingchat.PingchatChatResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *pingchat.PingchatChatInfo) (*pingchat.PingchatChatResponse, error)); ok { - return rf(ctx, chatInfo) - } - if rf, ok := ret.Get(0).(func(context.Context, *pingchat.PingchatChatInfo) *pingchat.PingchatChatResponse); ok { - r0 = rf(ctx, chatInfo) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*pingchat.PingchatChatResponse) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *pingchat.PingchatChatInfo) error); ok { - r1 = rf(ctx, chatInfo) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // CompleteUpload provides a mock function with given fields: ctx, clusterId, uploadId, parts func (_m *TiDBCloudClient) CompleteUpload(ctx context.Context, clusterId string, uploadId *string, parts *[]imp.CompletePart) error { ret := _m.Called(ctx, clusterId, uploadId, parts) diff --git a/internal/mock/sender.go b/internal/mock/sender.go index 5defa82a..b13c700a 100644 --- a/internal/mock/sender.go +++ b/internal/mock/sender.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.43.0. DO NOT EDIT. +// Code generated by mockery v2.53.5. DO NOT EDIT. package mock diff --git a/internal/mock/uploader.go b/internal/mock/uploader.go index bc417f52..701a0a4c 100644 --- a/internal/mock/uploader.go +++ b/internal/mock/uploader.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.43.0. DO NOT EDIT. +// Code generated by mockery v2.53.5. DO NOT EDIT. package mock diff --git a/internal/prop/property.go b/internal/prop/property.go index fc2f8849..0bf9b383 100644 --- a/internal/prop/property.go +++ b/internal/prop/property.go @@ -24,7 +24,6 @@ const ( PublicKey string = "public-key" PrivateKey string = "private-key" CurProfile string = "current-profile" - ApiUrl string = "api-url" ServerlessEndpoint string = "serverless-endpoint" IAMEndpoint string = "iam-endpoint" OAuthEndpoint string = "oauth-endpoint" @@ -43,7 +42,7 @@ func GlobalProperties() []string { } func ProfileProperties() []string { - return []string{PublicKey, PrivateKey, ApiUrl, ServerlessEndpoint, IAMEndpoint, OAuthEndpoint, OAuthClientID, OAuthClientSecret, TelemetryEnabled} + return []string{PublicKey, PrivateKey, ServerlessEndpoint, IAMEndpoint, OAuthEndpoint, OAuthClientID, OAuthClientSecret, TelemetryEnabled} } func ValidateApiUrl(value string) (*url.URL, error) { diff --git a/internal/service/aws/s3/uploader.go b/internal/service/aws/s3/uploader.go index 31c94447..0da5269e 100644 --- a/internal/service/aws/s3/uploader.go +++ b/internal/service/aws/s3/uploader.go @@ -495,7 +495,7 @@ func (u *multiUploader) shouldContinue(part int32, nextChunkLen int, err error) msg = fmt.Sprintf("exceeded total allowed S3 limit MaxUploadParts (%d). Adjust PartSize to fit in this limit", MaxUploadParts) } - return false, fmt.Errorf(msg) + return false, errors.New(msg) } return true, err diff --git a/internal/service/cloud/api_client.go b/internal/service/cloud/api_client.go index a5605e9a..3b22db26 100644 --- a/internal/service/cloud/api_client.go +++ b/internal/service/cloud/api_client.go @@ -26,7 +26,6 @@ import ( "github.com/tidbcloud/tidbcloud-cli/internal/config" "github.com/tidbcloud/tidbcloud-cli/internal/prop" "github.com/tidbcloud/tidbcloud-cli/internal/version" - "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/pingchat" "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/v1beta1/iam" "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless/auditlog" "github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless/br" @@ -39,7 +38,6 @@ import ( ) const ( - DefaultApiUrl = "https://api.tidbcloud.com" DefaultServerlessEndpoint = "https://serverless.tidbapi.com" DefaultIAMEndpoint = "https://iam.tidbapi.com" ) @@ -77,8 +75,6 @@ type TiDBCloudClient interface { ResetBranch(ctx context.Context, clusterId string, branchId string) (*branch.Branch, error) - Chat(ctx context.Context, chatInfo *pingchat.PingchatChatInfo) (*pingchat.PingchatChatResponse, error) - DeleteBackup(ctx context.Context, backupId string) (*br.V1beta1Backup, error) GetBackup(ctx context.Context, backupId string) (*br.V1beta1Backup, error) @@ -139,7 +135,6 @@ type TiDBCloudClient interface { type ClientDelegate struct { ic *iam.APIClient bc *branch.APIClient - pc *pingchat.APIClient brc *br.APIClient sc *cluster.APIClient sic *imp.APIClient @@ -147,16 +142,15 @@ type ClientDelegate struct { alc *auditlog.APIClient } -func NewClientDelegateWithToken(token string, apiUrl string, serverlessEndpoint string, iamEndpoint string) (*ClientDelegate, error) { +func NewClientDelegateWithToken(token string, serverlessEndpoint string, iamEndpoint string) (*ClientDelegate, error) { transport := NewBearTokenTransport(token) - bc, sc, pc, brc, sic, ec, ic, alc, err := NewApiClient(transport, apiUrl, serverlessEndpoint, iamEndpoint) + bc, sc, brc, sic, ec, ic, alc, err := NewApiClient(transport, serverlessEndpoint, iamEndpoint) if err != nil { return nil, err } return &ClientDelegate{ bc: bc, sc: sc, - pc: pc, brc: brc, ec: ec, ic: ic, @@ -165,16 +159,15 @@ func NewClientDelegateWithToken(token string, apiUrl string, serverlessEndpoint }, nil } -func NewClientDelegateWithApiKey(publicKey string, privateKey string, apiUrl string, serverlessEndpoint string, iamEndpoint string) (*ClientDelegate, error) { +func NewClientDelegateWithApiKey(publicKey string, privateKey string, serverlessEndpoint string, iamEndpoint string) (*ClientDelegate, error) { transport := NewDigestTransport(publicKey, privateKey) - bc, sc, pc, brc, sic, ec, ic, alc, err := NewApiClient(transport, apiUrl, serverlessEndpoint, iamEndpoint) + bc, sc, brc, sic, ec, ic, alc, err := NewApiClient(transport, serverlessEndpoint, iamEndpoint) if err != nil { return nil, err } return &ClientDelegate{ bc: bc, sc: sc, - pc: pc, brc: brc, ec: ec, ic: ic, @@ -323,15 +316,6 @@ func (d *ClientDelegate) ResetBranch(ctx context.Context, clusterId string, bran return b, parseError(err, h) } -func (d *ClientDelegate) Chat(ctx context.Context, chatInfo *pingchat.PingchatChatInfo) (*pingchat.PingchatChatResponse, error) { - r := d.pc.PingChatServiceAPI.Chat(ctx) - if chatInfo != nil { - r = r.ChatInfo(*chatInfo) - } - resp, h, err := r.Execute() - return resp, parseError(err, h) -} - func (d *ClientDelegate) DeleteBackup(ctx context.Context, backupId string) (*br.V1beta1Backup, error) { b, h, err := d.brc.BackupRestoreServiceAPI.BackupRestoreServiceDeleteBackup(ctx, backupId).Execute() return b, parseError(err, h) @@ -582,26 +566,20 @@ func (d *ClientDelegate) GetAuditLogConfig(ctx context.Context, clusterID string return res, parseError(err, h) } -func NewApiClient(rt http.RoundTripper, apiUrl string, serverlessEndpoint string, iamEndpoint string) (*branch.APIClient, *cluster.APIClient, *pingchat.APIClient, *br.APIClient, *imp.APIClient, *export.APIClient, *iam.APIClient, *auditlog.APIClient, error) { +func NewApiClient(rt http.RoundTripper, serverlessEndpoint string, iamEndpoint string) (*branch.APIClient, *cluster.APIClient, *br.APIClient, *imp.APIClient, *export.APIClient, *iam.APIClient, *auditlog.APIClient, error) { httpclient := &http.Client{ Transport: rt, } - // v1beta api - u, err := prop.ValidateApiUrl(apiUrl) - if err != nil { - return nil, nil, nil, nil, nil, nil, nil, nil, err - } - // v1beta1 api (serverless) serverlessURL, err := prop.ValidateApiUrl(serverlessEndpoint) if err != nil { - return nil, nil, nil, nil, nil, nil, nil, nil, err + return nil, nil, nil, nil, nil, nil, nil, err } iamURL, err := prop.ValidateApiUrl(iamEndpoint) if err != nil { - return nil, nil, nil, nil, nil, nil, nil, nil, err + return nil, nil, nil, nil, nil, nil, nil, err } userAgent := fmt.Sprintf("%s/%s", config.CliName, version.Version) @@ -636,18 +614,13 @@ func NewApiClient(rt http.RoundTripper, apiUrl string, serverlessEndpoint string backupRestoreCfg.Host = serverlessURL.Host backupRestoreCfg.UserAgent = userAgent - pingchatCfg := pingchat.NewConfiguration() - pingchatCfg.HTTPClient = httpclient - pingchatCfg.Host = u.Host - pingchatCfg.UserAgent = userAgent - auditLogCfg := auditlog.NewConfiguration() auditLogCfg.HTTPClient = httpclient auditLogCfg.Host = serverlessURL.Host auditLogCfg.UserAgent = userAgent return branch.NewAPIClient(branchCfg), cluster.NewAPIClient(clusterCfg), - pingchat.NewAPIClient(pingchatCfg), br.NewAPIClient(backupRestoreCfg), + br.NewAPIClient(backupRestoreCfg), imp.NewAPIClient(importCfg), export.NewAPIClient(exportCfg), iam.NewAPIClient(iamCfg), auditlog.NewAPIClient(auditLogCfg), nil } diff --git a/pkg/go.mod b/pkg/go.mod index e36c610b..2296cd86 100644 --- a/pkg/go.mod +++ b/pkg/go.mod @@ -1,3 +1,3 @@ module github.com/tidbcloud/tidbcloud-cli/pkg -go 1.23 +go 1.24 diff --git a/pkg/tidbcloud/pingchat.swagger.json b/pkg/tidbcloud/pingchat.swagger.json deleted file mode 100644 index 82494260..00000000 --- a/pkg/tidbcloud/pingchat.swagger.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "schemes": [ - "https" - ], - "swagger": "2.0", - "info": { - "title": "PingChat Swagger API", - "termsOfService": "http://swagger.io/terms/", - "contact": {}, - "version": "1.0" - }, - "host": "api.tidbcloud.com", - "paths": { - "/ecosystem/api/internal/pingchat/chat": { - "post": { - "description": "Chat with PingChat", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "PingChatService" - ], - "operationId": "Chat", - "parameters": [ - { - "description": "chat information", - "name": "chatInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/pingchat.ChatInfo" - } - } - ], - "responses": { - "200": { - "description": "ok", - "schema": { - "$ref": "#/definitions/pingchat.ChatResponse" - } - }, - "400": { - "description": "error", - "schema": { - "type": "object" - } - }, - "500": { - "description": "error", - "schema": { - "type": "object" - } - }, - "default": { - "description": "other error", - "schema": { - "type": "object" - } - } - } - } - } - }, - "definitions": { - "pingchat.ChatInfo": { - "type": "object", - "required": [ - "messages" - ], - "properties": { - "domain": { - "type": "array", - "items": { - "type": "string", - "enum": [ - "tidb", - "tidbcloud", - "asktug", - "blog", - "community", - "knowledge-base-cn", - "kb" - ] - } - }, - "messages": { - "description": "https://pkg.go.dev/gopkg.in/bluesuncorp/validator.v9#hdr-Dive", - "type": "array", - "items": { - "$ref": "#/definitions/pingchat.ChatMessage" - } - } - } - }, - "pingchat.ChatMessage": { - "type": "object", - "required": [ - "content", - "role" - ], - "properties": { - "content": { - "description": "Dialogue content", - "type": "string" - }, - "role": { - "description": "User's input as \"user\", AI assistant's reply as \"assistant\", see https://github.com/gin-gonic/gin/issues/3234.", - "type": "string", - "enum": [ - "user", - "assistant" - ] - } - } - }, - "pingchat.ChatResponse": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "links": { - "description": "Reference Document Links", - "type": "array", - "items": { - "$ref": "#/definitions/pingchat.Link" - } - } - } - }, - "pingchat.Link": { - "type": "object", - "properties": { - "link": { - "type": "string" - }, - "title": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/pkg/tidbcloud/pingchat/.gitignore b/pkg/tidbcloud/pingchat/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/pkg/tidbcloud/pingchat/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/pkg/tidbcloud/pingchat/.openapi-generator-ignore b/pkg/tidbcloud/pingchat/.openapi-generator-ignore deleted file mode 100644 index 7484ee59..00000000 --- a/pkg/tidbcloud/pingchat/.openapi-generator-ignore +++ /dev/null @@ -1,23 +0,0 @@ -# OpenAPI Generator Ignore -# Generated by openapi-generator https://github.com/openapitools/openapi-generator - -# Use this file to prevent files from being overwritten by the generator. -# The patterns follow closely to .gitignore or .dockerignore. - -# As an example, the C# client generator defines ApiClient.cs. -# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: -#ApiClient.cs - -# You can match any string of characters against a directory, file or extension with a single asterisk (*): -#foo/*/qux -# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux - -# You can recursively match patterns against a directory, file or extension with a double asterisk (**): -#foo/**/qux -# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux - -# You can also negate patterns with an exclamation (!). -# For example, you can ignore all files in a docs folder with the file extension .md: -#docs/*.md -# Then explicitly reverse the ignore rule for a single file: -#!docs/README.md diff --git a/pkg/tidbcloud/pingchat/.openapi-generator/FILES b/pkg/tidbcloud/pingchat/.openapi-generator/FILES deleted file mode 100644 index 8b95663d..00000000 --- a/pkg/tidbcloud/pingchat/.openapi-generator/FILES +++ /dev/null @@ -1,17 +0,0 @@ -.gitignore -.openapi-generator-ignore -.travis.yml -README.md -api/openapi.yaml -api_ping_chat_service.go -client.go -configuration.go -git_push.sh -model_pingchat_chat_info.go -model_pingchat_chat_info_domain_inner.go -model_pingchat_chat_message.go -model_pingchat_chat_message_role.go -model_pingchat_chat_response.go -model_pingchat_link.go -response.go -utils.go diff --git a/pkg/tidbcloud/pingchat/.openapi-generator/VERSION b/pkg/tidbcloud/pingchat/.openapi-generator/VERSION deleted file mode 100644 index 5f84a81d..00000000 --- a/pkg/tidbcloud/pingchat/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -7.12.0 diff --git a/pkg/tidbcloud/pingchat/.travis.yml b/pkg/tidbcloud/pingchat/.travis.yml deleted file mode 100644 index f5cb2ce9..00000000 --- a/pkg/tidbcloud/pingchat/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -install: - - go get -d -v . - -script: - - go build -v ./ - diff --git a/pkg/tidbcloud/pingchat/README.md b/pkg/tidbcloud/pingchat/README.md deleted file mode 100644 index 15c53bf2..00000000 --- a/pkg/tidbcloud/pingchat/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# Go API client for pingchat - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -## Overview -This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. - -- API version: 1.0 -- Package version: 1.0.0 -- Generator version: 7.12.0 -- Build package: org.openapitools.codegen.languages.GoClientCodegen - -## Installation - -Install the following dependencies: - -```sh -go get github.com/stretchr/testify/assert -go get golang.org/x/net/context -``` - -Put the package under your project folder and add the following in import: - -```go -import pingchat "github.com/GIT_USER_ID/GIT_REPO_ID" -``` - -To use a proxy, set the environment variable `HTTP_PROXY`: - -```go -os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") -``` - -## Configuration of Server URL - -Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. - -### Select Server Configuration - -For using other server than the one defined on index 0 set context value `pingchat.ContextServerIndex` of type `int`. - -```go -ctx := context.WithValue(context.Background(), pingchat.ContextServerIndex, 1) -``` - -### Templated Server URL - -Templated server URL is formatted using default variables from configuration or from context value `pingchat.ContextServerVariables` of type `map[string]string`. - -```go -ctx := context.WithValue(context.Background(), pingchat.ContextServerVariables, map[string]string{ - "basePath": "v2", -}) -``` - -Note, enum values are always validated and all unused variables are silently ignored. - -### URLs Configuration per Operation - -Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. -An operation is uniquely identified by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `pingchat.ContextOperationServerIndices` and `pingchat.ContextOperationServerVariables` context maps. - -```go -ctx := context.WithValue(context.Background(), pingchat.ContextOperationServerIndices, map[string]int{ - "{classname}Service.{nickname}": 2, -}) -ctx = context.WithValue(context.Background(), pingchat.ContextOperationServerVariables, map[string]map[string]string{ - "{classname}Service.{nickname}": { - "port": "8443", - }, -}) -``` - -## Documentation for API Endpoints - -All URIs are relative to *https://api.tidbcloud.com* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*PingChatServiceAPI* | [**Chat**](docs/PingChatServiceAPI.md#chat) | **Post** /ecosystem/api/internal/pingchat/chat | - - -## Documentation For Models - - - [PingchatChatInfo](docs/PingchatChatInfo.md) - - [PingchatChatInfoDomainInner](docs/PingchatChatInfoDomainInner.md) - - [PingchatChatMessage](docs/PingchatChatMessage.md) - - [PingchatChatMessageRole](docs/PingchatChatMessageRole.md) - - [PingchatChatResponse](docs/PingchatChatResponse.md) - - [PingchatLink](docs/PingchatLink.md) - - -## Documentation For Authorization - -Endpoints do not require authorization. - - -## Documentation for Utility Methods - -Due to the fact that model structure members are all pointers, this package contains -a number of utility functions to easily obtain pointers to values of basic types. -Each of these functions takes a value of the given basic type and returns a pointer to it: - -* `PtrBool` -* `PtrInt` -* `PtrInt32` -* `PtrInt64` -* `PtrFloat` -* `PtrFloat32` -* `PtrFloat64` -* `PtrString` -* `PtrTime` - -## Author - - - diff --git a/pkg/tidbcloud/pingchat/api/openapi.yaml b/pkg/tidbcloud/pingchat/api/openapi.yaml deleted file mode 100644 index 8540b3f9..00000000 --- a/pkg/tidbcloud/pingchat/api/openapi.yaml +++ /dev/null @@ -1,120 +0,0 @@ -openapi: 3.0.1 -info: - contact: {} - termsOfService: http://swagger.io/terms/ - title: PingChat Swagger API - version: "1.0" -servers: -- url: https://api.tidbcloud.com/ -paths: - /ecosystem/api/internal/pingchat/chat: - post: - description: Chat with PingChat - operationId: Chat - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/pingchat.ChatInfo' - description: chat information - required: true - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/pingchat.ChatResponse' - description: ok - "400": - content: - application/json: - schema: - type: object - description: error - "500": - content: - application/json: - schema: - type: object - description: error - default: - content: - application/json: - schema: - type: object - description: other error - tags: - - PingChatService - x-codegen-request-body-name: chatInfo -components: - schemas: - pingchat.ChatInfo: - properties: - domain: - items: - $ref: '#/components/schemas/pingchat_ChatInfo_domain_inner' - type: array - messages: - description: https://pkg.go.dev/gopkg.in/bluesuncorp/validator.v9#hdr-Dive - items: - $ref: '#/components/schemas/pingchat.ChatMessage' - type: array - required: - - messages - type: object - pingchat.ChatMessage: - properties: - content: - description: Dialogue content - type: string - role: - $ref: '#/components/schemas/pingchat_ChatMessage_role' - required: - - content - - role - type: object - pingchat.ChatResponse: - example: - links: - - link: link - title: title - - link: link - title: title - content: content - properties: - content: - type: string - links: - description: Reference Document Links - items: - $ref: '#/components/schemas/pingchat.Link' - type: array - type: object - pingchat.Link: - example: - link: link - title: title - properties: - link: - type: string - title: - type: string - type: object - pingchat_ChatInfo_domain_inner: - enum: - - tidb - - tidbcloud - - asktug - - blog - - community - - knowledge-base-cn - - kb - type: string - pingchat_ChatMessage_role: - description: "User's input as \"user\", AI assistant's reply as \"assistant\"\ - , see https://github.com/gin-gonic/gin/issues/3234." - enum: - - user - - assistant - type: string -x-original-swagger-version: "2.0" diff --git a/pkg/tidbcloud/pingchat/api_ping_chat_service.go b/pkg/tidbcloud/pingchat/api_ping_chat_service.go deleted file mode 100644 index f522766d..00000000 --- a/pkg/tidbcloud/pingchat/api_ping_chat_service.go +++ /dev/null @@ -1,164 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "bytes" - "context" - "io" - "net/http" - "net/url" -) - -// PingChatServiceAPIService PingChatServiceAPI service -type PingChatServiceAPIService service - -type ApiChatRequest struct { - ctx context.Context - ApiService *PingChatServiceAPIService - chatInfo *PingchatChatInfo -} - -// chat information -func (r ApiChatRequest) ChatInfo(chatInfo PingchatChatInfo) ApiChatRequest { - r.chatInfo = &chatInfo - return r -} - -func (r ApiChatRequest) Execute() (*PingchatChatResponse, *http.Response, error) { - return r.ApiService.ChatExecute(r) -} - -/* -Chat Method for Chat - -Chat with PingChat - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiChatRequest -*/ -func (a *PingChatServiceAPIService) Chat(ctx context.Context) ApiChatRequest { - return ApiChatRequest{ - ApiService: a, - ctx: ctx, - } -} - -// Execute executes the request -// -// @return PingchatChatResponse -func (a *PingChatServiceAPIService) ChatExecute(r ApiChatRequest) (*PingchatChatResponse, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodPost - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *PingchatChatResponse - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PingChatServiceAPIService.Chat") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/ecosystem/api/internal/pingchat/chat" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - if r.chatInfo == nil { - return localVarReturnValue, nil, reportError("chatInfo is required and must be specified") - } - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json"} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - // body params - localVarPostBody = r.chatInfo - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - if localVarHTTPResponse.StatusCode == 400 { - var v map[string]interface{} - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } - if localVarHTTPResponse.StatusCode == 500 { - var v map[string]interface{} - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } - var v map[string]interface{} - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} diff --git a/pkg/tidbcloud/pingchat/client.go b/pkg/tidbcloud/pingchat/client.go deleted file mode 100644 index 741e3974..00000000 --- a/pkg/tidbcloud/pingchat/client.go +++ /dev/null @@ -1,655 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "bytes" - "context" - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "io" - "log" - "mime/multipart" - "net/http" - "net/http/httputil" - "net/url" - "os" - "path/filepath" - "reflect" - "regexp" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -var ( - JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) - XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) - queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) - queryDescape = strings.NewReplacer("%5B", "[", "%5D", "]") -) - -// APIClient manages communication with the PingChat Swagger API API v1.0 -// In most cases there should be only one, shared, APIClient. -type APIClient struct { - cfg *Configuration - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // API Services - - PingChatServiceAPI *PingChatServiceAPIService -} - -type service struct { - client *APIClient -} - -// NewAPIClient creates a new API client. Requires a userAgent string describing your application. -// optionally a custom http.Client to allow for advanced features such as caching. -func NewAPIClient(cfg *Configuration) *APIClient { - if cfg.HTTPClient == nil { - cfg.HTTPClient = http.DefaultClient - } - - c := &APIClient{} - c.cfg = cfg - c.common.client = c - - // API Services - c.PingChatServiceAPI = (*PingChatServiceAPIService)(&c.common) - - return c -} - -func atoi(in string) (int, error) { - return strconv.Atoi(in) -} - -// selectHeaderContentType select a content type from the available list. -func selectHeaderContentType(contentTypes []string) string { - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] // use the first content type specified in 'consumes' -} - -// selectHeaderAccept join all accept types and return -func selectHeaderAccept(accepts []string) string { - if len(accepts) == 0 { - return "" - } - - if contains(accepts, "application/json") { - return "application/json" - } - - return strings.Join(accepts, ",") -} - -// contains is a case insensitive match, finding needle in a haystack -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.EqualFold(a, needle) { - return true - } - } - return false -} - -// Verify optional parameters are of the correct type. -func typeCheckParameter(obj interface{}, expected string, name string) error { - // Make sure there is an object. - if obj == nil { - return nil - } - - // Check the type is as expected. - if reflect.TypeOf(obj).String() != expected { - return fmt.Errorf("expected %s to be of type %s but received %s", name, expected, reflect.TypeOf(obj).String()) - } - return nil -} - -func parameterValueToString(obj interface{}, key string) string { - if reflect.TypeOf(obj).Kind() != reflect.Ptr { - if actualObj, ok := obj.(interface{ GetActualInstanceValue() interface{} }); ok { - return fmt.Sprintf("%v", actualObj.GetActualInstanceValue()) - } - - return fmt.Sprintf("%v", obj) - } - var param, ok = obj.(MappedNullable) - if !ok { - return "" - } - dataMap, err := param.ToMap() - if err != nil { - return "" - } - return fmt.Sprintf("%v", dataMap[key]) -} - -// parameterAddToHeaderOrQuery adds the provided object to the request header or url query -// supporting deep object syntax -func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, style string, collectionType string) { - var v = reflect.ValueOf(obj) - var value = "" - if v == reflect.ValueOf(nil) { - value = "null" - } else { - switch v.Kind() { - case reflect.Invalid: - value = "invalid" - - case reflect.Struct: - if t, ok := obj.(MappedNullable); ok { - dataMap, err := t.ToMap() - if err != nil { - return - } - parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, style, collectionType) - return - } - if t, ok := obj.(time.Time); ok { - parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339Nano), style, collectionType) - return - } - value = v.Type().String() + " value" - case reflect.Slice: - var indValue = reflect.ValueOf(obj) - if indValue == reflect.ValueOf(nil) { - return - } - var lenIndValue = indValue.Len() - for i := 0; i < lenIndValue; i++ { - var arrayValue = indValue.Index(i) - var keyPrefixForCollectionType = keyPrefix - if style == "deepObject" { - keyPrefixForCollectionType = keyPrefix + "[" + strconv.Itoa(i) + "]" - } - parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefixForCollectionType, arrayValue.Interface(), style, collectionType) - } - return - - case reflect.Map: - var indValue = reflect.ValueOf(obj) - if indValue == reflect.ValueOf(nil) { - return - } - iter := indValue.MapRange() - for iter.Next() { - k, v := iter.Key(), iter.Value() - parameterAddToHeaderOrQuery(headerOrQueryParams, fmt.Sprintf("%s[%s]", keyPrefix, k.String()), v.Interface(), style, collectionType) - } - return - - case reflect.Interface: - fallthrough - case reflect.Ptr: - parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, v.Elem().Interface(), style, collectionType) - return - - case reflect.Int, reflect.Int8, reflect.Int16, - reflect.Int32, reflect.Int64: - value = strconv.FormatInt(v.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, - reflect.Uint32, reflect.Uint64, reflect.Uintptr: - value = strconv.FormatUint(v.Uint(), 10) - case reflect.Float32, reflect.Float64: - value = strconv.FormatFloat(v.Float(), 'g', -1, 32) - case reflect.Bool: - value = strconv.FormatBool(v.Bool()) - case reflect.String: - value = v.String() - default: - value = v.Type().String() + " value" - } - } - - switch valuesMap := headerOrQueryParams.(type) { - case url.Values: - if collectionType == "csv" && valuesMap.Get(keyPrefix) != "" { - valuesMap.Set(keyPrefix, valuesMap.Get(keyPrefix)+","+value) - } else { - valuesMap.Add(keyPrefix, value) - } - break - case map[string]string: - valuesMap[keyPrefix] = value - break - } -} - -// helper for converting interface{} parameters to json strings -func parameterToJson(obj interface{}) (string, error) { - jsonBuf, err := json.Marshal(obj) - if err != nil { - return "", err - } - return string(jsonBuf), err -} - -// callAPI do the request. -func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { - if c.cfg.Debug { - dump, err := httputil.DumpRequestOut(request, true) - if err != nil { - return nil, err - } - log.Printf("\n%s\n", string(dump)) - } - - resp, err := c.cfg.HTTPClient.Do(request) - if err != nil { - return resp, err - } - - if c.cfg.Debug { - dump, err := httputil.DumpResponse(resp, true) - if err != nil { - return resp, err - } - log.Printf("\n%s\n", string(dump)) - } - return resp, err -} - -// Allow modification of underlying config for alternate implementations and testing -// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior -func (c *APIClient) GetConfig() *Configuration { - return c.cfg -} - -type formFile struct { - fileBytes []byte - fileName string - formFileName string -} - -// prepareRequest build the request -func (c *APIClient) prepareRequest( - ctx context.Context, - path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams url.Values, - formFiles []formFile) (localVarRequest *http.Request, err error) { - - var body *bytes.Buffer - - // Detect postBody type and post. - if postBody != nil { - contentType := headerParams["Content-Type"] - if contentType == "" { - contentType = detectContentType(postBody) - headerParams["Content-Type"] = contentType - } - - body, err = setBody(postBody, contentType) - if err != nil { - return nil, err - } - } - - // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { - if body != nil { - return nil, errors.New("Cannot specify postBody and multipart form at the same time.") - } - body = &bytes.Buffer{} - w := multipart.NewWriter(body) - - for k, v := range formParams { - for _, iv := range v { - if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return nil, err - } - } else { // form value - w.WriteField(k, iv) - } - } - } - for _, formFile := range formFiles { - if len(formFile.fileBytes) > 0 && formFile.fileName != "" { - w.Boundary() - part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) - if err != nil { - return nil, err - } - _, err = part.Write(formFile.fileBytes) - if err != nil { - return nil, err - } - } - } - - // Set the Boundary in the Content-Type - headerParams["Content-Type"] = w.FormDataContentType() - - // Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - w.Close() - } - - if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { - if body != nil { - return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") - } - body = &bytes.Buffer{} - body.WriteString(formParams.Encode()) - // Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - } - - // Setup path and query parameters - url, err := url.Parse(path) - if err != nil { - return nil, err - } - - // Override request host, if applicable - if c.cfg.Host != "" { - url.Host = c.cfg.Host - } - - // Override request scheme, if applicable - if c.cfg.Scheme != "" { - url.Scheme = c.cfg.Scheme - } - - // Adding Query Param - query := url.Query() - for k, v := range queryParams { - for _, iv := range v { - query.Add(k, iv) - } - } - - // Encode the parameters. - url.RawQuery = queryParamSplit.ReplaceAllStringFunc(query.Encode(), func(s string) string { - pieces := strings.Split(s, "=") - pieces[0] = queryDescape.Replace(pieces[0]) - return strings.Join(pieces, "=") - }) - - // Generate a new request - if body != nil { - localVarRequest, err = http.NewRequest(method, url.String(), body) - } else { - localVarRequest, err = http.NewRequest(method, url.String(), nil) - } - if err != nil { - return nil, err - } - - // add header parameters, if any - if len(headerParams) > 0 { - headers := http.Header{} - for h, v := range headerParams { - headers[h] = []string{v} - } - localVarRequest.Header = headers - } - - // Add the user agent to the request. - localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) - - if ctx != nil { - // add context to the request - localVarRequest = localVarRequest.WithContext(ctx) - - // Walk through any authentication. - - } - - for header, value := range c.cfg.DefaultHeader { - localVarRequest.Header.Add(header, value) - } - return localVarRequest, nil -} - -func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { - if len(b) == 0 { - return nil - } - if s, ok := v.(*string); ok { - *s = string(b) - return nil - } - if f, ok := v.(*os.File); ok { - f, err = os.CreateTemp("", "HttpClientFile") - if err != nil { - return - } - _, err = f.Write(b) - if err != nil { - return - } - _, err = f.Seek(0, io.SeekStart) - return - } - if f, ok := v.(**os.File); ok { - *f, err = os.CreateTemp("", "HttpClientFile") - if err != nil { - return - } - _, err = (*f).Write(b) - if err != nil { - return - } - _, err = (*f).Seek(0, io.SeekStart) - return - } - if XmlCheck.MatchString(contentType) { - if err = xml.Unmarshal(b, v); err != nil { - return err - } - return nil - } - if JsonCheck.MatchString(contentType) { - if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas - if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined - if err = unmarshalObj.UnmarshalJSON(b); err != nil { - return err - } - } else { - return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") - } - } else if err = json.Unmarshal(b, v); err != nil { // simple model - return err - } - return nil - } - return errors.New("undefined response type") -} - -// Add a file to the multipart request -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(filepath.Clean(path)) - if err != nil { - return err - } - err = file.Close() - if err != nil { - return err - } - - part, err := w.CreateFormFile(fieldName, filepath.Base(path)) - if err != nil { - return err - } - _, err = io.Copy(part, file) - - return err -} - -// Set request body from an interface{} -func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { - if bodyBuf == nil { - bodyBuf = &bytes.Buffer{} - } - - if reader, ok := body.(io.Reader); ok { - _, err = bodyBuf.ReadFrom(reader) - } else if fp, ok := body.(*os.File); ok { - _, err = bodyBuf.ReadFrom(fp) - } else if b, ok := body.([]byte); ok { - _, err = bodyBuf.Write(b) - } else if s, ok := body.(string); ok { - _, err = bodyBuf.WriteString(s) - } else if s, ok := body.(*string); ok { - _, err = bodyBuf.WriteString(*s) - } else if JsonCheck.MatchString(contentType) { - err = json.NewEncoder(bodyBuf).Encode(body) - } else if XmlCheck.MatchString(contentType) { - var bs []byte - bs, err = xml.Marshal(body) - if err == nil { - bodyBuf.Write(bs) - } - } - - if err != nil { - return nil, err - } - - if bodyBuf.Len() == 0 { - err = fmt.Errorf("invalid body type %s\n", contentType) - return nil, err - } - return bodyBuf, nil -} - -// detectContentType method is used to figure out `Request.Body` content type for request header -func detectContentType(body interface{}) string { - contentType := "text/plain; charset=utf-8" - kind := reflect.TypeOf(body).Kind() - - switch kind { - case reflect.Struct, reflect.Map, reflect.Ptr: - contentType = "application/json; charset=utf-8" - case reflect.String: - contentType = "text/plain; charset=utf-8" - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = "application/json; charset=utf-8" - } - } - - return contentType -} - -// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go -type cacheControl map[string]string - -func parseCacheControl(headers http.Header) cacheControl { - cc := cacheControl{} - ccHeader := headers.Get("Cache-Control") - for _, part := range strings.Split(ccHeader, ",") { - part = strings.Trim(part, " ") - if part == "" { - continue - } - if strings.ContainsRune(part, '=') { - keyval := strings.Split(part, "=") - cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") - } else { - cc[part] = "" - } - } - return cc -} - -// CacheExpires helper function to determine remaining time before repeating a request. -func CacheExpires(r *http.Response) time.Time { - // Figure out when the cache expires. - var expires time.Time - now, err := time.Parse(time.RFC1123, r.Header.Get("date")) - if err != nil { - return time.Now() - } - respCacheControl := parseCacheControl(r.Header) - - if maxAge, ok := respCacheControl["max-age"]; ok { - lifetime, err := time.ParseDuration(maxAge + "s") - if err != nil { - expires = now - } else { - expires = now.Add(lifetime) - } - } else { - expiresHeader := r.Header.Get("Expires") - if expiresHeader != "" { - expires, err = time.Parse(time.RFC1123, expiresHeader) - if err != nil { - expires = now - } - } - } - return expires -} - -func strlen(s string) int { - return utf8.RuneCountInString(s) -} - -// GenericOpenAPIError Provides access to the body, error and model on returned errors. -type GenericOpenAPIError struct { - body []byte - error string - model interface{} -} - -// Error returns non-empty string if there was an error. -func (e GenericOpenAPIError) Error() string { - return e.error -} - -// Body returns the raw bytes of the response -func (e GenericOpenAPIError) Body() []byte { - return e.body -} - -// Model returns the unpacked model of the error -func (e GenericOpenAPIError) Model() interface{} { - return e.model -} - -// format error message using title and detail when model implements rfc7807 -func formatErrorMessage(status string, v interface{}) string { - str := "" - metaValue := reflect.ValueOf(v).Elem() - - if metaValue.Kind() == reflect.Struct { - field := metaValue.FieldByName("Title") - if field != (reflect.Value{}) { - str = fmt.Sprintf("%s", field.Interface()) - } - - field = metaValue.FieldByName("Detail") - if field != (reflect.Value{}) { - str = fmt.Sprintf("%s (%s)", str, field.Interface()) - } - } - - return strings.TrimSpace(fmt.Sprintf("%s %s", status, str)) -} diff --git a/pkg/tidbcloud/pingchat/configuration.go b/pkg/tidbcloud/pingchat/configuration.go deleted file mode 100644 index 3bc45509..00000000 --- a/pkg/tidbcloud/pingchat/configuration.go +++ /dev/null @@ -1,214 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "context" - "fmt" - "net/http" - "strings" -) - -// contextKeys are used to identify the type of value in the context. -// Since these are string, it is possible to get a short description of the -// context key for logging and debugging using key.String(). - -type contextKey string - -func (c contextKey) String() string { - return "auth " + string(c) -} - -var ( - // ContextServerIndex uses a server configuration from the index. - ContextServerIndex = contextKey("serverIndex") - - // ContextOperationServerIndices uses a server configuration from the index mapping. - ContextOperationServerIndices = contextKey("serverOperationIndices") - - // ContextServerVariables overrides a server configuration variables. - ContextServerVariables = contextKey("serverVariables") - - // ContextOperationServerVariables overrides a server configuration variables using operation specific values. - ContextOperationServerVariables = contextKey("serverOperationVariables") -) - -// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth -type BasicAuth struct { - UserName string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` -} - -// APIKey provides API key based authentication to a request passed via context using ContextAPIKey -type APIKey struct { - Key string - Prefix string -} - -// ServerVariable stores the information about a server variable -type ServerVariable struct { - Description string - DefaultValue string - EnumValues []string -} - -// ServerConfiguration stores the information about a server -type ServerConfiguration struct { - URL string - Description string - Variables map[string]ServerVariable -} - -// ServerConfigurations stores multiple ServerConfiguration items -type ServerConfigurations []ServerConfiguration - -// Configuration stores the configuration of the API client -type Configuration struct { - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - Debug bool `json:"debug,omitempty"` - Servers ServerConfigurations - OperationServers map[string]ServerConfigurations - HTTPClient *http.Client -} - -// NewConfiguration returns a new Configuration object -func NewConfiguration() *Configuration { - cfg := &Configuration{ - DefaultHeader: make(map[string]string), - UserAgent: "OpenAPI-Generator/1.0.0/go", - Debug: false, - Servers: ServerConfigurations{ - { - URL: "https://api.tidbcloud.com", - Description: "No description provided", - }, - }, - OperationServers: map[string]ServerConfigurations{}, - } - return cfg -} - -// AddDefaultHeader adds a new HTTP header to the default header in the request -func (c *Configuration) AddDefaultHeader(key string, value string) { - c.DefaultHeader[key] = value -} - -// URL formats template on a index using given variables -func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { - if index < 0 || len(sc) <= index { - return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1) - } - server := sc[index] - url := server.URL - - // go through variables and replace placeholders - for name, variable := range server.Variables { - if value, ok := variables[name]; ok { - found := bool(len(variable.EnumValues) == 0) - for _, enumValue := range variable.EnumValues { - if value == enumValue { - found = true - } - } - if !found { - return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) - } - url = strings.Replace(url, "{"+name+"}", value, -1) - } else { - url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) - } - } - return url, nil -} - -// ServerURL returns URL based on server settings -func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { - return c.Servers.URL(index, variables) -} - -func getServerIndex(ctx context.Context) (int, error) { - si := ctx.Value(ContextServerIndex) - if si != nil { - if index, ok := si.(int); ok { - return index, nil - } - return 0, reportError("Invalid type %T should be int", si) - } - return 0, nil -} - -func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { - osi := ctx.Value(ContextOperationServerIndices) - if osi != nil { - if operationIndices, ok := osi.(map[string]int); !ok { - return 0, reportError("Invalid type %T should be map[string]int", osi) - } else { - index, ok := operationIndices[endpoint] - if ok { - return index, nil - } - } - } - return getServerIndex(ctx) -} - -func getServerVariables(ctx context.Context) (map[string]string, error) { - sv := ctx.Value(ContextServerVariables) - if sv != nil { - if variables, ok := sv.(map[string]string); ok { - return variables, nil - } - return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) - } - return nil, nil -} - -func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { - osv := ctx.Value(ContextOperationServerVariables) - if osv != nil { - if operationVariables, ok := osv.(map[string]map[string]string); !ok { - return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) - } else { - variables, ok := operationVariables[endpoint] - if ok { - return variables, nil - } - } - } - return getServerVariables(ctx) -} - -// ServerURLWithContext returns a new server URL given an endpoint -func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { - sc, ok := c.OperationServers[endpoint] - if !ok { - sc = c.Servers - } - - if ctx == nil { - return sc.URL(0, nil) - } - - index, err := getServerOperationIndex(ctx, endpoint) - if err != nil { - return "", err - } - - variables, err := getServerOperationVariables(ctx, endpoint) - if err != nil { - return "", err - } - - return sc.URL(index, variables) -} diff --git a/pkg/tidbcloud/pingchat/git_push.sh b/pkg/tidbcloud/pingchat/git_push.sh deleted file mode 100644 index f53a75d4..00000000 --- a/pkg/tidbcloud/pingchat/git_push.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=$(git remote) -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' diff --git a/pkg/tidbcloud/pingchat/model_pingchat_chat_info.go b/pkg/tidbcloud/pingchat/model_pingchat_chat_info.go deleted file mode 100644 index 93df4b06..00000000 --- a/pkg/tidbcloud/pingchat/model_pingchat_chat_info.go +++ /dev/null @@ -1,193 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "bytes" - "encoding/json" - "fmt" -) - -// checks if the PingchatChatInfo type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &PingchatChatInfo{} - -// PingchatChatInfo struct for PingchatChatInfo -type PingchatChatInfo struct { - Domain []PingchatChatInfoDomainInner `json:"domain,omitempty"` - // https://pkg.go.dev/gopkg.in/bluesuncorp/validator.v9#hdr-Dive - Messages []PingchatChatMessage `json:"messages"` -} - -type _PingchatChatInfo PingchatChatInfo - -// NewPingchatChatInfo instantiates a new PingchatChatInfo object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewPingchatChatInfo(messages []PingchatChatMessage) *PingchatChatInfo { - this := PingchatChatInfo{} - this.Messages = messages - return &this -} - -// NewPingchatChatInfoWithDefaults instantiates a new PingchatChatInfo object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewPingchatChatInfoWithDefaults() *PingchatChatInfo { - this := PingchatChatInfo{} - return &this -} - -// GetDomain returns the Domain field value if set, zero value otherwise. -func (o *PingchatChatInfo) GetDomain() []PingchatChatInfoDomainInner { - if o == nil || IsNil(o.Domain) { - var ret []PingchatChatInfoDomainInner - return ret - } - return o.Domain -} - -// GetDomainOk returns a tuple with the Domain field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *PingchatChatInfo) GetDomainOk() ([]PingchatChatInfoDomainInner, bool) { - if o == nil || IsNil(o.Domain) { - return nil, false - } - return o.Domain, true -} - -// HasDomain returns a boolean if a field has been set. -func (o *PingchatChatInfo) HasDomain() bool { - if o != nil && !IsNil(o.Domain) { - return true - } - - return false -} - -// SetDomain gets a reference to the given []PingchatChatInfoDomainInner and assigns it to the Domain field. -func (o *PingchatChatInfo) SetDomain(v []PingchatChatInfoDomainInner) { - o.Domain = v -} - -// GetMessages returns the Messages field value -func (o *PingchatChatInfo) GetMessages() []PingchatChatMessage { - if o == nil { - var ret []PingchatChatMessage - return ret - } - - return o.Messages -} - -// GetMessagesOk returns a tuple with the Messages field value -// and a boolean to check if the value has been set. -func (o *PingchatChatInfo) GetMessagesOk() ([]PingchatChatMessage, bool) { - if o == nil { - return nil, false - } - return o.Messages, true -} - -// SetMessages sets field value -func (o *PingchatChatInfo) SetMessages(v []PingchatChatMessage) { - o.Messages = v -} - -func (o PingchatChatInfo) MarshalJSON() ([]byte, error) { - toSerialize, err := o.ToMap() - if err != nil { - return []byte{}, err - } - return json.Marshal(toSerialize) -} - -func (o PingchatChatInfo) ToMap() (map[string]interface{}, error) { - toSerialize := map[string]interface{}{} - if !IsNil(o.Domain) { - toSerialize["domain"] = o.Domain - } - toSerialize["messages"] = o.Messages - return toSerialize, nil -} - -func (o *PingchatChatInfo) UnmarshalJSON(data []byte) (err error) { - // This validates that all required properties are included in the JSON object - // by unmarshalling the object into a generic map with string keys and checking - // that every required field exists as a key in the generic map. - requiredProperties := []string{ - "messages", - } - - allProperties := make(map[string]interface{}) - - err = json.Unmarshal(data, &allProperties) - - if err != nil { - return err - } - - for _, requiredProperty := range requiredProperties { - if _, exists := allProperties[requiredProperty]; !exists { - return fmt.Errorf("no value given for required property %v", requiredProperty) - } - } - - varPingchatChatInfo := _PingchatChatInfo{} - - decoder := json.NewDecoder(bytes.NewReader(data)) - decoder.DisallowUnknownFields() - err = decoder.Decode(&varPingchatChatInfo) - - if err != nil { - return err - } - - *o = PingchatChatInfo(varPingchatChatInfo) - - return err -} - -type NullablePingchatChatInfo struct { - value *PingchatChatInfo - isSet bool -} - -func (v NullablePingchatChatInfo) Get() *PingchatChatInfo { - return v.value -} - -func (v *NullablePingchatChatInfo) Set(val *PingchatChatInfo) { - v.value = val - v.isSet = true -} - -func (v NullablePingchatChatInfo) IsSet() bool { - return v.isSet -} - -func (v *NullablePingchatChatInfo) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullablePingchatChatInfo(val *PingchatChatInfo) *NullablePingchatChatInfo { - return &NullablePingchatChatInfo{value: val, isSet: true} -} - -func (v NullablePingchatChatInfo) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullablePingchatChatInfo) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/pkg/tidbcloud/pingchat/model_pingchat_chat_info_domain_inner.go b/pkg/tidbcloud/pingchat/model_pingchat_chat_info_domain_inner.go deleted file mode 100644 index ab16e31c..00000000 --- a/pkg/tidbcloud/pingchat/model_pingchat_chat_info_domain_inner.go +++ /dev/null @@ -1,115 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "encoding/json" -) - -// PingchatChatInfoDomainInner the model 'PingchatChatInfoDomainInner' -type PingchatChatInfoDomainInner string - -// List of pingchat_ChatInfo_domain_inner -const ( - PINGCHATCHATINFODOMAININNER_TIDB PingchatChatInfoDomainInner = "tidb" - PINGCHATCHATINFODOMAININNER_TIDBCLOUD PingchatChatInfoDomainInner = "tidbcloud" - PINGCHATCHATINFODOMAININNER_ASKTUG PingchatChatInfoDomainInner = "asktug" - PINGCHATCHATINFODOMAININNER_BLOG PingchatChatInfoDomainInner = "blog" - PINGCHATCHATINFODOMAININNER_COMMUNITY PingchatChatInfoDomainInner = "community" - PINGCHATCHATINFODOMAININNER_KNOWLEDGE_BASE_CN PingchatChatInfoDomainInner = "knowledge-base-cn" - PINGCHATCHATINFODOMAININNER_KB PingchatChatInfoDomainInner = "kb" -) - -// All allowed values of PingchatChatInfoDomainInner enum -var AllowedPingchatChatInfoDomainInnerEnumValues = []PingchatChatInfoDomainInner{ - "tidb", - "tidbcloud", - "asktug", - "blog", - "community", - "knowledge-base-cn", - "kb", -} - -func (v *PingchatChatInfoDomainInner) UnmarshalJSON(src []byte) error { - var value string - err := json.Unmarshal(src, &value) - if err != nil { - return err - } - enumTypeValue := PingchatChatInfoDomainInner(value) - for _, existing := range AllowedPingchatChatInfoDomainInnerEnumValues { - if existing == enumTypeValue { - *v = enumTypeValue - return nil - } - } - - *v = PingchatChatInfoDomainInner(value) - return nil -} - -// NewPingchatChatInfoDomainInnerFromValue returns a pointer to a valid PingchatChatInfoDomainInner for the value passed as argument -func NewPingchatChatInfoDomainInnerFromValue(v string) *PingchatChatInfoDomainInner { - ev := PingchatChatInfoDomainInner(v) - return &ev -} - -// IsValid return true if the value is valid for the enum, false otherwise -func (v PingchatChatInfoDomainInner) IsValid() bool { - for _, existing := range AllowedPingchatChatInfoDomainInnerEnumValues { - if existing == v { - return true - } - } - return false -} - -// Ptr returns reference to pingchat_ChatInfo_domain_inner value -func (v PingchatChatInfoDomainInner) Ptr() *PingchatChatInfoDomainInner { - return &v -} - -type NullablePingchatChatInfoDomainInner struct { - value *PingchatChatInfoDomainInner - isSet bool -} - -func (v NullablePingchatChatInfoDomainInner) Get() *PingchatChatInfoDomainInner { - return v.value -} - -func (v *NullablePingchatChatInfoDomainInner) Set(val *PingchatChatInfoDomainInner) { - v.value = val - v.isSet = true -} - -func (v NullablePingchatChatInfoDomainInner) IsSet() bool { - return v.isSet -} - -func (v *NullablePingchatChatInfoDomainInner) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullablePingchatChatInfoDomainInner(val *PingchatChatInfoDomainInner) *NullablePingchatChatInfoDomainInner { - return &NullablePingchatChatInfoDomainInner{value: val, isSet: true} -} - -func (v NullablePingchatChatInfoDomainInner) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullablePingchatChatInfoDomainInner) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/pkg/tidbcloud/pingchat/model_pingchat_chat_message.go b/pkg/tidbcloud/pingchat/model_pingchat_chat_message.go deleted file mode 100644 index 00d0d634..00000000 --- a/pkg/tidbcloud/pingchat/model_pingchat_chat_message.go +++ /dev/null @@ -1,185 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "bytes" - "encoding/json" - "fmt" -) - -// checks if the PingchatChatMessage type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &PingchatChatMessage{} - -// PingchatChatMessage struct for PingchatChatMessage -type PingchatChatMessage struct { - // Dialogue content - Content string `json:"content"` - Role PingchatChatMessageRole `json:"role"` -} - -type _PingchatChatMessage PingchatChatMessage - -// NewPingchatChatMessage instantiates a new PingchatChatMessage object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewPingchatChatMessage(content string, role PingchatChatMessageRole) *PingchatChatMessage { - this := PingchatChatMessage{} - this.Content = content - this.Role = role - return &this -} - -// NewPingchatChatMessageWithDefaults instantiates a new PingchatChatMessage object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewPingchatChatMessageWithDefaults() *PingchatChatMessage { - this := PingchatChatMessage{} - return &this -} - -// GetContent returns the Content field value -func (o *PingchatChatMessage) GetContent() string { - if o == nil { - var ret string - return ret - } - - return o.Content -} - -// GetContentOk returns a tuple with the Content field value -// and a boolean to check if the value has been set. -func (o *PingchatChatMessage) GetContentOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Content, true -} - -// SetContent sets field value -func (o *PingchatChatMessage) SetContent(v string) { - o.Content = v -} - -// GetRole returns the Role field value -func (o *PingchatChatMessage) GetRole() PingchatChatMessageRole { - if o == nil { - var ret PingchatChatMessageRole - return ret - } - - return o.Role -} - -// GetRoleOk returns a tuple with the Role field value -// and a boolean to check if the value has been set. -func (o *PingchatChatMessage) GetRoleOk() (*PingchatChatMessageRole, bool) { - if o == nil { - return nil, false - } - return &o.Role, true -} - -// SetRole sets field value -func (o *PingchatChatMessage) SetRole(v PingchatChatMessageRole) { - o.Role = v -} - -func (o PingchatChatMessage) MarshalJSON() ([]byte, error) { - toSerialize, err := o.ToMap() - if err != nil { - return []byte{}, err - } - return json.Marshal(toSerialize) -} - -func (o PingchatChatMessage) ToMap() (map[string]interface{}, error) { - toSerialize := map[string]interface{}{} - toSerialize["content"] = o.Content - toSerialize["role"] = o.Role - return toSerialize, nil -} - -func (o *PingchatChatMessage) UnmarshalJSON(data []byte) (err error) { - // This validates that all required properties are included in the JSON object - // by unmarshalling the object into a generic map with string keys and checking - // that every required field exists as a key in the generic map. - requiredProperties := []string{ - "content", - "role", - } - - allProperties := make(map[string]interface{}) - - err = json.Unmarshal(data, &allProperties) - - if err != nil { - return err - } - - for _, requiredProperty := range requiredProperties { - if _, exists := allProperties[requiredProperty]; !exists { - return fmt.Errorf("no value given for required property %v", requiredProperty) - } - } - - varPingchatChatMessage := _PingchatChatMessage{} - - decoder := json.NewDecoder(bytes.NewReader(data)) - decoder.DisallowUnknownFields() - err = decoder.Decode(&varPingchatChatMessage) - - if err != nil { - return err - } - - *o = PingchatChatMessage(varPingchatChatMessage) - - return err -} - -type NullablePingchatChatMessage struct { - value *PingchatChatMessage - isSet bool -} - -func (v NullablePingchatChatMessage) Get() *PingchatChatMessage { - return v.value -} - -func (v *NullablePingchatChatMessage) Set(val *PingchatChatMessage) { - v.value = val - v.isSet = true -} - -func (v NullablePingchatChatMessage) IsSet() bool { - return v.isSet -} - -func (v *NullablePingchatChatMessage) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullablePingchatChatMessage(val *PingchatChatMessage) *NullablePingchatChatMessage { - return &NullablePingchatChatMessage{value: val, isSet: true} -} - -func (v NullablePingchatChatMessage) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullablePingchatChatMessage) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/pkg/tidbcloud/pingchat/model_pingchat_chat_message_role.go b/pkg/tidbcloud/pingchat/model_pingchat_chat_message_role.go deleted file mode 100644 index 0afacf81..00000000 --- a/pkg/tidbcloud/pingchat/model_pingchat_chat_message_role.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "encoding/json" -) - -// PingchatChatMessageRole User's input as \"user\", AI assistant's reply as \"assistant\", see https://github.com/gin-gonic/gin/issues/3234. -type PingchatChatMessageRole string - -// List of pingchat_ChatMessage_role -const ( - PINGCHATCHATMESSAGEROLE_USER PingchatChatMessageRole = "user" - PINGCHATCHATMESSAGEROLE_ASSISTANT PingchatChatMessageRole = "assistant" -) - -// All allowed values of PingchatChatMessageRole enum -var AllowedPingchatChatMessageRoleEnumValues = []PingchatChatMessageRole{ - "user", - "assistant", -} - -func (v *PingchatChatMessageRole) UnmarshalJSON(src []byte) error { - var value string - err := json.Unmarshal(src, &value) - if err != nil { - return err - } - enumTypeValue := PingchatChatMessageRole(value) - for _, existing := range AllowedPingchatChatMessageRoleEnumValues { - if existing == enumTypeValue { - *v = enumTypeValue - return nil - } - } - - *v = PingchatChatMessageRole(value) - return nil -} - -// NewPingchatChatMessageRoleFromValue returns a pointer to a valid PingchatChatMessageRole for the value passed as argument -func NewPingchatChatMessageRoleFromValue(v string) *PingchatChatMessageRole { - ev := PingchatChatMessageRole(v) - return &ev -} - -// IsValid return true if the value is valid for the enum, false otherwise -func (v PingchatChatMessageRole) IsValid() bool { - for _, existing := range AllowedPingchatChatMessageRoleEnumValues { - if existing == v { - return true - } - } - return false -} - -// Ptr returns reference to pingchat_ChatMessage_role value -func (v PingchatChatMessageRole) Ptr() *PingchatChatMessageRole { - return &v -} - -type NullablePingchatChatMessageRole struct { - value *PingchatChatMessageRole - isSet bool -} - -func (v NullablePingchatChatMessageRole) Get() *PingchatChatMessageRole { - return v.value -} - -func (v *NullablePingchatChatMessageRole) Set(val *PingchatChatMessageRole) { - v.value = val - v.isSet = true -} - -func (v NullablePingchatChatMessageRole) IsSet() bool { - return v.isSet -} - -func (v *NullablePingchatChatMessageRole) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullablePingchatChatMessageRole(val *PingchatChatMessageRole) *NullablePingchatChatMessageRole { - return &NullablePingchatChatMessageRole{value: val, isSet: true} -} - -func (v NullablePingchatChatMessageRole) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullablePingchatChatMessageRole) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/pkg/tidbcloud/pingchat/model_pingchat_chat_response.go b/pkg/tidbcloud/pingchat/model_pingchat_chat_response.go deleted file mode 100644 index 13fd6459..00000000 --- a/pkg/tidbcloud/pingchat/model_pingchat_chat_response.go +++ /dev/null @@ -1,161 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "encoding/json" -) - -// checks if the PingchatChatResponse type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &PingchatChatResponse{} - -// PingchatChatResponse struct for PingchatChatResponse -type PingchatChatResponse struct { - Content *string `json:"content,omitempty"` - // Reference Document Links - Links []PingchatLink `json:"links,omitempty"` -} - -// NewPingchatChatResponse instantiates a new PingchatChatResponse object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewPingchatChatResponse() *PingchatChatResponse { - this := PingchatChatResponse{} - return &this -} - -// NewPingchatChatResponseWithDefaults instantiates a new PingchatChatResponse object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewPingchatChatResponseWithDefaults() *PingchatChatResponse { - this := PingchatChatResponse{} - return &this -} - -// GetContent returns the Content field value if set, zero value otherwise. -func (o *PingchatChatResponse) GetContent() string { - if o == nil || IsNil(o.Content) { - var ret string - return ret - } - return *o.Content -} - -// GetContentOk returns a tuple with the Content field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *PingchatChatResponse) GetContentOk() (*string, bool) { - if o == nil || IsNil(o.Content) { - return nil, false - } - return o.Content, true -} - -// HasContent returns a boolean if a field has been set. -func (o *PingchatChatResponse) HasContent() bool { - if o != nil && !IsNil(o.Content) { - return true - } - - return false -} - -// SetContent gets a reference to the given string and assigns it to the Content field. -func (o *PingchatChatResponse) SetContent(v string) { - o.Content = &v -} - -// GetLinks returns the Links field value if set, zero value otherwise. -func (o *PingchatChatResponse) GetLinks() []PingchatLink { - if o == nil || IsNil(o.Links) { - var ret []PingchatLink - return ret - } - return o.Links -} - -// GetLinksOk returns a tuple with the Links field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *PingchatChatResponse) GetLinksOk() ([]PingchatLink, bool) { - if o == nil || IsNil(o.Links) { - return nil, false - } - return o.Links, true -} - -// HasLinks returns a boolean if a field has been set. -func (o *PingchatChatResponse) HasLinks() bool { - if o != nil && !IsNil(o.Links) { - return true - } - - return false -} - -// SetLinks gets a reference to the given []PingchatLink and assigns it to the Links field. -func (o *PingchatChatResponse) SetLinks(v []PingchatLink) { - o.Links = v -} - -func (o PingchatChatResponse) MarshalJSON() ([]byte, error) { - toSerialize, err := o.ToMap() - if err != nil { - return []byte{}, err - } - return json.Marshal(toSerialize) -} - -func (o PingchatChatResponse) ToMap() (map[string]interface{}, error) { - toSerialize := map[string]interface{}{} - if !IsNil(o.Content) { - toSerialize["content"] = o.Content - } - if !IsNil(o.Links) { - toSerialize["links"] = o.Links - } - return toSerialize, nil -} - -type NullablePingchatChatResponse struct { - value *PingchatChatResponse - isSet bool -} - -func (v NullablePingchatChatResponse) Get() *PingchatChatResponse { - return v.value -} - -func (v *NullablePingchatChatResponse) Set(val *PingchatChatResponse) { - v.value = val - v.isSet = true -} - -func (v NullablePingchatChatResponse) IsSet() bool { - return v.isSet -} - -func (v *NullablePingchatChatResponse) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullablePingchatChatResponse(val *PingchatChatResponse) *NullablePingchatChatResponse { - return &NullablePingchatChatResponse{value: val, isSet: true} -} - -func (v NullablePingchatChatResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullablePingchatChatResponse) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/pkg/tidbcloud/pingchat/model_pingchat_link.go b/pkg/tidbcloud/pingchat/model_pingchat_link.go deleted file mode 100644 index 8f018721..00000000 --- a/pkg/tidbcloud/pingchat/model_pingchat_link.go +++ /dev/null @@ -1,160 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "encoding/json" -) - -// checks if the PingchatLink type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &PingchatLink{} - -// PingchatLink struct for PingchatLink -type PingchatLink struct { - Link *string `json:"link,omitempty"` - Title *string `json:"title,omitempty"` -} - -// NewPingchatLink instantiates a new PingchatLink object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewPingchatLink() *PingchatLink { - this := PingchatLink{} - return &this -} - -// NewPingchatLinkWithDefaults instantiates a new PingchatLink object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewPingchatLinkWithDefaults() *PingchatLink { - this := PingchatLink{} - return &this -} - -// GetLink returns the Link field value if set, zero value otherwise. -func (o *PingchatLink) GetLink() string { - if o == nil || IsNil(o.Link) { - var ret string - return ret - } - return *o.Link -} - -// GetLinkOk returns a tuple with the Link field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *PingchatLink) GetLinkOk() (*string, bool) { - if o == nil || IsNil(o.Link) { - return nil, false - } - return o.Link, true -} - -// HasLink returns a boolean if a field has been set. -func (o *PingchatLink) HasLink() bool { - if o != nil && !IsNil(o.Link) { - return true - } - - return false -} - -// SetLink gets a reference to the given string and assigns it to the Link field. -func (o *PingchatLink) SetLink(v string) { - o.Link = &v -} - -// GetTitle returns the Title field value if set, zero value otherwise. -func (o *PingchatLink) GetTitle() string { - if o == nil || IsNil(o.Title) { - var ret string - return ret - } - return *o.Title -} - -// GetTitleOk returns a tuple with the Title field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *PingchatLink) GetTitleOk() (*string, bool) { - if o == nil || IsNil(o.Title) { - return nil, false - } - return o.Title, true -} - -// HasTitle returns a boolean if a field has been set. -func (o *PingchatLink) HasTitle() bool { - if o != nil && !IsNil(o.Title) { - return true - } - - return false -} - -// SetTitle gets a reference to the given string and assigns it to the Title field. -func (o *PingchatLink) SetTitle(v string) { - o.Title = &v -} - -func (o PingchatLink) MarshalJSON() ([]byte, error) { - toSerialize, err := o.ToMap() - if err != nil { - return []byte{}, err - } - return json.Marshal(toSerialize) -} - -func (o PingchatLink) ToMap() (map[string]interface{}, error) { - toSerialize := map[string]interface{}{} - if !IsNil(o.Link) { - toSerialize["link"] = o.Link - } - if !IsNil(o.Title) { - toSerialize["title"] = o.Title - } - return toSerialize, nil -} - -type NullablePingchatLink struct { - value *PingchatLink - isSet bool -} - -func (v NullablePingchatLink) Get() *PingchatLink { - return v.value -} - -func (v *NullablePingchatLink) Set(val *PingchatLink) { - v.value = val - v.isSet = true -} - -func (v NullablePingchatLink) IsSet() bool { - return v.isSet -} - -func (v *NullablePingchatLink) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullablePingchatLink(val *PingchatLink) *NullablePingchatLink { - return &NullablePingchatLink{value: val, isSet: true} -} - -func (v NullablePingchatLink) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullablePingchatLink) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/pkg/tidbcloud/pingchat/response.go b/pkg/tidbcloud/pingchat/response.go deleted file mode 100644 index 27ad11e0..00000000 --- a/pkg/tidbcloud/pingchat/response.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "net/http" -) - -// APIResponse stores the API response returned by the server. -type APIResponse struct { - *http.Response `json:"-"` - Message string `json:"message,omitempty"` - // Operation is the name of the OpenAPI operation. - Operation string `json:"operation,omitempty"` - // RequestURL is the request URL. This value is always available, even if the - // embedded *http.Response is nil. - RequestURL string `json:"url,omitempty"` - // Method is the HTTP method used for the request. This value is always - // available, even if the embedded *http.Response is nil. - Method string `json:"method,omitempty"` - // Payload holds the contents of the response body (which may be nil or empty). - // This is provided here as the raw response.Body() reader will have already - // been drained. - Payload []byte `json:"-"` -} - -// NewAPIResponse returns a new APIResponse object. -func NewAPIResponse(r *http.Response) *APIResponse { - - response := &APIResponse{Response: r} - return response -} - -// NewAPIResponseWithError returns a new APIResponse object with the provided error message. -func NewAPIResponseWithError(errorMessage string) *APIResponse { - - response := &APIResponse{Message: errorMessage} - return response -} diff --git a/pkg/tidbcloud/pingchat/utils.go b/pkg/tidbcloud/pingchat/utils.go deleted file mode 100644 index cfd18242..00000000 --- a/pkg/tidbcloud/pingchat/utils.go +++ /dev/null @@ -1,361 +0,0 @@ -/* -PingChat Swagger API - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -API version: 1.0 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package pingchat - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "time" -) - -// PtrBool is a helper routine that returns a pointer to given boolean value. -func PtrBool(v bool) *bool { return &v } - -// PtrInt is a helper routine that returns a pointer to given integer value. -func PtrInt(v int) *int { return &v } - -// PtrInt32 is a helper routine that returns a pointer to given integer value. -func PtrInt32(v int32) *int32 { return &v } - -// PtrInt64 is a helper routine that returns a pointer to given integer value. -func PtrInt64(v int64) *int64 { return &v } - -// PtrFloat32 is a helper routine that returns a pointer to given float value. -func PtrFloat32(v float32) *float32 { return &v } - -// PtrFloat64 is a helper routine that returns a pointer to given float value. -func PtrFloat64(v float64) *float64 { return &v } - -// PtrString is a helper routine that returns a pointer to given string value. -func PtrString(v string) *string { return &v } - -// PtrTime is helper routine that returns a pointer to given Time value. -func PtrTime(v time.Time) *time.Time { return &v } - -type NullableBool struct { - value *bool - isSet bool -} - -func (v NullableBool) Get() *bool { - return v.value -} - -func (v *NullableBool) Set(val *bool) { - v.value = val - v.isSet = true -} - -func (v NullableBool) IsSet() bool { - return v.isSet -} - -func (v *NullableBool) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableBool(val *bool) *NullableBool { - return &NullableBool{value: val, isSet: true} -} - -func (v NullableBool) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableBool) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableInt struct { - value *int - isSet bool -} - -func (v NullableInt) Get() *int { - return v.value -} - -func (v *NullableInt) Set(val *int) { - v.value = val - v.isSet = true -} - -func (v NullableInt) IsSet() bool { - return v.isSet -} - -func (v *NullableInt) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableInt(val *int) *NullableInt { - return &NullableInt{value: val, isSet: true} -} - -func (v NullableInt) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableInt) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableInt32 struct { - value *int32 - isSet bool -} - -func (v NullableInt32) Get() *int32 { - return v.value -} - -func (v *NullableInt32) Set(val *int32) { - v.value = val - v.isSet = true -} - -func (v NullableInt32) IsSet() bool { - return v.isSet -} - -func (v *NullableInt32) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableInt32(val *int32) *NullableInt32 { - return &NullableInt32{value: val, isSet: true} -} - -func (v NullableInt32) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableInt32) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableInt64 struct { - value *int64 - isSet bool -} - -func (v NullableInt64) Get() *int64 { - return v.value -} - -func (v *NullableInt64) Set(val *int64) { - v.value = val - v.isSet = true -} - -func (v NullableInt64) IsSet() bool { - return v.isSet -} - -func (v *NullableInt64) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableInt64(val *int64) *NullableInt64 { - return &NullableInt64{value: val, isSet: true} -} - -func (v NullableInt64) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableInt64) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableFloat32 struct { - value *float32 - isSet bool -} - -func (v NullableFloat32) Get() *float32 { - return v.value -} - -func (v *NullableFloat32) Set(val *float32) { - v.value = val - v.isSet = true -} - -func (v NullableFloat32) IsSet() bool { - return v.isSet -} - -func (v *NullableFloat32) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableFloat32(val *float32) *NullableFloat32 { - return &NullableFloat32{value: val, isSet: true} -} - -func (v NullableFloat32) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableFloat32) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableFloat64 struct { - value *float64 - isSet bool -} - -func (v NullableFloat64) Get() *float64 { - return v.value -} - -func (v *NullableFloat64) Set(val *float64) { - v.value = val - v.isSet = true -} - -func (v NullableFloat64) IsSet() bool { - return v.isSet -} - -func (v *NullableFloat64) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableFloat64(val *float64) *NullableFloat64 { - return &NullableFloat64{value: val, isSet: true} -} - -func (v NullableFloat64) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableFloat64) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableString struct { - value *string - isSet bool -} - -func (v NullableString) Get() *string { - return v.value -} - -func (v *NullableString) Set(val *string) { - v.value = val - v.isSet = true -} - -func (v NullableString) IsSet() bool { - return v.isSet -} - -func (v *NullableString) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableString(val *string) *NullableString { - return &NullableString{value: val, isSet: true} -} - -func (v NullableString) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableString) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableTime struct { - value *time.Time - isSet bool -} - -func (v NullableTime) Get() *time.Time { - return v.value -} - -func (v *NullableTime) Set(val *time.Time) { - v.value = val - v.isSet = true -} - -func (v NullableTime) IsSet() bool { - return v.isSet -} - -func (v *NullableTime) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableTime(val *time.Time) *NullableTime { - return &NullableTime{value: val, isSet: true} -} - -func (v NullableTime) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableTime) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -// IsNil checks if an input is nil -func IsNil(i interface{}) bool { - if i == nil { - return true - } - switch reflect.TypeOf(i).Kind() { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: - return reflect.ValueOf(i).IsNil() - case reflect.Array: - return reflect.ValueOf(i).IsZero() - } - return false -} - -type MappedNullable interface { - ToMap() (map[string]interface{}, error) -} - -// A wrapper for strict JSON decoding -func newStrictDecoder(data []byte) *json.Decoder { - dec := json.NewDecoder(bytes.NewBuffer(data)) - dec.DisallowUnknownFields() - return dec -} - -// Prevent trying to import "fmt" -func reportError(format string, a ...interface{}) error { - return fmt.Errorf(format, a...) -}