xref: /inferno-os/utils/mk/shprint.c (revision 7ef44d652ae9e5e1f5b3465d73684e4a54de73c0)
1 #include	"mk.h"
2 
3 static char *vexpand(char*, Envy*, Bufblock*);
4 
5 void
6 shprint(char *s, Envy *env, Bufblock *buf)
7 {
8 	int n;
9 	Rune r;
10 
11 	while(*s) {
12 		n = chartorune(&r, s);
13 		if (r == '$')
14 			s = vexpand(s, env, buf);
15 		else {
16 			rinsert(buf, r);
17 			s += n;
18 			s = copyq(s, r, buf);	/*handle quoted strings*/
19 		}
20 	}
21 	insert(buf, 0);
22 }
23 
24 static char *
25 mygetenv(char *name, Envy *env)
26 {
27 	if (!env)
28 		return 0;
29 	if (symlook(name, S_WESET, 0) == 0 && symlook(name, S_INTERNAL, 0) == 0)
30 		return 0;
31 		/* only resolve internal variables and variables we've set */
32 	for(; env->name; env++){
33 		if (strcmp(env->name, name) == 0)
34 			return wtos(env->values, ' ');
35 	}
36 	return 0;
37 }
38 
39 static char *
40 vexpand(char *w, Envy *env, Bufblock *buf)
41 {
42 	char *s, carry, *p, *q;
43 
44 	assert("vexpand no $", *w == '$');
45 	p = w+1;	/* skip dollar sign */
46 	if(*p == '{') {
47 		p++;
48 		q = utfrune(p, '}');
49 		if (!q)
50 			q = strchr(p, 0);
51 	} else
52 		q = shname(p);
53 	carry = *q;
54 	*q = 0;
55 	s = mygetenv(p, env);
56 	*q = carry;
57 	if (carry == '}')
58 		q++;
59 	if (s) {
60 		bufcpy(buf, s, strlen(s));
61 		free(s);
62 	} else 		/* copy name intact*/
63 		bufcpy(buf, w, q-w);
64 	return(q);
65 }
66 
67 void
68 front(char *s)
69 {
70 	char *t, *q;
71 	int i, j;
72 	char *flds[512];
73 
74 	q = strdup(s);
75 	i = getfields(q, flds, 512, 0, " \t\n");
76 	if(i > 5){
77 		flds[4] = flds[i-1];
78 		flds[3] = "...";
79 		i = 5;
80 	}
81 	t = s;
82 	for(j = 0; j < i; j++){
83 		for(s = flds[j]; *s; *t++ = *s++);
84 		*t++ = ' ';
85 	}
86 	*t = 0;
87 	free(q);
88 }
89