source: branches/profile/CORE/arb_pattern.cxx

Last change on this file was 12587, checked in by epruesse, 10 years ago
  • add arb_open_socket()
  • fix bug in arb_shell_expand()
File size: 2.2 KB
Line 
1#include "arb_pattern.h"
2#include "arb_core.h"
3#include "arb_strbuf.h"
4#include "arb_msg.h"
5
6#include <wordexp.h>
7
8
9/**
10 * Performs shell-like path expansion on @param str:
11 *  - Tilde-Expansion
12 *  - Environment variable substitution
13 *  - Command substitition
14 *  - Arithmetic expansion
15 *  - Wildcard expansion
16 *  - Quote removal
17 *
18 * The implementation uses wordexp (see man wordexp).
19 *
20 *  @return Expanded string (must be freed)
21 */
22char* arb_shell_expand(const char* str) {
23    wordexp_t result;
24    GB_ERROR error = NULL;
25
26    switch (wordexp(str, &result, 0)) {
27    case 0:
28        break;
29    case WRDE_BADCHAR:
30        error = "Illegal character";
31        break;
32    case WRDE_BADVAL:
33        error = "Undefined variable referenced";
34        break; 
35    case WRDE_CMDSUB:
36        error = "Command substitution not allowed";
37        break;
38    case WRDE_NOSPACE:
39        error = "Out of memory";
40        break;
41    case WRDE_SYNTAX:
42        error = "Syntax error";
43        break;
44    default:
45        error = "Unknown error";
46    }
47
48    if (error) {
49        GB_export_errorf("Encountered error \"%s\" while expanding \"%s\"",
50                        error, str);
51        return strdup(str);
52    }
53
54    if (result.we_wordc == 0) {
55        return strdup("");
56    }
57   
58    GBS_strstruct *out = GBS_stropen(strlen(str)+100);
59    GBS_strcat(out, result.we_wordv[0]);
60    for (unsigned int i = 1; i < result.we_wordc; i++) {
61        GBS_chrcat(out, ' ');
62        GBS_strcat(out, result.we_wordv[i]);
63    }
64
65    wordfree(&result);
66    return GBS_strclose(out);
67}
68
69////////// UNIT TESTS ///////////
70
71#ifdef UNIT_TESTS
72
73#ifndef TEST_UNIT_H
74#include <test_unit.h>
75#endif
76
77void TEST_arb_shell_expand() {
78    char *res;
79
80    res = arb_shell_expand("");
81    TEST_REJECT(GB_have_error());
82    TEST_EXPECT_EQUAL(res, "");
83    free(res);
84
85    res = arb_shell_expand("test");
86    TEST_REJECT(GB_have_error());
87    TEST_EXPECT_EQUAL(res, "test");
88    free(res);
89
90    res = arb_shell_expand("$ARBHOME");
91    TEST_REJECT(GB_have_error());
92    TEST_EXPECT_EQUAL(res, getenv("ARBHOME"));
93    free(res);
94
95    res = arb_shell_expand("$ARBHOME&");
96    TEST_EXPECT(GB_have_error());
97    GB_await_error();
98    TEST_EXPECT_EQUAL(res, "$ARBHOME&");
99    free(res);
100   
101}
102
103
104
105#endif
Note: See TracBrowser for help on using the repository browser.