2024-01-11 17:59:26 +00:00
|
|
|
// Copyright (C) 2024 Umorpha Systems
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
|
2024-01-11 20:36:03 +00:00
|
|
|
package gitcache
|
2024-01-11 17:59:26 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2024-01-28 05:56:36 +00:00
|
|
|
func NormalizeURL(url string) string {
|
2024-01-11 17:59:26 +00:00
|
|
|
// > Clients MUST strip a trailing `/`, if present, from the
|
|
|
|
// > user supplied `$GIT_URL` string
|
|
|
|
// -- gitprotocol-http(5)
|
|
|
|
url = strings.TrimRight(url, "/")
|
2024-01-28 05:56:36 +00:00
|
|
|
return url
|
|
|
|
}
|
|
|
|
|
|
|
|
func ValidateURL(url string) bool {
|
|
|
|
return NormalizeURL(url) != ""
|
|
|
|
}
|
|
|
|
|
|
|
|
func URL2NS(url string) string {
|
|
|
|
url = NormalizeURL(url)
|
2024-01-11 17:59:26 +00:00
|
|
|
|
|
|
|
var id strings.Builder
|
|
|
|
id.Grow(len(url))
|
2024-01-28 05:31:51 +00:00
|
|
|
for i := 0; i < len(url); i++ {
|
|
|
|
b := url[i]
|
2024-01-11 17:59:26 +00:00
|
|
|
switch {
|
2024-01-28 05:31:51 +00:00
|
|
|
case b == '!', // our own escape
|
2024-01-11 17:59:26 +00:00
|
|
|
// see: git-check-ref-format(1)
|
2024-01-28 05:31:51 +00:00
|
|
|
b <= ' ', b == '\x7F', // never: ASCII control characters
|
|
|
|
b == '~', b == '^', b == ':', // never: gitrevision meaning
|
|
|
|
b == '?', b == '*', b == '[', // never: refspec pattern
|
|
|
|
b == '\\', // never: backslash
|
|
|
|
b == '.', b == '@', b == '/': // sometimes: special rules
|
|
|
|
fmt.Fprintf(&id, "!%02x", b)
|
2024-01-11 17:59:26 +00:00
|
|
|
default:
|
2024-01-28 05:31:51 +00:00
|
|
|
id.WriteByte(b)
|
2024-01-11 17:59:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return id.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
var reEsc = regexp.MustCompile("![0-9a-f]{2}")
|
|
|
|
|
|
|
|
func hex2int(h byte) byte {
|
|
|
|
switch {
|
|
|
|
case '0' <= h && h <= '9':
|
|
|
|
return h - '0'
|
|
|
|
case 'a' <= h && h <= 'f':
|
2024-01-28 05:31:51 +00:00
|
|
|
return h - 'a' + 0xa
|
2024-01-11 17:59:26 +00:00
|
|
|
default:
|
|
|
|
panic("should not happen")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-20 18:07:48 +00:00
|
|
|
func NS2URL(id string) string {
|
2024-01-11 17:59:26 +00:00
|
|
|
return reEsc.ReplaceAllStringFunc(id, func(esc string) string {
|
2024-01-28 05:31:51 +00:00
|
|
|
b := hex2int(esc[1])<<4 | hex2int(esc[2])
|
|
|
|
return string([]byte{b})
|
2024-01-11 17:59:26 +00:00
|
|
|
})
|
|
|
|
}
|