-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
84 lines (73 loc) · 2.25 KB
/
table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package registry
import (
"context"
"fmt"
"net/http"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
type TableConvertor struct {
Resource schema.GroupResource
// cells creates a single row of cells of the table from a runtime.Object
Cells func(obj runtime.Object) []interface{}
// columns stores column definitions for the table convertor
Columns []metav1.TableColumnDefinition
}
// ConvertToTable implements rest.TableConvertor
func (r TableConvertor) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {
var table metav1.Table
fn := func(obj runtime.Object) error {
cells := r.Cells(obj)
if len(cells) == 0 {
return errNotAcceptable{resource: r.Resource}
}
table.Rows = append(table.Rows, metav1.TableRow{
Cells: cells,
Object: runtime.RawExtension{Object: obj},
})
return nil
}
// Create table rows
switch {
case meta.IsListType(object):
if err := meta.EachListItem(object, fn); err != nil {
return nil, err
}
default:
if err := fn(object); err != nil {
return nil, err
}
}
// Populate table metadata
table.APIVersion = metav1.SchemeGroupVersion.Identifier()
table.Kind = "Table"
if l, err := meta.ListAccessor(object); err == nil {
table.ResourceVersion = l.GetResourceVersion()
table.Continue = l.GetContinue()
table.RemainingItemCount = l.GetRemainingItemCount()
} else if c, err := meta.CommonAccessor(object); err == nil {
table.ResourceVersion = c.GetResourceVersion()
//table.SelfLink = c.GetSelfLink()
}
if opt, ok := tableOptions.(*metav1.TableOptions); !ok || !opt.NoHeaders {
table.ColumnDefinitions = r.Columns
}
return &table, nil
}
// errNotAcceptable indicates the resource doesn't support Table conversion
type errNotAcceptable struct {
resource schema.GroupResource
}
func (e errNotAcceptable) Error() string {
return fmt.Sprintf("the resource %s does not support being converted to a Table", e.resource)
}
func (e errNotAcceptable) Status() metav1.Status {
return metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusNotAcceptable,
Reason: metav1.StatusReason("NotAcceptable"),
Message: e.Error(),
}
}