pax_global_header00006660000000000000000000000064147476002440014522gustar00rootroot0000000000000052 comment=b0982efed09e41a771e0c32f70bdd90fcf8e34c8 go-locale-1.1.3/000077500000000000000000000000001474760024400133665ustar00rootroot00000000000000go-locale-1.1.3/.github/000077500000000000000000000000001474760024400147265ustar00rootroot00000000000000go-locale-1.1.3/.github/dependabot.yml000066400000000000000000000001541474760024400175560ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "daily" go-locale-1.1.3/.github/workflows/000077500000000000000000000000001474760024400167635ustar00rootroot00000000000000go-locale-1.1.3/.github/workflows/test.yml000066400000000000000000000013711474760024400204670ustar00rootroot00000000000000name: "Test" on: push: branches: - master tags: - '*' pull_request: branches: - master workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} cancel-in-progress: true jobs: test: name: Test strategy: matrix: go: [ "1.21", "1.22", "1.23" ] os: [ ubuntu-latest, windows-latest, macos-latest ] runs-on: ${{ matrix.os }} steps: - name: Set up Go 1.x uses: actions/setup-go@v5 with: go-version: ${{ matrix.go }} check-latest: true - name: Checkout repository uses: actions/checkout@v4 - name: Build run: make build - name: Test run: make test go-locale-1.1.3/.gitignore000066400000000000000000000005051474760024400153560ustar00rootroot00000000000000 ### Go template # 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 # Dependency directories (remove the comment below to include it) # vendor/ bin/ release/ coverage/ coverage*.** go-locale-1.1.3/CHANGELOG.md000066400000000000000000000102171474760024400152000ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [v1.1.3] - 2025-02-02 ### Changed * build(deps): Bump golang.org/x/sys from 0.25.0 to 0.28.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/89 * build(deps): Bump golang.org/x/text from 0.18.0 to 0.21.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/90 * ci: Add test for go 1.23 by @Xuanwo in https://github.com/Xuanwo/go-locale/pull/91 * chore: Bump go version to 1.20 by @Xuanwo in https://github.com/Xuanwo/go-locale/pull/92 ## [v1.1.2] - 2024-09-07 ### Changed * build(deps): Bump golang.org/x/sys from 0.22.0 to 0.23.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/78 * build(deps): Bump golang.org/x/text from 0.16.0 to 0.17.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/79 * build(deps): Bump golang.org/x/sys from 0.23.0 to 0.24.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/80 * build(deps): Bump golang.org/x/text from 0.17.0 to 0.18.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/82 * build(deps): Bump golang.org/x/sys from 0.24.0 to 0.25.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/81 ## [v1.1.1] - 2024-08-04 ### Changed * refactor: Remove convery and assert by @Xuanwo in https://github.com/Xuanwo/go-locale/pull/75 ### Fixed * fix: GH Actions' errors and security issues. [Drop Go 1.14-1.16 support] by @KEINOS in https://github.com/Xuanwo/go-locale/pull/64 ### Docs * docs: Update README.md by @Xuanwo in https://github.com/Xuanwo/go-locale/pull/72 ### Dependencies * build(deps): Bump github.com/smartystreets/goconvey from 1.6.7 to 1.7.2 by @dependabot in https://github.com/Xuanwo/go-locale/pull/40 * build(deps): Bump github.com/stretchr/testify from 1.7.0 to 1.7.1 by @dependabot in https://github.com/Xuanwo/go-locale/pull/41 * build(deps): Bump github.com/stretchr/testify from 1.7.1 to 1.7.5 by @dependabot in https://github.com/Xuanwo/go-locale/pull/45 * build(deps): Bump github.com/stretchr/testify from 1.7.5 to 1.8.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/52 * build(deps): Bump golang.org/x/sys from 0.7.0 to 0.22.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/69 * build(deps): Bump github.com/stretchr/testify from 1.8.2 to 1.9.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/68 * build(deps): Bump golang.org/x/text from 0.9.0 to 0.16.0 by @dependabot in https://github.com/Xuanwo/go-locale/pull/65 * chore: upgraded golang.org/x/sys by @sumit-tembe in https://github.com/Xuanwo/go-locale/pull/53 ## [v1.1.0] - 2021-10-25 ### Added - feat(darwin): Allow read global values, add AppleLocale support ### Changed - Use github actions for test - Add tests for go 1.16 and go 1.17 - ci: Remove tags to simplify build steps ### Fixed - fix: Windows reports checkptr errors ### Upgraded - build(deps): Bump golang.org/x/text to 0.3.7 (#33) - build(deps): Bump github.com/smartystreets/goconvey to 1.6.7 (#35) ## [v1.0.0] - 2020-08-03 ### Added - Add support for all os that go support - aix - hurd - js - nacl - plan9 - zos - windows: Add env support ### Changed - windows: Read windows registry instead of OLE ## [v0.3.0] - 2020-06-03 ### Added - Add FreeBSD/OpenBSD support (#12) ### Changed - unix: Detect via locale.conf instead of locale command (#14) ## [v0.2.0] - 2020-04-21 ### Added - Add system v support (#8) - Add full windows LCID support (#10) ## v0.1.0 - 2020-02-20 ### Added - Support Linux, macOS X and Windows platforms - Support Detect and DetectAll [v1.1.3]: https://github.com/Xuanwo/go-locale/compare/v1.1.2...v1.1.3 [v1.1.2]: https://github.com/Xuanwo/go-locale/compare/v1.1.1...v1.1.2 [v1.1.1]: https://github.com/Xuanwo/go-locale/compare/v1.1.0...v1.1.1 [v1.1.0]: https://github.com/Xuanwo/go-locale/compare/v1.0.0...v1.1.0 [v1.0.0]: https://github.com/Xuanwo/go-locale/compare/v0.3.0...v1.0.0 [v0.3.0]: https://github.com/Xuanwo/go-locale/compare/v0.2.0...v0.3.0 [v0.2.0]: https://github.com/Xuanwo/go-locale/compare/v0.1.0...v0.2.0 go-locale-1.1.3/LICENSE000066400000000000000000000261351474760024400144020ustar00rootroot00000000000000 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. go-locale-1.1.3/Makefile000066400000000000000000000015111474760024400150240ustar00rootroot00000000000000SHELL := /bin/bash .PHONY: all check format vet build test tidy help: @echo "Please use \`make \` where is one of" @echo " check to format, vet " @echo " build to create bin directory and build" @echo " generate to generate code" @echo " unit_test to run unit test" @echo " integration_test to run integration test" check: format vet format: @echo "go fmt" @go fmt ./... @echo "ok" vet: @echo "go vet" @go vet ./... @echo "ok" build: tidy check @echo "build go-locale" @go build ./... @echo "ok" test: @echo "run unit test" @go test -race -cover -coverprofile=coverage.txt -v ./... @go tool cover -html="coverage.txt" -o "coverage.html" @echo "ok" tidy: @echo "Tidy and check the go mod files" @go mod tidy && go mod verify @echo "Done" go-locale-1.1.3/README.md000066400000000000000000000057721474760024400146600ustar00rootroot00000000000000# go-locale [![Build Status](https://img.shields.io/github/actions/workflow/status/Xuanwo/go-locale/test.yml?branch=master)](https://github.com/Xuanwo/go-locale/actions?query=branch%3master) [![Go Doc](https://pkg.go.dev/badge/github.com/Xuanwo/go-locale)](https://pkg.go.dev/github.com/Xuanwo/go-locale) [![Go Ver](https://img.shields.io/github/go-mod/go-version/Xuanwo/go-locale)](https://github.com/Xuanwo/go-locale/blob/master/go.mod) [![License](https://img.shields.io/badge/license-apache%20v2-blue.svg)](https://github.com/Xuanwo/go-locale/blob/master/LICENSE) [![Discord](https://img.shields.io/discord/1111711408875393035?logo=discord&label=discord)](https://discord.gg/kKqtVnvh) `go-locale` is a Golang lib for cross-platform locale detection. ## OS Support Support all OS that Golang supported, except `android`: - [aix: IBM AIX operating system](https://www.ibm.com/it-infrastructure/power/os/aix) - android (*have no idea on this*) - [darwin: Drawin, Mac OS X](https://opensource.apple.com/) - [dragonfly: DragonFly BSD](https://www.dragonflybsd.org/) - [freebsd: FreeBSD](https://www.freebsd.org/) - [hurd: GNU Hurd](https://en.wikipedia.org/wiki/GNU_Hurd) - [illumos](https://illumos.org/) - [js: JavaScript runtime, WebAssembly](https://webassembly.org/) - Linux: Ubuntu, CentOS, RHEL, Archlinux... - [nacl: Native Client](https://developer.chrome.com/native-client) - [netbsd: NetBSD](https://www.netbsd.org/) - [openbsd: OpenBSD](https://www.openbsd.org/) - [plan9: Plan 9 from Bell Labs](https://9p.io/plan9/) - [solaris: Solaris](https://www.oracle.com/solaris) - [windows: Windows](https://www.microsoft.com/en-us/windows/) - [zos: z/OS](https://www.ibm.com/it-infrastructure/z/zos) ### POSIX Compatible Systems - Lookup env `LANGUAGE` - Lookup env `LC_ALL` - Lookup env `LC_MESSAGES` - Lookup env `LANG` - Read file `$XDG_CONFIG_HOME/locale.conf` - Read file `$HOME/.config/locale.conf` - Read file `/etc/locale.conf` ### Js - Lookup env `LANGUAGE` - Lookup env `LC_ALL` ### Windows - Lookup env `LANGUAGE` - Lookup env `LC_ALL` - Lookup env `LC_MESSAGES` - Lookup env `LANG` - [Windows Registry](https://renenyffenegger.ch/notes/Windows/registry/tree/HKEY_CURRENT_USER/Control-Panel/International/index) ### macOS X (darwin) - Lookup env `LANGUAGE` - Lookup env `LC_ALL` - Lookup env `LC_MESSAGES` - Lookup env `LANG` - macOS X [User Defaults System](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/UserDefaults/AboutPreferenceDomains/AboutPreferenceDomains.html) - Lookup user AppleLocale - Lookup user AppleLanguages - Lookup global AppleLocale - Lookup global AppleLanguages ## Usage ```go import ( "github.com/Xuanwo/go-locale" ) func main() { tag, err := locale.Detect() if err != nil { log.Fatal(err) } // Have fun with language.Tag! tags, err := locale.DetectAll() if err != nil { log.Fatal(err) } // Get all available tags } ``` ## Acknowledgments Inspired by [jibber_jabber](https://github.com/cloudfoundry-attic/jibber_jabber) go-locale-1.1.3/codecov.yml000066400000000000000000000000261474760024400155310ustar00rootroot00000000000000ignore: - "error.go"go-locale-1.1.3/error.go000066400000000000000000000007771474760024400150610ustar00rootroot00000000000000package locale import ( "errors" ) var ( // ErrNotDetected returns while no locale detected. ErrNotDetected = errors.New("not detected") // ErrNotSupported means current platform or language is not supported. ErrNotSupported = errors.New("not supported") ) // Error is the error returned by locale. type Error struct { Op string Err error } func (e *Error) Error() string { return e.Op + ": " + e.Err.Error() } // Unwrap implements xerrors.Wrapper func (e *Error) Unwrap() error { return e.Err } go-locale-1.1.3/go.mod000066400000000000000000000001561474760024400144760ustar00rootroot00000000000000module github.com/Xuanwo/go-locale go 1.20 require ( golang.org/x/sys v0.28.0 golang.org/x/text v0.21.0 ) go-locale-1.1.3/go.sum000066400000000000000000000004641474760024400145250ustar00rootroot00000000000000golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= go-locale-1.1.3/locale.go000066400000000000000000000015131474760024400151540ustar00rootroot00000000000000package locale import ( "errors" "golang.org/x/text/language" ) // Detect will detect current env's language. func Detect() (tag language.Tag, err error) { tags, err := DetectAll() if err != nil { return language.Und, err } return tags[0], nil } // DetectAll will detect current env's all available language. func DetectAll() (tags []language.Tag, err error) { lang, err := detect() if err != nil { return } tags = make([]language.Tag, 0, len(lang)) for _, v := range lang { tags = append(tags, language.Make(v)) } return } type detector func() ([]string, error) func detect() (lang []string, err error) { for _, fn := range detectors { lang, err = fn() if err != nil && errors.Is(err, ErrNotDetected) { continue } if err != nil { return } return } return nil, &Error{"detect", ErrNotDetected} } go-locale-1.1.3/locale_darwin.go000066400000000000000000000522171474760024400165270ustar00rootroot00000000000000package locale import ( "bufio" "bytes" "os/exec" "strings" ) var detectors = []detector{ detectViaEnvLanguage, detectViaEnvLc, detectViaDefaultsSystem, } // detectViaUserDefaultsSystem will detect language via Apple User Defaults System // // We will read AppleLocale and AppleLanguages in this order: // - user AppleLocale // - user AppleLanguages // - global AppleLocale // - global AppleLanguages // // ref: // - Apple Developer Guide: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/UserDefaults/AboutPreferenceDomains/AboutPreferenceDomains.html // - Homebrew: https://github.com/Homebrew/brew/pull/7940 func detectViaDefaultsSystem() ([]string, error) { // Read user's apple locale setting. m, err := parseDefaultsSystemAppleLocale("-g") if err == nil { return m, nil } // Read user's apple languages setting. m, err = parseDefaultsSystemAppleLanguages("-g") if err == nil { return m, nil } // Read global locale preferences. m, err = parseDefaultsSystemAppleLocale("/Library/Preferences/.GlobalPreferences") if err == nil { return m, nil } // Read global language preferences. m, err = parseDefaultsSystemAppleLanguages("/Library/Preferences/.GlobalPreferences") if err == nil { return m, nil } return nil, &Error{"detect via defaults system", ErrNotDetected} } // parseDefaultsSystemAppleLocale will parse the AppleLocale output. func parseDefaultsSystemAppleLocale(domain string) ([]string, error) { cmd := exec.Command("defaults", "read", domain, "AppleLocale") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { return nil, &Error{"detect via user defaults system", err} } content := strings.TrimSpace(out.String()) if len(content) == 0 { return nil, &Error{"detect via defaults system", ErrNotDetected} } return []string{content}, nil } // parseDefaultsSystemAppleLanguages will parse the AppleLanguages output. // // Output should be like: // // ( // // en, // ja, // fr, // de, // es, // it, // pt, // "pt-PT", // nl, // sv, // nb, // da, // fi, // ru, // pl, // "zh-Hans", // "zh-Hant", // ko, // ar, // cs, // hu, // tr // // ) func parseDefaultsSystemAppleLanguages(domain string) ([]string, error) { cmd := exec.Command("defaults", "read", domain, "AppleLanguages") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { return nil, &Error{"detect via user defaults system", err} } m := make([]string, 0) s := bufio.NewScanner(&out) for s.Scan() { text := s.Text() // Ignore "(" and ")" if !strings.HasPrefix(text, " ") { continue } // Trim all space, " and , text = strings.Trim(text, " \",") // Doing canonicalize if value, ok := oldAppleLocaleToCanonical[text]; ok { text = value } m = append(m, text) } if len(m) == 0 { return nil, &Error{"detect via user defaults system", ErrNotDetected} } return m, nil } // oldAppleLocaleToCanonical is borrowed from swift-corelibs-foundation's CFLocaleIdentifier.c // // Old Apple devices could return "English" instead of "en-US", this map will make them canonical // // refs: // - CFLocaleIdentifier.c: https://github.com/apple/swift-corelibs-foundation/blob/main/CoreFoundation/Locale.subproj/CFLocaleIdentifier.c var oldAppleLocaleToCanonical = map[string]string{ "Afrikaans": "af", // # __CFBundleLanguageNamesArray "Albanian": "sq", // # __CFBundleLanguageNamesArray "Amharic": "am", // # __CFBundleLanguageNamesArray "Arabic": "ar", // # __CFBundleLanguageNamesArray "Armenian": "hy", // # __CFBundleLanguageNamesArray "Assamese": "as", // # __CFBundleLanguageNamesArray "Aymara": "ay", // # __CFBundleLanguageNamesArray "Azerbaijani": "az", // -Arab,-Cyrl,-Latn? # __CFBundleLanguageNamesArray (had 3 entries "Azerbaijani" for "az-Arab", "az-Cyrl", "az-Latn") "Basque": "eu", // # __CFBundleLanguageNamesArray "Belarusian": "be", // # handle other names "Belorussian": "be", // # handle other names "Bengali": "bn", // # __CFBundleLanguageNamesArray "Brazilian Portugese": "pt-BR", // # from Installer.app Info.plist IFLanguages key, misspelled "Brazilian Portuguese": "pt-BR", // # correct spelling for above "Breton": "br", // # __CFBundleLanguageNamesArray "Bulgarian": "bg", // # __CFBundleLanguageNamesArray "Burmese": "my", // # __CFBundleLanguageNamesArray "Byelorussian": "be", // # __CFBundleLanguageNamesArray "Catalan": "ca", // # __CFBundleLanguageNamesArray "Chewa": "ny", // # handle other names "Chichewa": "ny", // # handle other names "Chinese": "zh", // -Hans,-Hant? # __CFBundleLanguageNamesArray (had 2 entries "Chinese" for "zh-Hant", "zh-Hans") "Chinese, Simplified": "zh-Hans", // # from Installer.app Info.plist IFLanguages key "Chinese, Traditional": "zh-Hant", // # correct spelling for below "Chinese, Tradtional": "zh-Hant", // # from Installer.app Info.plist IFLanguages key, misspelled "Croatian": "hr", // # __CFBundleLanguageNamesArray "Czech": "cs", // # __CFBundleLanguageNamesArray "Danish": "da", // # __CFBundleLanguageNamesArray "Dutch": "nl", // # __CFBundleLanguageNamesArray (had 2 entries "Dutch" for "nl", "nl-BE") "Dzongkha": "dz", // # __CFBundleLanguageNamesArray "English": "en", // # __CFBundleLanguageNamesArray "Esperanto": "eo", // # __CFBundleLanguageNamesArray "Estonian": "et", // # __CFBundleLanguageNamesArray "Faroese": "fo", // # __CFBundleLanguageNamesArray "Farsi": "fa", // # __CFBundleLanguageNamesArray "Finnish": "fi", // # __CFBundleLanguageNamesArray "Flemish": "nl-BE", // # handle other names "French": "fr", // # __CFBundleLanguageNamesArray "Galician": "gl", // # __CFBundleLanguageNamesArray "Gallegan": "gl", // # handle other names "Georgian": "ka", // # __CFBundleLanguageNamesArray "German": "de", // # __CFBundleLanguageNamesArray "Greek": "el", // # __CFBundleLanguageNamesArray (had 2 entries "Greek" for "el", "grc") "Greenlandic": "kl", // # __CFBundleLanguageNamesArray "Guarani": "gn", // # __CFBundleLanguageNamesArray "Gujarati": "gu", // # __CFBundleLanguageNamesArray "Hawaiian": "haw", // # handle new languages "Hebrew": "he", // # __CFBundleLanguageNamesArray "Hindi": "hi", // # __CFBundleLanguageNamesArray "Hungarian": "hu", // # __CFBundleLanguageNamesArray "Icelandic": "is", // # __CFBundleLanguageNamesArray "Indonesian": "id", // # __CFBundleLanguageNamesArray "Inuktitut": "iu", // # __CFBundleLanguageNamesArray "Irish": "ga", // # __CFBundleLanguageNamesArray (had 2 entries "Irish" for "ga", "ga-dots") "Italian": "it", // # __CFBundleLanguageNamesArray "Japanese": "ja", // # __CFBundleLanguageNamesArray "Javanese": "jv", // # __CFBundleLanguageNamesArray "Kalaallisut": "kl", // # handle other names "Kannada": "kn", // # __CFBundleLanguageNamesArray "Kashmiri": "ks", // # __CFBundleLanguageNamesArray "Kazakh": "kk", // # __CFBundleLanguageNamesArray "Khmer": "km", // # __CFBundleLanguageNamesArray "Kinyarwanda": "rw", // # __CFBundleLanguageNamesArray "Kirghiz": "ky", // # __CFBundleLanguageNamesArray "Korean": "ko", // # __CFBundleLanguageNamesArray "Kurdish": "ku", // # __CFBundleLanguageNamesArray "Lao": "lo", // # __CFBundleLanguageNamesArray "Latin": "la", // # __CFBundleLanguageNamesArray "Latvian": "lv", // # __CFBundleLanguageNamesArray "Lithuanian": "lt", // # __CFBundleLanguageNamesArray "Macedonian": "mk", // # __CFBundleLanguageNamesArray "Malagasy": "mg", // # __CFBundleLanguageNamesArray "Malay": "ms", // -Latn,-Arab? # __CFBundleLanguageNamesArray (had 2 entries "Malay" for "ms-Latn", "ms-Arab") "Malayalam": "ml", // # __CFBundleLanguageNamesArray "Maltese": "mt", // # __CFBundleLanguageNamesArray "Manx": "gv", // # __CFBundleLanguageNamesArray "Marathi": "mr", // # __CFBundleLanguageNamesArray "Moldavian": "mo", // # __CFBundleLanguageNamesArray "Mongolian": "mn", // -Mong,-Cyrl? # __CFBundleLanguageNamesArray (had 2 entries "Mongolian" for "mn-Mong", "mn-Cyrl") "Nepali": "ne", // # __CFBundleLanguageNamesArray "Norwegian": "nb", // # __CFBundleLanguageNamesArray (had "Norwegian" mapping to "no") "Nyanja": "ny", // # __CFBundleLanguageNamesArray "Nynorsk": "nn", // # handle other names (no entry in __CFBundleLanguageNamesArray) "Oriya": "or", // # __CFBundleLanguageNamesArray "Oromo": "om", // # __CFBundleLanguageNamesArray "Panjabi": "pa", // # handle other names "Pashto": "ps", // # __CFBundleLanguageNamesArray "Persian": "fa", // # handle other names "Polish": "pl", // # __CFBundleLanguageNamesArray "Portuguese": "pt", // # __CFBundleLanguageNamesArray "Portuguese, Brazilian": "pt-BR", // # handle other names "Punjabi": "pa", // # __CFBundleLanguageNamesArray "Pushto": "ps", // # handle other names "Quechua": "qu", // # __CFBundleLanguageNamesArray "Romanian": "ro", // # __CFBundleLanguageNamesArray "Ruanda": "rw", // # handle other names "Rundi": "rn", // # __CFBundleLanguageNamesArray "Russian": "ru", // # __CFBundleLanguageNamesArray "Sami": "se", // # __CFBundleLanguageNamesArray "Sanskrit": "sa", // # __CFBundleLanguageNamesArray "Scottish": "gd", // # __CFBundleLanguageNamesArray "Serbian": "sr", // # __CFBundleLanguageNamesArray "Simplified Chinese": "zh-Hans", // # handle other names "Sindhi": "sd", // # __CFBundleLanguageNamesArray "Sinhalese": "si", // # __CFBundleLanguageNamesArray "Slovak": "sk", // # __CFBundleLanguageNamesArray "Slovenian": "sl", // # __CFBundleLanguageNamesArray "Somali": "so", // # __CFBundleLanguageNamesArray "Spanish": "es", // # __CFBundleLanguageNamesArray "Sundanese": "su", // # __CFBundleLanguageNamesArray "Swahili": "sw", // # __CFBundleLanguageNamesArray "Swedish": "sv", // # __CFBundleLanguageNamesArray "Tagalog": "fil", // # __CFBundleLanguageNamesArray "Tajik": "tg", // # handle other names "Tajiki": "tg", // # __CFBundleLanguageNamesArray "Tamil": "ta", // # __CFBundleLanguageNamesArray "Tatar": "tt", // # __CFBundleLanguageNamesArray "Telugu": "te", // # __CFBundleLanguageNamesArray "Thai": "th", // # __CFBundleLanguageNamesArray "Tibetan": "bo", // # __CFBundleLanguageNamesArray "Tigrinya": "ti", // # __CFBundleLanguageNamesArray "Tongan": "to", // # __CFBundleLanguageNamesArray "Traditional Chinese": "zh-Hant", // # handle other names "Turkish": "tr", // # __CFBundleLanguageNamesArray "Turkmen": "tk", // # __CFBundleLanguageNamesArray "Uighur": "ug", // # __CFBundleLanguageNamesArray "Ukrainian": "uk", // # __CFBundleLanguageNamesArray "Urdu": "ur", // # __CFBundleLanguageNamesArray "Uzbek": "uz", // # __CFBundleLanguageNamesArray "Vietnamese": "vi", // # __CFBundleLanguageNamesArray "Welsh": "cy", // # __CFBundleLanguageNamesArray "Yiddish": "yi", // # __CFBundleLanguageNamesArray "ar_??": "ar", // # from old MapScriptInfoAndISOCodes "az.Ar": "az-Arab", // # from old LocaleRefGetPartString "az.Cy": "az-Cyrl", // # from old LocaleRefGetPartString "az.La": "az", // # from old LocaleRefGetPartString "be_??": "be_BY", // # from old MapScriptInfoAndISOCodes "bn_??": "bn", // # from old LocaleRefGetPartString "bo_??": "bo", // # from old MapScriptInfoAndISOCodes "br_??": "br", // # from old MapScriptInfoAndISOCodes "cy_??": "cy", // # from old MapScriptInfoAndISOCodes "de-96": "de-1996", // # from old MapScriptInfoAndISOCodes // <1.9> "de_96": "de-1996", // # from old MapScriptInfoAndISOCodes // <1.9> "de_??": "de-1996", // # from old MapScriptInfoAndISOCodes "el.El-P": "grc", // # from old LocaleRefGetPartString "en-ascii": "en_001", // # from earlier version of tables in this file! "en_??": "en_001", // # from old MapScriptInfoAndISOCodes "eo_??": "eo", // # from old MapScriptInfoAndISOCodes "es_??": "es_419", // # from old MapScriptInfoAndISOCodes "es_XL": "es_419", // # from earlier version of tables in this file! "fr_??": "fr_001", // # from old MapScriptInfoAndISOCodes "ga-dots": "ga-Latg", // # from earlier version of tables in this file! // <1.8> "ga-dots_IE": "ga-Latg_IE", // # from earlier version of tables in this file! // <1.8> "ga.Lg": "ga-Latg", // # from old LocaleRefGetPartString // <1.8> "ga.Lg_IE": "ga-Latg_IE", // # from old LocaleRefGetPartString // <1.8> "gd_??": "gd", // # from old MapScriptInfoAndISOCodes "gv_??": "gv", // # from old MapScriptInfoAndISOCodes "jv.La": "jv", // # logical extension // <1.9> "jw.La": "jv", // # from old LocaleRefGetPartString "kk.Cy": "kk", // # from old LocaleRefGetPartString "kl.La": "kl", // # from old LocaleRefGetPartString "kl.La_GL": "kl_GL", // # from old LocaleRefGetPartString // <1.9> "lp_??": "se", // # from old MapScriptInfoAndISOCodes "mk_??": "mk_MK", // # from old MapScriptInfoAndISOCodes "mn.Cy": "mn", // # from old LocaleRefGetPartString "mn.Mn": "mn-Mong", // # from old LocaleRefGetPartString "ms.Ar": "ms-Arab", // # from old LocaleRefGetPartString "ms.La": "ms", // # from old LocaleRefGetPartString "nl-be": "nl-BE", // # from old LocaleRefGetPartString "nl-be_BE": "nl_BE", // # from old LocaleRefGetPartString "no-NO": "nb-NO", // # not handled by localeStringPrefixToCanonical "no-NO_NO": "nb-NO_NO", // # not handled by localeStringPrefixToCanonical "pa_??": "pa", // # from old LocaleRefGetPartString "sa.Dv": "sa", // # from old LocaleRefGetPartString "sl_??": "sl_SI", // # from old MapScriptInfoAndISOCodes "sr_??": "sr_RS", // # from old MapScriptInfoAndISOCodes // <1.18> "su.La": "su", // # from old LocaleRefGetPartString "yi.He": "yi", // # from old LocaleRefGetPartString "zh-simp": "zh-Hans", // # from earlier version of tables in this file! "zh-trad": "zh-Hant", // # from earlier version of tables in this file! "zh.Ha-S": "zh-Hans", // # from old LocaleRefGetPartString "zh.Ha-S_CN": "zh_CN", // # from old LocaleRefGetPartString "zh.Ha-T": "zh-Hant", // # from old LocaleRefGetPartString "zh.Ha-T_TW": "zh_TW", // # from old LocaleRefGetPartString } go-locale-1.1.3/locale_darwin_test.go000066400000000000000000000004671474760024400175660ustar00rootroot00000000000000package locale import ( "testing" ) func TestDetectViaUserDefaultsSystem(t *testing.T) { langs, err := detectViaDefaultsSystem() t.Logf("langs: %v", langs) if err != nil { t.Errorf("Expected nil error, got: %v", err) } if len(langs) == 0 { t.Error("Expected non-empty langs, got empty slice") } } go-locale-1.1.3/locale_js.go000066400000000000000000000001261474760024400156470ustar00rootroot00000000000000package locale var detectors = []detector{ detectViaEnvLanguage, detectViaEnvLc, } go-locale-1.1.3/locale_posix.go000066400000000000000000000050201474760024400163730ustar00rootroot00000000000000//go:build aix || dragonfly || freebsd || hurd || illumos || linux || nacl || netbsd || openbsd || plan9 || solaris || zos // +build aix dragonfly freebsd hurd illumos linux nacl netbsd openbsd plan9 solaris zos package locale import ( "bufio" "os" "path" "strings" ) var detectors = []detector{ detectViaEnvLanguage, detectViaEnvLc, detectViaLocaleConf, } func detectViaLocaleConf() (_ []string, err error) { defer func() { if err != nil { err = &Error{"detect via locale conf", err} } }() fp := getLocaleConfPath() if fp == "" { return nil, ErrNotDetected } f, err := os.Open(fp) if err != nil { return nil, err } // Output should be like: // // LANG=en_US.UTF-8 // LC_CTYPE="en_US.UTF-8" // LC_NUMERIC="en_US.UTF-8" // LC_TIME="en_US.UTF-8" // LC_COLLATE="en_US.UTF-8" // LC_MONETARY="en_US.UTF-8" // LC_MESSAGES= // LC_PAPER="en_US.UTF-8" // LC_NAME="en_US.UTF-8" // LC_ADDRESS="en_US.UTF-8" // LC_TELEPHONE="en_US.UTF-8" // LC_MEASUREMENT="en_US.UTF-8" // LC_IDENTIFICATION="en_US.UTF-8" // LC_ALL= m := make(map[string]string) s := bufio.NewScanner(f) for s.Scan() { value := strings.Split(s.Text(), "=") // Ignore not set locale value. if len(value) != 2 || value[1] == "" { continue } m[value[0]] = strings.Trim(value[1], "\"") } for _, v := range envs { x, ok := m[v] if ok { return []string{parseEnvLc(x)}, nil } } return nil, ErrNotDetected } // getLocaleConfPath will try to get correct locale conf path. // // Following path could be returned: // - "$XDG_CONFIG_HOME/locale.conf" (follow XDG Base Directory specification) // - "$HOME/.config/locale.conf" (user level locale config) // - "/etc/locale.conf" (system level locale config) // - "" (empty means no valid path found, caller need to handle this.) // // ref: // - POSIX Locale: https://pubs.opengroup.org/onlinepubs/9699919799/ // - XDG Base Directory: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html func getLocaleConfPath() string { // Try to loading from $XDG_CONFIG_HOME/locale.conf xdg, ok := os.LookupEnv("XDG_CONFIG_HOME") if ok { fp := path.Join(xdg, "locale.conf") _, err := os.Stat(fp) if err == nil { return fp } } // Try to loading from $HOME/.config/locale.conf home, ok := os.LookupEnv("HOME") if ok { fp := path.Join(home, ".config", "locale.conf") _, err := os.Stat(fp) if err == nil { return fp } } // Try to loading from /etc/locale.conf fp := "/etc/locale.conf" _, err := os.Stat(fp) if err == nil { return fp } return "" } go-locale-1.1.3/locale_posix_test.go000066400000000000000000000030051474760024400174330ustar00rootroot00000000000000//go:build !windows && !darwin && !js // +build !windows,!darwin,!js package locale import ( "os" "path" "testing" ) func TestXDGConfigHome(t *testing.T) { setupEnv() tmpDir := setupLocaleConf("locale.conf") defer os.RemoveAll(tmpDir) err := os.Setenv("XDG_CONFIG_HOME", tmpDir) if err != nil { t.Fatal(err) } fp := getLocaleConfPath() expected := path.Join(tmpDir, "locale.conf") if fp != expected { t.Errorf("Expected path %s, got %s", expected, fp) } } func TestHOME(t *testing.T) { setupEnv() tmpDir := setupLocaleConf(".config/locale.conf") defer os.RemoveAll(tmpDir) err := os.Setenv("HOME", tmpDir) if err != nil { t.Fatal(err) } fp := getLocaleConfPath() expected := path.Join(tmpDir, ".config/locale.conf") if fp != expected { t.Errorf("Expected path %s, got %s", expected, fp) } } func TestFallbackToSystem(t *testing.T) { setupEnv() var localeExist bool _, err := os.Stat("/etc/locale.conf") if err == nil { localeExist = true } fp := getLocaleConfPath() if (fp == "/etc/locale.conf") != localeExist { t.Errorf("Expected path to be /etc/locale.conf: %v, got: %s", localeExist, fp) } } func TestDetectViaLocaleConf(t *testing.T) { setupEnv() tmpDir := setupLocaleConf("locale.conf") defer os.RemoveAll(tmpDir) err := os.Setenv("XDG_CONFIG_HOME", tmpDir) if err != nil { t.Fatal(err) } lang, err := detectViaLocaleConf() if err != nil { t.Errorf("Expected no error, got %v", err) } if len(lang) == 0 { t.Error("Expected non-empty lang, got empty string") } } go-locale-1.1.3/locale_shared.go000066400000000000000000000035271474760024400165110ustar00rootroot00000000000000package locale import ( "os" "strings" ) // Unless we call LookupEnv more than 9 times, we should not use Environ. // // goos: linux // goarch: amd64 // pkg: github.com/Xuanwo/go-locale // BenchmarkLookupEnv // BenchmarkLookupEnv-8 37024654 32.4 ns/op // BenchmarkEnviron // BenchmarkEnviron-8 4275735 281 ns/op // PASS // envs is the env to be checked. // // LC_ALL will overwrite all LC_* options. // FIXME: LC_ALL=C should overwrite $LANGUAGE env // // LC_MESSAGES is the config for messages. // FIXME: LC_MESSAGES=C should overwrite $LANGUAGE env // // LANG is the default locale. var envs = []string{"LC_ALL", "LC_MESSAGES", "LANG"} // detectViaEnvLanguage checks env LANGUAGE // // Program use gettext will respect LANGUAGE env func detectViaEnvLanguage() ([]string, error) { s, ok := os.LookupEnv("LANGUAGE") if !ok || s == "" { return nil, &Error{"detect via env language", ErrNotDetected} } return parseEnvLanguage(s), nil } // detectViaEnvLc checks LC_* in order which decided by // unix convention // // ref: // - http://man7.org/linux/man-pages/man7/locale.7.html // - https://linux.die.net/man/3/gettext // - https://wiki.archlinux.org/index.php/Locale func detectViaEnvLc() ([]string, error) { for _, v := range envs { s, ok := os.LookupEnv(v) if ok && s != "" { return []string{parseEnvLc(s)}, nil } } return nil, &Error{"detect via env lc", ErrNotDetected} } // parseEnvLanguage will parse LANGUAGE env. // Input could be: "en_AU:en_GB:en" func parseEnvLanguage(s string) []string { return strings.Split(s, ":") } // parseEnvLc will parse LC_* env. // Input could be: "en_US.UTF-8" func parseEnvLc(s string) string { x := strings.Split(s, ".") // "C" means "ANSI-C" and "POSIX", if locale set to C, we can simple // set returned language to "en_US" if x[0] == "C" { return "en_US" } return x[0] } go-locale-1.1.3/locale_shared_test.go000066400000000000000000000040261474760024400175430ustar00rootroot00000000000000package locale import ( "errors" "os" "reflect" "testing" ) func TestDetectViaEnvLanguage(t *testing.T) { tests := []struct { name string envValue string want []string wantErr error }{ {"Valid single value", "en_US", []string{"en_US"}, nil}, {"Multiple values", "en_US:zh_CN", []string{"en_US", "zh_CN"}, nil}, {"Empty value", "", nil, ErrNotDetected}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { setupEnv() defer setupEnv() err := os.Setenv("LANGUAGE", tt.envValue) if err != nil { t.Fatal(err) } got, err := detectViaEnvLanguage() t.Logf("langs: %v", got) if !errors.Is(err, tt.wantErr) { t.Errorf("detectViaEnvLanguage() error = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, tt.want) { t.Errorf("detectViaEnvLanguage() = %v, want %v", got, tt.want) } }) } } func TestDetectViaEnvLc(t *testing.T) { tests := []struct { name string setEnv bool envKey string envVal string want []string wantErr error }{ {"LC_ALL set", true, "LC_ALL", "en_US.UTF-8", []string{"en_US"}, nil}, {"No LC env set", false, "", "", nil, ErrNotDetected}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { setupEnv() defer setupEnv() if tt.setEnv { err := os.Setenv(tt.envKey, tt.envVal) if err != nil { t.Fatal(err) } } got, err := detectViaEnvLc() t.Logf("langs: %v", got) if !errors.Is(err, tt.wantErr) { t.Errorf("detectViaEnvLc() error = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, tt.want) { t.Errorf("detectViaEnvLc() = %v, want %v", got, tt.want) } }) } } func TestParseEnvLc(t *testing.T) { tests := []struct { name string input string want string }{ {"en_US.UTF-8", "en_US.UTF-8", "en_US"}, {"C.UTF-8", "C.UTF-8", "en_US"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := parseEnvLc(tt.input); got != tt.want { t.Errorf("parseEnvLc() = %v, want %v", got, tt.want) } }) } } go-locale-1.1.3/locale_test.go000066400000000000000000000051151474760024400162150ustar00rootroot00000000000000package locale import ( "errors" "reflect" "sync" "testing" "golang.org/x/text/language" ) var mockLang mock type mock struct { s []string err error sync.Mutex } func (l *mock) get() ([]string, error) { l.Lock() defer l.Unlock() return l.s, l.err } func (l *mock) set(s []string, e error) { l.Lock() defer l.Unlock() l.s = s l.err = e } func TestInternalDetect(t *testing.T) { detectors = []detector{mockLang.get} testErr := errors.New("test error") tests := []struct { name string mockString []string mockError error expectString []string expectError error }{ {"normal", []string{"en_US"}, nil, []string{"en_US"}, nil}, {"not detected", nil, ErrNotDetected, nil, ErrNotDetected}, {"other error", nil, testErr, nil, testErr}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockLang.set(tt.mockString, tt.mockError) lang, err := detect() if !errors.Is(err, tt.expectError) { t.Errorf("detect() error = %v, expectError %v", err, tt.expectError) } if !reflect.DeepEqual(lang, tt.expectString) { t.Errorf("detect() = %v, want %v", lang, tt.expectString) } }) } } func TestDetect(t *testing.T) { detectors = []detector{mockLang.get} tests := []struct { name string mockString []string mockError error expectLang language.Tag expectError error }{ {"normal", []string{"en-US"}, nil, language.AmericanEnglish, nil}, {"not detected", nil, ErrNotDetected, language.Und, ErrNotDetected}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockLang.set(tt.mockString, tt.mockError) lang, err := Detect() if !errors.Is(err, tt.expectError) { t.Errorf("Detect() error = %v, expectError %v", err, tt.expectError) } if lang != tt.expectLang { t.Errorf("Detect() = %v, want %v", lang, tt.expectLang) } }) } } func TestDetectAll(t *testing.T) { detectors = []detector{mockLang.get} tests := []struct { name string mockString []string mockError error expectLang []language.Tag expectError error }{ {"normal", []string{"en-US"}, nil, []language.Tag{language.AmericanEnglish}, nil}, {"not detected", nil, ErrNotDetected, nil, ErrNotDetected}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockLang.set(tt.mockString, tt.mockError) lang, err := DetectAll() if !errors.Is(err, tt.expectError) { t.Errorf("DetectAll() error = %v, expectError %v", err, tt.expectError) } if !reflect.DeepEqual(lang, tt.expectLang) { t.Errorf("DetectAll() = %v, want %v", lang, tt.expectLang) } }) } } go-locale-1.1.3/locale_utils_test.go000066400000000000000000000022521474760024400174340ustar00rootroot00000000000000package locale import ( "io/ioutil" "os" "path" "strings" "sync" "testing" "time" ) var env struct { Env map[string]string sync.Mutex sync.Once } func setupLocaleConf(filePath string) (dir string) { confContent := `LANG=en_US.UTF-8` tmpDir := "/tmp/" + time.Now().String() baseDir := path.Dir(path.Join(tmpDir, filePath)) err := os.MkdirAll(baseDir, 0755) if err != nil { panic(err) } err = ioutil.WriteFile(path.Join(tmpDir, filePath), []byte(confContent), 0644) if err != nil { panic(err) } return tmpDir } func setupEnv() { env.Lock() defer env.Unlock() env.Do(func() { env.Env = make(map[string]string) for _, v := range os.Environ() { x := strings.SplitN(v, "=", 2) // Ignore all language related env if strings.HasPrefix(x[0], "LANG") || strings.HasPrefix(x[0], "LC") { continue } env.Env[x[0]] = x[1] } }) os.Clearenv() for k, v := range env.Env { err := os.Setenv(k, v) if err != nil { panic(err) } } return } func BenchmarkLookupEnv(b *testing.B) { for i := 0; i < b.N; i++ { _, _ = os.LookupEnv("LANGUAGE") } } func BenchmarkEnviron(b *testing.B) { for i := 0; i < b.N; i++ { _ = os.Environ() } } go-locale-1.1.3/locale_windows.go000066400000000000000000000013731474760024400167320ustar00rootroot00000000000000package locale import ( "golang.org/x/sys/windows/registry" ) var detectors = []detector{ detectViaEnvLanguage, detectViaEnvLc, detectViaRegistry, } // detectViaRegistry will detect language via Windows Registry // // ref: https://renenyffenegger.ch/notes/Windows/registry/tree/HKEY_CURRENT_USER/Control-Panel/International/index func detectViaRegistry() (langs []string, err error) { defer func() { if err != nil { err = &Error{"detect via registry", err} } }() key, err := registry.OpenKey(registry.CURRENT_USER, `Control Panel\International`, registry.QUERY_VALUE) if err != nil { return nil, err } defer key.Close() lang, _, err := key.GetStringValue("LocaleName") if err != nil { return nil, err } return []string{lang}, nil } go-locale-1.1.3/locale_windows_test.go000066400000000000000000000004511474760024400177650ustar00rootroot00000000000000package locale import ( "testing" ) func Test_detectViaRegistry(t *testing.T) { langs, err := detectViaRegistry() t.Logf("langs: %v", langs) if err != nil { t.Errorf("Expected no error, got: %v", err) } if len(langs) == 0 { t.Error("Expected non-empty langs, got empty slice") } }