parent
27eafc7b9c
commit
d1d8771348
@ -0,0 +1,25 @@
|
||||
CC := gcc
|
||||
CFLAGS := -Wall -Wextra
|
||||
CPPFLAGS := -isystemthird-party
|
||||
|
||||
all: test
|
||||
|
||||
test: testEscape
|
||||
./testEscape
|
||||
|
||||
testEscape: build/escape.o build/testEscape.o ../static-string-builder/build/builder.o
|
||||
$(CC) -o $@ $^
|
||||
|
||||
build/escape.o: src/escape.c src/escape.h | build
|
||||
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
|
||||
|
||||
build/testEscape.o: test/testEscape.c src/escape.h | build
|
||||
$(CC) $(CPPFLAGS) $(CFLAGS) -Isrc/ -c $< -o $@
|
||||
|
||||
build:
|
||||
mkdir build
|
||||
|
||||
clean:
|
||||
rm -rf testEscape build
|
||||
|
||||
.PHONY: all test clean
|
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "shell-escape"
|
||||
version = "0.1.0"
|
||||
description = "Escape shell characters"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
static-string-builder = "^0.1"
|
@ -0,0 +1,45 @@
|
||||
#include "escape.h"
|
||||
|
||||
#include <static-string-builder/builder.h>
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
|
||||
bool isShellSafe(char ch) {
|
||||
return strchr("@%+=:,./-_", ch) != NULL || isalnum(ch);
|
||||
}
|
||||
|
||||
bool isSafeShellStr(const char *str) {
|
||||
for (; *str; str++) {
|
||||
if (!isShellSafe(*str)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const char *shellEscape(const char *str) {
|
||||
if (isSafeShellStr(str)) {
|
||||
return str;
|
||||
}
|
||||
|
||||
char *result = tmp_end();
|
||||
|
||||
tmp_append_char('\'');
|
||||
while (str) {
|
||||
char *end = strchr(str, '\'');
|
||||
if (end) {
|
||||
tmp_append_sized(str, end - str);
|
||||
tmp_append_cstr("'\"'\"'");
|
||||
str = end + 1;
|
||||
} else {
|
||||
tmp_append_cstr(str);
|
||||
str = NULL;
|
||||
}
|
||||
}
|
||||
tmp_append_char('\'');
|
||||
tmp_append_char('\0');
|
||||
|
||||
return result;
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
#ifndef SHELL_ESCAPE_H
|
||||
#define SHELL_ESCAPE_H
|
||||
|
||||
const char *shellEscape(const char *str);
|
||||
|
||||
#endif // SHELL_ESCAPE_H
|
@ -0,0 +1,15 @@
|
||||
#include "escape.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(void) {
|
||||
assert(strcmp("aa", shellEscape("aa")) == 0);
|
||||
assert(strcmp("'aa bb'", shellEscape("aa bb")) == 0);
|
||||
assert(strcmp("'a(b)'", shellEscape("a(b)")) == 0);
|
||||
assert(strcmp("'aa && bb'", shellEscape("aa && bb")) == 0);
|
||||
assert(strcmp("'echo aa '\"'\"'s'\"'\"''", shellEscape("echo aa 's'")) == 0);
|
||||
return 0;
|
||||
}
|
||||
|
@ -0,0 +1 @@
|
||||
../../static-string-builder/src/
|
Loading…
Reference in new issue