Created
September 25, 2020 13:28
-
-
Save MyKo101/726475d91fe33314eca6f1a1f2f69d5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#install.packages(here) | |
#install.packages(crayon) | |
p <- function(str){ | |
structure(str,class=c("path","character")) | |
} | |
`/.path` <- function(a,b){ | |
p(paste(a,b,sep="/")) | |
} | |
print.path <- function(x){ | |
header <- "<object of class path, which does" | |
if(path_exists(x)){ | |
header <- crayon::green(paste(header,"exist>\n")) | |
} else { | |
header <- crayon::red(paste(header,"not exist yet>\n")) | |
} | |
cat(header) | |
cat(x,"\n") | |
} | |
path_exists <- function(x){ | |
if(!inherits(x,"path")) | |
stop("x is not of class 'path'",call.=F) | |
file.exists(here::here(x)) | |
} | |
path_create <- function(x,dir=F,warn=T){ | |
if(path_exists(x)){ | |
if(warn) | |
warning(paste0("Path '",x,"' already exists"),call.=F) | |
} else { | |
if(dir){ | |
invisible(dir.create(x,recursive = T)) | |
} else { | |
path_create(path(dirname(x)),dir=T,warn=F) | |
invisible(file.create(x)) | |
} | |
} | |
} | |
#As long as one of the elements is a path class, it works | |
p1 <- p("folder one") | |
p2 <- p1 / "folder two" | |
p3 <- "folder three" / p("folder four") / "Test text2.txt" | |
p1 #Tells us that it doesn't exist | |
path_exists(p1) #FALSE - Because we've not made it yet | |
path_create(p2,dir=T) #Creates the path as a directory | |
path_create(p2,dir=T) #Warns that it already exists | |
path_exists(p1) #TRUE - because this now exists | |
path_exists(p2) #TRUE - As does this | |
p2 #This now exists | |
p3 #This doesn't | |
writeLines("Testing",p3) # Error because the directory doesn't exist | |
path_create(p3) #Create this file | |
path_exists(p3) #TRUE - It does exist | |
writeLines("Testing",p3) #No Error because it exists now | |
readLines(p3) #Read it back to check | |
p3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
p(paste(a,b,sep="/"))
=>p(file.path(a,b))
this makes it cross-platform