source: tags/ms_r17q2/CORE/arb_pattern.cxx

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