| 1 |
package git |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"strings" |
| 6 |
) |
| 7 |
|
| 8 |
// preReceiveHook returns the bytes of a pre-receive hook script |
| 9 |
// that prints m before exiting successfully |
| 10 |
func preReceiveHook(m string) []byte { |
| 11 |
return []byte(fmt.Sprintf("#!/bin/rc\necho -n %s\n", quote(m))) |
| 12 |
} |
| 13 |
|
| 14 |
const quoteChar = '\'' |
| 15 |
|
| 16 |
func needsQuote(s string) bool { |
| 17 |
for i := 0; i < len(s); i++ { |
| 18 |
c := s[i] |
| 19 |
if c == quoteChar || c <= ' ' { // quote, blanks, or control characters |
| 20 |
return true |
| 21 |
} |
| 22 |
} |
| 23 |
return false |
| 24 |
} |
| 25 |
|
| 26 |
// Quote adds single quotes to s in the style of rc(1) if they are needed. |
| 27 |
// The behaviour should be identical to Plan 9's quote(3). |
| 28 |
func quote(s string) string { |
| 29 |
if s == "" { |
| 30 |
return "''" |
| 31 |
} |
| 32 |
if !needsQuote(s) { |
| 33 |
return s |
| 34 |
} |
| 35 |
var b strings.Builder |
| 36 |
b.Grow(10 + len(s)) // Enough room for few quotes |
| 37 |
b.WriteByte(quoteChar) |
| 38 |
for i := 0; i < len(s); i++ { |
| 39 |
c := s[i] |
| 40 |
if c == quoteChar { |
| 41 |
b.WriteByte(quoteChar) |
| 42 |
} |
| 43 |
b.WriteByte(c) |
| 44 |
} |
| 45 |
b.WriteByte(quoteChar) |
| 46 |
return b.String() |
| 47 |
} |