From 1da44322ba5265c8bd1574fef1c399f3a33b2c84 Mon Sep 17 00:00:00 2001 From: ZhangJian He Date: Sat, 30 Nov 2024 09:57:49 +0800 Subject: [PATCH] first commit --- .github/workflows/commit_lint.yml | 12 ++ .github/workflows/go_ci_lint.yml | 22 ++++ .github/workflows/go_imports.yml | 23 ++++ .github/workflows/go_mod_check.yml | 22 ++++ .github/workflows/go_unit_test.yml | 26 ++++ .github/workflows/line_lint.yml | 13 ++ .github/workflows/typo_check.yml | 13 ++ .gitignore | 26 ++++ .idea/.gitignore | 8 ++ .idea/asciitable.iml | 9 ++ .idea/modules.xml | 8 ++ .idea/vcs.xml | 6 + .idea/workspace.xml | 105 +++++++++++++++ LICENSE | 202 +++++++++++++++++++++++++++++ README.md | 18 +++ decode.go | 99 ++++++++++++++ decode_name_age_score.txt | 7 + decode_test.go | 31 +++++ go.mod | 11 ++ go.sum | 10 ++ 20 files changed, 671 insertions(+) create mode 100644 .github/workflows/commit_lint.yml create mode 100644 .github/workflows/go_ci_lint.yml create mode 100644 .github/workflows/go_imports.yml create mode 100644 .github/workflows/go_mod_check.yml create mode 100644 .github/workflows/go_unit_test.yml create mode 100644 .github/workflows/line_lint.yml create mode 100644 .github/workflows/typo_check.yml create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/asciitable.iml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 .idea/workspace.xml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 decode.go create mode 100644 decode_name_age_score.txt create mode 100644 decode_test.go create mode 100644 go.mod create mode 100644 go.sum diff --git a/.github/workflows/commit_lint.yml b/.github/workflows/commit_lint.yml new file mode 100644 index 0000000..0bd90b9 --- /dev/null +++ b/.github/workflows/commit_lint.yml @@ -0,0 +1,12 @@ +name: commit lint +on: + pull_request: + branches: + - main + +jobs: + commitlint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: wagoid/commitlint-github-action@v5 diff --git a/.github/workflows/go_ci_lint.yml b/.github/workflows/go_ci_lint.yml new file mode 100644 index 0000000..f6c6560 --- /dev/null +++ b/.github/workflows/go_ci_lint.yml @@ -0,0 +1,22 @@ +name: go ci Lint +on: + push: + branches: + - main + pull_request: + branches: + - main +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: "go.mod" + - name: golangci-lint + uses: golangci/golangci-lint-action@v6 + with: + version: latest + args: --timeout 3m0s diff --git a/.github/workflows/go_imports.yml b/.github/workflows/go_imports.yml new file mode 100644 index 0000000..f5db139 --- /dev/null +++ b/.github/workflows/go_imports.yml @@ -0,0 +1,23 @@ +name: go imports +on: + push: + branches: + - main + pull_request: + branches: + - main +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: 'stable' + - name: install goimports + run: go install golang.org/x/tools/cmd/goimports@latest + - name: run goimports + run: goimports -w . + - name: check for unformatted code + run: git diff --exit-code diff --git a/.github/workflows/go_mod_check.yml b/.github/workflows/go_mod_check.yml new file mode 100644 index 0000000..7080017 --- /dev/null +++ b/.github/workflows/go_mod_check.yml @@ -0,0 +1,22 @@ +name: go mod check + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + go_mod_check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: "go.mod" + - name: Run Go Mod Check Action + uses: shoothzj/go-mod-check-action@main + with: + prohibitIndirectDepUpdate: 'true' diff --git a/.github/workflows/go_unit_test.yml b/.github/workflows/go_unit_test.yml new file mode 100644 index 0000000..75c1a57 --- /dev/null +++ b/.github/workflows/go_unit_test.yml @@ -0,0 +1,26 @@ +name: go unit test + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + go_unit_test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: "go.mod" + - name: setup ZooKeeper + uses: shoothzj/setup-zookeeper-action@main + - name: Run coverage + run: go test ./... -coverpkg=./... -race -coverprofile=coverage.txt -covermode=atomic + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v4 + with: + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/line_lint.yml b/.github/workflows/line_lint.yml new file mode 100644 index 0000000..3051729 --- /dev/null +++ b/.github/workflows/line_lint.yml @@ -0,0 +1,13 @@ +name: line lint +on: + pull_request: + branches: + - main +jobs: + line_lint: + name: line lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: linelint + uses: shoothzj/linelint@main diff --git a/.github/workflows/typo_check.yml b/.github/workflows/typo_check.yml new file mode 100644 index 0000000..b89a9f9 --- /dev/null +++ b/.github/workflows/typo_check.yml @@ -0,0 +1,13 @@ +name: typo check +on: + pull_request: + branches: + - main +jobs: + typo_check: + name: typo check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Check typos + uses: crate-ci/typos@master diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b712300 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +# file system +.DS_Store + +# ide +.idea/** +.vscode/** +!.idea/icon.svg +!.idea/vcs.xml + +target/* + +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Go workspace file +go.work diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/asciitable.iml b/.idea/asciitable.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/asciitable.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..c2e3cb9 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..def7933 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c041c7a --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# asciitable + +![License](https://img.shields.io/badge/license-Apache2.0-green) +![Language](https://img.shields.io/badge/Language-Go-blue.svg) +[![version](https://img.shields.io/github/v/tag/libgox/asciitable?label=release&color=blue)](https://github.com/libgox/asciitable/releases) +[![Godoc](http://img.shields.io/badge/docs-go.dev-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/libgox/asciitable) +[![Go report](https://goreportcard.com/badge/github.com/libgox/asciitable)](https://goreportcard.com/report/github.com/libgox/asciitable) +[![codecov](https://codecov.io/gh/libgox/asciitable/branch/main/graph/badge.svg)](https://codecov.io/gh/libgox/asciitable) + +## 📋 Requirements + +- Go 1.18+ + +## 🚀 Install + +``` +go get github.com/libgox/asciitable +``` diff --git a/decode.go b/decode.go new file mode 100644 index 0000000..cca00b1 --- /dev/null +++ b/decode.go @@ -0,0 +1,99 @@ +package asciitable + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" +) + +// Unmarshal parses an ASCII table into a slice of the specified type. +func Unmarshal[E any](asciiTable string, v E) ([]string, []E, error) { + lines := strings.Split(strings.TrimSpace(asciiTable), "\n") + if len(lines) < 4 { + return nil, nil, errors.New("invalid ascii table format, must have at least 4 lines") + } + + // Extract headers + headerLine := strings.Trim(lines[1], "| ") + headers := splitRow(headerLine) + + // Reflect on the type of E + var results []E + elemType := reflect.TypeOf(v) + if elemType.Kind() != reflect.Struct { + return nil, nil, errors.New("v must be a struct type") + } + + // Process rows + for _, line := range lines[3 : len(lines)-1] { // Skip header and separator line + row := splitRow(strings.Trim(line, "| ")) + if len(row) != len(headers) { + return nil, nil, fmt.Errorf("row length does not match header length: %v", row) + } + + // Map header to struct fields + elem := reflect.New(elemType).Elem() + for i, header := range headers { + fieldFound := false + for j := 0; j < elem.NumField(); j++ { + field := elemType.Field(j) + tag := field.Tag.Get("asciitable") + if tag == header { + fieldFound = true + value := row[i] + err := setFieldValue(elem.Field(j), value) + if err != nil { + return nil, nil, fmt.Errorf("failed to set value for field '%s': %v", field.Name, err) + } + } + } + if !fieldFound { + return nil, nil, fmt.Errorf("header '%s' does not match any struct fields", header) + } + } + + // Append to results + results = append(results, elem.Interface().(E)) + } + + return headers, results, nil +} + +// Helper function to split a row by `|` and trim whitespace +func splitRow(row string) []string { + cells := strings.Split(row, "|") + for i := range cells { + cells[i] = strings.TrimSpace(cells[i]) + } + return cells +} + +// Helper function to set a field value with proper type conversion +func setFieldValue(field reflect.Value, value string) error { + if !field.CanSet() { + return errors.New("cannot set value to the field") + } + + switch field.Kind() { + case reflect.String: + field.SetString(value) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + intVal, err := strconv.Atoi(value) + if err != nil { + return err + } + field.SetInt(int64(intVal)) + case reflect.Float32, reflect.Float64: + floatVal, err := strconv.ParseFloat(value, 64) + if err != nil { + return err + } + field.SetFloat(floatVal) + default: + return fmt.Errorf("unsupported field type: %s", field.Kind()) + } + + return nil +} diff --git a/decode_name_age_score.txt b/decode_name_age_score.txt new file mode 100644 index 0000000..7ee9ada --- /dev/null +++ b/decode_name_age_score.txt @@ -0,0 +1,7 @@ ++---------+-----+-------+ +| Name | Age | Score | ++---------+-----+-------+ +| Alice | 24 | 89 | +| Bob | 19 | 72 | +| Charlie | 22 | 95 | ++---------+-----+-------+ diff --git a/decode_test.go b/decode_test.go new file mode 100644 index 0000000..2ab2ace --- /dev/null +++ b/decode_test.go @@ -0,0 +1,31 @@ +package asciitable + +import ( + "github.com/stretchr/testify/require" + "os" + "testing" +) + +type nameAgeScore struct { + Name string `asciitable:"Name"` + Age int `asciitable:"Age"` + Score int `asciitable:"Score"` +} + +func TestDecodeNameAgeScore(t *testing.T) { + bytes, err := os.ReadFile("decode_name_age_score.txt") + require.NoError(t, err) + + table := string(bytes) + headers, results, err := Unmarshal(table, nameAgeScore{}) + require.NoError(t, err) + + require.Equal(t, []string{"Name", "Age", "Score"}, headers) + + expected := []nameAgeScore{ + {Name: "Alice", Age: 24, Score: 89}, + {Name: "Bob", Age: 19, Score: 72}, + {Name: "Charlie", Age: 22, Score: 95}, + } + require.Equal(t, expected, results) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..aa7d517 --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +module asciitable + +go 1.18 + +require github.com/stretchr/testify v1.10.0 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..713a0b4 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=