Skip to content

Commit

Permalink
Merge pull request #19 from shogo82148/download-tzdata-from-iana
Browse files Browse the repository at this point in the history
  • Loading branch information
Code-Hex authored Oct 2, 2023
2 parents a5125e0 + e7ea3ad commit 040cb63
Showing 1 changed file with 52 additions and 9 deletions.
61 changes: 52 additions & 9 deletions scripts/tzgen/main.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,63 @@
package main

import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"context"
"fmt"
"go/format"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)

const tzdataURL = "https://data.iana.org/time-zones/releases/tzdata2023c.tar.gz"

func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}

func run(ctx context.Context) error {
tzs, err := listTimeZone()
// download tzdata
req, err := http.NewRequestWithContext(ctx, http.MethodGet, tzdataURL, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to download tzdata: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download tzdata: %s", resp.Status)
}

// extract zone.tab
gr, err := gzip.NewReader(resp.Body)
if err != nil {
return err
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
h, err := tr.Next()
if err != nil {
return err
}
if h.Name == "zone.tab" {
break
}
}

// read zone.tab
tzs, err := listTimeZone(tr)
if err != nil {
return err
}
Expand All @@ -28,17 +66,22 @@ func run(ctx context.Context) error {
return fmt.Errorf("%q: %w", tz, err)
}
}
return nil
}

func listTimeZone() (tz []string, _ error) {
file, err := os.Open("/usr/share/zoneinfo/zone.tab")
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
// skip other files
for {
_, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
}
defer file.Close()
return nil
}

scanner := bufio.NewScanner(file)
func listTimeZone(r io.Reader) (tz []string, err error) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "#") {
Expand Down

0 comments on commit 040cb63

Please sign in to comment.