ARB
arb_pattern.cxx
Go to the documentation of this file.
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 
22 char* arb_shell_expand(const char* str) {
23  char *expanded = NULp;
24  wordexp_t result;
26 
27  switch (wordexp(str, &result, 0)) {
28  case 0:
29  break;
30  case WRDE_BADCHAR:
31  error = "Illegal character";
32  break;
33  case WRDE_BADVAL:
34  error = "Undefined variable referenced";
35  break;
36  case WRDE_CMDSUB:
37  error = "Command substitution not allowed";
38  break;
39  case WRDE_NOSPACE:
40  error = "Out of memory";
41  break;
42  case WRDE_SYNTAX:
43  error = "Syntax error";
44  break;
45  default:
46  error = "Unknown error";
47  }
48 
49  if (error) {
50  GB_export_errorf("Encountered error \"%s\" while expanding \"%s\"",
51  error, str);
52  expanded = ARB_strdup(str);
53  }
54  else {
55  if (result.we_wordc == 0) {
56  expanded = ARB_strdup("");
57  }
58  else {
59  GBS_strstruct out(strlen(str)+100);
60  out.cat(result.we_wordv[0]);
61  for (unsigned int i = 1; i < result.we_wordc; i++) {
62  out.put(' ');
63  out.cat(result.we_wordv[i]);
64  }
65 
66  expanded = out.release();
67  }
68  wordfree(&result);
69  }
70  return expanded;
71 }
72 
74 
75 #ifdef UNIT_TESTS
76 
77 #ifndef TEST_UNIT_H
78 #include <test_unit.h>
79 #endif
80 
81 void TEST_arb_shell_expand() {
82  char *res;
83 
84  res = arb_shell_expand("");
86  TEST_EXPECT_EQUAL(res, "");
87  free(res);
88 
89  res = arb_shell_expand("test");
91  TEST_EXPECT_EQUAL(res, "test");
92  free(res);
93 
94  res = arb_shell_expand("$ARBHOME");
96  TEST_EXPECT_EQUAL(res, getenv("ARBHOME"));
97  free(res);
98 
99  res = arb_shell_expand("$ARBHOME&");
100  TEST_EXPECT_CONTAINS(GB_incur_error(), "Illegal character");
101  TEST_EXPECT_EQUAL(res, "$ARBHOME&");
102  free(res);
103 
104 }
105 TEST_PUBLISH(TEST_arb_shell_expand);
106 
107 #endif
const char * GB_ERROR
Definition: arb_core.h:25
string result
GB_ERROR GB_incur_error()
Definition: arb_msg.h:49
char * ARB_strdup(const char *str)
Definition: arb_string.h:27
bool GB_have_error()
Definition: arb_msg.cxx:338
char * release()
Definition: arb_strbuf.h:129
void cat(const char *from)
Definition: arb_strbuf.h:199
#define TEST_PUBLISH(testfunction)
Definition: test_unit.h:1517
#define TEST_EXPECT_CONTAINS(str, part)
Definition: test_unit.h:1316
char * arb_shell_expand(const char *str)
Definition: arb_pattern.cxx:22
#define TEST_REJECT(cond)
Definition: test_unit.h:1330
static void error(const char *msg)
Definition: mkptypes.cxx:96
GB_ERROR GB_export_errorf(const char *templat,...)
Definition: arb_msg.cxx:262
#define NULp
Definition: cxxforward.h:116
#define TEST_EXPECT_EQUAL(expr, want)
Definition: test_unit.h:1294
void put(char c)
Definition: arb_strbuf.h:174