1 /* ISC license. */
2
3 #include <string.h>
4 #include <skalibs/sgetopt.h>
5 #include <skalibs/strerr2.h>
6 #include <skalibs/stralloc.h>
7 #include <skalibs/genalloc.h>
8 #include <skalibs/env.h>
9 #include <execline/execline.h>
10 #include "exlsn.h"
11
exlsn_importas(int argc,char const ** argv,char const * const * envp,exlsn_t * info)12 int exlsn_importas (int argc, char const **argv, char const *const *envp, exlsn_t *info)
13 {
14 eltransforminfo_t si = ELTRANSFORMINFO_ZERO ;
15 subgetopt_t localopt = SUBGETOPT_ZERO ;
16 elsubst_t blah ;
17 char const *defaultval = 0 ;
18 char const *x ;
19 int insist = 0 ;
20 int unexport = 0 ;
21 blah.var = info->vars.len ;
22 blah.value = info->values.len ;
23
24 for (;;)
25 {
26 int opt = subgetopt_r(argc, argv, "iuD:NnsCcd:", &localopt) ;
27 if (opt < 0) break ;
28 switch (opt)
29 {
30 case 'i' : insist = 1 ; break ;
31 case 'u' : unexport = 1 ; break ;
32 case 'D' : defaultval = localopt.arg ; break ;
33 case 'N' : si.chomp = 0 ; break ;
34 case 'n' : si.chomp = 1 ; break ;
35 case 's' : si.split = 1 ; break ;
36 case 'C' : si.crunch = 1 ; break ;
37 case 'c' : si.crunch = 0 ; break ;
38 case 'd' : si.delim = localopt.arg ; break ;
39 default : return -3 ;
40 }
41 }
42 argc -= localopt.ind ; argv += localopt.ind ;
43
44 if ((unsigned int)argc < 2) return -3 ;
45 if (!*argv[0] || el_vardupl(argv[0], info->vars.s, info->vars.len)) return -2 ;
46 if (!stralloc_catb(&info->vars, argv[0], strlen(argv[0]) + 1)) return -1 ;
47 x = env_get2(envp, argv[1]) ;
48 if (!x)
49 {
50 if (insist) strerr_dienotset(100, argv[1]) ;
51 x = defaultval ;
52 }
53 else if (unexport)
54 {
55 if (!stralloc_catb(&info->modifs, argv[1], strlen(argv[1]) + 1)) goto err ;
56 }
57 if (!x) blah.n = 0 ;
58 else
59 {
60 int r ;
61 if (!stralloc_cats(&info->values, x)) goto err ;
62 r = el_transform(&info->values, blah.value, &si) ;
63 if (r < 0) goto err ;
64 blah.n = r ;
65 }
66 if (!genalloc_append(elsubst_t, &info->data, &blah)) goto err ;
67 return localopt.ind + 2 ;
68
69 err:
70 info->vars.len = blah.var ;
71 info->values.len = blah.value ;
72 return -1 ;
73 }
74