Skip to content

Commit 53600f3

Browse files
authored
Merge pull request #74 from ropensci/better-file-detection
Better file detection
2 parents 31d2104 + ac32d2a commit 53600f3

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

DESCRIPTION

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Package: jsonvalidate
22
Title: Validate 'JSON' Schema
3-
Version: 1.4.1
3+
Version: 1.4.2
44
Authors@R: c(person("Rich", "FitzJohn", role = c("aut", "cre"),
55
email = "[email protected]"),
66
person("Rob", "Ashton", role = "aut"),

R/util.R

+10-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ get_string <- function(x, what = deparse(substitute(x))) {
66
stop(sprintf("Expected a character vector for %s", what))
77
}
88

9-
## TODO: this will get looked at in the next PR as we need to force
10-
## filenames better; it's not possible with this approach to error
11-
## if a file is missed through a typo.
12-
if (length(x) == 1 && file.exists(x)) {
9+
if (refers_to_file(x)) {
1310
x <- paste(readLines(x), collapse = "\n")
1411
} else if (length(x) > 1L) {
1512
x <- paste(x, collapse = "\n")
@@ -19,6 +16,15 @@ get_string <- function(x, what = deparse(substitute(x))) {
1916
}
2017

2118

19+
refers_to_file <- function(x) {
20+
## good reasons not to be a file:
21+
if (length(x) != 1 || inherits(x, "json") || grepl("{", x, fixed = TRUE)) {
22+
return(FALSE)
23+
}
24+
file.exists(x)
25+
}
26+
27+
2228
`%||%` <- function(a, b) {
2329
if (is.null(a)) b else a
2430
}

tests/testthat/test-util.R

+11
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,17 @@ test_that("get_string reads files as a string", {
1313
})
1414

1515

16+
test_that("detect probable files", {
17+
path <- tempfile()
18+
expect_false(refers_to_file('{"a": 1}'))
19+
expect_false(refers_to_file(structure("1", class = "json")))
20+
expect_false(refers_to_file(c("a", "b")))
21+
expect_false(refers_to_file(path))
22+
writeLines(c("some", "test"), path)
23+
expect_true(refers_to_file(path))
24+
})
25+
26+
1627
test_that("get_string concatenates character vectors", {
1728
expect_equal(get_string(c("some", "text")),
1829
"some\ntext")

0 commit comments

Comments
 (0)