move ssh regexp test to common location

- include testing
- improve hostname checking

Signed-off-by: Alex Couture-Beil <alex@earthly.dev>
v0.8
Alex Couture-Beil 2020-12-10 14:36:58 -08:00 committed by Tõnis Tiigi
parent 23af9dcb86
commit 3fa063dcf3
4 changed files with 28 additions and 8 deletions

View File

@ -5,7 +5,6 @@ import (
_ "crypto/sha256" // for opencontainers/go-digest
"encoding/json"
"os"
"regexp"
"strconv"
"strings"
@ -207,8 +206,6 @@ const (
gitProtocolUnknown
)
var gitSSHRegex = regexp.MustCompile("^[a-z0-9]+@[^:]+:.*$")
func getGitProtocol(remote string) (string, int) {
prefixes := map[string]int{
"http://": gitProtocolHTTP,
@ -224,7 +221,7 @@ func getGitProtocol(remote string) (string, int) {
}
}
if protocolType == gitProtocolUnknown && gitSSHRegex.MatchString(remote) {
if protocolType == gitProtocolUnknown && sshutil.IsSSHTransport(remote) {
protocolType = gitProtocolSSH
}

View File

@ -2,9 +2,9 @@ package source
import (
"net/url"
"regexp"
"strings"
"github.com/moby/buildkit/util/sshutil"
"github.com/pkg/errors"
)
@ -19,8 +19,6 @@ type GitIdentifier struct {
KnownSSHHosts string
}
var gitSSHRegex = regexp.MustCompile("^[a-z0-9]+@[^:]+:.*$")
func NewGitIdentifier(remoteURL string) (*GitIdentifier, error) {
repo := GitIdentifier{}
@ -61,7 +59,7 @@ func (i *GitIdentifier) ID() string {
// isGitTransport returns true if the provided str is a git transport by inspecting
// the prefix of the string for known protocols used in git.
func isGitTransport(str string) bool {
return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://") || strings.HasPrefix(str, "git://") || gitSSHRegex.MatchString(str)
return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://") || strings.HasPrefix(str, "git://") || sshutil.IsSSHTransport(str)
}
func getRefAndSubdir(fragment string) (ref string, subdir string) {

View File

@ -0,0 +1,11 @@
package sshutil
import (
"regexp"
)
var gitSSHRegex = regexp.MustCompile("^[a-z0-9]+@[a-zA-Z0-9-.]+:.*$")
func IsSSHTransport(s string) bool {
return gitSSHRegex.MatchString(s)
}

View File

@ -0,0 +1,14 @@
package sshutil
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestIsSSHTransport(t *testing.T) {
require.False(t, IsSSHTransport("http://github.com/moby/buildkit"))
require.False(t, IsSSHTransport("github.com/moby/buildkit"))
require.True(t, IsSSHTransport("git@github.com:moby/buildkit.git"))
require.True(t, IsSSHTransport("nonstandarduser@example.com:/srv/repos/weird/project.git"))
}