1/* $OpenBSD$ */
2
3/*
4 * Copyright (c) 2009 Nicholas Marriott <[email protected]>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19#include <sys/types.h>
20
21#include <stdlib.h>
22#include <string.h>
23
24#include "tmux.h"
25
26/*
27 * Set an environment variable.
28 */
29
30static enum cmd_retval cmd_set_environment_exec(struct cmd *,
31 struct cmdq_item *);
32
33const struct cmd_entry cmd_set_environment_entry = {
34 .name = "set-environment",
35 .alias = "setenv",
36
37 .args = { "grt:u", 1, 2 },
38 .usage = "[-gru] " CMD_TARGET_SESSION_USAGE " name [value]",
39
40 .target = { 't', CMD_FIND_SESSION, CMD_FIND_CANFAIL },
41
42 .flags = CMD_AFTERHOOK,
43 .exec = cmd_set_environment_exec
44};
45
46static enum cmd_retval
47cmd_set_environment_exec(struct cmd *self, struct cmdq_item *item)
48{
49 struct args *args = self->args;
50 struct environ *env;
51 const char *name, *value, *target;
52
53 name = args->argv[0];
54 if (*name == '\0') {
55 cmdq_error(item, "empty variable name");
56 return (CMD_RETURN_ERROR);
57 }
58 if (strchr(name, '=') != NULL) {
59 cmdq_error(item, "variable name contains =");
60 return (CMD_RETURN_ERROR);
61 }
62
63 if (args->argc < 2)
64 value = NULL;
65 else
66 value = args->argv[1];
67
68 if (args_has(self->args, 'g'))
69 env = global_environ;
70 else {
71 if (item->target.s == NULL) {
72 target = args_get(args, 't');
73 if (target != NULL)
74 cmdq_error(item, "no such session: %s", target);
75 else
76 cmdq_error(item, "no current session");
77 return (CMD_RETURN_ERROR);
78 }
79 env = item->target.s->environ;
80 }
81
82 if (args_has(self->args, 'u')) {
83 if (value != NULL) {
84 cmdq_error(item, "can't specify a value with -u");
85 return (CMD_RETURN_ERROR);
86 }
87 environ_unset(env, name);
88 } else if (args_has(self->args, 'r')) {
89 if (value != NULL) {
90 cmdq_error(item, "can't specify a value with -r");
91 return (CMD_RETURN_ERROR);
92 }
93 environ_clear(env, name);
94 } else {
95 if (value == NULL) {
96 cmdq_error(item, "no value specified");
97 return (CMD_RETURN_ERROR);
98 }
99 environ_set(env, name, "%s", value);
100 }
101
102 return (CMD_RETURN_NORMAL);
103}
104