Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ node_modules/
# Environment
.env
.env.*
.codegraph/
.codegraph/.pi/
74 changes: 62 additions & 12 deletions cmd/get_config.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package cmd

import (
"encoding/json"
"fmt"
"os"
"strings"

"github.com/nacos-group/nacos-cli/internal/help"
"github.com/spf13/cobra"
)

var configGetOutput string // pretty (default) | json | raw

var getConfigCmd = &cobra.Command{
Use: "config-get [dataId] [group]",
Short: "Get a specific configuration",
Expand All @@ -19,25 +24,70 @@ var getConfigCmd = &cobra.Command{
// Create Nacos client
nacosClient := mustNewNacosClient()

// Get config
fmt.Printf("Fetching config: %s (%s)...\n\n", dataID, group)
output := strings.ToLower(configGetOutput)
if output == "" {
output = "pretty"
}
if output == "pretty" {
fmt.Printf("Fetching config: %s (%s)...\n\n", dataID, group)
}

content, err := nacosClient.GetConfig(dataID, group)
checkError(err)

if content == "" {
fmt.Println("Configuration not found")
return
switch output {
case "pretty":
renderConfigGetPretty(dataID, group, content)
case "json":
renderConfigGetJSON(dataID, group, content)
case "raw":
renderConfigGetRaw(content)
default:
fmt.Fprintf(os.Stderr, "Error: unsupported --output value %q (expect 'pretty', 'json' or 'raw')\n", configGetOutput)
os.Exit(1)
}

// Display content
fmt.Println("═══════════════════════════════════════")
fmt.Printf("Data ID: %s\n", dataID)
fmt.Printf("Group: %s\n", group)
fmt.Println("═══════════════════════════════════════")
fmt.Println(content)
},
}

func init() {
getConfigCmd.Flags().StringVar(&configGetOutput, "output", "pretty", "Output format: pretty | json | raw")
rootCmd.AddCommand(getConfigCmd)
}

// renderConfigGetPretty prints a human-readable header frame followed by the
// config content.
func renderConfigGetPretty(dataID, group, content string) {
if content == "" {
fmt.Println("Configuration not found")
return
}
fmt.Println("═══════════════════════════════════════")
fmt.Printf("Data ID: %s\n", dataID)
fmt.Printf("Group: %s\n", group)
fmt.Println("═══════════════════════════════════════")
fmt.Println(content)
}

// renderConfigGetRaw prints the config content verbatim with no decoration, so
// it can be piped to a file or another tool without contamination.
func renderConfigGetRaw(content string) {
if content == "" {
return
}
fmt.Print(content)
}

// renderConfigGetJSON emits the raw {dataId, group, content} payload so scripts
// can consume it without parsing decorative output.
func renderConfigGetJSON(dataID, group, content string) {
data, err := json.MarshalIndent(map[string]string{
"dataId": dataID,
"group": group,
"content": content,
}, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to encode JSON: %v\n", err)
os.Exit(1)
}
fmt.Println(string(data))
}
117 changes: 117 additions & 0 deletions cmd/get_config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package cmd

import (
"encoding/json"
"strings"
"testing"
)

func TestRenderConfigGetPretty_WithContent(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetPretty("my-data-id", "my-group", "key: value\nfoo: bar\n")
})

if !strings.Contains(got, "Data ID: my-data-id") {
t.Fatalf("missing data ID header\ngot:\n%s", got)
}
if !strings.Contains(got, "Group: my-group") {
t.Fatalf("missing group header\ngot:\n%s", got)
}
if !strings.Contains(got, "key: value") {
t.Fatalf("missing content\ngot:\n%s", got)
}
if !strings.Contains(got, "═══════════════════════════════════════") {
t.Fatalf("missing separator\ngot:\n%s", got)
}
}

func TestRenderConfigGetPretty_Empty(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetPretty("d", "g", "")
})

if got != "Configuration not found\n" {
t.Fatalf("got %q, want %q", got, "Configuration not found\n")
}
}

func TestRenderConfigGetJSON(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetJSON("my-data-id", "my-group", "hello\nworld")
})

var parsed map[string]string
if err := json.Unmarshal([]byte(got), &parsed); err != nil {
t.Fatalf("invalid JSON: %v\nraw: %s", err, got)
}

if parsed["dataId"] != "my-data-id" {
t.Errorf("dataId = %q, want %q", parsed["dataId"], "my-data-id")
}
if parsed["group"] != "my-group" {
t.Errorf("group = %q, want %q", parsed["group"], "my-group")
}
if parsed["content"] != "hello\nworld" {
t.Errorf("content = %q, want %q", parsed["content"], "hello\nworld")
}
}

func TestRenderConfigGetJSON_EmptyContent(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetJSON("d", "g", "")
})

var parsed map[string]string
if err := json.Unmarshal([]byte(got), &parsed); err != nil {
t.Fatalf("invalid JSON: %v\nraw: %s", err, got)
}

if parsed["dataId"] != "d" {
t.Errorf("dataId = %q", parsed["dataId"])
}
if parsed["group"] != "g" {
t.Errorf("group = %q", parsed["group"])
}
if parsed["content"] != "" {
t.Errorf("content = %q, want empty", parsed["content"])
}
}

func TestRenderConfigGetRaw(t *testing.T) {
t.Run("with content", func(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetRaw("line1\nline2\n")
})
if got != "line1\nline2\n" {
t.Fatalf("got %q, want %q", got, "line1\nline2\n")
}
})

t.Run("without trailing newline", func(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetRaw("no-newline")
})
if got != "no-newline" {
t.Fatalf("got %q, want %q", got, "no-newline")
}
})

t.Run("empty content", func(t *testing.T) {
got := captureStdout(t, func() {
renderConfigGetRaw("")
})
if got != "" {
t.Fatalf("got %q, want empty", got)
}
})
}

func TestConfigGetOutputFlagRegistered(t *testing.T) {
flag := getConfigCmd.Flags().Lookup("output")
if flag == nil {
t.Fatal("--output flag not registered on config-get command")
}
if flag.DefValue != "pretty" {
t.Errorf("default = %q, want %q", flag.DefValue, "pretty")
}
}
5 changes: 4 additions & 1 deletion cmd/set_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"fmt"
"os"

"github.com/nacos-group/nacos-cli/internal/client"
"github.com/nacos-group/nacos-cli/internal/help"
"github.com/spf13/cobra"
)

var setConfigFile string
var setConfigType string

var setConfigCmd = &cobra.Command{
Use: "config-set [dataId] [group]",
Expand All @@ -32,7 +34,7 @@ var setConfigCmd = &cobra.Command{
nacosClient := mustNewNacosClient()

fmt.Printf("Publishing config: %s (%s)...\n", dataID, group)
err = nacosClient.PublishConfig(dataID, group, content)
err = nacosClient.PublishConfigWithOptions(dataID, group, content, client.PublishConfigOptions{Type: setConfigType})
checkError(err)

fmt.Println("Configuration published successfully")
Expand Down Expand Up @@ -64,6 +66,7 @@ func readSetConfigContent() (string, error) {

func init() {
setConfigCmd.Flags().StringVarP(&setConfigFile, "file", "f", "", "Path to config file (default: read from stdin)")
setConfigCmd.Flags().StringVarP(&setConfigType, "type", "t", "", "Nacos config type metadata (for example yaml, json, text)")
_ = setConfigCmd.MarkFlagFilename("file")
rootCmd.AddCommand(setConfigCmd)
}
101 changes: 100 additions & 1 deletion internal/client/nacos_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,11 @@ func (c *NacosClient) GetConfig(dataID, group string) (string, error) {
ns = ""
}

// Nacos 2.x 服务端没有 v3 client API,回退到 v1
if c.authLoginVersion == "v1" {
return c.getConfigV1(dataID, group, ns)
}

params := url.Values{}
params.Set("dataId", dataID)
params.Set("groupName", group)
Expand Down Expand Up @@ -704,8 +709,51 @@ func (c *NacosClient) GetConfig(dataID, group string) (string, error) {
return config.Content, nil
}

// PublishConfig publishes a configuration
// getConfigV1 retrieves a specific configuration using Nacos v1 API.
// Nacos 2.x 服务端不存在 v3 client API(/nacos/v3/client/cs/config),
// 当登录探测判定为 v1 时回退到此实现。
func (c *NacosClient) getConfigV1(dataID, group, namespace string) (string, error) {
params := url.Values{}
params.Set("dataId", dataID)
params.Set("group", group)
if namespace != "" {
params.Set("tenant", namespace)
}

if c.AuthType == AuthTypeNacos && c.AccessToken != "" {
params.Set("accessToken", c.AccessToken)
}

v1URL := fmt.Sprintf("%s/nacos/v1/cs/configs", c.BaseURL())
resp, err := c.doWithStsRetry(func() (*resty.Response, error) {
req := c.httpClient.R().SetQueryString(params.Encode())
c.setSpasHeaders(req, namespace, group)
return req.Get(v1URL)
})
if err != nil {
return "", fmt.Errorf("v1 get config failed: %w", err)
}

if resp.StatusCode() != 200 {
return "", ParseHTTPError(resp.StatusCode(), resp.Body(), "get config (v1)")
}

// v1 直接返回配置内容(非 JSON 包装),404 时返回空串由上层处理
return string(resp.Body()), nil
}

// PublishConfigOptions contains optional metadata used when publishing config.
type PublishConfigOptions struct {
Type string
}

// PublishConfig publishes a configuration.
func (c *NacosClient) PublishConfig(dataID, group, content string) error {
return c.PublishConfigWithOptions(dataID, group, content, PublishConfigOptions{})
}

// PublishConfigWithOptions publishes a configuration with optional metadata.
func (c *NacosClient) PublishConfigWithOptions(dataID, group, content string, opts PublishConfigOptions) error {
if err := c.EnsureTokenValid(); err != nil {
return err
}
Expand All @@ -714,11 +762,19 @@ func (c *NacosClient) PublishConfig(dataID, group, content string) error {
"groupName": group,
"content": content,
}
if opts.Type != "" {
params["type"] = opts.Type
}

if c.Namespace != "" {
params["namespaceId"] = c.Namespace
}

// Nacos 2.x 服务端没有 v3 admin API(/nacos/v3/admin/cs/config),回退到 v1
if c.authLoginVersion == "v1" {
return c.publishConfigV1(dataID, group, content, opts)
}

apiURL := fmt.Sprintf("%s/nacos/v3/admin/cs/config", c.BaseURL())
resp, err := c.doWithStsRetry(func() (*resty.Response, error) {
req := c.httpClient.R().SetFormData(params)
Expand Down Expand Up @@ -757,3 +813,46 @@ func (c *NacosClient) PublishConfig(dataID, group, content string) error {

return nil
}

// publishConfigV1 publishes a configuration using Nacos v1 API.
// Nacos 2.x 服务端不存在 v3 admin API(/nacos/v3/admin/cs/config),
// 当登录探测判定为 v1 时回退到此实现。
// v1 与 v3 的差异:路径 /nacos/v1/cs/configs;参数 group(非 groupName)、
// tenant(非 namespaceId);token 放 accessToken 表单字段(非 Authorization 头);
// 响应为字面量 "true"/"false"(非 JSON 包装)。
func (c *NacosClient) publishConfigV1(dataID, group, content string, opts PublishConfigOptions) error {
params := map[string]string{
"dataId": dataID,
"group": group,
"content": content,
}
if opts.Type != "" {
params["type"] = opts.Type
}
if c.Namespace != "" {
params["tenant"] = c.Namespace
}
if c.AuthType == AuthTypeNacos && c.AccessToken != "" {
params["accessToken"] = c.AccessToken
}

v1URL := fmt.Sprintf("%s/nacos/v1/cs/configs", c.BaseURL())
resp, err := c.doWithStsRetry(func() (*resty.Response, error) {
req := c.httpClient.R().SetFormData(params)
c.setSpasHeaders(req, c.Namespace, group)
return req.Post(v1URL)
})
if err != nil {
return fmt.Errorf("publish config failed (v1): %w", err)
}

if resp.StatusCode() != 200 {
return ParseHTTPError(resp.StatusCode(), resp.Body(), "publish config (v1)")
}

// v1 成功返回字面量 "true"
if strings.TrimSpace(string(resp.Body())) == "true" {
return nil
}
return fmt.Errorf("publish config failed (v1): server returned %s", string(resp.Body()))
}
Loading