1// Copyright 2020 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
3
4package util
5
6import "testing"
7
8func TestShellEscape(t *testing.T) {
9 tests := []struct {
10 name string
11 toEscape string
12 want string
13 }{
14 {
15 "Simplest case - nothing to escape",
16 "a/b/c/d",
17 "a/b/c/d",
18 }, {
19 "Prefixed tilde - with normal stuff - should not escape",
20 "~/src/go/gitea/gitea",
21 "~/src/go/gitea/gitea",
22 }, {
23 "Typical windows path with spaces - should get doublequote escaped",
24 `C:\Program Files\Gitea v1.13 - I like lots of spaces\gitea`,
25 `"C:\\Program Files\\Gitea v1.13 - I like lots of spaces\\gitea"`,
26 }, {
27 "Forward-slashed windows path with spaces - should get doublequote escaped",
28 "C:/Program Files/Gitea v1.13 - I like lots of spaces/gitea",
29 `"C:/Program Files/Gitea v1.13 - I like lots of spaces/gitea"`,
30 }, {
31 "Prefixed tilde - but then a space filled path",
32 "~git/Gitea v1.13/gitea",
33 `~git/"Gitea v1.13/gitea"`,
34 }, {
35 "Bangs are unfortunately not predictable so need to be singlequoted",
36 "C:/Program Files/Gitea!/gitea",
37 `'C:/Program Files/Gitea!/gitea'`,
38 }, {
39 "Newlines are just irritating",
40 "/home/git/Gitea\n\nWHY-WOULD-YOU-DO-THIS\n\nGitea/gitea",
41 "'/home/git/Gitea\n\nWHY-WOULD-YOU-DO-THIS\n\nGitea/gitea'",
42 }, {
43 "Similarly we should nicely handle multiple single quotes if we have to single-quote",
44 "'!''!'''!''!'!'",
45 `\''!'\'\''!'\'\'\''!'\'\''!'\''!'\'`,
46 }, {
47 "Double quote < ...",
48 "~/<gitea",
49 "~/\"<gitea\"",
50 }, {
51 "Double quote > ...",
52 "~/gitea>",
53 "~/\"gitea>\"",
54 }, {
55 "Double quote and escape $ ...",
56 "~/$gitea",
57 "~/\"\\$gitea\"",
58 }, {
59 "Double quote {...",
60 "~/{gitea",
61 "~/\"{gitea\"",
62 }, {
63 "Double quote }...",
64 "~/gitea}",
65 "~/\"gitea}\"",
66 }, {
67 "Double quote ()...",
68 "~/(gitea)",
69 "~/\"(gitea)\"",
70 }, {
71 "Double quote and escape `...",
72 "~/gitea`",
73 "~/\"gitea\\`\"",
74 }, {
75 "Double quotes can handle a number of things without having to escape them but not everything ...",
76 "~/<gitea> ${gitea} `gitea` [gitea] (gitea) \"gitea\" \\gitea\\ 'gitea'",
77 "~/\"<gitea> \\${gitea} \\`gitea\\` [gitea] (gitea) \\\"gitea\\\" \\\\gitea\\\\ 'gitea'\"",
78 }, {
79 "Single quotes don't need to escape except for '...",
80 "~/<gitea> ${gitea} `gitea` (gitea) !gitea! \"gitea\" \\gitea\\ 'gitea'",
81 "~/'<gitea> ${gitea} `gitea` (gitea) !gitea! \"gitea\" \\gitea\\ '\\''gitea'\\'",
82 },
83 }
84 for _, tt := range tests {
85 t.Run(tt.name, func(t *testing.T) {
86 if got := ShellEscape(tt.toEscape); got != tt.want {
87 t.Errorf("ShellEscape(%q):\nGot: %s\nWanted: %s", tt.toEscape, got, tt.want)
88 }
89 })
90 }
91}