Skip to content

Commit

Permalink
Tunnel refactoring (#74)
Browse files Browse the repository at this point in the history
* Refactor tunnel handling

* Move code around
  • Loading branch information
fabpot committed Jan 30, 2022
1 parent 642a999 commit 0c0d432
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 92 deletions.
7 changes: 5 additions & 2 deletions commands/local_var_expose.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"github.com/symfony-cli/console"
"github.com/symfony-cli/symfony-cli/envs"
"github.com/symfony-cli/symfony-cli/local/platformsh"
"github.com/symfony-cli/terminal"
)

Expand All @@ -45,9 +46,11 @@ var localVariableExposeFromTunnelCmd = &console.Command{
}
}

tunnel := envs.Tunnel{
Dir: dir,
project, err := platformsh.ProjectFromDir(dir, false)
if err != nil {
return err
}
tunnel := envs.Tunnel{Project: project}

if c.Bool("off") {
terminal.Eprintln("Stop exposing tunnel service environment variables ")
Expand Down
14 changes: 12 additions & 2 deletions envs/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,17 @@ func (l *Local) Relationships() Relationships {
// we need to call it in all cases so that l.DockerEnv is set correctly
dockerRel := l.RelationshipsFromDocker()

tunnel := Tunnel{Dir: l.Dir, Debug: l.Debug}
project, err := platformsh.ProjectFromDir(l.Dir, l.Debug)
if err != nil {
if l.Debug {
fmt.Fprint(os.Stderr, "ERROR: unable to get Platform.sh project information\n")
}
return dockerRel
}
tunnel := Tunnel{
Project: project,
Debug: l.Debug,
}
if !tunnel.IsExposed() {
return dockerRel
}
Expand Down Expand Up @@ -139,7 +149,7 @@ func (l *Local) Language() string {
if language != "" {
return language
}
projectRoot, err := util.GetProjectRoot(l.Debug)
projectRoot, err := platformsh.GetProjectRoot(l.Debug)
if err != nil {
if l.Debug {
fmt.Fprint(os.Stderr, "ERROR: unable to get project root\n")
Expand Down
10 changes: 7 additions & 3 deletions envs/local_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"path/filepath"

"github.com/mitchellh/go-homedir"
"github.com/symfony-cli/symfony-cli/local/platformsh"
. "gopkg.in/check.v1"
)

Expand All @@ -46,9 +47,12 @@ func (s *LocalSuite) TestTunnelFilePath(c *C) {
defer func() {
os.Rename("testdata/project/.git", "testdata/project/git")
}()
tunnel := Tunnel{Dir: l.Dir}
tunnelPath, _ := tunnel.computePath()
c.Assert(filepath.Base(tunnelPath), Equals, "ism4mega7wpx6-toto--security.json")
project, err := platformsh.ProjectFromDir(l.Dir, false)
if err != nil {
panic(err)
}
tunnel := Tunnel{Project: project}
c.Assert(filepath.Base(tunnel.path()), Equals, "ism4mega7wpx6-toto--security-expose.json")
}

func (s *LocalSuite) TestRelationships(c *C) {
Expand Down
85 changes: 20 additions & 65 deletions envs/local_tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import (
"strconv"

"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"github.com/symfony-cli/symfony-cli/local/platformsh"
"github.com/symfony-cli/symfony-cli/util"
)
Expand All @@ -46,18 +45,10 @@ type pshtunnel struct {
}

func (l *Local) relationshipsFromTunnel() Relationships {
projectRoot := util.RepositoryRootDir(l.Dir)
envID, err := util.PotentialCurrentEnvironmentID(projectRoot)
project, err := platformsh.ProjectFromDir(l.Dir, l.Debug)
if err != nil {
if l.Debug {
fmt.Fprintf(os.Stderr, "WARNING: unable to find the env: %s\n", err)
}
return nil
}
app := platformsh.GuessSelectedAppByDirectory(l.Dir, platformsh.FindLocalApplications(projectRoot))
if app == nil {
if l.Debug {
fmt.Fprintf(os.Stderr, "WARNING: unable to find the app: %s\n", err)
fmt.Fprintf(os.Stderr, "WARNING: unable to detect Platform.sh project: %s\n", err)
}
return nil
}
Expand Down Expand Up @@ -88,16 +79,9 @@ func (l *Local) relationshipsFromTunnel() Relationships {
tunnels = append(tunnels, config)
}
}
gitConfig := util.GetProjectConfig(projectRoot, l.Debug)
if gitConfig == nil {
if l.Debug {
fmt.Fprintf(os.Stderr, "WARNING: unable to read Git config: %s\n", err)
}
return nil
}
rels := make(Relationships)
for _, config := range tunnels {
if config.ProjectID == gitConfig.ID && config.EnvironmentID == envID && config.AppName == app.Name {
if config.ProjectID == project.ID && config.EnvironmentID == project.Env && config.AppName == project.App {
config.Service["port"] = strconv.Itoa(config.LocalPort)
config.Service["host"] = "127.0.0.1"
config.Service["ip"] = "127.0.0.1"
Expand All @@ -106,7 +90,7 @@ func (l *Local) relationshipsFromTunnel() Relationships {
}

if len(rels) > 0 {
l.Tunnel = envID
l.Tunnel = project.Env
l.TunnelEnv = true
return rels
}
Expand All @@ -117,83 +101,54 @@ func (l *Local) relationshipsFromTunnel() Relationships {
var pathCleaningRegex = regexp.MustCompile("[^a-zA-Z0-9-\\.]+")

type Tunnel struct {
Dir string
Worker string
Debug bool
path string
Project *platformsh.Project
Worker string
Debug bool
}

func (t *Tunnel) IsExposed() bool {
path, err := t.computePath()
if err != nil {
return false
}
if _, err := os.Stat(path + "-expose"); err != nil {
if _, err := os.Stat(t.path()); err != nil {
return false
}
return true
}

func (t *Tunnel) Expose(expose bool) error {
path, err := t.computePath()
if err != nil {
return err
}

path := t.path()
if expose {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
file, err := os.Create(path + "-expose")
file, err := os.Create(path)
if err != nil {
return err
}
return file.Close()
}

os.Remove(path + "-expose")
os.Remove(path)
return nil
}

// Path returns the path to the Platform.sh local tunnel state file
func (t *Tunnel) computePath() (string, error) {
if t.path != "" {
return t.path, nil
}
projectRoot, projectInfo := util.GuessProjectRoot(t.Dir, t.Debug)
if projectInfo == nil {
return "", errors.New("unable to get project root")
}
envID, err := util.PotentialCurrentEnvironmentID(projectRoot)
if err != nil {
return "", errors.Wrap(err, "unable to get current env")
}
app := platformsh.GuessSelectedAppByDirectory(t.Dir, platformsh.FindLocalApplications(projectRoot))
if app == nil {
return "", errors.New("unable to get current application")
}
t.path = getControlFileName(filepath.Join(util.GetHomeDir(), "tunnels"), projectInfo.ID, envID, app.Name, t.Worker)
return t.path, nil
}

func getControlFileName(dir, projectID, envID, appName, workerName string) string {
func (t *Tunnel) path() string {
var filename bytes.Buffer

filename.WriteString(projectID)
filename.WriteString(t.Project.ID)
filename.WriteRune('-')
filename.WriteString(envID)
filename.WriteString(t.Project.Env)

if appName != "" {
if t.Project.App != "" {
filename.WriteString("--")
filename.WriteString(appName)
filename.WriteString(t.Project.App)
}

if workerName != "" {
if t.Worker != "" {
filename.WriteString("--")
filename.WriteString(workerName)
filename.WriteString(t.Worker)
}

filename.WriteString(".json")
filename.WriteString("-expose.json")

return filepath.Join(dir, pathCleaningRegex.ReplaceAllString(path.Clean(filename.String()), "-"))
return filepath.Join(filepath.Join(util.GetHomeDir(), "tunnels"), pathCleaningRegex.ReplaceAllString(path.Clean(filename.String()), "-"))
}
60 changes: 40 additions & 20 deletions util/project.go → local/platformsh/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package util
package platformsh

import (
goerr "errors"
Expand All @@ -36,28 +36,54 @@ var (
ErrNoGitBranchMatching = goerr.New("current git branch name doesn't match any Platform.sh environments")
)

type Project struct {
ID string
App string
Env string
}

func ProjectFromDir(dir string, debug bool) (*Project, error) {
projectRoot, projectID := guessProjectRoot(dir, debug)
if projectID == "" {
return nil, errors.New("unable to get project root")
}
envID, err := potentialCurrentEnvironmentID(projectRoot)
if err != nil {
return nil, errors.Wrap(err, "unable to get current env")
}
app := GuessSelectedAppByDirectory(dir, FindLocalApplications(projectRoot))
if app == nil {
return nil, errors.New("unable to get current application")
}
return &Project{
ID: projectID,
App: app.Name,
Env: envID,
}, nil
}

func GetProjectRoot(debug bool) (string, error) {
currentDir, err := os.Getwd()
if err != nil {
return "", errors.WithStack(err)
}

if projectRoot, _ := GuessProjectRoot(currentDir, debug); projectRoot != "" {
if projectRoot, _ := guessProjectRoot(currentDir, debug); projectRoot != "" {
return projectRoot, nil
}

return "", errors.WithStack(ErrProjectRootNotFoundNoGitRemote)
}

func PotentialCurrentEnvironmentID(cwd string) (string, error) {
func potentialCurrentEnvironmentID(cwd string) (string, error) {
for _, potentialEnvironment := range guessCloudBranch(cwd) {
return potentialEnvironment, nil
}

return "", errors.New("no known git upstream, branch or environment name")
}

func RepositoryRootDir(currentDir string) string {
func repositoryRootDir(currentDir string) string {
for {
f, err := os.Stat(filepath.Join(currentDir, ".git"))
if err == nil && f.IsDir() {
Expand All @@ -74,29 +100,25 @@ func RepositoryRootDir(currentDir string) string {
return ""
}

func GuessProjectRoot(currentDir string, debug bool) (string, *gitInfo) {
rootDir := RepositoryRootDir(currentDir)
func guessProjectRoot(currentDir string, debug bool) (string, string) {
rootDir := repositoryRootDir(currentDir)
if rootDir == "" {
return "", nil
return "", ""
}
config := GetProjectConfig(rootDir, debug)
if config == nil {
return "", nil
config := getProjectConfig(rootDir, debug)
if config == "" {
return "", ""
}
return rootDir, config
}

type gitInfo struct {
ID string
}

func GetProjectConfig(projectRoot string, debug bool) *gitInfo {
func getProjectConfig(projectRoot string, debug bool) string {
contents, err := ioutil.ReadFile(filepath.Join(projectRoot, ".platform", "local", "project.yaml"))
if err != nil {
if debug {
fmt.Fprintf(os.Stderr, "WARNING: unable to find Platform.sh config file: %s\n", err)
}
return nil
return ""
}
var config struct {
ID string `yaml:"id"`
Expand All @@ -105,11 +127,9 @@ func GetProjectConfig(projectRoot string, debug bool) *gitInfo {
if debug {
fmt.Fprintf(os.Stderr, "ERROR: unable to decode Platform.sh config file: %s\n", err)
}
return nil
}
return &gitInfo{
ID: config.ID,
return ""
}
return config.ID
}

func guessCloudBranch(cwd string) []string {
Expand Down

0 comments on commit 0c0d432

Please sign in to comment.