2 * paths.c - Path manipulation routines
6 * Copyright (C) 2012, 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
29 #include "wimlib/paths.h"
30 #include "wimlib/util.h"
34 /* Like the basename() function, but does not modify @path; it just returns a
35 * pointer to it. This assumes the path separator is the
36 * OS_PREFERRED_PATH_SEPARATOR. */
38 path_basename(const tchar *path)
40 return path_basename_with_len(path, tstrlen(path));
43 /* Like path_basename(), but take an explicit string length. */
45 path_basename_with_len(const tchar *path, size_t len)
47 const tchar *p = &path[len];
52 } while (*--p == OS_PREFERRED_PATH_SEPARATOR);
57 } while (*--p != OS_PREFERRED_PATH_SEPARATOR);
63 /* Returns a pointer to the part of @path following the first colon in the last
64 * path component, or NULL if the last path component does not contain a colon
65 * or has no characters following the first colon. */
67 path_stream_name(const tchar *path)
69 const tchar *base = path_basename(path);
70 const tchar *stream_name = tstrchr(base, T(':'));
71 if (stream_name == NULL || *(stream_name + 1) == T('\0'))
74 return stream_name + 1;
77 /* Duplicate a path; return empty string for NULL input. */
79 canonicalize_fs_path(const tchar *fs_path)
83 return TSTRDUP(fs_path);
87 * canonicalize_wim_path() - Given a user-provided path to a file within a WIM
88 * image, translate it into a "canonical" path.
90 * - Translate both types of slash into a consistent type (WIM_PATH_SEPARATOR).
91 * - Collapse path separators.
92 * - Add leading slash if missing.
93 * - Strip trailing slashes.
95 * Examples (with WIM_PATH_SEPARATOR == '/'):
97 * => / [ either NULL or empty string ]
105 * /hello//1 => /hello/1
106 * \\hello\\1\\ => /hello/1
109 canonicalize_wim_path(const tchar *wim_path)
119 result = MALLOC((1 + tstrlen(in) + 1) * sizeof(result[0]));
125 /* Add leading slash if missing */
126 if (!is_any_path_separator(*in))
127 *out++ = WIM_PATH_SEPARATOR;
130 if (is_any_path_separator(*in)) {
131 /* Collapse multiple path separators into one */
132 *out++ = WIM_PATH_SEPARATOR;
135 } while (is_any_path_separator(*in));
137 /* Copy non-path-separator character */
142 /* Remove trailing slash if existent */
143 if (*(out - 1) == WIM_PATH_SEPARATOR && (out - 1) != result)