diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json new file mode 100644 index 0000000..dd8b384 --- /dev/null +++ b/.devcontainer/devcontainer-lock.json @@ -0,0 +1,14 @@ +{ + "features": { + "ghcr.io/devcontainers-extra/features/mise:1": { + "version": "1.0.0", + "resolved": "ghcr.io/devcontainers-extra/features/mise@sha256:5c389ab1e3c8e44e5e0ff119f6868d54dbb781bc860bd8587dc66209cb8c4a8c", + "integrity": "sha256:5c389ab1e3c8e44e5e0ff119f6868d54dbb781bc860bd8587dc66209cb8c4a8c" + }, + "ghcr.io/devcontainers/features/github-cli:1": { + "version": "1.1.0", + "resolved": "ghcr.io/devcontainers/features/github-cli@sha256:d22f50b70ed75339b4eed1ba9ecde3a1791f90e88d37936517e3bace0bbad671", + "integrity": "sha256:d22f50b70ed75339b4eed1ba9ecde3a1791f90e88d37936517e3bace0bbad671" + } + } +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index d134ae2..e7d3c58 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,4 +1,4 @@ - // For format details, see https://aka.ms/devcontainer.json. +// For format details, see https://aka.ms/devcontainer.json. { "name": "Ubuntu", // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile @@ -6,13 +6,15 @@ // Features to add to the dev container. More info: https://containers.dev/features. "features": { "ghcr.io/devcontainers-extra/features/mise:1": {}, - "ghcr.io/devcontainers/features/docker-in-docker:2": {} + "ghcr.io/devcontainers/features/github-cli:1": {} }, "postCreateCommand": "bash .devcontainer/post_create.sh", "customizations": { "vscode": { "extensions": [ - "golang.go" + "golang.go", + "hverlin.mise-vscode", + "tamasfe.even-better-toml" ] } } diff --git a/.devcontainer/post_create.sh b/.devcontainer/post_create.sh index a190145..ec19e0a 100644 --- a/.devcontainer/post_create.sh +++ b/.devcontainer/post_create.sh @@ -1,9 +1,9 @@ #!/bin/bash -# note that bash will read from ~/.profile or ~/.bash_profile if the latter exists -# ergo, you may want to check to see which is defined on your system and only append to the existing file -echo 'eval "$(mise activate bash --shims)"' >>~/.bash_profile # this sets up non-interactive sessions -echo 'eval "$(mise activate bash)"' >>~/.bashrc # this sets up interactive sessions +set -euo pipefail + +echo 'eval "$(mise activate bash --shims)"' >>~/.bash_profile +echo 'eval "$(mise activate bash)"' >>~/.bashrc mise trust . @@ -13,3 +13,7 @@ mise exec -- go mod download mise exec -- go install -v golang.org/x/tools/gopls@latest mise exec -- go install -v github.com/go-delve/delve/cmd/dlv@latest + +if [[ -f ".devcontainer/post_create.local.sh" ]]; then + source ".devcontainer/post_create.local.sh" +fi diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 820bfcf..50598df 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -3,49 +3,99 @@ # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. -name: "CodeQL" +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL Advanced" on: push: - branches: - - main + branches: [ "main" ] pull_request: - # The branches below must be a subset of the branches above - branches: - - main + branches: [ "main" ] schedule: - cron: "0 17 * * 5" jobs: analyze: - name: Analyze - runs-on: ubuntu-latest - + name: Analyze (${{ matrix.language }}) + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners (GitHub.com only) + # Consider using larger runners or machines with greater resources for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} permissions: # required for all workflows security-events: write + # required to fetch internal or private CodeQL packs + packages: read + + # only required for workflows in private repositories + actions: read + contents: read + strategy: fail-fast: false matrix: - # Override automatic language detection by changing the below list - # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] - # TODO: Enable for javascript later - language: ["go"] - + include: + - language: actions + build-mode: none + - language: go + build-mode: autobuild + # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift' + # Use `c-cpp` to analyze code written in C, C++ or both + # Use 'java-kotlin' to analyze code written in Java, Kotlin or both + # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both + # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, + # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. + # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how + # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages steps: - - name: Checkout repository - uses: actions/checkout@v5 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v4 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4 + - name: Checkout repository + uses: actions/checkout@v6 + + # Add any setup steps before running the `github/codeql-action/init` action. + # This includes steps like installing compilers or runtimes (`actions/setup-node` + # or others). This is typically only required for manual builds. + # - name: Setup runtime (example) + # uses: actions/setup-example@v1 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + # If the analyze step fails for one of the languages you are analyzing with + # "We were unable to automatically build your code", modify the matrix above + # to set the build mode to "manual" for that language. Then modify this step + # to build your code. + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + - name: Run manual build steps + if: matrix.build-mode == 'manual' + shell: bash + run: | + echo 'If you are using a "manual" build mode for one or more of the' \ + 'languages you are analyzing, replace this with the commands to build' \ + 'your code, for example:' + echo ' make bootstrap' + echo ' make release' + exit 1 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml new file mode 100644 index 0000000..60ab883 --- /dev/null +++ b/.github/workflows/coverage.yml @@ -0,0 +1,52 @@ +name: Coverage + +on: + push: + branches: + - main + tags: + - 'v*' + +permissions: + contents: read + +concurrency: + group: coverage-${{ github.ref }} + cancel-in-progress: true + +jobs: + coverage: + name: Coverage + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Install mise + uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + + - name: Cache Go modules and build + uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: go-${{ runner.os }}-${{ hashFiles('**/go.sum') }} + restore-keys: go-${{ runner.os }}- + + - name: Download Go dependencies + run: go mod download + + - name: Run tests with coverage + run: make cover + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + files: coverage.out + fail_ci_if_error: true + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index 29e78aa..0580ebb 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -5,10 +5,18 @@ on: branches: - main +permissions: + contents: read + +concurrency: + group: pr-check-${{ github.ref }} + cancel-in-progress: true + jobs: check: name: Check runs-on: ubuntu-latest + timeout-minutes: 15 steps: - name: Checkout uses: actions/checkout@v6 @@ -16,7 +24,23 @@ jobs: fetch-depth: 0 - name: Install mise - uses: jdx/mise-action@v4 + uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + + - name: Cache Go modules and build + uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: go-${{ runner.os }}-${{ hashFiles('**/go.sum') }} + restore-keys: go-${{ runner.os }}- + + - name: Cache golangci-lint + uses: actions/cache@v4 + with: + path: ~/.cache/golangci-lint + key: golangci-lint-${{ runner.os }}-${{ hashFiles('mise.toml', '.golangci.yaml') }} + restore-keys: golangci-lint-${{ runner.os }}- - name: Download Go dependencies run: go mod download diff --git a/.gitignore b/.gitignore index 66fd13c..3ae48d9 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,12 @@ # Dependency directories (remove the comment below to include it) # vendor/ + +# coverage output +coverage.out +coverage.html + +# Local configuration files +*.local.* +*.local/ +*.local diff --git a/.golangci.yaml b/.golangci.yaml index eb3c803..e6a233c 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -10,10 +10,6 @@ issues: severity: default: error - # rules: - # - linters: - # - dupl - # severity: error formatters: enable: @@ -22,7 +18,7 @@ formatters: - gofumpt - goimports - golines - - swaggo + settings: gofmt: rewrite-rules: @@ -30,8 +26,8 @@ formatters: replacement: "any" gofumpt: extra-rules: true - exclusions: - paths: [] + golines: + max-len: 120 linters: default: none @@ -45,33 +41,65 @@ linters: # Additional - bodyclose + - canonicalheader + - copyloopvar - depguard + - dupword + - durationcheck + - errchkjson - errname - errorlint + - exptostd + - fatcontext + - gocheckcompilerdirectives - gocognit - - goconst - - goheader - - gomodguard + - gocritic + - gomodguard_v2 - goprintffuncname - gosec + - intrange + - loggercheck + - mirror + - misspell + - modernize + - musttag - nakedret + - nestif - nilerr + - nilnesserr - nilnil - noctx - nolintlint + - nosprintfhostport + - perfsprint - prealloc - promlinter + - recvcheck - revive + - rowserrcheck + - sloglint + - spancheck + - sqlclosecheck - testifylint - testpackage - thelper + - unconvert + - unparam - usestdlibvars + - usetesting - wastedassign + - whitespace - wsl_v5 - disable: [] - settings: + govet: + enable: + - nilness + + modernize: + disable: + - omitzero + depguard: rules: main: @@ -84,16 +112,3 @@ linters: desc: Use github.com/go-resty/resty/v2 instead - pkg: github.com/aws/smithy-go/ptr$ desc: Use github.com/aws/aws-sdk-go-v2/aws instead - govet: - enable: - - nilness - - # exclusions: - # paths: - # - (.+)_test\.go - # rules: - # - path: (.+)_test\.go - # linters: - # - dupl - # - mnd - # - lll diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..01498bd --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,8 @@ +{ + "recommendations": [ + "ms-vscode-remote.remote-containers", + "golang.go", + "hverlin.mise-vscode", + "tamasfe.even-better-toml" + ] +} diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index fb9c0f8..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,44 +0,0 @@ -# Project Guidelines - -## Overview - -`github.com/min0625/tz` is a small, single-file Go library that provides a `TimeZone` type backed by the IANA time zone database. -It exposes no external dependencies beyond the standard library (test-only dependency: `testify`). - -## Architecture - -- **`time_zone.go`** — the entire public API: `TimeZone` struct, `LoadTimeZone`, `LoadString`, and implementations of `fmt.Stringer`, `sql.Scanner`, `driver.Valuer`, `encoding.TextMarshaler/Unmarshaler`, `json.Marshaler/Unmarshaler`. -- **`time_zone_test.go`** — table-driven unit tests in package `tz_test`. -- **`time_zone_example_test.go`** — runnable `Example*` tests in package `tz_test`. - -## Build and Test - -```sh -# Run all tests (with race detector) -make test -# equivalent: go test -v -race -failfast ./... - -# Lint (golangci-lint) -make lint - -# Lint with auto-fix -make fix - -# Lint + test -make check -``` - -Embed the IANA timezone database in tests by importing `_ "time/tzdata"`. - -## Code Conventions - -- **Go version**: 1.24+. Use modern idioms (e.g. `any` instead of `interface{}`, no `tt := tt` loop-variable copy). -- **Formatting**: `gofmt`, `gofumpt`, `goimports`, `gci`, `golines` — run `make fix` to auto-apply. -- **Tests**: all tests must be parallel (`t.Parallel()`). Use table-driven tests. Test package is `tz_test` (black-box). -- **UTC invariant**: loading `"UTC"` or `""` must always produce the zero value `TimeZone{}`. -- **No Local**: `"Local"` must always be rejected with an error; `time.Local` must never be stored. -- **Interfaces**: any new serialisation format must maintain the UTC-as-zero-value invariant. SQL NULL must be rejected explicitly (return an error). JSON `null` follows the Go standard convention — ignore it and leave the receiver unchanged (see [`encoding/json.Unmarshaler`](https://pkg.go.dev/encoding/json#Unmarshaler)). - -## Linting - -golangci-lint is configured in `.golangci.yaml`. Key enabled linters: `errcheck`, `staticcheck`, `gosec`, `errorlint`, `testifylint`, `testpackage`, `wsl_v5`. Do not add `//nolint` directives without a clear justification comment. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..476473e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,31 @@ +# Project Guidelines + +## Overview + +`github.com/min0625/tz` is a small, single-file Go library that provides a `TimeZone` type backed by the IANA time zone database. +It has no external dependencies beyond the standard library (test-only dependency: `testify`). + +## Architecture + +- **[time_zone.go](time_zone.go)** — the entire public API: `TimeZone` struct, `UTCTimeZone` sentinel, `LoadTimeZone`, and method implementations of `Location`, `LoadString`, `fmt.Stringer`, `sql.Scanner`, `driver.Valuer`, `encoding.TextMarshaler/Unmarshaler`, `json.Marshaler/Unmarshaler`. +- **[time_zone_test.go](time_zone_test.go)** — table-driven unit tests in package `tz_test`. Embeds the IANA database via `_ "time/tzdata"`. +- **[time_zone_example_test.go](time_zone_example_test.go)** — runnable `Example*` tests in package `tz_test`. + +## Build and Test + +```sh +make test # go test -race -failfast ./... +make lint # golangci-lint config verify + golangci-lint run +make fix # lint with auto-fix +make check # check-tidy + lint + test +``` + +## Code Conventions + +- **Go version**: 1.24+. Use modern idioms (`any` instead of `interface{}`, no `tt := tt` loop-variable copy). +- **Formatting**: `gofmt`, `gofumpt`, `goimports`, `gci`, `golines` — run `make fix` to auto-apply. +- **Tests**: all tests must be parallel (`t.Parallel()`). Use table-driven tests. Test package is `tz_test` (black-box). +- **UTC invariant**: loading `"UTC"` or `""` must always produce the zero value `TimeZone{}`. +- **No Local**: `"Local"` must always be rejected with an error; `time.Local` must never be stored. +- **Interfaces**: any new serialisation format must maintain the UTC-as-zero-value invariant. SQL NULL must be rejected explicitly (return an error). JSON `null` follows the Go standard — ignore it and leave the receiver unchanged (see [`encoding/json.Unmarshaler`](https://pkg.go.dev/encoding/json#Unmarshaler)). +- **Linting**: golangci-lint is configured in [.golangci.yaml](.golangci.yaml). Key linters: `errcheck`, `staticcheck`, `gosec`, `errorlint`, `testifylint`, `testpackage`, `wsl_v5`. Do not add `//nolint` directives without a clear justification comment. diff --git a/Makefile b/Makefile index 78bf91e..779e053 100644 --- a/Makefile +++ b/Makefile @@ -1,16 +1,31 @@ NEW_FROM_REV ?= HEAD +.PHONY: fix fix: go mod tidy - golangci-lint run -v --new-from-rev=$(NEW_FROM_REV) --fix ./... + golangci-lint run --new-from-rev=$(NEW_FROM_REV) --fix ./... +.PHONY: lint lint: - golangci-lint run -v --new-from-rev=$(NEW_FROM_REV) ./... + golangci-lint config verify + golangci-lint run --new-from-rev=$(NEW_FROM_REV) ./... +.PHONY: test test: - go test -v -race -failfast ./... + go test -race -failfast ./... +.PHONY: cover +cover: + go test -race -covermode=atomic -coverprofile=coverage.out ./... + go tool cover -func=coverage.out + +.PHONY: cover-html +cover-html: cover + go tool cover -html=coverage.out -o coverage.html + +.PHONY: check-tidy check-tidy: go mod tidy -diff +.PHONY: check check: check-tidy lint test diff --git a/README.md b/README.md index 3853238..b0856e7 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,33 @@ -# Golang Time Zone Type +# Go Time Zone Type + [![Go Reference](https://pkg.go.dev/badge/github.com/min0625/tz.svg)](https://pkg.go.dev/github.com/min0625/tz) +[![codecov](https://codecov.io/gh/min0625/tz/branch/main/graph/badge.svg)](https://codecov.io/gh/min0625/tz) + +**English** | [繁體中文](./README.zh-TW.md) + +A small Go library providing a `TimeZone` type backed by the IANA time zone database. ## Features -- Based on `time.LoadLocation` format; the `"Local"` time zone is not supported. -- Accepts `"UTC"`, an empty string, or any IANA time zone database name (e.g. `"America/New_York"`). See: https://www.iana.org/time-zones. -- The zero value represents the UTC time zone; loading `"UTC"` or `""` always produces the zero value. -- Implements `fmt.Stringer` -- Implements `sql.Scanner` -- Implements `driver.Valuer` -- Implements `encoding.TextMarshaler` -- Implements `encoding.TextUnmarshaler` -- Implements `json.Marshaler` -- Implements `json.Unmarshaler` + +- **Zero value is UTC** — `TimeZone{}` represents UTC; loading `"UTC"` or `""` always yields the zero value. +- **IANA names** — accepts any [IANA time zone database](https://www.iana.org/time-zones) name (e.g. `"America/New_York"`). +- **No `"Local"`** — the `"Local"` time zone is always rejected with an error. +- **Comparable** — `TimeZone` is a plain struct; use `==` for equality checks. +- **Rich interface support** — implements `fmt.Stringer`, `sql.Scanner`, `driver.Valuer`, `encoding.TextMarshaler/Unmarshaler`, and `json.Marshaler/Unmarshaler`. +- **No dependencies** — built entirely on the standard library. ## Installation + ```sh go get github.com/min0625/tz ``` +Requires Go 1.24 or later. + ## Quick start > **Note**: Import `_ "time/tzdata"` to embed the IANA time zone database directly into your binary, -> so it works correctly in environments where the system timezone data may be absent (e.g. scratch/Alpine containers). +> so it works correctly in environments where system timezone data may be absent (e.g. scratch or Alpine containers). ```go package main @@ -40,14 +46,20 @@ func main() { panic(err) } - fmt.Println(z.String()) - fmt.Println(time.Time{}.In(z.Location()).Location().String()) + fmt.Println(z) // America/New_York + fmt.Println(time.Now().In(z.Location()).Location()) // America/New_York - // Output: - // America/New_York - // America/New_York + // UTC is the zero value + utc, _ := tz.LoadTimeZone("UTC") + fmt.Println(utc == tz.TimeZone{}) // true } ``` -## Example -See: [./time_zone_example_test.go](./time_zone_example_test.go) +## Documentation + +- API reference: [pkg.go.dev/github.com/min0625/tz](https://pkg.go.dev/github.com/min0625/tz) +- Runnable examples: [time_zone_example_test.go](./time_zone_example_test.go) + +## License + +See [LICENSE](./LICENSE). diff --git a/README.zh-TW.md b/README.zh-TW.md new file mode 100644 index 0000000..a410e9d --- /dev/null +++ b/README.zh-TW.md @@ -0,0 +1,65 @@ +# Go 時區型別 + +[![Go Reference](https://pkg.go.dev/badge/github.com/min0625/tz.svg)](https://pkg.go.dev/github.com/min0625/tz) +[![codecov](https://codecov.io/gh/min0625/tz/branch/main/graph/badge.svg)](https://codecov.io/gh/min0625/tz) + +[English](./README.md) | **繁體中文** + +針對 Go 所提供的 `TimeZone` 型別,以 IANA 時區資料庫為基礎的小型函式庫。 + +## 特色 + +- **零值即 UTC** — `TimeZone{}` 代表 UTC;載入 `"UTC"` 或 `""` 必定回傳零值。 +- **IANA 名稱** — 接受任何 [IANA 時區資料庫](https://www.iana.org/time-zones) 名稱(例如 `"America/New_York"`)。 +- **不支援 `"Local"`** — `"Local"` 時區一律以錯誤拒絕。 +- **可比較** — `TimeZone` 為一般結構體;可直接使用 `==` 進行相等判斷。 +- **豐富的介面支援** — 實作 `fmt.Stringer`、`sql.Scanner`、`driver.Valuer`、`encoding.TextMarshaler/Unmarshaler` 及 `json.Marshaler/Unmarshaler`。 +- **零相依** — 完全建構於標準函式庫之上。 + +## 安裝 + +```sh +go get github.com/min0625/tz +``` + +需要 Go 1.24 或更新版本。 + +## 快速開始 + +> **注意**:匯入 `_ "time/tzdata"` 可將 IANA 時區資料庫直接嵌入二進位檔, +> 確保在系統時區資料可能不存在的環境(例如 scratch 或 Alpine 容器)中也能正確運作。 + +```go +package main + +import ( + "fmt" + "time" + _ "time/tzdata" + + "github.com/min0625/tz" +) + +func main() { + z, err := tz.LoadTimeZone("America/New_York") + if err != nil { + panic(err) + } + + fmt.Println(z) // America/New_York + fmt.Println(time.Now().In(z.Location()).Location()) // America/New_York + + // UTC 為零值 + utc, _ := tz.LoadTimeZone("UTC") + fmt.Println(utc == tz.TimeZone{}) // true +} +``` + +## 文件 + +- API 參考文件:[pkg.go.dev/github.com/min0625/tz](https://pkg.go.dev/github.com/min0625/tz) +- 可執行範例:[time_zone_example_test.go](./time_zone_example_test.go) + +## 授權 + +請參閱 [LICENSE](./LICENSE)。 diff --git a/mise.toml b/mise.toml index 42162e8..7847d7f 100644 --- a/mise.toml +++ b/mise.toml @@ -1,3 +1,3 @@ [tools] -go = "1.24.13" -golangci-lint = "2.11.2" +go = "1.26.4" +golangci-lint = "2.12.2" diff --git a/time_zone_example_test.go b/time_zone_example_test.go index 2f471a5..d3e9ea4 100644 --- a/time_zone_example_test.go +++ b/time_zone_example_test.go @@ -1,6 +1,7 @@ package tz_test import ( + "encoding/json" "fmt" "time" _ "time/tzdata" @@ -68,3 +69,66 @@ func ExampleTimeZone_Value_zeroValue() { // Output: // UTC string } + +func ExampleUTCTimeZone() { + z, _ := tz.LoadTimeZone("UTC") + fmt.Println(z == tz.UTCTimeZone) + + // Output: + // true +} + +func ExampleTimeZone_MarshalText() { + z, _ := tz.LoadTimeZone("Asia/Tokyo") + text, _ := z.MarshalText() + fmt.Println(string(text)) + + // Output: + // Asia/Tokyo +} + +func ExampleTimeZone_UnmarshalText() { + var z tz.TimeZone + + _ = z.UnmarshalText([]byte("Asia/Tokyo")) + fmt.Println(z) + + // Output: + // Asia/Tokyo +} + +func ExampleTimeZone_MarshalJSON() { + type Event struct { + Name string `json:"name"` + TimeZone tz.TimeZone `json:"time_zone"` + } + + e := Event{Name: "Meeting", TimeZone: func() tz.TimeZone { z, _ := tz.LoadTimeZone("Europe/London"); return z }()} + + data, err := json.Marshal(e) + if err != nil { + panic(err) + } + + fmt.Println(string(data)) + + // Output: + // {"name":"Meeting","time_zone":"Europe/London"} +} + +func ExampleTimeZone_UnmarshalJSON() { + type Event struct { + Name string `json:"name"` + TimeZone tz.TimeZone `json:"time_zone"` + } + + data := []byte(`{"name":"Meeting","time_zone":"Europe/London"}`) + + var e Event + + _ = json.Unmarshal(data, &e) + fmt.Println(e.Name, e.TimeZone) + + // Output: + // Meeting Europe/London +} diff --git a/time_zone_test.go b/time_zone_test.go index 8e820df..08af274 100644 --- a/time_zone_test.go +++ b/time_zone_test.go @@ -53,6 +53,12 @@ func TestLoadTimeZone(t *testing.T) { want: mustLoadTimeZone(t, "America/New_York"), wantErr: false, }, + { + testName: "InvalidName", + name: "Invalid/Zone", + want: tz.TimeZone{}, + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { @@ -75,6 +81,16 @@ func TestTimeZone_Location_ZeroValueReturnUTC(t *testing.T) { assert.Same(t, tz.TimeZone{}.Location(), time.UTC) } +func TestTimeZone_Location_NonUTC(t *testing.T) { + t.Parallel() + + z := mustLoadTimeZone(t, "America/New_York") + loc := z.Location() + + assert.Equal(t, "America/New_York", loc.String()) + assert.NotSame(t, loc, time.UTC) +} + func TestTimeZone_LoadString(t *testing.T) { t.Parallel() @@ -357,6 +373,12 @@ func TestTimeZone_UnmarshalText(t *testing.T) { wantTimeZone: mustLoadTimeZone(t, "Asia/Tokyo"), wantErr: false, }, + { + name: "Empty", + data: []byte(""), + wantTimeZone: tz.TimeZone{}, + wantErr: false, + }, { name: "ErrName", giveTimeZone: mustLoadTimeZone(t, "America/New_York"), @@ -364,6 +386,13 @@ func TestTimeZone_UnmarshalText(t *testing.T) { wantTimeZone: mustLoadTimeZone(t, "America/New_York"), wantErr: true, }, + { + name: "Local", + giveTimeZone: mustLoadTimeZone(t, "America/New_York"), + data: []byte("Local"), + wantTimeZone: mustLoadTimeZone(t, "America/New_York"), + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -463,6 +492,20 @@ func TestTimeZone_UnmarshalJSON(t *testing.T) { wantTimeZone: mustLoadTimeZone(t, "America/New_York"), wantErr: false, }, + { + name: "Local", + giveTimeZone: mustLoadTimeZone(t, "America/New_York"), + data: []byte(`"Local"`), + wantTimeZone: mustLoadTimeZone(t, "America/New_York"), + wantErr: true, + }, + { + name: "NumberNotString", + giveTimeZone: mustLoadTimeZone(t, "America/New_York"), + data: []byte(`123`), + wantTimeZone: mustLoadTimeZone(t, "America/New_York"), + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -481,3 +524,60 @@ func TestTimeZone_UnmarshalJSON(t *testing.T) { }) } } + +func TestTimeZone_JSONRoundTrip(t *testing.T) { + t.Parallel() + + for _, name := range []string{"", "UTC", "America/New_York", "Asia/Tokyo", "Europe/London"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + + original := mustLoadTimeZone(t, name) + + data, err := original.MarshalJSON() + require.NoError(t, err) + + var decoded tz.TimeZone + require.NoError(t, decoded.UnmarshalJSON(data)) + assert.Equal(t, original, decoded) + }) + } +} + +func TestTimeZone_TextRoundTrip(t *testing.T) { + t.Parallel() + + for _, name := range []string{"", "UTC", "America/New_York", "Asia/Tokyo", "Europe/London"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + + original := mustLoadTimeZone(t, name) + + text, err := original.MarshalText() + require.NoError(t, err) + + var decoded tz.TimeZone + require.NoError(t, decoded.UnmarshalText(text)) + assert.Equal(t, original, decoded) + }) + } +} + +func TestTimeZone_SQLRoundTrip(t *testing.T) { + t.Parallel() + + for _, name := range []string{"UTC", "America/New_York", "Asia/Tokyo", "Europe/London"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + + original := mustLoadTimeZone(t, name) + + v, err := original.Value() + require.NoError(t, err) + + var decoded tz.TimeZone + require.NoError(t, decoded.Scan(v)) + assert.Equal(t, original, decoded) + }) + } +}