blob: cf5b838a1201dbd272c71a6506de5e09e9782f61 [file] [log] [blame]
Matt Kraaia7cecbc2001-08-10 15:05:27 +00001/* vi: set sw=4 ts=4: */
2/*
3 * simplify_path implementation for busybox
4 *
5 *
Matt Kraai0a685902001-08-14 17:10:08 +00006 * Copyright (C) 2001 Manuel Novoa III <mjn3@opensource.lineo.com>
Matt Kraaia7cecbc2001-08-10 15:05:27 +00007 *
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 *
23 */
24
25#include <stdlib.h>
26
27#include "libbb.h"
28
Matt Kraaia7cecbc2001-08-10 15:05:27 +000029char *simplify_path(const char *path)
30{
Matt Kraai0a685902001-08-14 17:10:08 +000031 char *s, *start, *p;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000032
33 if (path[0] == '/')
Matt Kraai0a685902001-08-14 17:10:08 +000034 start = xstrdup(path);
Matt Kraaia7cecbc2001-08-10 15:05:27 +000035 else {
Matt Kraai0a685902001-08-14 17:10:08 +000036 s = xgetcwd(NULL);
37 start = concat_path_file(s, path);
38 free(s);
Matt Kraaia7cecbc2001-08-10 15:05:27 +000039 }
Matt Kraai0a685902001-08-14 17:10:08 +000040 p = s = start;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000041
Matt Kraai0a685902001-08-14 17:10:08 +000042 do {
43 if (*p == '/') {
44 if (*s == '/') { /* skip duplicate (or initial) slash */
45 continue;
46 } else if (*s == '.') {
47 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
48 continue;
49 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
50 ++s;
51 if (p > start) {
52 while (*--p != '/'); /* omit previous dir */
53 }
54 continue;
55 }
Matt Kraaia7cecbc2001-08-10 15:05:27 +000056 }
57 }
Matt Kraai0a685902001-08-14 17:10:08 +000058 *++p = *s;
59 } while (*++s);
60
61 if ((p == start) || (*p != '/')) { /* not a trailing slash */
62 ++p; /* so keep last character */
Matt Kraaia7cecbc2001-08-10 15:05:27 +000063 }
Matt Kraai0a685902001-08-14 17:10:08 +000064 *p = 0;
65
Matt Kraaia7cecbc2001-08-10 15:05:27 +000066 return start;
67}