Skip to content

Commit

Permalink
Append string when no extension is available
Browse files Browse the repository at this point in the history
  • Loading branch information
philipdelff committed Nov 8, 2024
1 parent c0fa868 commit 5d1e2c3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 25 deletions.
31 changes: 18 additions & 13 deletions R/fnAppend.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,34 @@
##' @export


fnAppend <- function(fn,x,pad0=0,sep="_"){
fnAppend <- function(fn,x,pad0=0,sep="_",allow.noext=FALSE){

if((!is.numeric(x)&&!is.character(x))) stop("x must be numeric or character vector.")

has.ext <- grepl(".*[^\\.]\\.[a-zA-Z0-9]+",fn)
if(!all(has.ext)) stop("No file name extension found. Cannot append string.")


fnext <- sub(".*[^\\.]\\.([a-zA-Z0-9]+)$","\\1",fn)
## fnroot <- sub(paste0("\\.",fnext,"$"),"",fn)
fnroot <- sub(paste0("\\.[a-zA-Z0-9]+$"),"",fn)

if(is.numeric(x)){
string <- sprintf(fmt=paste("%0",pad0,"d",sep=""),x)
} else {
string <- x
}
string <- paste(string,collapse=sep)

if(nchar(string)==0) return(fn)

if(nchar(string)>0){
paste0(fnroot,sep,string,".",fnext)
} else {
fn
has.ext <- grepl(".*[^\\.]\\.[a-zA-Z0-9]+",fn)
if( !all(has.ext) && !allow.noext){
stop("Elements in fn have no extension and allow.noext=FALSE")
}


allext <- rep("",length(fn))
allext[has.ext] <- sub(".*[^\\.]\\.([a-zA-Z0-9]+)$","\\1",fn[has.ext])
allext[has.ext] <- paste0(".",allext[has.ext])

fnroot <- sub(paste0("\\.[a-zA-Z0-9]+$"),"",fn)



paste0(fnroot,sep,string,allext)

}
39 changes: 27 additions & 12 deletions tests/testthat/test_fnAppend.R
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,6 @@ test_that("basic",{

})

## library(devtools)
## load_all("~/wdirs/NMdata")
test_that("skip directory double dots",{
## todo. This should return an error. There is no extension to
## append in front of.
expect_error(fnAppend("fe/../egef","hmm"))
## should also return error:
expect_error(fnAppend("egef","hmm"))
})

test_that("empty string does notning",{

Expand All @@ -41,10 +32,34 @@ test_that("multiple strings to append",{

fileRef <- "testReference/fnAppend_02.rds"

res1 <- c(fnAppend("NMsim.rds",c("simname","sim2"))
,fnAppend(c("NMsim.rds","NMsim2.rds"),c("simname","sim2"))
)
res1 <- c(
fnAppend("NMsim.rds",c("simname","sim2"))
,
## the strings must both be appended to both fn's.
fnAppend(c("NMsim.rds","NMsim2.rds"),c("simname","sim2"))
)

expect_equal_to_reference(res1,fileRef)

})



test_that("skip directory double dots",{

fileRef <- "testReference/fnAppend_03.rds"

expect_error(
fnAppend("fe/../egef","hmm")
)
## should also return error:
expect_error(
fnAppend("egef","hmm")
)

res <- c(fnAppend("fe/../egef","hmm",allow.noext = TRUE),
fnAppend("egef","hmm",allow.noext = TRUE))

expect_equal_to_reference(res,fileRef)

})

0 comments on commit 5d1e2c3

Please sign in to comment.