Skip to content

Commit 43e1a4a

Browse files
committed
FileOps: add copy function
1 parent d791d6f commit 43e1a4a

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

modules/DependencyControl/FileOps.moon

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ class FileOps
1515
createError: "Error creating directory: %s."
1616
otherExists: "Couldn't create directory because a %s of the same name is already present."
1717
}
18+
copy: {
19+
targetExists: "Target file '%s' already exists"
20+
genericError: "An error occured while copying file '%s' to '%s':\n%s"
21+
dirCopyUnsupported: "Copying directories is currently not supported."
22+
missingSource: "Couldn't find source file '%s'."
23+
openError: "Couldn't open %s file '%s' for reading: \n%s"
24+
}
1825
move: {
1926
inUseTryingRename: "Target file '%s' already exists and appears to be in use. Trying to rename..."
2027
overwritingFile: "File '%s' already exists, overwriting..."
@@ -94,6 +101,52 @@ class FileOps
94101
config\write!
95102
return true
96103

104+
copy: ( source, target ) ->
105+
-- source check
106+
mode, sourceFullPath, _, _, fileName = FileOps.attributes source, "mode"
107+
switch mode
108+
when "directory"
109+
return false, msgs.copy.dirCopyUnsupported
110+
when nil
111+
return false, msgs.copy.genericError\format source, target, sourceFullPath
112+
when false
113+
return false, msgs.copy.missingSource\format source
114+
115+
-- target check
116+
checkTarget = (target) ->
117+
mode, targetFullPath = FileOps.attributes target, "mode"
118+
switch mode
119+
when "file"
120+
return false, msgs.copy.targetExists\format target
121+
when nil
122+
return false, msgs.copy.genericError\format source, target, targetFullPath
123+
when "directory"
124+
target ..= "/#{fileName}"
125+
return checkTarget target
126+
return true, targetFullPath
127+
128+
success, targetFullPath = checkTarget target
129+
return false, targetFullPath unless success
130+
131+
input, msg = io.open sourceFullPath, "rb"
132+
unless input
133+
return false, msgs.copy.openError\format "source", sourceFullPath, msg
134+
135+
output, msg = io.open targetFullPath, "wb"
136+
unless output
137+
input\close!
138+
return false, msgs.copy.openError\format "target", targetFullPath, msg
139+
140+
success, msg = output\write input\read "*a"
141+
input\close!
142+
output\close!
143+
144+
if success
145+
return true
146+
else
147+
return false, msgs.copy.genericError\format sourceFullPath, targetFullPath, msg
148+
149+
97150
move: (source, target) ->
98151
mode, err = FileOps.attributes target, "mode"
99152
if mode == "file"

0 commit comments

Comments
 (0)