From 18a93d8accdeb633f25d4200fdd003362bfcc6cb Mon Sep 17 00:00:00 2001 From: yangyile Date: Tue, 3 Dec 2024 17:22:07 +0700 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8D=95=E5=8D=87=E7=BA=A7=E4=BE=9D?= =?UTF-8?q?=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 73 +++++++++++++++++++ LICENSE | 21 ++++++ Makefile | 10 +++ README.md | 86 ++++++++++++++++++----- README.zh.md | 65 +++++++++++++++++ go.mod | 11 +-- go.sum | 15 ++-- internal/sures/sure_stub.gen_test.go | 72 +++++++++---------- neatjson.go | 99 +++++++++++++------------- neatjson_test.go | 10 +-- neatjsons/neatjsons_test.go | 101 ++++++++++++++++++++++++++- sure_cls.gen_test.go | 21 +++--- vars.go | 14 ++++ vars_test.go | 15 ++++ 14 files changed, 481 insertions(+), 132 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.zh.md create mode 100644 vars.go create mode 100644 vars_test.go diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..7af6886 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,73 @@ +name: create-release + +on: + push: + branches: + - main # 监听 main 分支的 push 操作(编译和测试/代码检查) + tags: + - 'v*' # 监听以 'v' 开头的标签的 push 操作(发布 Release) + +jobs: + lint: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v5 + with: + go-version: "1.23.x" + - uses: actions/checkout@v4 + - name: golangci-lint + uses: golangci/golangci-lint-action@v6 + with: + version: latest + + test: + runs-on: ubuntu-latest + strategy: + matrix: + go: [ "1.22.x", "1.23.x" ] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go }} + + - name: Run test + run: make test COVERAGE_DIR=/tmp/coverage + + - name: Send goveralls coverage + uses: shogo82148/actions-goveralls@v1 + with: + path-to-profile: /tmp/coverage/combined.txt + flag-name: Go-${{ matrix.go }} + parallel: true + + check-coverage: + name: Check coverage + needs: [ test ] + runs-on: ubuntu-latest + steps: + - uses: shogo82148/actions-goveralls@v1 + with: + parallel-finished: true + + # 发布 Release + release: + name: Release a new version + needs: [ lint, test ] + runs-on: ubuntu-latest + # 仅在推送标签时执行 + if: ${{ success() && startsWith(github.ref, 'refs/tags/v') }} + steps: + # 1. 检出代码 + - name: Checkout code + uses: actions/checkout@v4 + + # 2. 创建 Release 和上传源码包 + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + generate_release_notes: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7b2c0ba --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 yangyile-yyle88 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..40b7193 --- /dev/null +++ b/Makefile @@ -0,0 +1,10 @@ +COVERAGE_DIR ?= .coverage + +# cp from: https://github.com/yyle88/sure/blob/10a10cb5c07f6239fc8e310459fb6a240dd117ce/Makefile#L4 +test: + @-rm -r $(COVERAGE_DIR) + @mkdir $(COVERAGE_DIR) + make test-with-flags TEST_FLAGS='-v -race -covermode atomic -coverprofile $$(COVERAGE_DIR)/combined.txt -bench=. -benchmem -timeout 20m' + +test-with-flags: + @go test $(TEST_FLAGS) ./... diff --git a/README.md b/README.md index c9ab968..30c02d3 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,77 @@ +[![GitHub Workflow Status (branch)](https://img.shields.io/github/actions/workflow/status/yyle88/neatjson/release.yml?branch=main&label=BUILD)](https://github.com/yyle88/neatjson/actions/workflows/release.yml?query=branch%3Amain) +[![GoDoc](https://pkg.go.dev/badge/github.com/yyle88/neatjson)](https://pkg.go.dev/github.com/yyle88/neatjson) +[![Coverage Status](https://img.shields.io/coveralls/github/yyle88/neatjson/master.svg)](https://coveralls.io/github/yyle88/neatjson?branch=main) +![Supported Go Versions](https://img.shields.io/badge/Go-1.22%2C%201.23-lightgrey.svg) +[![GitHub Release](https://img.shields.io/github/release/yyle88/neatjson.svg)](https://github.com/yyle88/neatjson/releases) +[![Go Report Card](https://goreportcard.com/badge/github.com/yyle88/neatjson)](https://goreportcard.com/report/github.com/yyle88/neatjson) + # neatjson -neat json make it neat to use "encoding/json" in golang. -其操作很简单,就是把结构体转json时,传统结果是: -``` -{"a": "abc","n": 123} +`neatjson` make it neat to use "encoding/json" in golang. + +## CHINESE README + +[中文说明](README.zh.md) + +## Installation + +```bash +go get github.com/yyle88/neatjson ``` -这个是转带换行和缩进格式的,便于观察,仅此而已: + +## Features + +- Convert Go structures to indented JSON strings. +- Format JSON data from raw strings, byte arrays. + +## Usage + +Here's an example of how to format a Go data structure into a indented JSON string: + +```go +package main + +import ( + "fmt" + "github.com/yyle88/neatjson/neatjsons" +) + +func main() { + arg := map[string]any{"a": "abc", "n": 123} + res := neatjsons.S(arg) + + fmt.Println(res) +} ``` + +Output: + +```json { - "a": "abc", - "n": 123 + "a": "abc", + "n": 123 } ``` -具体使用方法是: -``` -go get github.com/yyle88/neatjson -``` -在代码中使用时: -``` -fmt.Println(neatjsons.S( a )) -``` -非常非常的方便。 + +--- + +## License + +`neatjson` is open-source and released under the MIT License. See the [LICENSE](LICENSE) file for more information. + +--- + +## Support + +Welcome to contribute to this project by submitting pull requests or reporting issues. + +If you find this package helpful, give it a star on GitHub! + +**Thank you for your support!** + +**Happy Coding with `neatjson`!** 🎉 + +Give me stars. Thank you!!! + +## See stars +[![see stars](https://starchart.cc/yyle88/neatjson.svg?variant=adaptive)](https://starchart.cc/yyle88/neatjson) diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..86851f6 --- /dev/null +++ b/README.zh.md @@ -0,0 +1,65 @@ +# neatjson + +`neatjson` 使得在 Golang 中使用 "encoding/json" 更加简洁和方便。 + +## 英文文档 + +[English README](README.md) + +## 安装 + +```bash +go get github.com/yyle88/neatjson +``` + +## 特性 + +- 将 Go 结构体转换为带缩进的 JSON 字符串。 +- 格式化原始字符串和字节数组中的 JSON 数据。 + +## 用法 + +以下是如何将 Go 数据结构格式化为带缩进的 JSON 字符串的示例: + +```go +package main + +import ( + "fmt" + "github.com/yyle88/neatjson/neatjsons" +) + +func main() { + arg := map[string]any{"a": "abc", "n": 123} + res := neatjsons.S(arg) + + fmt.Println(res) +} +``` + +输出: + +```json +{ + "a": "abc", + "n": 123 +} +``` + +--- + +## 许可 + +`neatjson` 是一个开源项目,发布于 MIT 许可证下。有关更多信息,请参阅 [LICENSE](LICENSE) 文件。 + +## 贡献与支持 + +欢迎通过提交 pull request 或报告问题来贡献此项目。 + +如果你觉得这个包对你有帮助,请在 GitHub 上给个 ⭐,感谢支持!!! + +**感谢你的支持!** + +**祝编程愉快!** 🎉 + +Give me stars. Thank you!!! diff --git a/go.mod b/go.mod index 514f339..6a72575 100644 --- a/go.mod +++ b/go.mod @@ -5,21 +5,24 @@ go 1.22.8 require ( github.com/stretchr/testify v1.10.0 github.com/yyle88/erero v1.0.14 - github.com/yyle88/runpath v1.0.21 - github.com/yyle88/sure v0.0.28 + github.com/yyle88/rese v0.0.1 + github.com/yyle88/runpath v1.0.22 + github.com/yyle88/sure v0.0.31 github.com/yyle88/syntaxgo v0.0.35 ) require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/yyle88/done v1.0.18 // indirect - github.com/yyle88/formatgo v1.0.17 // indirect + github.com/yyle88/formatgo v1.0.19 // indirect github.com/yyle88/must v0.0.9 // indirect github.com/yyle88/mutexmap v1.0.8 // indirect github.com/yyle88/printgo v1.0.1 // indirect - github.com/yyle88/rese v0.0.1 // indirect github.com/yyle88/tern v0.0.3 // indirect github.com/yyle88/zaplog v0.0.16 // indirect go.uber.org/multierr v1.11.0 // indirect diff --git a/go.sum b/go.sum index df80c4c..926c315 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,16 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= @@ -16,8 +19,8 @@ github.com/yyle88/done v1.0.18 h1:O71T+76laNmuY1kYP8PHkp6uceoN6ABTng/8c9KpZts= github.com/yyle88/done v1.0.18/go.mod h1:32UMgjuZP9LctfNNhBQqTyVbjggPOWpoXn8Mp0VrQbw= github.com/yyle88/erero v1.0.14 h1:ozS3iPLIsnRPSs8AdfbA/3f3hGw5EFkJMkfA/dfI+do= github.com/yyle88/erero v1.0.14/go.mod h1:NhP5EcPoVlShkMk1cVCFP3im5Zm+JRG35qIInMw7aeo= -github.com/yyle88/formatgo v1.0.17 h1:D+Y+nN2UC09NviEgiMtew80+VfQUsE9cZgBFd3kZXRk= -github.com/yyle88/formatgo v1.0.17/go.mod h1:B0JcneKcVTNjOUTPkg1nnnCemtdukfP7ijiTBVX/ItY= +github.com/yyle88/formatgo v1.0.19 h1:XgcSB8KsGLTnv7UOCVZDtrd3yJggFd2J82xG5qvmdFI= +github.com/yyle88/formatgo v1.0.19/go.mod h1:Q+JpNGVgskW2Xl+BdHXZ7r6y6TQlQOyN7/23Gu/wzoM= github.com/yyle88/must v0.0.9 h1:LA03i1O4/6Syopma8xqJMiWfAWeehoySeUaRmdQEvKY= github.com/yyle88/must v0.0.9/go.mod h1:5Ur4BKRx6GuW4gCZNx8Hf+iRS9lVmywSkCpxun/f+Do= github.com/yyle88/mutexmap v1.0.8 h1:VntAdXID5wbk211LZEPVK96jQBxIcfVIbQuk9cv3P/8= @@ -26,10 +29,10 @@ github.com/yyle88/printgo v1.0.1 h1:0lCpq28Tlf0jmYhSIlDQ7A3hAqVYswhBuURLR9xbmsw= github.com/yyle88/printgo v1.0.1/go.mod h1:yCvpShGBkKdWX5RO+yum2gLbru9ebc04sVmuzhPKSMw= github.com/yyle88/rese v0.0.1 h1:Eu2I+7BpbkX1n7SOu11AHVqecTuOVdg4becgt2ThGIo= github.com/yyle88/rese v0.0.1/go.mod h1:GoPiHJPEWyeBL0DxOHT5hLnibFbav+jck/NZxLqNVI8= -github.com/yyle88/runpath v1.0.21 h1:uWi1QrMCU5QUWU1oJJxbmlSCrCwPDRe+tlikV0JbvWM= -github.com/yyle88/runpath v1.0.21/go.mod h1:JRGxn/0Ytg6CvGoE2VrO74oX8Lu4jbOPZDKxr8tzPEg= -github.com/yyle88/sure v0.0.28 h1:zVvuVY4Z7cfWkvxEZp1QjbfSTEC2fy/YTlEjSC7Ua0Y= -github.com/yyle88/sure v0.0.28/go.mod h1:C4Mystu7UVdrP658hrxS5jlDE1soh9ZZ1NYJOIVQA6g= +github.com/yyle88/runpath v1.0.22 h1:gcyaNMNZq7yjL2Xlwvs0W7BOkzn4VJTJqA8ko7CKhKg= +github.com/yyle88/runpath v1.0.22/go.mod h1:JRGxn/0Ytg6CvGoE2VrO74oX8Lu4jbOPZDKxr8tzPEg= +github.com/yyle88/sure v0.0.31 h1:CBCppn/EtLBGyLBddPOI3GiLOkxexHU/Pj3ohN5aTBQ= +github.com/yyle88/sure v0.0.31/go.mod h1:29eZWpgHwkeK3bq8TL2Db7PP2Zi6JagGJd+gOAjcdjw= github.com/yyle88/syntaxgo v0.0.35 h1:jcDpBTkVehgaQq3LGOQD/jBFu7eauVn2rqc7qKCqzts= github.com/yyle88/syntaxgo v0.0.35/go.mod h1:blSLJ3XoI8KWT5FISdBTISi1cHElQxtBzZ2UaeDja9w= github.com/yyle88/tern v0.0.3 h1:Ut5p1wPAVcreEkmzDp+IiteA3K2vnTeAYE1PyBLNgjU= diff --git a/internal/sures/sure_stub.gen_test.go b/internal/sures/sure_stub.gen_test.go index 02573c9..5bdcea2 100644 --- a/internal/sures/sure_stub.gen_test.go +++ b/internal/sures/sure_stub.gen_test.go @@ -10,58 +10,58 @@ import ( ) func TestGenSoft(t *testing.T) { - param := cls_stub_gen.NewParam(&neatjson.Neatjson_Soft{}, "neatjson.TAB.Soft()") + stubParam := cls_stub_gen.NewStubParam(&neatjson.Neatjson_Soft{}, "neatjson.TAB.Soft()") - sourceDIRPath := runpath.PARENT.Join("./../../../neatjson") - t.Log(sourceDIRPath) + sourceRootPath := runpath.PARENT.Join("./../../../neatjson") + t.Log(sourceRootPath) - targetSrcPath := runpath.PARENT.Join("./../../neatjsons/neatjsons.go") - t.Log(targetSrcPath) + outputPath := runpath.PARENT.Join("./../../neatjsons/neatjsons.go") + t.Log(outputPath) - cfg := &cls_stub_gen.Config{ - SrcRoot: sourceDIRPath, - TargetPkgName: "neatjsons", - ImportOptions: syntaxgo_ast.NewPackageImportOptions(), - TargetSrcPath: targetSrcPath, - CanCreateFile: false, + config := &cls_stub_gen.StubGenConfig{ + SourceRootPath: sourceRootPath, + TargetPackageName: "neatjsons", + ImportOptions: syntaxgo_ast.NewPackageImportOptions(), + OutputPath: outputPath, + AllowFileCreation: false, } - cls_stub_gen.Gen(cfg, param) + cls_stub_gen.GenerateStubs(config, stubParam) } func TestGenMust(t *testing.T) { - param := cls_stub_gen.NewParam(&neatjson.Neatjson_Soft{}, "neatjson.TAB.Must()") + stubParam := cls_stub_gen.NewStubParam(&neatjson.Neatjson_Soft{}, "neatjson.TAB.Must()") - sourceDIRPath := runpath.PARENT.Join("./../../../neatjson") - t.Log(sourceDIRPath) + sourceRootPath := runpath.PARENT.Join("./../../../neatjson") + t.Log(sourceRootPath) - targetSrcPath := runpath.PARENT.Join("./../../neatjsonm/neatjsonm.go") - t.Log(targetSrcPath) + outputPath := runpath.PARENT.Join("./../../neatjsonm/neatjsonm.go") + t.Log(outputPath) - cfg := &cls_stub_gen.Config{ - SrcRoot: sourceDIRPath, - TargetPkgName: "neatjsonm", - ImportOptions: syntaxgo_ast.NewPackageImportOptions(), - TargetSrcPath: targetSrcPath, - CanCreateFile: false, + config := &cls_stub_gen.StubGenConfig{ + SourceRootPath: sourceRootPath, + TargetPackageName: "neatjsonm", + ImportOptions: syntaxgo_ast.NewPackageImportOptions(), + OutputPath: outputPath, + AllowFileCreation: false, } - cls_stub_gen.Gen(cfg, param) + cls_stub_gen.GenerateStubs(config, stubParam) } func TestGenOmit(t *testing.T) { - param := cls_stub_gen.NewParam(&neatjson.Neatjson_Soft{}, "neatjson.TAB.Omit()") + stubParam := cls_stub_gen.NewStubParam(&neatjson.Neatjson_Soft{}, "neatjson.TAB.Omit()") - sourceDIRPath := runpath.PARENT.Join("./../../../neatjson") - t.Log(sourceDIRPath) + sourceRootPath := runpath.PARENT.Join("./../../../neatjson") + t.Log(sourceRootPath) - targetSrcPath := runpath.PARENT.Join("./../../neatjsono/neatjsono.go") - t.Log(targetSrcPath) + outputPath := runpath.PARENT.Join("./../../neatjsono/neatjsono.go") + t.Log(outputPath) - cfg := &cls_stub_gen.Config{ - SrcRoot: sourceDIRPath, - TargetPkgName: "neatjsono", - ImportOptions: syntaxgo_ast.NewPackageImportOptions(), - TargetSrcPath: targetSrcPath, - CanCreateFile: false, + config := &cls_stub_gen.StubGenConfig{ + SourceRootPath: sourceRootPath, + TargetPackageName: "neatjsono", + ImportOptions: syntaxgo_ast.NewPackageImportOptions(), + OutputPath: outputPath, + AllowFileCreation: false, } - cls_stub_gen.Gen(cfg, param) + cls_stub_gen.GenerateStubs(config, stubParam) } diff --git a/neatjson.go b/neatjson.go index 7c73cbd..abf8651 100644 --- a/neatjson.go +++ b/neatjson.go @@ -7,45 +7,42 @@ import ( "github.com/yyle88/erero" ) -// 这里定义些 常用常量 以便于外部直接使用 -var ( - TAB = NewNeatjson("", "\t") - SP0 = NewNeatjson("", "") - SP1 = NewNeatjson("", " ") - SP2 = NewNeatjson("", " ") - SP3 = NewNeatjson("", " ") - SP4 = NewNeatjson("", " ") - - NOI = NewNeatjson("", "").setPrettyValue(false) //当使用这个转json时结果不换行 - - NON = NOI //换个名字有利于身心健康 -) - -// Neatjson 该类中实现各种简单的语法糖,以便于把 golang struct 转换为 json string,以便于开发者(我自己)使用 -// neat 含义有:整齐的、工整的、简洁的、整洁的 +// Neatjson implements various syntactic sugar to convert Go structs into JSON strings. +// The purpose of this package is to provide neat, indented JSON representations. +// Neatjson 实现了一些简单的语法糖,用于将 Go 的结构体转换为 JSON 字符串。 +// neat 的含义包括:整齐的、工整的、简洁的、整洁的。 type Neatjson struct { - prefix string - indent string - pretty bool //在转json时是否换行,当为false时不换行,还是用直接转的函数 + prefix string // Prefix for JSON indentation. // 结果 JSON 的缩进前缀。 + indent string // Indentation characters. // 缩进字符。 + active bool // Whether to use line breaks when converting to JSON. // 是否使用缩进的转换函数。 } +// NewNeatjson creates a new instance of Neatjson with the specified prefix and indent. +// NewNeatjson 根据指定的前缀和缩进字符创建一个 Neatjson 实例。 func NewNeatjson(prefix string, indent string) *Neatjson { return &Neatjson{ prefix: prefix, indent: indent, - pretty: true, //默认设置为换行的,因为这个包的主要目的是得到有换行的json,因此默认就是有换行的 + active: true, // Default to using line breaks because the main purpose of this package is to create indented JSON. // 默认启用换行,因为这个包的主要目的就是生成带缩进的 JSON。 } } -// Bytes 把结构体转换为字节数组,跟 "json.Marshal" 类似的,只是这是带缩进的 +// notNeatjson returns a Neatjson instance that disables line breaks. +// notNeatjson 返回一个禁用换行的 Neatjson 实例。 +func notNeatjson() *Neatjson { + return NewNeatjson("", "").withActive(false) +} + +// Bytes converts a struct to a JSON byte array, similar to "json.Marshal" but supports indentation. +// Bytes 将结构体转换为 JSON 字节数组,与 "json.Marshal" 类似,但支持缩进。 func (N *Neatjson) Bytes(v interface{}) ([]byte, error) { - if N.useIndentLogic() { + if N.needIndent() { // Check if indentation is required. // 检查是否需要缩进。 data, err := json.MarshalIndent(v, N.prefix, N.indent) if err != nil { return nil, erero.Wro(err) } return data, nil - } else { + } else { // Use standard JSON marshaling without indentation. // 使用标准的 JSON 转换,不带缩进。 data, err := json.Marshal(v) if err != nil { return nil, erero.Wro(err) @@ -54,19 +51,21 @@ func (N *Neatjson) Bytes(v interface{}) ([]byte, error) { } } -// 结果是否需要换行,因为发现单独写个包处理不换行这件事其实没必要,就在这里使用标识位判定 -func (N *Neatjson) useIndentLogic() bool { - return N.pretty || N.prefix != "" || N.indent != "" +// needIndent checks whether line breaks and indentation are required. +// needIndent 检查是否需要换行和缩进。 +func (N *Neatjson) needIndent() bool { + return N.active || N.prefix != "" || N.indent != "" } -// 设置是否需要换行,这里使用非导出函数 -func (N *Neatjson) setPrettyValue(pretty bool) *Neatjson { - N.pretty = pretty +// withActive sets whether line breaks are enabled for JSON conversion. +// withActive 设置 JSON 转换时是否启用换行。 +func (N *Neatjson) withActive(active bool) *Neatjson { + N.active = active return N } -// Sjson 把结构体转换为 string,但是由于 String 这个单词既不利于全局搜索(会干扰IDE索引)也不利于代码重构 -// 因此换个个性化的方法名,避免和 interface { String() } 接口重名 +// Sjson converts a struct to a JSON string with the desired formatting. +// Sjson 将结构体转换为符合要求格式的 JSON 字符串。 func (N *Neatjson) Sjson(v interface{}) (string, error) { data, err := N.Bytes(v) if err != nil { @@ -75,17 +74,20 @@ func (N *Neatjson) Sjson(v interface{}) (string, error) { return string(data), nil } -// S 就是 Sjson 方法的简称 +// S is a shorthand for Sjson. +// S 是 Sjson 方法的简写。 func (N *Neatjson) S(v interface{}) (string, error) { return N.Sjson(v) } -// B 就是 Bytes 方法的简称 +// B is a shorthand for Bytes. +// B 是 Bytes 方法的简写。 func (N *Neatjson) B(v interface{}) ([]byte, error) { return N.Bytes(v) } -// SxS 把 json string 转换得到 neat json string +// SxS converts a JSON string into a neat JSON string with the desired formatting. +// SxS 将 JSON 字符串转换为符合要求格式的整齐 JSON 字符串。 func (N *Neatjson) SxS(s string) (string, error) { data, err := N.BxB([]byte(s)) if err != nil { @@ -94,22 +96,22 @@ func (N *Neatjson) SxS(s string) (string, error) { return string(data), nil } -// BxB 把 json bytes 转换得到 neat json bytes +// BxB converts a JSON byte array into a neat JSON byte array with the desired formatting. +// BxB 将 JSON 字节数组转换为符合要求格式的整齐 JSON 字节数组。 func (N *Neatjson) BxB(data []byte) ([]byte, error) { - if N.useIndentLogic() { - var ob bytes.Buffer - if err := json.Indent(&ob, data, N.prefix, N.indent); err != nil { + if N.needIndent() { // Use json.Indent for formatting when indentation is needed. // 在需要缩进时使用 json.Indent 格式化。 + var result bytes.Buffer + if err := json.Indent(&result, data, N.prefix, N.indent); err != nil { return data, erero.Wro(err) } - return ob.Bytes(), nil + return result.Bytes(), nil } else { return data, nil } } -// SxB 把 json bytes 转换得到 neat json string. "x" means "from". -// 因为当做 json.Marshal 的时候会把 bytes 转换为 Base64 字符串,而有时这不是我们期望的 -// 该函数期望的是把 bytes 转换为带缩进的 json 结果 +// SxB converts a JSON byte array into a neat JSON string. "x" means "from". +// SxB 将 JSON 字节数组转换为整齐的 JSON 字符串。"x" 表示 "from"。 func (N *Neatjson) SxB(data []byte) (string, error) { res, err := N.BxB(data) if err != nil { @@ -118,7 +120,8 @@ func (N *Neatjson) SxB(data []byte) (string, error) { return string(res), nil } -// BxS 把 json string 转换得到 neat json bytes. "x" means "from". +// BxS converts a JSON string into a neat JSON byte array. "x" means "from". +// BxS 将 JSON 字符串转换为整齐的 JSON 字节数组。"x" 表示 "from"。 func (N *Neatjson) BxS(data string) ([]byte, error) { res, err := N.BxB([]byte(data)) if err != nil { @@ -127,16 +130,14 @@ func (N *Neatjson) BxS(data string) ([]byte, error) { return res, nil } -// B2S convert json bytes to neat json string. num 2 means "to". -// 而前面的 SxB 是 get neat json string from json bytes 两种命名看个人爱好吧 +// B2S converts JSON bytes into a neat JSON string. "2" means "to". +// B2S 将 JSON 字节数组转换为整齐的 JSON 字符串。"2" 表示 "to"。 func (N *Neatjson) B2S(data []byte) (string, error) { return N.SxB(data) } -// S2B convert json string to neat json bytes. num 2 means "to". -// 我认为把返回写在前面,有利于使用,因为我们在用函数时会更重视它的返回值 -// 毕竟返回值是和下文相关的,而下文是我们要开发的,要让注意力去思考下文的需要,而不是去回顾上文的结果,这样有利于提高开发效率 -// 因此我更倾向于使用 "x" 操作而非 "2" 操作 +// S2B converts a JSON string into a neat JSON byte array. "2" means "to". +// S2B 将 JSON 字符串转换为整齐的 JSON 字节数组。"2" 表示 "to"。 func (N *Neatjson) S2B(data string) ([]byte, error) { return N.BxS(data) } diff --git a/neatjson_test.go b/neatjson_test.go index f1d4c48..00704fb 100644 --- a/neatjson_test.go +++ b/neatjson_test.go @@ -28,12 +28,6 @@ func TestNeatjson_Sjson(t *testing.T) { t.Log(res) } -func TestNeatjson_SP0_Sjson(t *testing.T) { - res, err := SP0.Sjson(caseExample) - require.NoError(t, err) - t.Log(res) -} - func TestNeatjson_NOI_Sjson(t *testing.T) { res, err := NOI.Sjson(caseExample) require.NoError(t, err) @@ -47,9 +41,9 @@ func TestNeatjson_SxS(t *testing.T) { t.Log(res) } -func TestNeatjson_NOI_SxS(t *testing.T) { +func TestNeatjson_NON_SxS(t *testing.T) { arg := `{"a": "abc","n": 123}` - res, err := NOI.SxS(arg) + res, err := NON.SxS(arg) require.NoError(t, err) t.Log(res) } diff --git a/neatjsons/neatjsons_test.go b/neatjsons/neatjsons_test.go index 1ea1a7a..841e141 100644 --- a/neatjsons/neatjsons_test.go +++ b/neatjsons/neatjsons_test.go @@ -1,13 +1,108 @@ -package neatjsons +package neatjsons_test import ( "testing" + + "github.com/stretchr/testify/require" + "github.com/yyle88/neatjson/neatjsons" ) +func TestBytes(t *testing.T) { + input := map[string]any{"key": "value", "num": 123} + expected := `{ + "key": "value", + "num": 123 +}` + result := string(neatjsons.Bytes(input)) + require.Equal(t, expected, result) +} + +func TestSjson(t *testing.T) { + input := map[string]any{"key": "value", "num": 123} + expected := `{ + "key": "value", + "num": 123 +}` + result := neatjsons.Sjson(input) + require.Equal(t, expected, result) +} + func TestS(t *testing.T) { - t.Log(S(map[string]any{"a": "abc", "n": 123})) + input := map[string]any{"a": "abc", "n": 123} + expected := `{ + "a": "abc", + "n": 123 +}` + result := neatjsons.S(input) + require.Equal(t, expected, result) } func TestB(t *testing.T) { - t.Log(string(B(map[string]any{"a": "abc", "n": 123}))) + input := map[string]any{"a": "abc", "n": 123} + expected := `{ + "a": "abc", + "n": 123 +}` + result := string(neatjsons.B(input)) + require.Equal(t, expected, result) +} + +func TestSxS(t *testing.T) { + input := `{"a":"abc","n":123}` + expected := `{ + "a": "abc", + "n": 123 +}` + result := neatjsons.SxS(input) + require.Equal(t, expected, result) +} + +func TestBxB(t *testing.T) { + input := []byte(`{"a":"abc","n":123}`) + expected := []byte(`{ + "a": "abc", + "n": 123 +}`) + result := neatjsons.BxB(input) + require.Equal(t, string(expected), string(result)) +} + +func TestSxB(t *testing.T) { + input := []byte(`{"a":"abc","n":123}`) + expected := `{ + "a": "abc", + "n": 123 +}` + result := neatjsons.SxB(input) + require.Equal(t, expected, result) +} + +func TestBxS(t *testing.T) { + input := `{"a":"abc","n":123}` + expected := []byte(`{ + "a": "abc", + "n": 123 +}`) + result := neatjsons.BxS(input) + require.Equal(t, string(expected), string(result)) +} + +func TestB2S(t *testing.T) { + input := []byte(`{"key":"value","num":123}`) + expected := `{ + "key": "value", + "num": 123 +}` + result := neatjsons.B2S(input) + require.Equal(t, expected, result) +} + +func TestS2B(t *testing.T) { + input := `{"key":"value","num":123}` + expected := []byte(`{ + "key": "value", + "num": 123 +}`) + result := neatjsons.S2B(input) + require.Equal(t, string(expected), string(result)) } diff --git a/sure_cls.gen_test.go b/sure_cls.gen_test.go index 7ad1608..f547d8f 100644 --- a/sure_cls.gen_test.go +++ b/sure_cls.gen_test.go @@ -12,16 +12,17 @@ import ( ) func TestGen(t *testing.T) { - param := sure_cls_gen.NewGenParam(runpath.PARENT.Path()) - param.SetSubClassNamePartWords("_") - param.SetSubClassNameStyleEnum(sure_cls_gen.STYLE_SUFFIX_CAMELCASE_TYPE) - param.SetSureEnum(sure.MUST, sure.SOFT, sure.OMIT) + options := sure_cls_gen.NewClassGenOptions(runpath.PARENT.Path()). + WithNewClassNameParts("_"). + WithNamingPatternType(sure_cls_gen.STYLE_SUFFIX_CAMELCASE_TYPE). + MoreErrorHandlingModes(sure.MUST, sure.SOFT, sure.OMIT) - cfg := &sure_cls_gen.Config{ - GenParam: param, - PkgName: syntaxgo.CurrentPackageName(), - ImportOptions: syntaxgo_ast.NewPackageImportOptions(), - SrcPath: runtestpath.SrcPath(t), + config := &sure_cls_gen.ClassGenConfig{ + ClassGenOptions: options, + PackageName: syntaxgo.CurrentPackageName(), + ImportOptions: syntaxgo_ast.NewPackageImportOptions(), + OutputPath: runtestpath.SrcPath(t), } - sure_cls_gen.Gen(cfg, Neatjson{}) + + sure_cls_gen.GenerateClasses(config, Neatjson{}) } diff --git a/vars.go b/vars.go new file mode 100644 index 0000000..e79bddc --- /dev/null +++ b/vars.go @@ -0,0 +1,14 @@ +package neatjson + +// 这里定义些 常用常量 以便于外部直接使用 +var ( + TAB = NewNeatjson("", "\t") + SP0 = NewNeatjson("", "") + SP1 = NewNeatjson("", " ") + SP2 = NewNeatjson("", " ") + SP3 = NewNeatjson("", " ") + SP4 = NewNeatjson("", " ") + + NOI = notNeatjson() //在转json时结果不换行 + NON = notNeatjson() //在转json时结果不换行 +) diff --git a/vars_test.go b/vars_test.go new file mode 100644 index 0000000..0309ae0 --- /dev/null +++ b/vars_test.go @@ -0,0 +1,15 @@ +package neatjson + +import ( + "testing" + + "github.com/yyle88/rese" +) + +func TestNeatjson_SPX_Sjson(t *testing.T) { + t.Log(rese.C1(SP0.Sjson(caseExample))) + t.Log(rese.C1(SP1.Sjson(caseExample))) + t.Log(rese.C1(SP2.Sjson(caseExample))) + t.Log(rese.C1(SP3.Sjson(caseExample))) + t.Log(rese.C1(SP4.Sjson(caseExample))) +}