Skip to content

Commit

Permalink
feat: get & list proposal(#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
dayuy committed May 26, 2023
1 parent e68e625 commit 4502cd0
Show file tree
Hide file tree
Showing 6 changed files with 262 additions and 16 deletions.
3 changes: 2 additions & 1 deletion cmd/bc-cli/get/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package get

import (
"github.com/bestchains/bc-cli/pkg/federation"
"github.com/bestchains/bc-cli/pkg/proposal"
"os"

"github.com/bestchains/bc-cli/pkg/account"
Expand All @@ -42,7 +43,7 @@ func NewGetCmd() *cobra.Command {
//cmd.AddCommand(chaincodebuild.NewCCBGetCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}}))
//cmd.AddCommand(channel.NewChanGetCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}}))
//cmd.AddCommand(vote.NewVoteGetCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}}))
//cmd.AddCommand(proposal.NewProposalGetCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}}))
cmd.AddCommand(proposal.NewProposalGetCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}}))
//cmd.AddCommand(policy.NewPolicyGetCmd(common.Options{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}}))
return cmd
}
16 changes: 16 additions & 0 deletions pkg/common/ibp.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

Expand All @@ -37,6 +39,8 @@ const (
UserResource = "users"
Channel = "channels"
Configmap = "configmaps"
Proposal = "proposals"
Vote = "votes"
)

func InKubeGetter() (*clientcmdapi.Config, error) {
Expand Down Expand Up @@ -85,6 +89,18 @@ func InKubeGetter() (*clientcmdapi.Config, error) {
}, nil
}

func GetDynamicClient() (*dynamic.DynamicClient, error) {
cfg, err := clientcmd.BuildConfigFromKubeconfigGetter("", InKubeGetter)
if err != nil {
return nil, err
}
cli, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
return cli, nil
}

func ListToObj(list corev1.List) (runtime.Object, error) {
var obj runtime.Object
listJSON, err := json.Marshal(list)
Expand Down
26 changes: 15 additions & 11 deletions pkg/org/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubectl/pkg/cmd/get"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
)
Expand All @@ -45,12 +44,7 @@ func NewOrgGetCmd(option common.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "org [NAME]",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := clientcmd.BuildConfigFromKubeconfigGetter("", common.InKubeGetter)
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return err
}
cli, err := dynamic.NewForConfig(cfg)
cli, err := common.GetDynamicClient()
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return err
Expand All @@ -65,10 +59,7 @@ func NewOrgGetCmd(option common.Options) *cobra.Command {
}
var obj runtime.Object
if len(args) == 0 {
orgs, err := cli.Resource(schema.GroupVersionResource{Group: common.IBPGroup, Version: common.IBPVersion, Resource: common.OrganizationResource}).List(context.TODO(), v1.ListOptions{
LabelSelector: labelSelector,
FieldSelector: fieldSelector,
})
orgs, err := ListOrganizations(cli, labelSelector, fieldSelector)
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return err
Expand Down Expand Up @@ -119,3 +110,16 @@ func NewOrgGetCmd(option common.Options) *cobra.Command {

return cmd
}

// ListOrganizations returns a list of organizations filtered by labelSelector and fieldSelector.
// Return error if any error occurs
func ListOrganizations(cli *dynamic.DynamicClient, labelSelector string, fieldSelector string) (*unstructured.UnstructuredList, error) {
organizations, err := cli.Resource(schema.GroupVersionResource{Group: common.IBPGroup, Version: common.IBPVersion, Resource: common.OrganizationResource}).List(context.TODO(), v1.ListOptions{
LabelSelector: labelSelector,
FieldSelector: fieldSelector,
})
if err != nil {
return nil, err
}
return organizations, nil
}
99 changes: 95 additions & 4 deletions pkg/proposal/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,107 @@ limitations under the License.
package proposal

import (
"github.com/bestchains/bc-cli/pkg/common"
"context"
"encoding/json"
"fmt"
"github.com/bestchains/bc-cli/pkg/org"

"github.com/spf13/cobra"
"github.com/spf13/viper"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubectl/pkg/cmd/get"

"github.com/bestchains/bc-cli/pkg/common"
"github.com/bestchains/bc-cli/pkg/utils"
)

func NewProposalGetCmd(option common.Options) *cobra.Command {
defaultPrintFlag := get.NewGetPrintFlags()
cmd := &cobra.Command{
Use: "",
RunE: func(cmd *cobra.Command, args []string) error {
return nil
Use: "proposal [NAME]",
Run: func(cmd *cobra.Command, args []string) {
cli, err := common.GetDynamicClient()
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return
}

list := corev1.List{
TypeMeta: v1.TypeMeta{
Kind: "List",
APIVersion: "v1",
},
ListMeta: v1.ListMeta{},
}
var obj runtime.Object
if len(args) == 0 {
username := viper.GetString("auth.username")
organizations, err := org.ListOrganizations(cli, fmt.Sprintf("bestchains.organization.admin=%s", username), "")
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return
}
var proposalNames []string
for _, org := range organizations.Items {
namespace := org.GetName()
votes, err := cli.Resource(schema.GroupVersionResource{Group: common.IBPGroup, Version: common.IBPVersion, Resource: common.Vote}).Namespace(namespace).List(context.TODO(), v1.ListOptions{})
if err != nil {
fmt.Fprintln(option.ErrOut, err)
continue
}
for _, vote := range votes.Items {
proposalName := utils.GetNestedString(vote.Object, "spec", "proposalName")
proposalNames = append(proposalNames, proposalName)
}
}
for _, proposalName := range utils.RemoveDuplicateForStringSlice(proposalNames) {
proposal, err := cli.Resource(schema.GroupVersionResource{Group: common.IBPGroup, Version: common.IBPVersion, Resource: common.Proposal}).Get(context.TODO(), proposalName, v1.GetOptions{})
if err != nil {
fmt.Fprintln(option.ErrOut, err)
continue
}
list.Items = append(list.Items, runtime.RawExtension{Object: proposal})
}
} else {
for _, arg := range args {
proposal, err := cli.Resource(schema.GroupVersionResource{Group: common.IBPGroup, Version: common.IBPVersion, Resource: common.Proposal}).Get(context.TODO(), arg, v1.GetOptions{})
if err != nil {
fmt.Fprintln(option.ErrOut, err)
continue
}
list.Items = append(list.Items, runtime.RawExtension{Object: proposal})
}
}

if len(list.Items) != 1 {
listData, err := json.Marshal(list)
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return
}
converted, err := runtime.Decode(unstructured.UnstructuredJSONScheme, listData)
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return
}
obj = converted
} else {
obj = list.Items[0].Object
}

p, err := defaultPrintFlag.ToPrinter()
if err != nil {
fmt.Fprintln(option.ErrOut, err)
return
}
_ = p.PrintObj(obj, option.Out)
},
}
defaultPrintFlag.AddFlags(cmd)

return cmd
}
39 changes: 39 additions & 0 deletions pkg/utils/tools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Copyright 2023 The Bestchains 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 utils

import "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

// GetNestedString returns the string value of a nested field.
// Returns "" if value is not found or not a string.
func GetNestedString(obj map[string]interface{}, fields ...string) string {
val, _, _ := unstructured.NestedString(obj, fields...)
return val
}

// RemoveDuplicateForStringSlice returns a new slice with duplicate elements removed.
func RemoveDuplicateForStringSlice(elements []string) []string {
result := make([]string, 0, len(elements))
temp := map[string]struct{}{}
for _, element := range elements {
if _, ok := temp[element]; !ok && element != "" {
temp[element] = struct{}{}
result = append(result, element)
}
}
return result
}
95 changes: 95 additions & 0 deletions pkg/utils/tools_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
Copyright 2023 The Bestchains 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 utils

import (
"reflect"
"testing"
)

func TestGetNestedString(t *testing.T) {
obj := map[string]interface{}{
"foo": map[string]interface{}{
"bar": "baz",
},
}

// Test a valid nested string value.
expected := "baz"
actual := GetNestedString(obj, "foo", "bar")
if actual != expected {
t.Errorf("Expected %s but got %s", expected, actual)
}

// Test a missing nested field.
expected = ""
actual = GetNestedString(obj, "foo", "notfound")
if actual != expected {
t.Errorf("Expected %s but got %s", expected, actual)
}

// Test a non-string nested value.
obj["foo"].(map[string]interface{})["baz"] = 123
expected = ""
actual = GetNestedString(obj, "foo", "baz")
if actual != expected {
t.Errorf("Expected %s but got %s", expected, actual)
}
}

func TestRemoveDuplicateForStringSlice(t *testing.T) {
testCases := []struct {
name string
input []string
expected []string
}{
{
name: "no duplicates",
input: []string{"a", "b", "c"},
expected: []string{"a", "b", "c"},
},
{
name: "some duplicates",
input: []string{"a", "b", "a", "c", "b"},
expected: []string{"a", "b", "c"},
},
{
name: "all duplicates",
input: []string{"a", "a", "a", "a"},
expected: []string{"a"},
},
{
name: "empty string",
input: []string{"a", "b", ""},
expected: []string{"a", "b"},
},
{
name: "empty slice",
input: []string{},
expected: []string{},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := RemoveDuplicateForStringSlice(tc.input)
if !reflect.DeepEqual(result, tc.expected) {
t.Errorf("expected %v, but got %v", tc.expected, result)
}
})
}
}

0 comments on commit 4502cd0

Please sign in to comment.