Skip to content

Commit 400306a

Browse files
authored
Ensure we can write_utf8() even when outside a project (#1081)
* Add failing test * Make sure write_utf8() can operate outside a usethis project
1 parent cf8cb40 commit 400306a

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

R/write.R

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,22 @@ read_utf8 <- function(path, n = -1L) {
9292
base::readLines(path, n = n, encoding = "UTF-8", warn = FALSE)
9393
}
9494

95-
write_utf8 <- function(path, lines, append = FALSE, line_ending = proj_line_ending()) {
95+
write_utf8 <- function(path, lines, append = FALSE, line_ending = NULL) {
9696
stopifnot(is.character(path))
9797
stopifnot(is.character(lines))
9898

9999
file_mode <- if (append) "ab" else "wb"
100100
con <- file(path, open = file_mode, encoding = "utf-8")
101101
on.exit(close(con), add = TRUE)
102102

103+
if (is.null(line_ending)) {
104+
if (possibly_in_proj(path)) {
105+
line_ending <- proj_line_ending()
106+
} else {
107+
line_ending <- platform_line_ending()
108+
}
109+
}
110+
103111
# convert embedded newlines
104112
lines <- gsub("\r?\n", line_ending, lines)
105113
base::writeLines(enc2utf8(lines), con, sep = line_ending, useBytes = TRUE)

tests/testthat/test-write.R

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,21 +70,21 @@ test_that("write_over() leaves file 'as is'", {
7070
})
7171

7272
# https://github.com/r-lib/usethis/issues/514
73-
test_that("write_ut8 always produces a trailing newline", {
73+
test_that("write_utf8() always produces a trailing newline", {
7474
path <- file_temp()
7575
write_utf8(path, "x", line_ending = "\n")
7676
expect_equal(readChar(path, 2), "x\n")
7777
})
7878

79-
test_that("write_ut8 can append text when requested", {
79+
test_that("write_utf8() can append text when requested", {
8080
path <- file_temp()
8181
write_utf8(path, "x", line_ending = "\n")
8282
write_utf8(path, "x", line_ending = "\n", append = TRUE)
8383

8484
expect_equal(readChar(path, 4), "x\nx\n")
8585
})
8686

87-
test_that("write_utf8 respects line ending", {
87+
test_that("write_utf8() respects line ending", {
8888
path <- file_temp()
8989

9090
write_utf8(path, "x", line_ending = "\n")
@@ -93,3 +93,15 @@ test_that("write_utf8 respects line ending", {
9393
write_utf8(path, "x", line_ending = "\r\n")
9494
expect_equal(detect_line_ending(path), "\r\n")
9595
})
96+
97+
test_that("write_utf8() can operate outside of a project", {
98+
tmpdir <- file_temp()
99+
on.exit(dir_delete(tmpdir))
100+
dir_create(tmpdir)
101+
102+
withr::local_dir(tmpdir)
103+
local_project(NULL)
104+
105+
expect_false(proj_active())
106+
expect_error_free(write_utf8(path = "foo", letters[1:3]))
107+
})

0 commit comments

Comments
 (0)