data-raw/generate-vars.R

# This script is used to update the string-encoded tree and
# associated/mapped time-zones from https://raw.githubusercontent.com/darkskyapp/tz-lookup/master/tz.js
# that are stored in src/generated-vars.h

library(stringi)
library(Rcpp)

tf <- tempfile(fileext = ".js")
on.exit(unlink(tf), add=TRUE)

# Grab the pre-computed string tree and mapped TZ list
download.file(
  "https://raw.githubusercontent.com/darkskyapp/tz-lookup/master/tz.js",
  tf
)

l <- stri_read_lines(tf)
l <- sub('function tzlookup(Y,W){"use strict";', "", l, fixed=TRUE)
l <- unlist(stri_split_regex(l, '(var T\\=|,U=\\[|;if\\()'))

l[2] <- stri_replace_all_regex(l[2], '^"|"$', "")

# hard wrap lines at n chars
sourceCpp(code = "
#include <Rcpp.h>

// [[Rcpp::export]]
std::vector< std::string > fold(const std::string& input, int width) {

  int sz = input.length() / width;

  std::vector< std::string > out;
  out.reserve(sz); // shld make this more efficient

  for (unsigned long idx=0; idx<sz; idx++) out.push_back(input.substr(idx*width, width));

  if (input.length() % width != 0) out.push_back(input.substr(width*sz));

  return(out);

}
")

# Keeping this here in case we want to go back to the fold binary dependency
#
# tf2 <- tempfile(fileext = ".txt")
# on.exit(unlink(tf2), add=TRUE)
#
# cat(l[2], file=tf2, sep="")
#
# REQUIRES Linux or macOS (or similar) systems
# fold <- Sys.which("fold")
#
# if (fold == "") {
#   stop(
#     "The 'fold' macOS/Linux utility is required for this operation.",
#     call.=FALSE
#   )
# }
#
# stringtree <- system2(fold, c("-w", "70", "-s", tf2), stdout = TRUE)

stringtree <- fold(l[2], 70)
stringtree <- paste0(sprintf('  "%s"', stringtree), collapse = "\n")

l[3] <- stri_replace_last_regex(l[3], "\\]$", "")
l[3] <- stri_replace_all_fixed(l[3], ",", ", ")

paste0(
  sprintf("  %s", stri_wrap(l[3], width = 80, whitespace_only = TRUE)),
  collapse = "\n"
) -> zones

# Overwrite src/generated-vars.h
cat(
  "// This file is automatically generated by data-src/generate-vars.R\n",
  "// DO NOT MODIFY BY HAND as all changes will eventually be overwritten\n",
  "// File generated at: ", as.character(Sys.time(), usetz = TRUE), "\n\n",
  sprintf('const char *TZDATA = \n%s;\n\n', stringtree),
  "const char *_TZLIST[] = {\n",
  zones,
  "\n};\n\n",
  sep = "", file = here::here("src/generated-vars.h")
)

message("REMEMBER TO RE-BUILD AND RE-TEST THE PACKAGE")

unlink(tf)
# unlink(tf2)
ateucher/lutz documentation built on Oct. 17, 2023, 8:46 p.m.