aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/mk/shprint.c
blob: 9e15bcefb493b7d258493011878064b66200515e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include	"mk.h"

static char *vexpand(char*, Envy*, Bufblock*);

static int
getfields(char *str, char **args, int max, int mflag, char *set)
{
	Rune r;
	int nr, intok, narg;

	if(max <= 0)
		return 0;

	narg = 0;
	args[narg] = str;
	if(!mflag)
		narg++;
	intok = 0;
	for(;; str += nr) {
		nr = chartorune(&r, str);
		if(r == 0)
			break;
		if(utfrune(set, r)) {
			if(narg >= max)
				break;
			*str = 0;
			intok = 0;
			args[narg] = str + nr;
			if(!mflag)
				narg++;
		} else {
			if(!intok && mflag)
				narg++;
			intok = 1;
		}
	}
	return narg;
}

void
shprint(char *s, Envy *env, Bufblock *buf)
{
	int n;
	Rune r;

	while(*s) {
		n = chartorune(&r, s);
		if (r == '$')
			s = vexpand(s, env, buf);
		else {
			rinsert(buf, r);
			s += n;
			s = copyq(s, r, buf);	/*handle quoted strings*/
		}
	}
	insert(buf, 0);
}

static char *
mygetenv(char *name, Envy *env)
{
	if (!env)
		return 0;
	if (symlook(name, S_WESET, 0) == 0 && symlook(name, S_INTERNAL, 0) == 0)
		return 0;
		/* only resolve internal variables and variables we've set */
	for(; env->name; env++){
		if (strcmp(env->name, name) == 0)
			return wtos(env->values, ' ');
	}
	return 0;
}

static char *
vexpand(char *w, Envy *env, Bufblock *buf)
{
	char *s, carry, *p, *q;

	assert("vexpand no $", *w == '$');
	p = w+1;	/* skip dollar sign */
	if(*p == '{') {
		p++;
		q = utfrune(p, '}');
		if (!q)
			q = strchr(p, 0);
	} else
		q = shname(p);
	carry = *q;
	*q = 0;
	s = mygetenv(p, env);
	*q = carry;
	if (carry == '}')
		q++;
	if (s) {
		bufcpy(buf, s, strlen(s));
		free(s);
	} else 		/* copy name intact*/
		bufcpy(buf, w, q-w);
	return(q);
}

void
front(char *s)
{
	char *t, *q;
	int i, j;
	char *flds[512];

	q = strdup(s);
	i = getfields(q, flds, 512, 0, " \t\n");
	if(i > 5){
		flds[4] = flds[i-1];
		flds[3] = "...";
		i = 5;
	}
	t = s;
	for(j = 0; j < i; j++){
		for(s = flds[j]; *s; *t++ = *s++);
		*t++ = ' ';
	}
	*t = 0;
	free(q);
}