|
| 1 | +#' Function to access metadata |
| 2 | +#' |
| 3 | +#' @param data Dataset imported using one of the [phslookups] functions, |
| 4 | +#' e.g. `get_spd()`. |
| 5 | +#' |
| 6 | +#' @returns |
| 7 | +#' Metadata `tibble` associated with dataset. |
| 8 | +#' |
| 9 | +#' @examples |
| 10 | +#' library(phslookups) |
| 11 | +#' \dontrun{ |
| 12 | +#' spd <- get_spd() |
| 13 | +#' metadata(spd) |
| 14 | +#' } |
| 15 | +#' @export |
| 16 | +metadata <- function(data) { |
| 17 | + if (!inherits(data, "tbl_df")) { |
| 18 | + cli::cli_abort( |
| 19 | + "{.arg data} must must be a tibble loaded using {.pkg phslookups}." |
| 20 | + ) |
| 21 | + } |
| 22 | + |
| 23 | + # If already loaded, return immediately |
| 24 | + metadata <- attr(data, "metadata", exact = TRUE) |
| 25 | + if (!is.null(metadata)) { |
| 26 | + return(metadata) |
| 27 | + } |
| 28 | + |
| 29 | + ref <- attr(data, "metadata_ref", exact = TRUE) |
| 30 | + |
| 31 | + if (is.null(ref)) { |
| 32 | + cli::cli_abort("Metadata is not available for this data.") |
| 33 | + } |
| 34 | + |
| 35 | + if (rlang::is_false(ref$exists)) { |
| 36 | + cli::cli_abort(c( |
| 37 | + "x" = "{ref$type} metadata not available.", |
| 38 | + "i" = "Expected at {.path {ref$path}}" |
| 39 | + )) |
| 40 | + } |
| 41 | + |
| 42 | + metadata <- read_file( |
| 43 | + ref$path, |
| 44 | + col_select = 1:2, |
| 45 | + col_names = c("variable", "description"), |
| 46 | + skip = 1, |
| 47 | + col_types = readr::cols_only( |
| 48 | + variable = readr::col_character(), |
| 49 | + description = readr::col_character() |
| 50 | + ) |
| 51 | + ) |
| 52 | + |
| 53 | + inform_metadata_version(ref$version) |
| 54 | + |
| 55 | + # Attach metadata to the object |
| 56 | + set_metadata(data, metadata) |
| 57 | + |
| 58 | + metadata |
| 59 | +} |
| 60 | + |
| 61 | +set_metadata_ref <- function(data, path, type, version, exists) { |
| 62 | + attr(data, "metadata_ref") <- list( |
| 63 | + path = path, |
| 64 | + type = type, |
| 65 | + version = version, |
| 66 | + exists = exists |
| 67 | + ) |
| 68 | + data |
| 69 | +} |
| 70 | + |
| 71 | +set_metadata <- function(data, metadata) { |
| 72 | + attr(data, "metadata") <- metadata |
| 73 | + data |
| 74 | +} |
| 75 | + |
| 76 | +inform_metadata_access <- function(metadata) { |
| 77 | + cli::cli_inform(c( |
| 78 | + i = "Metadata is available and can be accessed using {.fun metadata}." |
| 79 | + )) |
| 80 | +} |
| 81 | + |
| 82 | +inform_metadata_version <- function(version) { |
| 83 | + if (version != "latest") { |
| 84 | + cli::cli_warn( |
| 85 | + "Metadata corresponds to the latest version of the data |
| 86 | + and may not exactly match the data currently loaded." |
| 87 | + ) |
| 88 | + } |
| 89 | +} |
0 commit comments