ropensci / mapscanner

R package to print maps, draw on them, and scan them back in
https://docs.ropensci.org/mapscanner/
Other
90 stars 7 forks source link

fix api key handling #23

Closed mpadge closed 5 years ago

mpadge commented 5 years ago

In response to error messages issued during review by @khondula:

Error in get_mapbox_token() : 
  Map generation requires a mapbox API key to be set with Sys.setenv with a name that includes either the strings 'mapbox' or 'mapscanner'
In addition: Warning message:
In if (length(tok) != 1 | tok == "") stop("Map generation requires a mapbox API key to be set with ",  :
  the condition has length > 1 and only the first element will be used
mpadge commented 5 years ago

The above closing commit implements this behaviour:

library (mapscanner)
e <- Sys.getenv()
e <- e [grep ("mapbox|mapscan", names (e), ignore.case = TRUE)]
names (e) # I have two envvars holding same token
#> [1] "MAPBOX_API_KEY" "MAPBOX_TOKEN"

mapbox_token <- get_mapbox_token () # works because only one unique token

# Then add another envvar with a different value
re <- "~/.Renviron"
invisible (file.copy (re, "~/.Renviron-cp"))
update_renv <- function (txt) {
    con <- file ("~/.Renviron", open = "a") # 'a' for append mode
    writeLines (txt, con = con)
    close (con)
    readRenviron (re) # re-load the ~/.Renviron file
}
update_renv ("MAPBOX_JUNK=\"i-already-have-a-mapbox-token-here\"")
mapbox_token <- get_mapbox_token () # fails because no unique token
#> Error: Map generation requires a mapbox API key to be set with Sys.setenv
#> or the package's 'set_mapbox_token' function, using a token name that
#> includes either the strings 'mapbox' or 'mapscanner'. Tokens can be obtained
#> from https://docs.mapbox.com/api/#access-tokens-and-token-scopes

# Then add a specific 'mapscanner' token
update_renv ("MAPSCANNER=\"mapbox-token-in-mapscanner-envvar\"")
mapbox_token <- get_mapbox_token () # succeeds because 'mapscanner' tok is unique
print (mapbox_token)
#> [1] "mapbox-token-in-mapscanner-envvar"

# restore ~.Renviron
invisible (file.copy ("~/.Renviron-cp", re, overwrite = TRUE))
invisible (file.remove ("~/.Renviron-cp"))

Created on 2019-10-21 by the reprex package (v0.3.0)