Skip to content

Commit

Permalink
Merge pull request #452 from ZackJagger/feat/get-current-preview
Browse files Browse the repository at this point in the history
feat: get current preview
  • Loading branch information
jenkins-x-bot authored Sep 14, 2023
2 parents dd9b216 + 79f796f commit 4541404
Show file tree
Hide file tree
Showing 9 changed files with 217 additions and 76 deletions.
2 changes: 1 addition & 1 deletion cmd/docs/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
Expand Down
2 changes: 1 addition & 1 deletion cmd/docs/md_docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
Expand Down
14 changes: 7 additions & 7 deletions pkg/client/clientset/versioned/fake/register.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions pkg/client/clientset/versioned/scheme/register.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 3 additions & 44 deletions pkg/cmd/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"strings"
"time"

"github.com/jenkins-x-plugins/jx-preview/pkg/common"

"github.com/jenkins-x/jx-helpers/v3/pkg/kube/pods"
corev1 "k8s.io/api/core/v1"

Expand Down Expand Up @@ -228,7 +230,7 @@ func (o *Options) Run() error {

o.updatePipelineActivity(url, preview.Spec.PullRequest.URL)

err = o.writeOutputEnvVars()
err = common.WriteOutputEnvVars(o.Dir, o.OutputEnvVars)
if err != nil {
return errors.Wrapf(err, "failed to write output environment variables")
}
Expand Down Expand Up @@ -704,49 +706,6 @@ func (o *Options) DiscoverPreviewHelmfile() error {
return nil
}

func (o *Options) writeOutputEnvVars() error {
path := filepath.Join(o.Dir, ".jx", "variables.sh")

text := ""
exists, err := files.FileExists(path)
if err != nil {
return errors.Wrapf(err, "failed to check for file exist %s", path)
}
if exists {
data, err := os.ReadFile(path)
if err != nil {
return errors.Wrapf(err, "failed to read %s", path)
}
text = string(data)
}

buf := strings.Builder{}
buf.WriteString("# preview environment variables\n")
for k, v := range o.OutputEnvVars {
buf.WriteString(fmt.Sprintf("export %s=%q\n", k, v))
}
if text != "" {
buf.WriteString("\n\n")
buf.WriteString(text)
}
text = buf.String()

// make sure dir exists
dir := filepath.Dir(path)
err = os.MkdirAll(dir, files.DefaultDirWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to make dir %s", dir)
}

err = os.WriteFile(path, []byte(text), files.DefaultFileWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to save file %s", path)
}

log.Logger().Infof("wrote preview environment variables to %s", info(path))
return nil
}

func (o *Options) watchNamespaceStart() error {
previewNamespace := o.Preview.Spec.Resources.Namespace
cmd := exec.Command("kubectl", "get", "event", "-w", "-n", previewNamespace)
Expand Down
79 changes: 63 additions & 16 deletions pkg/cmd/get/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import (
"fmt"
"os"

"github.com/jenkins-x-plugins/jx-preview/pkg/apis/preview/v1alpha1"
"github.com/jenkins-x-plugins/jx-preview/pkg/client/clientset/versioned"
"github.com/jenkins-x-plugins/jx-preview/pkg/common"
"github.com/jenkins-x-plugins/jx-preview/pkg/previews"
"github.com/jenkins-x-plugins/jx-preview/pkg/rootcmd"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/helper"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/templates"
"github.com/jenkins-x/jx-helpers/v3/pkg/scmhelpers"
"github.com/jenkins-x/jx-helpers/v3/pkg/table"
"github.com/pkg/errors"
"github.com/spf13/cobra"
Expand All @@ -19,8 +22,11 @@ import (

// Options containers the CLI options
type Options struct {
scmhelpers.PullRequestOptions

PreviewClient versioned.Interface
Namespace string
OutputEnvVars map[string]string

Current bool
}
Expand Down Expand Up @@ -100,34 +106,75 @@ func (o *Options) Validate() error {
if err != nil {
return errors.Wrapf(err, "failed to create Preview client")
}

return nil
}

func (o *Options) CurrentPreviewURL() error {
/* TODO
pipeline := o.GetJenkinsJobName()
if pipeline == "" {
return fmt.Errorf("No $JOB_NAME defined for the current pipeline job to use")
err := o.ValidateCurrent()
if err != nil {
return errors.Wrapf(err, "failed to validate current options")
}
name := naming.ToValidName(pipeline)

client, ns, err := o.JXClientAndDevNamespace()
_, err = o.DiscoverPullRequest()
if err != nil {
return err
return errors.Wrapf(err, "failed to read pull request options")
}

envList, err := client.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
ctx := context.Background()
ns := o.Namespace
resourceList, err := o.PreviewClient.PreviewV1alpha1().Previews(ns).List(ctx, metav1.ListOptions{})
if err != nil {
return err
if !apierrors.IsNotFound(err) {
return errors.Wrapf(err, "failed to list previews in namespace %s", ns)
}
}
for _, env := range envList.Items {
if env.Spec.Kind == v1.EnvironmentKindTypePreview && env.Name == name {
// lets log directly to stdout for easy capture of the URL from shell scripts
fmt.Println(env.Spec.PreviewGitSpec.ApplicationURL)
return nil

var currentPreview v1alpha1.Preview

for i := 0; i < len(resourceList.Items); i++ {
if resourceList.Items[i].Spec.PullRequest.Number == o.Number &&
resourceList.Items[i].Spec.PullRequest.Repository == o.Repository {
currentPreview = resourceList.Items[i]
break
}
}
return fmt.Errorf("No Preview for name: %s", name)
*/

if currentPreview.Spec.PullRequest.Repository != o.Repository {
return fmt.Errorf("no current preview for %s on pull request #%v", o.Repository, o.Number)
}

t := table.CreateTable(os.Stdout)
t.AddRow("PULL REQUEST", "NAMESPACE", "APPLICATION")
t.AddRow(currentPreview.Spec.PullRequest.URL,
currentPreview.Spec.Resources.Namespace,
currentPreview.Spec.Resources.URL)

t.Render()

o.OutputEnvVars["PREVIEW_URL"] = currentPreview.Spec.Resources.URL
o.OutputEnvVars["PREVIEW_NAME"] = currentPreview.Name
o.OutputEnvVars["PREVIEW_NAMESPACE"] = currentPreview.Spec.Resources.Namespace
o.OutputEnvVars["PREVIEW_PULL_REQUEST_URL"] = currentPreview.Spec.PullRequest.URL

err = common.WriteOutputEnvVars(o.Dir, o.OutputEnvVars)
if err != nil {
return errors.Wrapf(err, "failed to write output environment variables")
}

return nil
}

func (o *Options) ValidateCurrent() error {
if o.OutputEnvVars == nil {
o.OutputEnvVars = map[string]string{}
}
o.DiscoverFromGit = true

err := o.PullRequestOptions.Validate()
if err != nil {
return errors.Wrapf(err, "failed to validate pull request options")
}

return nil
}
79 changes: 79 additions & 0 deletions pkg/cmd/get/get_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package get

import (
"fmt"
"os"
"testing"

"github.com/jenkins-x-plugins/jx-preview/pkg/client/clientset/versioned/fake"
"github.com/jenkins-x-plugins/jx-preview/pkg/fakescms"
"github.com/jenkins-x-plugins/jx-preview/pkg/previews/fakepreviews"
fakescm "github.com/jenkins-x/go-scm/scm/driver/fake"
jxfake "github.com/jenkins-x/jx-api/v4/pkg/client/clientset/versioned/fake"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube/jxenv"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestPreviewGet(t *testing.T) {
scmClient, fakeData := fakescm.NewDefault()

owner := "owner"
repo := "test-repo"
prNumber := 1
sourceURL := fmt.Sprintf("https://fake.com/%s/%s", owner, repo)
ns := "jx"
tmpDir, err := os.MkdirTemp("", "")
require.NoError(t, err, "failed to create temp dir")

preview1, _ := fakepreviews.CreateTestPreviewAndPullRequest(fakeData, ns, owner, repo, 1)
fakescms.CreatePullRequest(fakeData, owner, repo, prNumber)

previewClient := fake.NewSimpleClientset(preview1)

devEnv := jxenv.CreateDefaultDevEnvironment(ns)
devEnv.Namespace = ns
devEnv.Spec.Source.URL = sourceURL

jxClient := jxfake.NewSimpleClientset(devEnv)

testCases := []struct {
name string
current bool
}{
{
name: "get",
current: false,
},
{
name: "get current",
current: true,
},
}

for _, tc := range testCases {
_, o := NewCmdGetPreview()

o.ScmClient = scmClient
o.PreviewClient = previewClient
o.JXClient = jxClient
o.SourceURL = sourceURL
o.PullRequestOptions.Number = prNumber
o.Repository = repo
o.DiscoverFromGit = false
o.Namespace = ns
o.Current = tc.current
o.Dir = tmpDir

t.Logf("running get for test: %s", tc.name)
err := o.Run()
require.NoError(t, err)

if tc.current {
assert.Equal(t, fmt.Sprintf("https://%s-pr%v.mqube-test.com", repo, prNumber), o.OutputEnvVars["PREVIEW_URL"])
assert.Equal(t, fmt.Sprintf("%s-%s-%v", owner, repo, prNumber), o.OutputEnvVars["PREVIEW_NAME"])
assert.Equal(t, fmt.Sprintf("%s-%s-%s-pr-%v", ns, owner, repo, prNumber), o.OutputEnvVars["PREVIEW_NAMESPACE"])
assert.Equal(t, sourceURL, o.OutputEnvVars["PREVIEW_PULL_REQUEST_URL"])
}
}
}
53 changes: 53 additions & 0 deletions pkg/common/helpers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package common

import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/jenkins-x/jx-helpers/v3/pkg/files"
"github.com/jenkins-x/jx-helpers/v3/pkg/termcolor"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
"github.com/pkg/errors"
)

// BinaryName the binary name to use in help docs
Expand All @@ -20,3 +28,48 @@ func init() {
TopLevelCommand = "jx remote"
}
}

var info = termcolor.ColorInfo

func WriteOutputEnvVars(currentDir string, outputEnvVars map[string]string) error {
path := filepath.Join(currentDir, ".jx", "variables.sh")

text := ""
exists, err := files.FileExists(path)
if err != nil {
return errors.Wrapf(err, "failed to check for file exist %s", path)
}
if exists {
data, err := os.ReadFile(path)
if err != nil {
return errors.Wrapf(err, "failed to read %s", path)
}
text = string(data)
}

buf := strings.Builder{}
buf.WriteString("# preview environment variables\n")
for k, v := range outputEnvVars {
buf.WriteString(fmt.Sprintf("export %s=%q\n", k, v))
}
if text != "" {
buf.WriteString("\n\n")
buf.WriteString(text)
}
text = buf.String()

// make sure dir exists
dir := filepath.Dir(path)
err = os.MkdirAll(dir, files.DefaultDirWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to make dir %s", dir)
}

err = os.WriteFile(path, []byte(text), files.DefaultFileWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to save file %s", path)
}

log.Logger().Infof("wrote preview environment variables to %s", info(path))
return nil
}
Loading

0 comments on commit 4541404

Please sign in to comment.