Skip to content

Commit

Permalink
deletion of registry through cli tui
Browse files Browse the repository at this point in the history
Signed-off-by: amands98 <amandeepsm.in@gmail.com>
  • Loading branch information
amands98 committed May 12, 2024
1 parent 44506e4 commit 81267d1
Show file tree
Hide file tree
Showing 5 changed files with 172 additions and 32 deletions.
3 changes: 1 addition & 2 deletions cmd/harbor/root/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ func initConfig() {

// cfgFile = viper.GetStering("config")
viper.SetConfigFile(cfgFile)
viper.SetDefault("output", "json")

if cfgFile != utils.DefaultConfigPath {
viper.SetConfigFile(cfgFile)
Expand Down Expand Up @@ -90,7 +89,7 @@ harbor help

cobra.OnInitialize(initConfig)

root.PersistentFlags().StringVarP(&output, "output", "o", "json", "Output format. One of: json|yaml")
root.PersistentFlags().StringVarP(&output, "output", "o", "", "Output format. One of: json|yaml")
root.PersistentFlags().StringVar(&cfgFile, "config", utils.DefaultConfigPath, "config file (default is $HOME/.harbor/config.yaml)")
root.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")

Expand Down
39 changes: 18 additions & 21 deletions cmd/harbor/root/registry/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,55 +2,52 @@ package registry

import (
"context"
"fmt"
"strconv"

"github.com/goharbor/go-client/pkg/sdk/v2.0/client/registry"
"github.com/goharbor/harbor-cli/pkg/constants"
"github.com/goharbor/harbor-cli/pkg/utils"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

type deleteRegistryOptions struct {
id int64
}

// NewDeleteRegistryCommand creates a new `harbor delete registry` command
func DeleteRegistryCommand() *cobra.Command {
var opts deleteRegistryOptions

cmd := &cobra.Command{
Use: "delete",
Short: "delete registry by id",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
id, err := strconv.Atoi(args[0])
if err != nil {
fmt.Printf("Invalid argument: %s. Expected an integer.\n", args[0])
return err
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var err error

if len(args) > 0 {
registryId, _ := strconv.ParseInt(args[0], 10, 64)
err = runDeleteRegistry(registryId)
} else {
registryId := utils.GetRegistryNameFromUser()
err = runDeleteRegistry(registryId)
}
opts.id = int64(id)

credentialName, err := cmd.Flags().GetString(constants.CredentialNameOption)
if err != nil {
return err
log.Errorf("failed to delete registry: %v", err)
}
return runDeleteRegistry(opts, credentialName)
},
}

return cmd
}

func runDeleteRegistry(opts deleteRegistryOptions, credentialName string) error {
func runDeleteRegistry(registryName int64) error {
credentialName := viper.GetString("current-credential-name")
client := utils.GetClientByCredentialName(credentialName)
ctx := context.Background()
response, err := client.Registry.DeleteRegistry(ctx, &registry.DeleteRegistryParams{ID: opts.id})
_, err := client.Registry.DeleteRegistry(ctx, &registry.DeleteRegistryParams{ID: registryName})

if err != nil {
return err
}

utils.PrintPayloadInJSONFormat(response)
log.Info("registry deleted successfully")

return nil
}
26 changes: 23 additions & 3 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
"os"

"github.com/goharbor/go-client/pkg/harbor"
view "github.com/goharbor/harbor-cli/pkg/views/project/select"

v2client "github.com/goharbor/go-client/pkg/sdk/v2.0/client"
"github.com/goharbor/go-client/pkg/sdk/v2.0/client/project"
"github.com/goharbor/go-client/pkg/sdk/v2.0/client/registry"
pview "github.com/goharbor/harbor-cli/pkg/views/project/select"
rview "github.com/goharbor/harbor-cli/pkg/views/registry/select"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -52,6 +53,25 @@ func PrintPayloadInJSONFormat(payload any) {
fmt.Println(string(jsonStr))
}

func GetRegistryNameFromUser() int64 {
registryId := make(chan int64)
go func() {
credentialName := viper.GetString("current-credential-name")
client := GetClientByCredentialName(credentialName)
ctx := context.Background()
response, err := client.Registry.ListRegistries(ctx, &registry.ListRegistriesParams{})
if err != nil {
log.Fatal(err)
}

rview.RegistryList(response.Payload, registryId)

}()

return <-registryId

}

func GetProjectNameFromUser() string {
projectName := make(chan string)
go func() {
Expand All @@ -62,7 +82,7 @@ func GetProjectNameFromUser() string {
if err != nil {
log.Fatal(err)
}
view.ProjectList(response.Payload, projectName)
pview.ProjectList(response.Payload, projectName)

}()

Expand Down
13 changes: 7 additions & 6 deletions pkg/views/registry/list/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/goharbor/go-client/pkg/sdk/v2.0/models"
"github.com/goharbor/harbor-cli/pkg/utils"
)

var baseStyle = lipgloss.NewStyle().
Expand Down Expand Up @@ -44,13 +45,13 @@ func (m model) View() string {
func ListRegistry(registry []*models.Registry) {
var rows []table.Row
for _, regis := range registry {
// createdTime, _ := utils.FormatCreatedTime(project.CreationTime.String())
createdTime, _ := utils.FormatCreatedTime(regis.CreationTime.String())
rows = append(rows, table.Row{
regis.Name, // Project Name
regis.Status, // Project Public
regis.URL, // Project Creation Time
regis.Type, // Project Update Time
regis.CreationTime.String(), // Project Update Time
regis.Name,
regis.Status,
regis.URL,
regis.Type,
createdTime,
regis.Description,
})
}
Expand Down
123 changes: 123 additions & 0 deletions pkg/views/registry/select/view.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package project

import (
"fmt"
"io"
"os"
"strings"

"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/goharbor/go-client/pkg/sdk/v2.0/models"
)

const listHeight = 14

var (
titleStyle = lipgloss.NewStyle().MarginLeft(2)
itemStyle = lipgloss.NewStyle().PaddingLeft(4)
selectedItemStyle = lipgloss.NewStyle().PaddingLeft(2).Foreground(lipgloss.Color("170"))
paginationStyle = list.DefaultStyles().PaginationStyle.PaddingLeft(4)
helpStyle = list.DefaultStyles().HelpStyle.PaddingLeft(4).PaddingBottom(1)
)

type item string

func (i item) FilterValue() string { return "" }

type itemDelegate struct{}

func (d itemDelegate) Height() int { return 1 }
func (d itemDelegate) Spacing() int { return 0 }
func (d itemDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }
func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
i, ok := listItem.(item)
if !ok {
return
}

str := fmt.Sprintf("%d. %s", index+1, i)

fn := itemStyle.Render
if index == m.Index() {
fn = func(s ...string) string {
return selectedItemStyle.Render("> " + strings.Join(s, " "))
}
}

fmt.Fprint(w, fn(str))
}

type model struct {
list list.Model
choice string
}

func (m model) Init() tea.Cmd {
return nil
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.list.SetWidth(msg.Width)
return m, nil

case tea.KeyMsg:
switch keypress := msg.String(); keypress {
case "enter":
i, ok := m.list.SelectedItem().(item)
if ok {
m.choice = string(i)
}
return m, tea.Quit
}
}

var cmd tea.Cmd
m.list, cmd = m.list.Update(msg)
return m, cmd
}

func (m model) View() string {
if m.choice != "" {
return ""
}
return "\n" + m.list.View()
}

func RegistryList(registry []*models.Registry, choice chan<- int64) {
itemsList := make([]list.Item, len(registry))

items := map[string]int64{}

for i, r := range registry {
items[r.Name] = r.ID
itemsList[i] = item(r.Name)
}

const defaultWidth = 20

l := list.New(itemsList, itemDelegate{}, defaultWidth, listHeight)
l.Title = "Select a Registry"
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.Styles.Title = titleStyle
l.Styles.PaginationStyle = paginationStyle
l.Styles.HelpStyle = helpStyle

m := model{list: l}

p, err := tea.NewProgram(m, tea.WithAltScreen()).Run()

if err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}

if p, ok := p.(model); ok {
choice <- items[p.choice]
}

}

0 comments on commit 81267d1

Please sign in to comment.