Skip to content

Commit

Permalink
CR-5108 (#50)
Browse files Browse the repository at this point in the history
* final

* bump

* git-source

* new file

* corrections

* lint

* Delete yarn.lock

* Delete .yarn-integrity

* after codegen

* gs using path param

* removed redundant

* name

* example

* without redundant condition

* .

* added files

* bump

* .

* gitSourceOptions

* go.mod no replace

* optional

* with --git-src-repo check

* example in error

* Use:

* Join

* removed redundant

* after codegen

* tested

* bump
  • Loading branch information
elad-codefresh authored Aug 10, 2021
1 parent 98b61a1 commit 4221f36
Show file tree
Hide file tree
Showing 12 changed files with 289 additions and 76 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION=v0.0.55
VERSION=v0.0.56
OUT_DIR=dist
YEAR?=$(shell date +"%Y")

Expand Down
198 changes: 198 additions & 0 deletions cmd/commands/git-source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// Copyright 2021 The Codefresh Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package commands

import (
"context"
"fmt"

"github.com/codefresh-io/cli-v2/pkg/log"
"github.com/codefresh-io/cli-v2/pkg/runtime"
"github.com/codefresh-io/cli-v2/pkg/store"
"github.com/codefresh-io/cli-v2/pkg/util"

"github.com/argoproj-labs/argocd-autopilot/pkg/application"
"github.com/argoproj-labs/argocd-autopilot/pkg/fs"
"github.com/argoproj-labs/argocd-autopilot/pkg/git"
apstore "github.com/argoproj-labs/argocd-autopilot/pkg/store"
wf "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow"
wfv1alpha1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/go-git/go-billy/v5/memfs"
"github.com/spf13/cobra"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type (
GitSourceCreateOptions struct {
insCloneOpts *git.CloneOptions
gsCloneOpts *git.CloneOptions
gsName string
runtimeName string
fullGsPath string
}
)

func NewGitSourceCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "git-source",
Short: "Manage git-sources of Codefresh runtimes",
Run: func(cmd *cobra.Command, args []string) {
cmd.HelpFunc()(cmd, args)
exit(1)
},
}

cmd.AddCommand(NewGitSourceCreateCommand())

return cmd
}

func NewGitSourceCreateCommand() *cobra.Command {
var (
insCloneOpts *git.CloneOptions
gsCloneOpts *git.CloneOptions
)

cmd := &cobra.Command{
Use: "create runtime_name git-source_name",
Short: "add a new git-source to an existing runtime",
Example: util.Doc(`
<BIN> git-source create runtime_name git-source-name https://github.com/owner/repo-name/my-workflow
`),
PreRun: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()

if len(args) < 1 {
log.G(ctx).Fatal("must enter runtime name")
}

if len(args) < 2 {
log.G(ctx).Fatal("must enter git-source name")
}

if gsCloneOpts.Repo == "" {
log.G(ctx).Fatal("must enter a valid value to --git-src-repo. Example: https://github.com/owner/repo-name/path/to/workflow")
}

if gsCloneOpts.Auth.Password == "" {
gsCloneOpts.Auth.Password = insCloneOpts.Auth.Password
}

insCloneOpts.Parse()
gsCloneOpts.Parse()
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()

return RunCreateGitSource(ctx, &GitSourceCreateOptions{
insCloneOpts: insCloneOpts,
gsCloneOpts: gsCloneOpts,
gsName: args[1],
runtimeName: args[0],
fullGsPath: gsCloneOpts.Path(),
})
},
}

insCloneOpts = git.AddFlags(cmd, &git.AddFlagsOptions{
CreateIfNotExist: true,
FS: memfs.New(),
})
gsCloneOpts = git.AddFlags(cmd, &git.AddFlagsOptions{
Prefix: "git-src",
Optional: true,
CreateIfNotExist: true,
FS: memfs.New(),
})

return cmd
}

func RunCreateGitSource(ctx context.Context, opts *GitSourceCreateOptions) error {
gsRepo, gsFs, err := opts.gsCloneOpts.GetRepo(ctx)
if err != nil {
return err
}

fi, err := gsFs.ReadDir(".")

if err != nil {
return fmt.Errorf("failed to read files in git-source repo. Err: %w", err)
}

if len(fi) == 0 {
if err = createDemoWorkflowTemplate(gsFs, opts.gsName, opts.runtimeName); err != nil {
return fmt.Errorf("failed to create demo workflowTemplate: %w", err)
}

_, err = gsRepo.Persist(ctx, &git.PushOptions{
CommitMsg: fmt.Sprintf("Created demo workflow template in %s Directory", opts.gsCloneOpts.Path()),
})

if err != nil {
return fmt.Errorf("failed to push changes. Err: %w", err)
}
}

appDef := &runtime.AppDef{
Name: opts.gsName,
Type: application.AppTypeDirectory,
URL: opts.gsCloneOpts.Repo,
}
if err := appDef.CreateApp(ctx, nil, opts.insCloneOpts, opts.runtimeName, store.Get().CFGitSourceType, nil); err != nil {
return fmt.Errorf("failed to create git-source application. Err: %w", err)
}

log.G(ctx).Infof("done creating a new git-source: '%s'", opts.gsName)

return nil
}

func createDemoWorkflowTemplate(gsFs fs.FS, gsName, runtimeName string) error {
var err error

gsPath := gsFs.Join(apstore.Default.AppsDir, gsName, runtimeName, "demo-wf-template.yaml")
wfTemplate := &wfv1alpha1.WorkflowTemplate{
TypeMeta: metav1.TypeMeta{
Kind: wf.WorkflowTemplateKind,
APIVersion: wfv1alpha1.SchemeGroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "demo-workflow-template",
Namespace: runtimeName,
},
Spec: wfv1alpha1.WorkflowTemplateSpec{
WorkflowSpec: wfv1alpha1.WorkflowSpec{
Entrypoint: "whalesay",
Templates: []wfv1alpha1.Template{
{
Name: "whalesay",
Container: &v1.Container{
Image: "docker/whalesay",
Command: []string{"cowsay"},
Args: []string{"Hello World"},
},
},
},
},
},
}
if err = gsFs.WriteYamls(gsPath, wfTemplate); err != nil {
return err
}

return err
}
1 change: 1 addition & 0 deletions cmd/commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ variables in advanced to simplify the use of those commands.
cmd.AddCommand(NewVersionCommand())
cmd.AddCommand(NewConfigCommand())
cmd.AddCommand(NewRuntimeCommand())
cmd.AddCommand(NewGitSourceCommand())

cobra.OnInitialize(func() { postInitCommands(cmd.Commands()) })

Expand Down
78 changes: 11 additions & 67 deletions cmd/commands/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ import (
apstore "github.com/argoproj-labs/argocd-autopilot/pkg/store"
aputil "github.com/argoproj-labs/argocd-autopilot/pkg/util"
argocdv1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
wf "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow"
wfv1alpha1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/ghodss/yaml"
"github.com/go-git/go-billy/v5/memfs"
"github.com/juju/ansiterm"
Expand Down Expand Up @@ -127,7 +125,7 @@ func NewRuntimeInstallCommand() *cobra.Command {
insCloneOpts.Parse()
if gsCloneOpts.Repo == "" {
host, orgRepo, _, _, _, suffix, _ := aputil.ParseGitUrl(insCloneOpts.Repo)
gsCloneOpts.Repo = host + orgRepo + "_git_source" + suffix
gsCloneOpts.Repo = host + orgRepo + "_git-source" + suffix + "/workflows"
}

gsCloneOpts.Parse()
Expand Down Expand Up @@ -243,12 +241,16 @@ func RunRuntimeInstall(ctx context.Context, opts *RuntimeInstallOptions) error {
return fmt.Errorf("failed to create workflows-reporter: %w", err)
}

if err = createDemoWorkflowTemplate(ctx, opts.gsCloneOpts, store.Get().GitSourceName, opts.RuntimeName); err != nil {
return fmt.Errorf("failed to create demo workflowTemplate: %w", err)
}
gsPath := opts.gsCloneOpts.FS.Join(apstore.Default.AppsDir, store.Get().GitSourceName, opts.RuntimeName)
fullGsPath := opts.gsCloneOpts.FS.Join(opts.gsCloneOpts.FS.Root(), gsPath)[1:]

if err = createGitSource(ctx, opts.insCloneOpts, opts.gsCloneOpts, store.Get().GitSourceName, opts.RuntimeName,
opts.commonConfig.CodefreshBaseURL); err != nil {
if err = RunCreateGitSource(ctx, &GitSourceCreateOptions{
insCloneOpts: opts.insCloneOpts,
gsCloneOpts: opts.gsCloneOpts,
gsName: store.Get().GitSourceName,
runtimeName: opts.RuntimeName,
fullGsPath: fullGsPath,
}); err != nil {
return fmt.Errorf("failed to create `%s`: %w", store.Get().GitSourceName, err)
}

Expand All @@ -258,7 +260,7 @@ func RunRuntimeInstall(ctx context.Context, opts *RuntimeInstallOptions) error {

func NewRuntimeListCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "list ",
Use: "list [runtime_name]",
Short: "List all Codefresh runtimes",
Example: util.Doc(`<BIN> runtime list`),
RunE: func(_ *cobra.Command, _ []string) error {
Expand Down Expand Up @@ -759,61 +761,3 @@ func createSensor(repofs fs.FS, name, path, namespace, eventSourceName, trigger,
})
return repofs.WriteYamls(repofs.Join(path, "sensor.yaml"), sensor)
}

func createDemoWorkflowTemplate(ctx context.Context, gsCloneOpts *git.CloneOptions, gsName, runtimeName string) error {
gsRepo, gsFs, err := gsCloneOpts.GetRepo(ctx)
if err != nil {
return err
}

gsPath := gsCloneOpts.FS.Join(apstore.Default.AppsDir, gsName, runtimeName)
wfTemplate := &wfv1alpha1.WorkflowTemplate{
TypeMeta: metav1.TypeMeta{
Kind: wf.WorkflowTemplateKind,
APIVersion: wfv1alpha1.SchemeGroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "demo-workflow-template",
Namespace: runtimeName,
},
Spec: wfv1alpha1.WorkflowTemplateSpec{
WorkflowSpec: wfv1alpha1.WorkflowSpec{
Entrypoint: "whalesay",
Templates: []wfv1alpha1.Template{
{
Name: "whalesay",
Container: &v1.Container{
Image: "docker/whalesay",
Command: []string{"cowsay"},
Args: []string{"Hello World"},
},
},
},
},
},
}
if err = gsFs.WriteYamls(gsFs.Join(gsPath, "demo-wf-template.yaml"), wfTemplate); err != nil {
return err
}

_, err = gsRepo.Persist(ctx, &git.PushOptions{
CommitMsg: fmt.Sprintf("Created %s Directory", gsPath),
})
return err
}

func createGitSource(ctx context.Context, insCloneOpts *git.CloneOptions, gsCloneOpts *git.CloneOptions, gsName, runtimeName, cfBaseURL string) error {
gsPath := gsCloneOpts.FS.Join(apstore.Default.AppsDir, gsName, runtimeName)
fullGsPath := gsCloneOpts.FS.Join(gsCloneOpts.FS.Root(), gsPath)[1:]

appDef := &runtime.AppDef{
Name: gsName,
Type: application.AppTypeDirectory,
URL: gsCloneOpts.URL() + fullGsPath,
}
if err := appDef.CreateApp(ctx, nil, insCloneOpts, runtimeName, store.Get().CFGitSourceType, nil); err != nil {
return fmt.Errorf("failed to create git-source: %w", err)
}

return nil
}
1 change: 1 addition & 0 deletions docs/commands/cli-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ cli-v2 [flags]
### SEE ALSO

* [cli-v2 config](cli-v2_config.md) - Manage Codefresh authentication contexts
* [cli-v2 git-source](cli-v2_git-source.md) - Manage git-sources of Codefresh runtimes
* [cli-v2 runtime](cli-v2_runtime.md) - Manage Codefresh runtimes
* [cli-v2 version](cli-v2_version.md) - Show cli version

28 changes: 28 additions & 0 deletions docs/commands/cli-v2_git-source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
## cli-v2 git-source

Manage git-sources of Codefresh runtimes

```
cli-v2 git-source [flags]
```

### Options

```
-h, --help help for git-source
```

### Options inherited from parent commands

```
--auth-context string Run the next command using a specific authentication context
--cfconfig string Custom path for authentication contexts config file (default "/home/user")
--insecure Disable certificate validation for TLS connections (e.g. to g.codefresh.io)
--request-timeout duration Request timeout (default 30s)
```

### SEE ALSO

* [cli-v2](cli-v2.md) - cli-v2 is used for installing and managing codefresh installations using gitops
* [cli-v2 git-source create](cli-v2_git-source_create.md) - add a new git-source to an existing runtime

Loading

0 comments on commit 4221f36

Please sign in to comment.