Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 27 additions & 35 deletions lib/xy.h
Original file line number Diff line number Diff line change
Expand Up @@ -912,54 +912,46 @@ xy_normalize_path (const char *path)
{
char *new = xy_str_strip (path); // 防止开发者多写了空白符

if (xy_on_windows)
if (xy_str_start_with (new, "~"))
{
if (xy_str_start_with (new, "~/"))
{
// 或 %USERPROFILE%
new = xy_strjoin (3, xy_os_home, "\\",
xy_str_delete_prefix (new, "~/"));
}
new = xy_str_gsub (new, "/", "\\");
}
else
{
if (xy_str_start_with (new, "~/"))
{
new = xy_strjoin (3, xy_os_home, "/",
xy_str_delete_prefix (new, "~/"));
}
new = xy_strjoin (3, xy_os_home, "/",
xy_str_delete_prefix (new, "~"));
}

return new;
new = xy_str_gsub (new, "\\", "/");
new = xy_str_gsub (new, "//", "/");

if (xy_on_windows)
return xy_str_gsub (new, "/", "\\");
else
return new;
}

/**
* @note 总是返回不含末尾斜杠的父目录路径
*/
static char *
xy_parent_dir (const char *path)
{
char *dir = xy_normalize_path (path);
dir = xy_str_gsub (dir, "\\", "/");
if (xy_str_end_with (dir, "/"))
dir = xy_str_delete_suffix (dir, "/");

char *last = NULL;
if (xy_on_windows)

last = strrchr (dir, '/');
if (!last)
{
last = strrchr (dir, '\\');
if (!last)
{
/* current dir */
return ".";
}
*last = '\0';
/* current dir */
return ".";
}
*last = '\0';

if (xy_on_windows)
return xy_str_gsub (dir, "/", "\\");
else
{
last = strrchr (dir, '/');
if (!last)
{
/* current dir */
return ".";
}
*last = '\0';
}
return dir;
return dir;
}

#endif
9 changes: 9 additions & 0 deletions test/xy.c
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@ main (int argc, char const *argv[])
assert (xy_file_exist (xy_win_powershell_profile));
assert (true == xy_file_exist (xy_win_powershellv5_profile));
assert (xy_dir_exist ("C:\\Users"));
assert_str (xy_normalize_path ("C:\\a bc\\def\\"), "C:\\a bc\\def\\");
assert_str (xy_normalize_path ("a/b c/d"), "a\\b c\\d");
assert_str (xy_normalize_path ("a/b c/d/"), "a\\b c\\d\\");
assert_str (xy_parent_dir ("a/b c/d"), "a\\b c");
assert_str (xy_parent_dir ("a/b c\\d/"), "a\\b c");
assert_str (xy_parent_dir (xy_normalize_path ("~/")), "C:\\Users");
assert_str (xy_parent_dir (xy_normalize_path ("~")), "C:\\Users");
}
else
{
Expand All @@ -115,6 +122,8 @@ main (int argc, char const *argv[])
assert (xy_file_exist (xy_bashrc));
}
assert (xy_dir_exist ("/etc"));
assert_str (xy_normalize_path ("a\\b c\\d"), "a/b c/d");
assert_str (xy_normalize_path ("a\\b c\\d\\"), "a/b c/d/");
}

println (xy_normalize_path (" \n ~/haha/test/123 \n\r "));
Expand Down