Skip to content

Commit

Permalink
Add support for plural version
Browse files Browse the repository at this point in the history
  • Loading branch information
sdassow committed Nov 20, 2024
1 parent 66c137f commit a6166fd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
13 changes: 13 additions & 0 deletions locale_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package locale
#include <AppKit/AppKit.h>
char *preferredLocalization();
int preferredLocalizations(char ***);
*/
import "C"
import (
Expand All @@ -18,6 +19,7 @@ import (
"regexp"
"strings"
"syscall"
"unsafe"
)

func execCommand(cmd string, args ...string) (status int, out string, err error) {
Expand Down Expand Up @@ -68,6 +70,17 @@ var appleLanguagesRegex = regexp.MustCompile(`([a-z]{2}(?:-[A-Z]{2})?)`)

// GetLocales retrieves the IETF BCP 47 language tags set on the system.
func GetLocales() ([]string, error) {
var locs **C.char

if n := C.preferredLocalizations(&locs); n > 0 {
r := make([]string, n)
for m, v := range unsafe.Slice(locs, n) {
r[m] = strings.Replace(C.GoString(v), "_", "-", 1)
}

return r, nil
}

_, output, err := execCommand("defaults", "read", "-g", "AppleLanguages")
if err != nil {
return nil, fmt.Errorf("cannot determine locale: %v (output: %s)", err, output)
Expand Down
27 changes: 27 additions & 0 deletions locale_darwin.m
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,30 @@

return (char *) [localization UTF8String];
}

int preferredLocalizations(char ***list) {
NSArray *locs = [NSBundle mainBundle].preferredLocalizations;
int nlocs = [locs count];
char **r = calloc(nlocs, sizeof(char *));

if (r == NULL)
return -1;

for (int n = 0; n < nlocs; n++) {
r[n] = strdup([locs[n] UTF8String]);
if (r[n] == NULL)
goto fail;
}

*list = r;

return nlocs;

fail:
for (int n = 0; n < nlocs; n++) {
if (r[n] != NULL)
free(r[n]);
}
free(r);
return -1;
}

0 comments on commit a6166fd

Please sign in to comment.