Skip to content

Commit

Permalink
Allow last to work with length 2 vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
rundel committed Aug 15, 2024
1 parent 2ddcc1a commit 31f9c6c
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
11 changes: 9 additions & 2 deletions R/glue.R
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,15 @@ collapse_head_notrim <- function(x, trunc, sep, sep2, last, ellipsis) {

lnx <- length(x)

if (lnx == 1L) return(x)
if (lnx == 2L) return(paste0(x, collapse = sep2))
if (lnx == 1L)
return(x)
if (lnx == 2L) {
# Handle the case where last is changed and sep2 is not
if (sep2 == " and " & last != ", and ")
return(paste0(x, collapse = last))
else
return(paste0(x, collapse = sep2))
}
if (lnx <= trunc) {
# no truncation
return(paste0(
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/_snaps/collapsing.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,22 @@
Output
[1] "a, b, c, d, e, f, g, h, i, and j"

# Issue #681

Code
v <- cli::cli_vec(c("foo", "bar", "foobar"), style = list(`vec-last` = ", or "))
cli::cli_text("Must be one of: {v}.")
Message
Must be one of: foo, bar, or foobar.
Code
v <- cli::cli_vec(c("foo", "bar"), style = list(`vec-last` = " or "))
cli::cli_text("Must be one of: {v}.")
Message
Must be one of: foo or bar.
Code
v <- cli::cli_vec(c("foo", "bar"), style = list(`vec-last` = " or ",
`vec-sep2` = " xor "))
cli::cli_text("Must be one of: {v}.")
Message
Must be one of: foo xor bar.

27 changes: 27 additions & 0 deletions tests/testthat/test-collapsing.R
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,30 @@ test_that("ansi_collapse uses `sep2` for length-two inputs", {
expect_equal(ansi_collapse(1:2, trunc = 2, style = "head"),
"1 and 2")
})


test_that("Issue #681", {
expect_equal(ansi_collapse(1:2, last = " or "), "1 or 2")
expect_equal(ansi_collapse(1:2, sep2 = " and ", last = " or "), "1 or 2")
expect_equal(ansi_collapse(1:2, sep2 = " xor ", last = " or "), "1 xor 2")

expect_snapshot({
v <- cli::cli_vec(
c("foo", "bar", "foobar"),
style = list("vec-last" = ", or ")
)
cli::cli_text("Must be one of: {v}.")

v <- cli::cli_vec(
c("foo", "bar"),
style = list("vec-last" = " or ")
)
cli::cli_text("Must be one of: {v}.")

v <- cli::cli_vec(
c("foo", "bar"),
style = list("vec-last" = " or ", "vec-sep2" = " xor ")
)
cli::cli_text("Must be one of: {v}.")
})
})

0 comments on commit 31f9c6c

Please sign in to comment.