diff --git a/vlib/os/os_c.v b/vlib/os/os_c.v index 69934085c4..b95406b72e 100644 --- a/vlib/os/os_c.v +++ b/vlib/os/os_c.v @@ -787,7 +787,7 @@ pub fn real_path(fpath string) string { ret := C.GetFullPathName(fpath.to_wide(), max_path_len, fullpath, 0) if ret == 0 { unsafe { free(fullpath) } - return fpath + return fpath.clone() } res = unsafe { string_from_wide(fullpath) } } $else { @@ -795,7 +795,7 @@ pub fn real_path(fpath string) string { ret := &char(C.realpath(&char(fpath.str), &char(fullpath))) if ret == 0 { unsafe { free(fullpath) } - return fpath + return fpath.clone() } res = unsafe { fullpath.vstring() } } diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index 07f17ae404..9735007588 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -284,10 +284,51 @@ fn test_cp_all() { assert os.exists(os.join_path('nonexisting', 'ex1.txt')) } -fn test_realpath() { +fn test_realpath_of_empty_string_works() { assert os.real_path('') == '' } +fn test_realpath_non_existing() { + non_existing_path := 'sdyfuisd_non_existing_file' + assert os.real_path(non_existing_path) == non_existing_path +} + +fn test_realpath_existing() { + existing_file_name := 'existing_file.txt' + existing_file := os.join_path(os.temp_dir(), existing_file_name) + os.rm(existing_file) or {} + os.write_file(existing_file, 'abc') or {} + assert os.exists(existing_file) + assert os.real_path(existing_file) == existing_file + os.rm(existing_file) or {} +} + +fn test_realpath_removes_dots() { + examples_folder := os.join_path(@VEXEROOT, 'vlib', 'v', '..', '..', 'cmd', '.', '..', + 'examples') + real_path_of_examples_folder := os.real_path(examples_folder) + assert real_path_of_examples_folder.len < examples_folder.len + assert !real_path_of_examples_folder.contains('..') +} + +fn test_realpath_absolutizes_existing_relative_paths() { + old_wd := os.getwd() + defer { + os.chdir(old_wd) + } + os.chdir(@VEXEROOT) + examples_folder := os.join_path('vlib', 'v', '..', '..', 'cmd', '.', '..', 'examples') + real_path_of_examples_folder := os.real_path(examples_folder) + assert os.is_abs_path(real_path_of_examples_folder) +} + +// TODO: think much more about whether this is desirable +fn test_realpath_does_not_absolutize_non_existing_relative_paths() { + relative_path := os.join_path('one', 'nonexisting_folder', '..', 'something') + assert os.real_path(relative_path).contains('..') + assert os.real_path(relative_path) == relative_path +} + fn test_tmpdir() { t := os.temp_dir() assert t.len > 0