sal/rhaiexamples/05_directory_operations.rhai
2025-04-04 18:38:53 +02:00

84 lines
2.8 KiB
Plaintext

// 05_directory_operations.rhai
// Demonstrates directory operations using SAL, including the new chdir function
// Create a test directory structure
let base_dir = "rhai_dir_test";
let sub_dir = base_dir + "/tmp/test";
println("Creating directory structure...");
let base_result = mkdir(base_dir+"/subdir");
println(`Base directory creation result: ${base_result}`);
let sub_result = mkdir(sub_dir);
println(`Subdirectory creation result: ${sub_result}`);
// Create a test file in the base directory
let base_file = base_dir + "/base_file.txt";
let base_content = "This is a file in the base directory.";
// First touch the file
run_command(`touch ${base_file}`);
// Then write to it with a separate command
run_command(`echo ${base_content} > ${base_file}`);
// Create a test file in the subdirectory
let sub_file = sub_dir + "/sub_file.txt";
let sub_content = "This is a file in the subdirectory.";
// First touch the file
run_command(`touch ${sub_file}`);
// Then write to it with a separate command
run_command(`echo ${sub_content} > ${sub_file}`);
// Get the current working directory before changing
let pwd_before = run_command("pwd");
println(`Current directory before chdir: ${pwd_before.stdout.trim()}`);
// Change to the base directory
println(`Changing directory to: ${base_dir}`);
let chdir_result = chdir(base_dir);
println(`Directory change result: ${chdir_result}`);
// Get the current working directory after changing
let pwd_after = run_command("pwd");
println(`Current directory after chdir: ${pwd_after.stdout.trim()}`);
// List files in the current directory (which should now be the base directory)
println("Files in the current directory:");
let files = find_files(".", "*");
println("Files found:");
for file in files {
println(`- ${file}`);
}
// Change to the subdirectory
println(`Changing directory to: subdir`);
let chdir_sub_result = chdir("subdir");
println(`Directory change result: ${chdir_sub_result}`);
// Get the current working directory after changing to subdirectory
let pwd_final = run_command("pwd");
println(`Current directory after second chdir: ${pwd_final.stdout.trim()}`);
// List files in the subdirectory
println("Files in the subdirectory:");
let subdir_files = find_files(".", "*");
println("Files found:");
for file in subdir_files {
println(`- ${file}`);
}
// Change back to the parent directory
println("Changing directory back to parent...");
let chdir_parent_result = chdir("..");
println(`Directory change result: ${chdir_parent_result}`);
// Clean up (uncomment to actually delete the files)
// println("Cleaning up...");
// Change back to the original directory first
// chdir(pwd_before.stdout.trim());
// delete(sub_file);
// delete(base_file);
// delete(sub_dir);
// delete(base_dir);
// println("Cleanup complete");
"Directory operations script completed successfully!"