7 #include <tool/libarray.h>
9 static char* helptext
=
10 "Usage: loadenv [-0c] <FILE> <COMMAND> [<ARG> [...]]\n"
22 remove_duplicate(array_index_t index
, char* item
, struct dedupdata
* dedupdata
)
24 if(strchr(item
, '=')-item
== dedupdata
->envnamelen
&& strncmp(item
, dedupdata
->env
, dedupdata
->envnamelen
) == 0)
26 array_delete(dedupdata
->envarray
, index
, 1);
27 return ARRAY_LOOP_STOP
;
29 return ARRAY_LOOP_CONTINUE
;
34 pprint(array_index_t index
, char * item
, void * x
)
36 warnx("index %d item %s", index
, item
);
37 return ARRAY_LOOP_CONTINUE
;
41 int main(int argc
, char** argv
, char** current_env
)
46 unsigned char delimiter
;
52 struct dedupdata dedupdata
;
53 unsigned char copy_current_environment
;
57 copy_current_environment
= 0;
62 if(strcmp(argv
[argidx
], "-0")==0)
66 else if(strcmp(argv
[argidx
], "-c")==0)
68 copy_current_environment
= 1;
70 else if(strcmp(argv
[argidx
], "--help")==0)
72 printf("%s", helptext
);
75 else if(argv
[argidx
][0] == '-')
77 errx(-2, "unknown option: %s", argv
[argidx
]);
87 if(envfile
= fopen(argv
[argidx
], "r"))
89 array_init(&envarray
, 2);
91 /* copy current environment */
92 if(copy_current_environment
)
94 for(it
= 0; current_env
[it
] != NULL
; it
++)
96 array_append(&envarray
, current_env
[it
]);
100 /* read up environments from file */
105 read_status
= getdelim(&env
, &envsize
, delimiter
, envfile
);
106 if(read_status
== -1) break;
107 if(!env
) goto read_next_env
;
110 envsize
= strlen(env
);
111 if(envsize
== 0) goto read_next_env
;
112 if(env
[envsize
-1] == delimiter
) env
[envsize
-1] = '\0';
113 envsize
= strlen(env
);
116 if(envsize
== 0) goto read_next_env
;
119 if(delimiter
== '\n' && env
[0] == '#') goto read_next_env
;
122 envval
= strchr(env
, '=');
126 // remove the named environment variable if it's a name only without '=' equal sign in it.
127 dedupdata
.envnamelen
= envsize
;
129 dedupdata
.envarray
= &envarray
;
130 array_foreach(&envarray
, 0, (array_loop_control(*)(array_index_t
, char*, void*))remove_duplicate
, &dedupdata
);
134 envval
++; // envval point past to the '=' equal sign
137 array_foreach(&envarray
, 0, pprint
, NULL
);
141 dedupdata
.envnamelen
= envval
- env
- 1;
143 dedupdata
.envarray
= &envarray
;
144 array_foreach(&envarray
, 0, (array_loop_control(*)(array_index_t
, char*, void*))remove_duplicate
, &dedupdata
);
146 // add to the env list
147 array_append(&envarray
, env
);
154 array_append(&envarray
, NULL
);
163 array_foreach(&envarray
, 0, pprint
, NULL
);
166 execvpe(argv
[argidx
+1], &argv
[argidx
+1], array_getarray(&envarray
));
171 fprintf(stderr
, "%s", helptext
);
176 return errno
== 0 ? -1 : errno
;