feat: improve file handling with OS-specific functions and tests (#178)

- Add functions for removing and creating files/directories based on the operating system
- Add unit tests for the functions
This commit is contained in:
Bo-Yi Wu 2023-04-16 12:15:02 +08:00 committed by GitHub
parent 665c665298
commit cf87fecefa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 1 deletions

View File

@ -1,22 +1,29 @@
package main
// This function returns the appropriate command for removing a file/directory based on the operating system.
func rmcmd(os, target string) string {
switch os {
case "windows":
// On Windows, use DEL command to delete files and folders recursively
return "DEL /F /S " + target
case "unix":
// On Unix-based systems, use rm command to delete files and folders recursively
return "rm -rf " + target
}
// Return an empty string if the operating system is not recognized
return ""
}
// This function returns the appropriate command for creating a directory based on the operating system.
func mkdircmd(os, target string) string {
switch os {
case "windows":
// On Windows, use mkdir command to create directory and check if it exists
return "if not exist " + target + " mkdir " + target
case "unix":
// On Unix-based systems, use mkdir command with -p option to create directories recursively
return "mkdir -p " + target
}
// Return an empty string if the operating system is not recognized
return ""
}

42
command_test.go Normal file
View File

@ -0,0 +1,42 @@
package main
import "testing"
// Unit tests for rmcmd and mkdircmd
func TestCommands(t *testing.T) {
// Test rmcmd on Windows
os1 := "windows"
target1 := "C:\\path\\to\\file"
expected1 := "DEL /F /S " + target1
actual1 := rmcmd(os1, target1)
if actual1 != expected1 {
t.Errorf("rmcmd(%s, %s) = %s; expected %s", os1, target1, actual1, expected1)
}
// Test rmcmd on Unix-based system
os2 := "unix"
target2 := "/path/to/folder"
expected2 := "rm -rf " + target2
actual2 := rmcmd(os2, target2)
if actual2 != expected2 {
t.Errorf("rmcmd(%s, %s) = %s; expected %s", os2, target2, actual2, expected2)
}
// Test mkdircmd on Windows
os3 := "windows"
target3 := "C:\\path\\to\\folder"
expected3 := "if not exist " + target3 + " mkdir " + target3
actual3 := mkdircmd(os3, target3)
if actual3 != expected3 {
t.Errorf("mkdircmd(%s, %s) = %s; expected %s", os3, target3, actual3, expected3)
}
// Test mkdircmd on Unix-based system
os4 := "unix"
target4 := "/path/to/folder"
expected4 := "mkdir -p " + target4
actual4 := mkdircmd(os4, target4)
if actual4 != expected4 {
t.Errorf("mkdircmd(%s, %s) = %s; expected %s", os4, target4, actual4, expected4)
}
}