~sircmpwn/hare

ref: c80c71f920b0e94370338341fef35b7f6fd4f07c hare/shlex/escape.ha -rw-r--r-- 1.3 KiB
c80c71f9Sebastian shlex: return number of bytes written for quote 4 months ago
                                                                                
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
use ascii;
use encoding::utf8;
use io;
use strings;
use strio;

fn is_safe(s: str) bool = {
	const iter = strings::iter(s);
	for (true) {
		const rn = match (strings::next(&iter)) {
		case let rn: rune =>
			yield rn;
		case void =>
			break;
		};


		switch (rn) {
		case '@', '%', '+', '=', ':', ',', '.', '/', '-' =>
			void;
		case =>
			if (!ascii::isalnum(rn) || ascii::isspace(rn)) {
				return false;
			};
		};
	};
	return true;
};

// Quotes a shell string and writes it to the provided I/O handle.
export fn quote(sink: io::handle, s: str) (size | io::error) = {
	if (len(s) == 0) {
		return io::writeall(sink, strings::toutf8(`''`))?;
	};
	if (is_safe(s)) {
		return io::writeall(sink, strings::toutf8(s))?;
	};

	let z = io::writeall(sink, ['"'])?;

	const iter = strings::iter(s);
	for (true) {
		const rn = match (strings::next(&iter)) {
		case let rn: rune =>
			yield rn;
		case void =>
			break;
		};

		if (rn == '"') {
			z += io::writeall(sink, strings::toutf8(`"'"'"`))?;
		} else {
			z += io::writeall(sink, utf8::encoderune(rn))?;
		};
	};

	z += io::writeall(sink, ['"'])?;
	return z;
};

// Quotes a shell string and returns a new string. The caller must free the
// return value.
export fn quotestr(s: str) str = {
	const sink = strio::dynamic();
	quote(&sink, s)!;
	return strio::string(&sink);
};