Skip to content

Commit

Permalink
Verify column positions for vroom_fwf
Browse files Browse the repository at this point in the history
Fixes #217
  • Loading branch information
jimhester committed Mar 2, 2020
1 parent ebca8bb commit cf229c5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
@@ -1,5 +1,7 @@
# vroom (development version)

* `vroom_fwf()` now verifies that the positions are valid, namely that the begin value is always less than the previous end (#217).

* `vroom_lines()` gains a `locale` argument so you can control the encoding of the file (#218)

* `vroom()` columns now support indexing with NA values (#201)
Expand Down
10 changes: 10 additions & 0 deletions R/vroom_fwf.R
Expand Up @@ -31,6 +31,8 @@ vroom_fwf <- function(file,
progress = vroom_progress(),
.name_repair = "unique") {

verify_fwf_positions(col_positions)

if (!rlang::is_missing(altrep_opts)) {
lifecycle::deprecate_warn("1.1.0", "vroom_fwf(altrep_opts = )", "vroom_fwf(altrep = )")
altrep <- altrep_opts
Expand Down Expand Up @@ -154,3 +156,11 @@ fwf_col_names <- function(nm, n) {
nm[nm_empty] <- paste0("X", seq_len(n))[nm_empty]
nm
}

verify_fwf_positions <- function(col_positions) {
is_greater <- na.omit(col_positions$begin > col_positions$end)
if (any(is_greater)) {
bad <- which(is_greater)
stop("`col_positions` must have begin less than end.\n* Invalid values at position(s): ", paste0(collapse = ", ", bad), call. = FALSE)
}
}
13 changes: 13 additions & 0 deletions tests/testthat/test-vroom_fwf.R
Expand Up @@ -274,3 +274,16 @@ test_that("vroom_fwf() is robust to improper inputs", {
vroom_fwf("A\n a\n")
)
})

test_that("Errors if begin is greater than end", {
positions <- fwf_positions(
start = c(1, 3, 5),
end = c(3, 1, NA),
col_names = c("foo", "bar", "baz")
)

expect_error(
vroom_fwf("1 2 3\n", positions),
"`col_positions` must have begin less than end"
)
})

0 comments on commit cf229c5

Please sign in to comment.