Archived
1
0
Fork 0

common/path.c: ~ expand in normalize

This commit is contained in:
H Hautakoski 2010-09-18 21:05:23 +02:00 committed by Henrik Hautakoski
parent 8b0772d0f1
commit 4ca920dc01
2 changed files with 35 additions and 4 deletions

View file

@ -13,11 +13,14 @@
*/ */
#include <string.h> #include <string.h>
#include <stdlib.h>
#include "debug.h" #include "debug.h"
#include "strbuf.h" #include "strbuf.h"
#include "path.h" #include "path.h"
static char path_null = '\0';
/* /*
* allocates and initilizes a path * allocates and initilizes a path
*/ */
@ -118,17 +121,33 @@ size_t pathlen(const char *path) {
return size; return size;
} }
static char* expand_home() {
char *home = getenv("HOME");
if (!home)
home = &path_null;
return home;
}
char* path_normalize(const char *base, const char *name, unsigned char dir) { char* path_normalize(const char *base, const char *name, unsigned char dir) {
strbuf_t sb = STRBUF_INIT; strbuf_t sb = STRBUF_INIT;
if (base == NULL || !is_abspath(base) || has_delim(name)) if (base == NULL || has_delim(name))
return NULL; return NULL;
strbuf_append_str(&sb, base); if (*base == '~') {
base++;
strbuf_append_str(&sb, expand_home());
strbuf_term(&sb, '/');
}
if (sb.buf[sb.len] != '/') strbuf_append_str(&sb, base);
strbuf_append_ch(&sb, '/'); strbuf_term(&sb, '/');
if (!is_abspath(sb.buf))
goto cleanup;
if (name) { if (name) {
strbuf_append_str(&sb, name); strbuf_append_str(&sb, name);
@ -140,4 +159,7 @@ char* path_normalize(const char *base, const char *name, unsigned char dir) {
strbuf_squeeze(&sb, '/'); strbuf_squeeze(&sb, '/');
return strbuf_release(&sb); return strbuf_release(&sb);
cleanup:
strbuf_free(&sb);
return NULL;
} }

View file

@ -1,6 +1,7 @@
#include <malloc.h> #include <malloc.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include "unit.h" #include "unit.h"
#include "../src/common/path.h" #include "../src/common/path.h"
@ -23,6 +24,14 @@ void test_normalize() {
assert_string(ptr, "/stuff/with/ahell/lot/of/slashes/at/the/end/"); assert_string(ptr, "/stuff/with/ahell/lot/of/slashes/at/the/end/");
free(ptr); free(ptr);
ptr = path_normalize("~", NULL, 0);
printf("HOME EXPAND: %s\n", ptr);
free(ptr);
ptr = path_normalize("~/sub", "file", 0);
printf("HOME EXPAND2: %s\n", ptr);
free(ptr);
ptr = path_normalize("/mnt/cdrom", "keff", 0); ptr = path_normalize("/mnt/cdrom", "keff", 0);
assert_string(ptr, "/mnt/cdrom/keff"); assert_string(ptr, "/mnt/cdrom/keff");
free(ptr); free(ptr);