~sircmpwn/hare

ref: 732383144a66c247b6c732b1ce7f46342d340019 hare/shlex/escape.ha -rw-r--r-- 1.3 KiB
73238314Alexey Yerin cmd/harec: display error even if it includes invalid UTF-8 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
68
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) (void | io::error) = {
	if (len(s) == 0) {
		io::write(sink, strings::toutf8(`''`))?;
		return;
	};
	if (is_safe(s)) {
		io::write(sink, strings::toutf8(s))?;
		return;
	};

	io::write(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 == '"') {
			io::write(sink, strings::toutf8(`"'"'"`))?;
		} else {
			io::write(sink, utf8::encoderune(rn))?;
		};
	};

	io::write(sink, ['"'])?;
};

// 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);
};