@@ -17,73 +17,88 @@ create_if_needed <- function(
1717 " file" ,
1818 " directory"
1919 ),
20- content = NULL
20+ content = NULL ,
21+ overwrite = FALSE ,
22+ warn_if_exists = TRUE
2123) {
2224 type <- match.arg(
2325 type
2426 )
2527
2628 # Check if file or dir already exist
2729 if (type == " file" ) {
28- dont_exist <- Negate(
29- fs_file_exists
30- )(
31- path
32- )
30+ already_exists <- fs_file_exists(path )
3331 } else if (type == " directory" ) {
34- dont_exist <- Negate(
35- fs_dir_exists
36- )(
37- path
38- )
32+ already_exists <- fs_dir_exists(path )
33+ }
34+
35+ # If it already exists, handle overwrite logic
36+ if (already_exists ) {
37+ if (! overwrite ) {
38+ if (rlang_is_interactive()) {
39+ # In interactive mode, ask user if they want to overwrite
40+ ask <- yesno(
41+ sprintf(
42+ " The %s %s already exists, overwrite?" ,
43+ basename(path ),
44+ type
45+ )
46+ )
47+ if (! ask ) {
48+ return (TRUE ) # File exists, user doesn't want to overwrite
49+ }
50+ } else {
51+ # In non-interactive mode, warn but don't overwrite (if warnings enabled)
52+ if (warn_if_exists ) {
53+ warning(
54+ sprintf(
55+ " The %s %s already exists and will not be overwritten. Set overwrite = TRUE to force overwrite." ,
56+ basename(path ),
57+ type
58+ ),
59+ call. = FALSE
60+ )
61+ }
62+ return (TRUE ) # File exists, not overwriting
63+ }
64+ }
65+ # If we reach here, either overwrite = TRUE or user said yes to overwrite
3966 }
40- # If it doesn't exist, ask if we are allowed to create it
41- if (dont_exist ) {
42- if (rlang_is_interactive()) {
67+
68+ # If it doesn't exist, or we're overwriting, create it
69+ if (! already_exists || overwrite ) {
70+ if (rlang_is_interactive() && ! already_exists ) {
71+ # In interactive mode, ask if we should create new files/dirs
4372 ask <- ask_golem_creation_file(
4473 path ,
4574 type
4675 )
4776 # Return early if the user doesn't allow
4877 if (! ask ) {
49- return (
50- FALSE
51- )
78+ return (FALSE )
5279 }
53- # Create the file
54- if (type == " file" ) {
55- fs_file_create(
56- path
57- )
80+ }
81+
82+ # Create the file or directory
83+ if (type == " file" ) {
84+ fs_file_create(path )
85+ if (! is.null(content )) {
5886 write(
5987 content ,
6088 path ,
61- append = TRUE
62- )
63- } else if (type == " directory" ) {
64- fs_dir_create(
65- path ,
66- recurse = TRUE
89+ append = ! overwrite # If overwriting, don't append
6790 )
6891 }
69- } else {
70- # We don't create the file if we are not in
71- # interactive mode
72- stop(
73- sprintf(
74- " The %s %s doesn't exist." ,
75- basename(
76- path
77- ),
78- type
79- )
92+ } else if (type == " directory" ) {
93+ fs_dir_create(
94+ path ,
95+ recurse = TRUE
8096 )
8197 }
8298 }
99+
83100 # TRUE means that file exists (either created or already there)
84- return (
85- TRUE
86- )
101+ return (TRUE )
87102}
88103
89104ask_golem_creation_file <- function (
0 commit comments