Improve sanitize maching name fn (#303)

This commit is contained in:
Marko Gaćeša 2023-02-03 18:56:20 +01:00 committed by GitHub
parent eaaa825e67
commit 89c135f94b

View File

@ -8,7 +8,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"unicode"
"github.com/harness/gitness/events"
"github.com/harness/gitness/gitrpc"
@ -17,6 +17,9 @@ import (
"github.com/harness/gitness/types"
"github.com/kelseyhightower/envconfig"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
// LoadConfig returns the system configuration from the
@ -48,9 +51,21 @@ func getSanitizedMachineName() (string, error) {
// NOTE: this could theoretically lead to overlaps, then it should be passed explicitly
// NOTE: for k8s names/ids below modifications are all noops
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/
hostName = strings.ToLower(hostName)
hostName = strings.Map(func(r rune) rune {
// The following code will:
// * remove invalid runes
// * remove diacritical marks (ie "smörgåsbord" to "smorgasbord")
// * lowercase A-Z to a-z
// * leave only a-z, 0-9, '-', '.' and replace everything else with '_'
hostName, _, err = transform.String(
transform.Chain(
norm.NFD,
runes.ReplaceIllFormed(),
runes.Remove(runes.In(unicode.Mn)),
runes.Map(func(r rune) rune {
switch {
case 'A' <= r && r <= 'Z':
return r + 32
case 'a' <= r && r <= 'z':
return r
case '0' <= r && r <= '9':
@ -60,7 +75,12 @@ func getSanitizedMachineName() (string, error) {
default:
return '_'
}
}, hostName)
}),
norm.NFC),
hostName)
if err != nil {
return "", err
}
return hostName, nil
}